@openpeepshq/core 0.2.0 → 0.2.2

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 (74) hide show
  1. package/LICENSE +674 -0
  2. package/dist/accounts/mutations.js +9 -0
  3. package/dist/analytics/cache.js +1 -1
  4. package/dist/config/index.d.ts +3 -336
  5. package/dist/db/explorer/index.d.ts +1 -1
  6. package/dist/db/explorer/index.js +1 -1
  7. package/dist/db/index.d.ts +1 -1
  8. package/dist/db/index.js +1 -1
  9. package/dist/db/pg/map/registry.js +3 -2
  10. package/dist/federation/actors.d.ts +32 -0
  11. package/dist/federation/actors.js +136 -0
  12. package/dist/federation/identity.d.ts +11 -0
  13. package/dist/federation/identity.js +11 -0
  14. package/dist/federation/index.d.ts +8 -1
  15. package/dist/federation/index.js +5 -1
  16. package/dist/federation/ingest.d.ts +9 -0
  17. package/dist/federation/ingest.js +60 -0
  18. package/dist/federation/notes.d.ts +8 -0
  19. package/dist/federation/notes.js +30 -0
  20. package/dist/federation/peers.d.ts +3 -0
  21. package/dist/federation/peers.js +24 -0
  22. package/dist/jams/export.d.ts +2 -0
  23. package/dist/jams/export.js +5 -0
  24. package/dist/jams/finders.d.ts +1 -0
  25. package/dist/jams/finders.js +1 -0
  26. package/dist/jams/health.d.ts +23 -0
  27. package/dist/jams/health.js +79 -7
  28. package/dist/jams/index.d.ts +1 -1
  29. package/dist/jams/index.js +10 -3
  30. package/dist/jams/token.js +6 -2
  31. package/dist/jams/waitingRoom.js +3 -1
  32. package/dist/media/garbageCollection.d.ts +109 -0
  33. package/dist/media/garbageCollection.js +603 -0
  34. package/dist/media/garbageCollectionJobs.d.ts +14 -0
  35. package/dist/media/garbageCollectionJobs.js +55 -0
  36. package/dist/media/index.d.ts +10 -0
  37. package/dist/media/index.js +39 -15
  38. package/dist/media/streaming.d.ts +2 -0
  39. package/dist/media/streaming.js +8 -0
  40. package/dist/notifications/defaultNotifications/index.js +2 -0
  41. package/dist/notifications/defaultNotifications/jamStarted/index.d.ts +1 -0
  42. package/dist/notifications/defaultNotifications/jamStarted/index.js +61 -13
  43. package/dist/notifications/defaultNotifications/waitlistOffer/index.d.ts +24 -0
  44. package/dist/notifications/defaultNotifications/waitlistOffer/index.js +40 -0
  45. package/dist/notifications/index.d.ts +1 -1
  46. package/dist/notifications/index.js +1 -1
  47. package/dist/plugins/pluginAuth.js +1 -0
  48. package/dist/posts/conversationQueries.d.ts +31 -0
  49. package/dist/posts/conversationQueries.js +150 -24
  50. package/dist/posts/finders.d.ts +9 -0
  51. package/dist/posts/finders.js +23 -3
  52. package/dist/posts/helpers/index.d.ts +10 -2
  53. package/dist/posts/helpers/index.js +6 -0
  54. package/dist/posts/index.d.ts +3 -1
  55. package/dist/posts/index.js +3 -1
  56. package/dist/posts/mapping.d.ts +14 -0
  57. package/dist/posts/mutations.d.ts +13 -6
  58. package/dist/posts/mutations.js +271 -72
  59. package/dist/posts/rsvpExport.d.ts +47 -0
  60. package/dist/posts/rsvpExport.js +178 -0
  61. package/dist/posts/unseenCounts.d.ts +6 -0
  62. package/dist/posts/unseenCounts.js +51 -1
  63. package/dist/posts/waitlist.d.ts +13 -0
  64. package/dist/posts/waitlist.js +75 -0
  65. package/dist/posts/waitlistOfferJobs.d.ts +10 -0
  66. package/dist/posts/waitlistOfferJobs.js +91 -0
  67. package/dist/profiles/index.js +6 -1
  68. package/dist/profiles/mutations.js +6 -3
  69. package/dist/reports/mapping.d.ts +1 -1
  70. package/dist/server/index.d.ts +1 -0
  71. package/dist/stats/mapping.d.ts +1 -0
  72. package/dist/stripe/connection.js +1 -1
  73. package/dist/stripe/helpers.js +7 -3
  74. package/package.json +11 -10
@@ -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, rsvpTargetsPastEvent, 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 = {}) => {
@@ -197,10 +199,51 @@ export const deletePost = async (post, profile) => {
197
199
  }
198
200
  return postsMapping.find(db, post.id);
199
201
  };
200
- export const vote = (profile, post, data) => allpeepDb().then(({ db }) => entryConnector(db, profile, post, {
201
- type: 'answer',
202
- data,
203
- }).then(() => hub.emit('entryCreated', profile, post, { type: 'answer', data })));
202
+ export const validatePollVote = (post, data) => {
203
+ if (post.data?.type !== 'question')
204
+ return;
205
+ const question = post.data;
206
+ if (question.expiresAt &&
207
+ Date.now() > new Date(question.expiresAt).getTime()) {
208
+ throw forbidden({ errorKey: 'error.pollClosed' });
209
+ }
210
+ const multiple = question.multiple ?? false;
211
+ const optionsCount = question.options.length;
212
+ // Empty selection is allowed — it clears an existing vote (undo).
213
+ if (data.selection.length === 0)
214
+ return;
215
+ if (!multiple && data.selection.length !== 1) {
216
+ throw unprocessableRequest({
217
+ errorKey: 'error.invalidPollVote',
218
+ parameters: { reason: 'singleChoiceRequired' },
219
+ });
220
+ }
221
+ const seen = new Set();
222
+ for (const index of data.selection) {
223
+ if (index < 0 || index >= optionsCount) {
224
+ throw unprocessableRequest({
225
+ errorKey: 'error.invalidPollVote',
226
+ parameters: { reason: 'optionOutOfRange' },
227
+ });
228
+ }
229
+ if (seen.has(index)) {
230
+ throw unprocessableRequest({
231
+ errorKey: 'error.invalidPollVote',
232
+ parameters: { reason: 'duplicateOption' },
233
+ });
234
+ }
235
+ seen.add(index);
236
+ }
237
+ };
238
+ export const vote = async (profile, post, data) => {
239
+ validatePollVote(post, data);
240
+ const { db } = await allpeepDb();
241
+ await entryConnector(db, profile, post, {
242
+ type: 'answer',
243
+ data,
244
+ });
245
+ await hub.emit('entryCreated', profile, post, { type: 'answer', data });
246
+ };
204
247
  const attendingRsvp = (response) => response === 'yes' || response === 'tentative';
205
248
  const rsvpOccurrenceIds = (data) => {
206
249
  if (data.recurrenceIds?.length)
@@ -209,6 +252,40 @@ const rsvpOccurrenceIds = (data) => {
209
252
  return [data.recurrenceId];
210
253
  return undefined;
211
254
  };
255
+ const latestOwnResponse = (post, profileId, occurrenceIds) => {
256
+ const previousResponses = occurrenceIds
257
+ ? occurrenceIds.map((id) => getEffectiveRsvp(post, profileId, id)?.response)
258
+ : undefined;
259
+ if (previousResponses) {
260
+ return previousResponses.every(attendingRsvp)
261
+ ? previousResponses[0]
262
+ : previousResponses.find((response) => !attendingRsvp(response));
263
+ }
264
+ return [...(post.rsvps ?? [])]
265
+ .filter((rsvp) => rsvp.profile.id === profileId)
266
+ .filter((rsvp) => !rsvp.recurrenceId)
267
+ .sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1))[0]?.response;
268
+ };
269
+ const rsvpWrites = (post, profileId, response, occurrenceIds) => {
270
+ if (response === 'waitlist') {
271
+ const waitlistJoinedAt = new Date().toISOString();
272
+ return occurrenceIds?.length
273
+ ? occurrenceIds.map((recurrenceId) => ({
274
+ response,
275
+ recurrenceId,
276
+ waitlistJoinedAt,
277
+ }))
278
+ : [{ response, waitlistJoinedAt }];
279
+ }
280
+ return occurrenceIds
281
+ ? occurrenceIds.map((recurrenceId) => ({ response, recurrenceId }))
282
+ : overlaySeriesRsvpEntries(response, instanceRsvpIdsForProfile(post, profileId));
283
+ };
284
+ const publishCapacityPlans = async (postId, fromProfileId, plans) => {
285
+ if (!plans.length)
286
+ return;
287
+ await publishWaitlistPlans(postId, fromProfileId, plans).catch(() => undefined);
288
+ };
212
289
  export const rsvpRespond = async (profile, post, data) => {
213
290
  if (profile.id === post.profile.id) {
214
291
  return;
@@ -222,64 +299,112 @@ export const rsvpRespond = async (profile, post, data) => {
222
299
  if (data.response === 'removed') {
223
300
  throw forbidden({ errorKey: 'error.rsvpRemovedForbidden' });
224
301
  }
225
- if (getEffectiveRsvp(post, profile.id)?.response === 'removed') {
226
- throw forbidden({ errorKey: 'error.rsvpRemoved' });
227
- }
228
302
  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
- });
303
+ if (rsvpTargetsPastEvent(post.data, {
304
+ occurrenceIds,
305
+ recurrenceId: data.recurrenceId,
306
+ })) {
307
+ throw unprocessableRequest({ errorKey: 'error.eventEnded' });
308
+ }
309
+ if (!post.data.maxAttendees) {
310
+ if (getEffectiveRsvp(post, profile.id)?.response === 'removed') {
311
+ throw forbidden({ errorKey: 'error.rsvpRemoved' });
235
312
  }
236
- if (data.response === 'yes') {
237
- if (!occurrenceIds && post.data.recurrence) {
238
- if (seriesYesBlockedByCapacity(post, profile.id)) {
239
- throw unprocessableRequest({ errorKey: 'error.eventAtCapacity' });
240
- }
313
+ if (data.response === 'waitlist') {
314
+ throw unprocessableRequest({ errorKey: 'error.eventWaitlistNotOpen' });
315
+ }
316
+ await writeRsvpResponse(profile, post, data.response, occurrenceIds);
317
+ return;
318
+ }
319
+ const plans = [];
320
+ let emitted;
321
+ let failure;
322
+ try {
323
+ await withRsvpCapacityLock(post.id, async () => {
324
+ const loaded = await findPost(post.id);
325
+ if (!loaded || loaded.data?.type !== 'event') {
326
+ throw unprocessableRequest({ errorKey: 'error.unprocessableRequest' });
241
327
  }
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
- }
328
+ if (getEffectiveRsvp(loaded, profile.id)?.response === 'removed') {
329
+ throw forbidden({ errorKey: 'error.rsvpRemoved' });
251
330
  }
252
- }
331
+ const prepared = await syncCapacityOccurrences(loaded.id, capacitySyncTargets(loaded, occurrenceIds));
332
+ plans.push(...prepared.plans);
333
+ const fresh = prepared.post;
334
+ if (!fresh || fresh.data?.type !== 'event') {
335
+ throw unprocessableRequest({ errorKey: 'error.unprocessableRequest' });
336
+ }
337
+ const decision = capacityRsvpDecision(fresh, profile.id, data.response, occurrenceIds);
338
+ if (!decision.ok) {
339
+ throw unprocessableRequest({ errorKey: decision.errorKey });
340
+ }
341
+ if (decision.occurrenceIds && decision.occurrenceIds.length === 0) {
342
+ return;
343
+ }
344
+ const writeIds = decision.occurrenceIds;
345
+ const previousResponse = latestOwnResponse(fresh, profile.id, writeIds);
346
+ const writes = rsvpWrites(fresh, profile.id, data.response, writeIds);
347
+ const { db } = await allpeepDb();
348
+ for (const entry of writes) {
349
+ await entryConnector(db, profile, fresh, {
350
+ type: 'rsvp',
351
+ data: entry,
352
+ });
353
+ }
354
+ const cancel = rsvpCancelNotice(fresh, profile.id, data.response, writeIds);
355
+ const settled = await syncCapacityOccurrences(fresh.id, capacitySyncTargets(fresh, writeIds));
356
+ plans.push(...settled.plans);
357
+ if (data.response === 'yes') {
358
+ const claimed = writeIds?.length ? writeIds : [undefined];
359
+ plans.push({
360
+ requeues: [],
361
+ withdraws: [],
362
+ offers: [],
363
+ clearOffers: claimed.map((recurrenceId) => ({
364
+ profileId: profile.id,
365
+ recurrenceId,
366
+ })),
367
+ });
368
+ }
369
+ emitted = { previousResponse, occurrenceIds: writeIds, cancel };
370
+ });
253
371
  }
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) => ({
372
+ catch (err) {
373
+ failure = err;
374
+ }
375
+ await publishCapacityPlans(post.id, post.profile.id, plans);
376
+ if (failure)
377
+ throw failure;
378
+ if (!emitted)
379
+ return;
380
+ hub.emit('rsvpCreated', profile, post, {
381
+ type: 'rsvp',
382
+ data: {
268
383
  response: data.response,
269
- recurrenceId,
270
- }))
271
- : overlaySeriesRsvpEntries(data.response, instanceRsvpIdsForProfile(post, profile.id));
384
+ ...(emitted.occurrenceIds?.length === 1
385
+ ? { recurrenceId: emitted.occurrenceIds[0] }
386
+ : {}),
387
+ },
388
+ occurrenceIds: emitted.occurrenceIds,
389
+ previousResponse: emitted.previousResponse,
390
+ ...(emitted.cancel ? { cancel: emitted.cancel } : {}),
391
+ });
392
+ };
393
+ const writeRsvpResponse = async (profile, post, response, occurrenceIds) => {
394
+ const previousResponse = latestOwnResponse(post, profile.id, occurrenceIds);
395
+ const writes = rsvpWrites(post, profile.id, response, occurrenceIds);
396
+ const { db } = await allpeepDb();
272
397
  for (const entry of writes) {
273
398
  await entryConnector(db, profile, post, {
274
399
  type: 'rsvp',
275
400
  data: entry,
276
401
  });
277
402
  }
278
- const cancel = rsvpCancelNotice(post, profile.id, data.response, occurrenceIds);
403
+ const cancel = rsvpCancelNotice(post, profile.id, response, occurrenceIds);
279
404
  hub.emit('rsvpCreated', profile, post, {
280
405
  type: 'rsvp',
281
406
  data: {
282
- response: data.response,
407
+ response,
283
408
  ...(occurrenceIds?.length === 1
284
409
  ? { recurrenceId: occurrenceIds[0] }
285
410
  : {}),
@@ -296,30 +421,80 @@ export const rsvpManageByOrganizer = async (actingProfile, targetProfile, post,
296
421
  if (targetProfile.id === post.profile.id) {
297
422
  throw forbidden({ errorKey: 'forbidden' });
298
423
  }
299
- if (post.type !== 'event') {
424
+ if (post.type !== 'event' || post.data?.type !== 'event') {
300
425
  throw unprocessableRequest({ errorKey: 'error.unprocessableRequest' });
301
426
  }
302
427
  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
- });
428
+ // Capacity events now enforce waitlist capacity checks even for organizer-managed
429
+ // RSVPs: an organizer cannot force 'yes' beyond the capacity window when the
430
+ // waitlist is active. Non-capacity events skip the lock entirely.
431
+ const capacity = !!post.data.maxAttendees;
432
+ if (!capacity) {
433
+ const { db } = await allpeepDb();
434
+ const previousResponse = organizerPreviousResponse(post, targetProfile.id, recurrenceId);
435
+ await entryConnector(db, targetProfile, post, { type: 'rsvp', data });
436
+ hub.emit('rsvpCreated', targetProfile, post, {
437
+ type: 'rsvp',
438
+ data,
439
+ previousResponse,
440
+ });
441
+ return;
442
+ }
443
+ const plans = [];
444
+ let previousResponse;
445
+ let failure;
446
+ try {
447
+ await withRsvpCapacityLock(post.id, async () => {
448
+ const loaded = await findPost(post.id);
449
+ if (!loaded || loaded.data?.type !== 'event') {
450
+ throw unprocessableRequest({ errorKey: 'error.unprocessableRequest' });
451
+ }
452
+ const targets = capacitySyncTargets(loaded, recurrenceId ? [recurrenceId] : undefined);
453
+ const prepared = await syncCapacityOccurrences(loaded.id, targets);
454
+ plans.push(...prepared.plans);
455
+ const fresh = prepared.post ?? loaded;
456
+ if (response === 'yes') {
457
+ const decision = capacityRsvpDecision(fresh, targetProfile.id, 'yes', recurrenceId ? [recurrenceId] : undefined);
458
+ if (!decision.ok) {
459
+ throw unprocessableRequest({ errorKey: decision.errorKey });
460
+ }
461
+ }
462
+ previousResponse = organizerPreviousResponse(fresh, targetProfile.id, recurrenceId);
463
+ const { db } = await allpeepDb();
464
+ await entryConnector(db, targetProfile, fresh, { type: 'rsvp', data });
465
+ const settled = await syncCapacityOccurrences(fresh.id, targets);
466
+ plans.push(...settled.plans);
467
+ if (response === 'yes') {
468
+ plans.push({
469
+ requeues: [],
470
+ withdraws: [],
471
+ offers: [],
472
+ clearOffers: [{ profileId: targetProfile.id, recurrenceId }],
473
+ });
474
+ }
475
+ });
476
+ }
477
+ catch (err) {
478
+ failure = err;
479
+ }
480
+ await publishCapacityPlans(post.id, post.profile.id, plans);
481
+ if (failure)
482
+ throw failure;
315
483
  hub.emit('rsvpCreated', targetProfile, post, {
316
484
  type: 'rsvp',
317
485
  data,
318
486
  previousResponse,
319
487
  });
320
488
  };
489
+ const organizerPreviousResponse = (post, profileId, recurrenceId) => [...(post.rsvps ?? [])]
490
+ .filter((rsvp) => rsvp.profile.id === profileId)
491
+ .filter((rsvp) => recurrenceId
492
+ ? sameRecurrenceId(rsvp.recurrenceId, recurrenceId) ||
493
+ !rsvp.recurrenceId
494
+ : !rsvp.recurrenceId)
495
+ .sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1))[0]?.response;
321
496
  /**
322
- * Remove a profile from a direct-message conversation thread.
497
+ * Remove a profile from a direct-message conversation.
323
498
  *
324
499
  * - Creates a system "X left" post (empty content) with the *remaining*
325
500
  * participants as audience. The leaving user is excluded so future
@@ -330,29 +505,53 @@ export const rsvpManageByOrganizer = async (actingProfile, targetProfile, post,
330
505
  * - The conversation post-creation endpoint detects leavers (author not in
331
506
  * their own post's audience) to block further posting and exclude them
332
507
  * 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.
508
+ * - A 1:1 conversation can span several roots, so each root's thread gets
509
+ * its own "left" post — otherwise the leaver's inbox would keep the
510
+ * threads whose newest post is still in their audience.
511
+ * - When the newest post's audience holds no one but the leaver (everyone
512
+ * else already left), removes the leaver from every post's audience of
513
+ * that root's thread instead of posting again.
337
514
  */
338
515
  export const leaveConversation = async (rootPost, profile) => {
339
516
  const { db } = await allpeepDb();
340
- const lastPostId = await findLatestThreadPostId(rootPost.id);
517
+ const participants = [...participantIds(rootPost)];
518
+ const isOneToOne = isOneToOneDm(rootPost);
519
+ const rootLeaves = isOneToOne
520
+ ? await listOneToOneConversationRootLeaves(db, participants[0], participants[1])
521
+ : [];
522
+ const lastPostId = rootLeaves.length
523
+ ? rootLeaves.reduce((latest, { leafId }) => (leafId > latest ? leafId : latest), rootPost.id)
524
+ : await findLatestThreadPostId(rootPost.id);
341
525
  const [lastPost] = lastPostId === rootPost.id
342
526
  ? [rootPost]
343
527
  : await findPostsForAuth([lastPostId]);
344
528
  if (!lastPost)
345
529
  return;
346
530
  const remainingAudience = lastPost.audience?.filter((p) => p.id !== profile.id) ?? [];
347
- if (remainingAudience.length > 0) {
531
+ if (isOneToOne) {
532
+ // Terminate every root's thread with the system "left" post so the
533
+ // conversation vanishes from the leaver's inbox under all roots. The
534
+ // fallback below covers a pair whose root does not match the pair
535
+ // condition (e.g. legacy rows) and falls back to the requested thread.
536
+ const leaves = rootLeaves.length
537
+ ? rootLeaves
538
+ : [{ rootId: rootPost.id, leafId: lastPostId }];
539
+ for (const { leafId } of leaves) {
540
+ await createPost({ type: 'note', content: '' }, profile, { type: 'note', visibility: 'direct', creatorId: profile.id }, {
541
+ inReplyToId: leafId,
542
+ audience: remainingAudience,
543
+ });
544
+ }
545
+ }
546
+ else if (remainingAudience.length > 0) {
348
547
  await createPost({ type: 'note', content: '' }, profile, { type: 'note', visibility: 'direct', creatorId: profile.id }, {
349
548
  inReplyToId: lastPost.id,
350
549
  audience: remainingAudience,
351
550
  });
352
551
  }
353
552
  else {
354
- // 1:1 DM — remove the user from every post's audience so the
355
- // thread no longer appears in their inbox.
553
+ // No one remains in the newest post's audience — remove the leaver from
554
+ // every post's audience so the thread no longer appears in their inbox.
356
555
  await db.execute(sql `
357
556
  WITH RECURSIVE t AS (
358
557
  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 {};
@@ -0,0 +1,178 @@
1
+ import { and, eq, inArray, isNull, sql } from 'drizzle-orm';
2
+ import { calculateEffectiveRsvps, effectiveEventTimes, eventRsvpOpen, occurrenceHasEnded, profileName, toCsvRow, } from '@openpeepshq/common/lib';
3
+ import { database } from '../db/index.js';
4
+ import { accounts, controls, profiles } from '../db/pg/schema/index.js';
5
+ import { listJamAttendeeProfileIds } from '../jams/export.js';
6
+ const attending = (response) => response === 'yes' || response === 'tentative';
7
+ /**
8
+ * Join records are the attendance log. Until someone has joined, the column
9
+ * stays off so a jam that has not started is not full of invented no-shows.
10
+ */
11
+ export const rsvpAttendanceLabel = (input) => {
12
+ if (!attending(input.response))
13
+ return '';
14
+ if (input.attended)
15
+ return 'attended';
16
+ return input.eventEnded ? 'no-show' : 'registered';
17
+ };
18
+ /**
19
+ * Member email lives on the controlling account, and more than one account
20
+ * can control a profile. Guests store the address they typed on the profile.
21
+ */
22
+ export const rsvpContactEmail = (input) => {
23
+ const accountsJoined = [
24
+ ...new Set(input.accountEmails.filter((email) => email.length > 0)),
25
+ ]
26
+ .sort()
27
+ .join('; ');
28
+ if (input.profileType === 'guest') {
29
+ return input.guestEmail || accountsJoined;
30
+ }
31
+ return accountsJoined;
32
+ };
33
+ export const rsvpExportEventEnded = (event, occurrenceId, now) => {
34
+ if (occurrenceId) {
35
+ const times = effectiveEventTimes(event, occurrenceId);
36
+ return occurrenceHasEnded(times.start, times.end, now);
37
+ }
38
+ if (event.recurrence)
39
+ return !eventRsvpOpen(event, { now });
40
+ return occurrenceHasEnded(event.start, event.end, now);
41
+ };
42
+ const rsvpExportHeaders = (columns) => [
43
+ 'Name',
44
+ 'Email',
45
+ 'RSVP Status',
46
+ 'RSVP At',
47
+ 'Member ID',
48
+ ...(columns.includeOccurrence ? ['Occurrence'] : []),
49
+ ...(columns.includeAttendance ? ['Attendance'] : []),
50
+ ];
51
+ export const rsvpExportCsv = (rows, columns) => [
52
+ toCsvRow(rsvpExportHeaders(columns)),
53
+ ...rows.map((row) => toCsvRow([
54
+ row.name,
55
+ row.email,
56
+ row.status,
57
+ row.rsvpAt,
58
+ row.memberId,
59
+ ...(columns.includeOccurrence ? [row.occurrence] : []),
60
+ ...(columns.includeAttendance ? [row.attendance] : []),
61
+ ])),
62
+ ].join('\n');
63
+ const compareRows = (a, b) => {
64
+ const byOccurrence = a.occurrence.localeCompare(b.occurrence);
65
+ if (byOccurrence !== 0)
66
+ return byOccurrence;
67
+ const byName = a.name.localeCompare(b.name);
68
+ if (byName !== 0)
69
+ return byName;
70
+ return a.rsvpAt.localeCompare(b.rsvpAt);
71
+ };
72
+ export const assembleRsvpExportCsv = (input) => {
73
+ const event = input.post.data?.type === 'event' ? input.post.data : undefined;
74
+ if (!event) {
75
+ return rsvpExportCsv([], {
76
+ includeOccurrence: false,
77
+ includeAttendance: false,
78
+ });
79
+ }
80
+ const now = input.now ?? new Date();
81
+ const includeAttendance = (input.attendeeIds?.size ?? 0) > 0;
82
+ const eventEnded = rsvpExportEventEnded(event, input.occurrenceId, now);
83
+ const rows = calculateEffectiveRsvps(input.post, input.occurrenceId)
84
+ .map((rsvp) => rowFromRsvp(rsvp, input, includeAttendance, eventEnded))
85
+ .sort(compareRows);
86
+ return rsvpExportCsv(rows, {
87
+ includeOccurrence: !!event.recurrence,
88
+ includeAttendance,
89
+ });
90
+ };
91
+ const rowFromRsvp = (rsvp, input, includeAttendance, eventEnded) => ({
92
+ name: profileName(rsvp.profile) ?? '',
93
+ email: input.emailsByProfileId.get(rsvp.profile.id) ?? '',
94
+ status: rsvp.response,
95
+ rsvpAt: rsvp.createdAt,
96
+ memberId: rsvp.profile.id,
97
+ occurrence: input.occurrenceId ?? rsvp.recurrenceId ?? '',
98
+ attendance: includeAttendance && input.attendeeIds
99
+ ? rsvpAttendanceLabel({
100
+ response: rsvp.response,
101
+ attended: input.attendeeIds.has(rsvp.profile.id),
102
+ eventEnded,
103
+ })
104
+ : '',
105
+ });
106
+ const guestEmailFromBody = (body) => {
107
+ if (!body || typeof body !== 'object')
108
+ return '';
109
+ const email = body.guestData?.email;
110
+ return typeof email === 'string' ? email : '';
111
+ };
112
+ const listRsvpContactEmails = async (profileIds) => {
113
+ const emails = new Map();
114
+ if (!profileIds.length)
115
+ return emails;
116
+ const db = await database();
117
+ const [profileRows, accountRows] = await Promise.all([
118
+ db
119
+ .select({
120
+ id: profiles.id,
121
+ type: profiles.type,
122
+ body: profiles.body,
123
+ })
124
+ .from(profiles)
125
+ .where(inArray(profiles.id, profileIds)),
126
+ db
127
+ .select({
128
+ profileId: controls.toId,
129
+ email: accounts.email,
130
+ })
131
+ .from(controls)
132
+ .innerJoin(accounts, eq(controls.fromId, sql `${accounts.id}::text`))
133
+ .where(and(inArray(controls.toId, profileIds), isNull(accounts.deletedAt))),
134
+ ]);
135
+ const accountsByProfile = new Map();
136
+ for (const row of accountRows) {
137
+ const current = accountsByProfile.get(row.profileId) ?? [];
138
+ accountsByProfile.set(row.profileId, [...current, row.email]);
139
+ }
140
+ const seen = new Set();
141
+ for (const row of profileRows) {
142
+ seen.add(row.id);
143
+ emails.set(row.id, rsvpContactEmail({
144
+ profileType: row.type,
145
+ guestEmail: guestEmailFromBody(row.body),
146
+ accountEmails: accountsByProfile.get(row.id) ?? [],
147
+ }));
148
+ }
149
+ for (const profileId of profileIds) {
150
+ if (seen.has(profileId))
151
+ continue;
152
+ emails.set(profileId, rsvpContactEmail({
153
+ profileType: undefined,
154
+ guestEmail: '',
155
+ accountEmails: accountsByProfile.get(profileId) ?? [],
156
+ }));
157
+ }
158
+ return emails;
159
+ };
160
+ export const exportEventRsvpsCsv = async (post, options) => {
161
+ const event = post.data?.type === 'event' ? post.data : undefined;
162
+ const profileIds = [
163
+ ...new Set(calculateEffectiveRsvps(post, options?.occurrenceId).map((rsvp) => rsvp.profile.id)),
164
+ ];
165
+ const [emailsByProfileId, attendeeIds] = await Promise.all([
166
+ listRsvpContactEmails(profileIds),
167
+ event?.jam
168
+ ? listJamAttendeeProfileIds(post.id)
169
+ : Promise.resolve([]),
170
+ ]);
171
+ return assembleRsvpExportCsv({
172
+ post,
173
+ occurrenceId: options?.occurrenceId,
174
+ emailsByProfileId,
175
+ attendeeIds: attendeeIds.length ? new Set(attendeeIds) : undefined,
176
+ now: options?.now,
177
+ });
178
+ };
@@ -9,4 +9,10 @@ export declare const listUnseenGroupPostIds: (db: PgDb, profileId: string, group
9
9
  * Walks reply_to to roots without hydrating posts.
10
10
  */
11
11
  export declare const countUnseenDirectPosts: (db: PgDb, profileId: string) => Promise<Record<string, number>>;
12
+ /**
13
+ * Merge 1:1 direct counts into the pair's oldest root key so a conversation
14
+ * with several roots keeps one badge. The key must match the inbox preview's
15
+ * canonical id (min uuidv7 root); non-1:1 roots keep their own key.
16
+ */
17
+ export declare const mergeOneToOneDirectCounts: (db: PgDb, counts: Record<string, number>) => Promise<Record<string, number>>;
12
18
  export declare const queryUnseenPostCounts: (db: PgDb, profileId: string, groupIds: string[]) => Promise<UnseenPostCounts>;