@openpeepshq/core 0.29.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/analytics/compile.js +15 -7
  2. package/dist/analytics/jamMetrics.d.ts +47 -0
  3. package/dist/analytics/jamMetrics.js +93 -0
  4. package/dist/analytics/pdfReport.js +40 -1
  5. package/dist/analytics/read.js +68 -5
  6. package/dist/analytics/report.d.ts +75 -0
  7. package/dist/analytics/report.js +1 -0
  8. package/dist/db/pg/map/registry.js +11 -1
  9. package/dist/db/pg/schema/analytics.d.ts +68 -0
  10. package/dist/db/pg/schema/analytics.js +10 -0
  11. package/dist/db/pg/schema/documents.d.ts +17 -0
  12. package/dist/db/pg/schema/documents.js +10 -1
  13. package/dist/db/pg/schema/index.d.ts +85 -0
  14. package/dist/db/pg/sql/0021_jam_occurrence_recurrence_id.sql +10 -0
  15. package/dist/db/pg/sql/meta/0021_snapshot.json +4718 -0
  16. package/dist/db/pg/sql/meta/0022_snapshot.json +56 -1
  17. package/dist/db/pg/sql/meta/_journal.json +7 -0
  18. package/dist/events/index.d.ts +17 -0
  19. package/dist/events/index.js +50 -1
  20. package/dist/federation/actors.d.ts +17 -0
  21. package/dist/federation/actors.js +22 -1
  22. package/dist/federation/identity.d.ts +2 -0
  23. package/dist/federation/identity.js +2 -0
  24. package/dist/federation/index.d.ts +1 -1
  25. package/dist/federation/index.js +1 -1
  26. package/dist/federation/notes.d.ts +18 -0
  27. package/dist/federation/notes.js +11 -0
  28. package/dist/jams/export.d.ts +17 -4
  29. package/dist/jams/export.js +36 -6
  30. package/dist/jams/finders.js +5 -1
  31. package/dist/jams/index.js +3 -0
  32. package/dist/jams/livekit.d.ts +18 -3
  33. package/dist/jams/livekit.js +37 -5
  34. package/dist/jams/mapping.d.ts +0 -27
  35. package/dist/jams/mapping.js +0 -15
  36. package/dist/jams/token.js +14 -6
  37. package/dist/notifications/defaultNotifications/mention/index.js +9 -3
  38. package/dist/posts/helpers/index.d.ts +5 -0
  39. package/dist/posts/helpers/index.js +30 -4
  40. package/dist/posts/mutations.js +3 -0
  41. package/dist/stats/finders.js +34 -7
  42. package/package.json +4 -4
@@ -5,6 +5,7 @@ import { analyticsDailyTotals } from '../db/pg/schema/analytics.js';
5
5
  import { logger } from '../log/index.js';
6
6
  import { invalidateAnalyticsCache } from './cache.js';
7
7
  import { localMemberScope } from './memberScope.js';
8
+ import { computeJamStats } from './jamMetrics.js';
8
9
  const log = logger('app:analytics:compile');
9
10
  const dayString = (d) => formatISO(startOfDay(d), { representation: 'date' });
10
11
  const dayBounds = (day) => {
@@ -21,7 +22,11 @@ const countScalar = async (db, query) => {
21
22
  export const compileAnalyticsDay = async (day) => {
22
23
  const db = await database();
23
24
  const { start, end } = dayBounds(day);
24
- const now = new Date().toISOString();
25
+ // Capture wall-clock once at entry: it stamps the rollup row AND caps the
26
+ // open-session end inside computeJamStats, so one compile pass is
27
+ // internally consistent.
28
+ const compileTimestampMs = Date.now();
29
+ const now = new Date(compileTimestampMs).toISOString();
25
30
  const newMembers = await countScalar(db, sql `select count(*)::int as c from profiles
26
31
  where deleted_at is null
27
32
  and type = 'local'
@@ -46,12 +51,7 @@ export const compileAnalyticsDay = async (day) => {
46
51
  where created_at >= ${start} and created_at < ${end}`);
47
52
  const viewEvents = await countScalar(db, sql `select count(*)::int as c from post_seen
48
53
  where created_at >= ${start} and created_at < ${end}`);
49
- const jamSessions = await countScalar(db, sql `select count(*)::int as c from jam_events
50
- where deleted_at is null and body->>'type' = 'start'
51
- and created_at >= ${start} and created_at < ${end}`);
52
- const jamParticipants = await countScalar(db, sql `select count(*)::int as c from jam_events
53
- where deleted_at is null and body->>'type' = 'join'
54
- and created_at >= ${start} and created_at < ${end}`);
54
+ const { jamSessions, jamParticipants, jamUniqueAttendees, jamMinutes, jamPeakConcurrent, jamRecordingsCompleted, } = await computeJamStats(db, start, end, compileTimestampMs);
55
55
  // Scope to the same population as newMembers/totalMembersAt (local,
56
56
  // non-deleted profiles) so the daily active_members rollup — and hence the
57
57
  // overview series/chart — cannot exceed the member series. Composes from
@@ -96,6 +96,10 @@ export const compileAnalyticsDay = async (day) => {
96
96
  viewEvents,
97
97
  jamSessions,
98
98
  jamParticipants,
99
+ jamMinutes,
100
+ jamUniqueAttendees,
101
+ jamPeakConcurrent,
102
+ jamRecordingsCompleted,
99
103
  compiledAt: now,
100
104
  })
101
105
  .onConflictDoUpdate({
@@ -114,6 +118,10 @@ export const compileAnalyticsDay = async (day) => {
114
118
  viewEvents,
115
119
  jamSessions,
116
120
  jamParticipants,
121
+ jamMinutes,
122
+ jamUniqueAttendees,
123
+ jamPeakConcurrent,
124
+ jamRecordingsCompleted,
117
125
  compiledAt: now,
118
126
  },
119
127
  });
@@ -0,0 +1,47 @@
1
+ import type { PgDb } from '../db';
2
+ /**
3
+ * Aggregate jam activity over a range of `analytics_daily_totals`-style
4
+ * bounds. `jamSessions` counts distinct (post, occurrence) starts in the range:
5
+ * a recurring series that met N times is N sessions (not 1), while a one-off
6
+ * event is a single session — the occurrence collapses to `''` for one-offs, so
7
+ * repeat starts of the same one-off coalesce. `jamParticipants` counts distinct
8
+ * (profile, jam) pairs — a person in 3 jams is 3 here; `jamUniqueAttendees`
9
+ * counts distinct profiles across the whole range — the same person in 3 jams
10
+ * is 1. Both are scoped to live local profiles (guests are public profiles and
11
+ * excluded, matching the rest of the analytics scope). `jamMinutes` and
12
+ * `jamPeakConcurrent` are derived from start…close session intervals; an open
13
+ * session (no close yet) contributes no minutes but does count toward
14
+ * concurrency until it closes. `jamRecordingsCompleted` counts recordings whose
15
+ * status transitioned to completed inside the range.
16
+ *
17
+ * `jamSessions`/`jamParticipants`/`jamUniqueAttendees` are live distinct
18
+ * counts over the raw `jam_events` rows, while the admin chart and CSV
19
+ * re-bucket the pre-aggregated `analytics_daily_totals`. The two are different
20
+ * aggregations, not two readings of one number, so they can legitimately
21
+ * disagree on the edges: the rollup attributes minutes and concurrency to the
22
+ * session's *start* day, a close that lands in a different day (or arrives after
23
+ * the start's day compiled) only lands on the start day when that day is
24
+ * recompiled, and a distinct count over a bucket can differ from summing the
25
+ * per-day distinct values.
26
+ *
27
+ * Session minutes are attributed to the session's *start* day. A close that
28
+ * lands in a different day than its start, or that arrives after the start's
29
+ * day has already been compiled, is only picked up when that day is recompiled
30
+ * (`compileAnalyticsDay` re-runs for a day on backfill), so same-day closes can
31
+ * briefly lag and midnight-spanning sessions always land on the start day.
32
+ *
33
+ * `now` (epoch ms, defaults to the current time) is the cap used for the
34
+ * open-session end of the concurrency sweep. Callers that compute a batch of
35
+ * results and cache them under a stable key should pass the same value they
36
+ * captured once at entry so a single pass is internally consistent and a
37
+ * rebuilt cache entry does not shift as real time elapses mid-pass.
38
+ */
39
+ export type JamStats = {
40
+ jamSessions: number;
41
+ jamParticipants: number;
42
+ jamUniqueAttendees: number;
43
+ jamMinutes: number;
44
+ jamPeakConcurrent: number;
45
+ jamRecordingsCompleted: number;
46
+ };
47
+ export declare const computeJamStats: (db: PgDb, start: string, end: string, now?: number) => Promise<JamStats>;
@@ -0,0 +1,93 @@
1
+ import { sql } from 'drizzle-orm';
2
+ const countScalar = async (db, query) => {
3
+ const result = await db.execute(query);
4
+ const rows = result.rows;
5
+ return Number(rows[0]?.c ?? 0);
6
+ };
7
+ export const computeJamStats = async (db, start, end, now = Date.now()) => {
8
+ const [jamSessions, jamParticipants, jamUniqueAttendees, jamRecordingsCompleted, startsRes, closesRes,] = await Promise.all([
9
+ // Distinct (jam, occurrence) — a recurring series is N sessions, not 1.
10
+ countScalar(db, sql `select count(distinct (post_id, coalesce(recurrence_id, '')))::int as c
11
+ from jam_events
12
+ where deleted_at is null and body->>'type' = 'start'
13
+ and created_at >= ${start} and created_at < ${end}`),
14
+ countScalar(db, sql `select count(distinct (je.body->>'profileId', je.post_id))::int as c
15
+ from jam_events je
16
+ join profiles p on p.id::text = je.body->>'profileId'
17
+ where je.deleted_at is null and je.body->>'type' = 'join'
18
+ and je.created_at >= ${start} and je.created_at < ${end}
19
+ and p.type = 'local' and p.deleted_at is null`),
20
+ countScalar(db, sql `select count(distinct je.body->>'profileId')::int as c
21
+ from jam_events je
22
+ join profiles p on p.id::text = je.body->>'profileId'
23
+ where je.deleted_at is null and je.body->>'type' = 'join'
24
+ and je.created_at >= ${start} and je.created_at < ${end}
25
+ and p.type = 'local' and p.deleted_at is null`),
26
+ countScalar(db, sql `select count(*)::int as c from jam_recordings
27
+ where body->>'status' = 'completed'
28
+ and updated_at >= ${start} and updated_at < ${end}`),
29
+ db.execute(sql `select post_id, coalesce(recurrence_id, '') as rid, created_at
30
+ from jam_events
31
+ where deleted_at is null and body->>'type' = 'start'
32
+ and created_at >= ${start} and created_at < ${end}
33
+ order by created_at`),
34
+ // No upper bound: a close after the window still settles the minutes of a
35
+ // session that started inside it.
36
+ db.execute(sql `select post_id, coalesce(recurrence_id, '') as rid, created_at
37
+ from jam_events
38
+ where deleted_at is null and body->>'type' = 'close'
39
+ and created_at >= ${start}
40
+ order by created_at`),
41
+ ]);
42
+ const starts = startsRes.rows.map((r) => ({
43
+ key: `${r.post_id}|${r.rid}`,
44
+ start: new Date(r.created_at).getTime(),
45
+ }));
46
+ const closeTimes = new Map();
47
+ for (const r of closesRes.rows) {
48
+ const key = `${r.post_id}|${r.rid}`;
49
+ const t = new Date(r.created_at).getTime();
50
+ const arr = closeTimes.get(key) ?? [];
51
+ arr.push(t);
52
+ closeTimes.set(key, arr);
53
+ }
54
+ let jamMinutes = 0;
55
+ const intervals = [];
56
+ for (const s of starts) {
57
+ const closes = closeTimes.get(s.key);
58
+ const close = closes?.find((c) => c >= s.start);
59
+ if (close !== undefined) {
60
+ const mins = Math.max(0, Math.round((close - s.start) / 60_000));
61
+ jamMinutes += mins;
62
+ intervals.push({ s: s.start, e: close });
63
+ }
64
+ else {
65
+ // Still in progress — no duration yet, but it overlaps other sessions.
66
+ // Capped at the caller-supplied `now` so a single pass is consistent.
67
+ intervals.push({ s: s.start, e: now });
68
+ }
69
+ }
70
+ let jamPeakConcurrent = 0;
71
+ if (intervals.length > 0) {
72
+ const points = [];
73
+ for (const iv of intervals) {
74
+ points.push({ t: iv.s, d: 1 });
75
+ points.push({ t: iv.e, d: -1 });
76
+ }
77
+ points.sort((a, b) => a.t - b.t || a.d - b.d);
78
+ let cur = 0;
79
+ for (const p of points) {
80
+ cur += p.d;
81
+ if (cur > jamPeakConcurrent)
82
+ jamPeakConcurrent = cur;
83
+ }
84
+ }
85
+ return {
86
+ jamSessions,
87
+ jamParticipants,
88
+ jamUniqueAttendees,
89
+ jamMinutes,
90
+ jamPeakConcurrent,
91
+ jamRecordingsCompleted,
92
+ };
93
+ };
@@ -10,7 +10,11 @@ const COLORS = {
10
10
  soft: '#f3f4f6',
11
11
  card: '#f9fafb',
12
12
  white: '#ffffff',
13
- accent: '#2563eb',
13
+ // Semantic `primary` theme token (--color-primary in
14
+ // libraries/react-ui/src/styles/globals.css), not a direct Tailwind color —
15
+ // the PDF generator has no CSS runtime, so the token is resolved to its hex
16
+ // here. Keep in sync if the theme's primary changes.
17
+ accent: '#0c90a7',
14
18
  positive: '#059669',
15
19
  negative: '#dc2626',
16
20
  };
@@ -736,6 +740,40 @@ const drawEngagementPage = (layout, engagement) => {
736
740
  },
737
741
  ]);
738
742
  };
743
+ const drawJamsPage = (layout, overview) => {
744
+ startSection(layout, 'Jams');
745
+ drawMetricCards(layout, [
746
+ {
747
+ label: 'Sessions',
748
+ value: formatNum(overview.metrics.jamSessions.value),
749
+ deltaPct: overview.metrics.jamSessions.deltaPct,
750
+ subtitle: 'This period',
751
+ },
752
+ {
753
+ label: 'Participants',
754
+ value: formatNum(overview.metrics.jamParticipants.value),
755
+ deltaPct: overview.metrics.jamParticipants.deltaPct,
756
+ subtitle: 'This period',
757
+ },
758
+ {
759
+ label: 'Minutes',
760
+ value: formatNum(overview.metrics.jamMinutes.value),
761
+ deltaPct: overview.metrics.jamMinutes.deltaPct,
762
+ subtitle: 'This period',
763
+ },
764
+ {
765
+ label: 'Peak concurrent',
766
+ value: formatNum(overview.metrics.jamPeakConcurrent.value),
767
+ deltaPct: overview.metrics.jamPeakConcurrent.deltaPct,
768
+ subtitle: 'This period',
769
+ },
770
+ ]);
771
+ drawSectionTitle(layout, 'Sessions over time');
772
+ drawBarChart(layout, overview.jamsOverTime.map((p) => ({
773
+ label: p.label,
774
+ value: p.value,
775
+ })));
776
+ };
739
777
  const drawGroupsPage = (layout, overview) => {
740
778
  startSection(layout, 'Groups');
741
779
  drawSectionTitle(layout, 'Top groups by activity');
@@ -799,6 +837,7 @@ export const buildAnalyticsPdf = async (data) => {
799
837
  drawOverviewPage(layout, data.overview);
800
838
  drawMembersPage(layout, data.overview, data.growth);
801
839
  drawContentPage(layout, data.overview);
840
+ drawJamsPage(layout, data.overview);
802
841
  drawEngagementPage(layout, data.engagement);
803
842
  drawGroupsPage(layout, data.overview);
804
843
  drawFooter(layout);
@@ -8,6 +8,7 @@ import { aggregateSeriesIntoBuckets, eachUtcDay, resolveAnalyticsRange, selectCh
8
8
  import { metricCard, sumSeries, averageSeries } from './metrics.js';
9
9
  import { isPublicAnalyticsGroup } from './privacy.js';
10
10
  import { localMemberScope } from './memberScope.js';
11
+ import { computeJamStats } from './jamMetrics.js';
11
12
  const POST_TYPE_KEYS = [
12
13
  'jam',
13
14
  'article',
@@ -517,8 +518,12 @@ export const getAnalyticsOverview = async (query = {}) => {
517
518
  const range = await resolveQueryRange(query);
518
519
  // Unique people in the window — summing daily rollups would count a
519
520
  // member once per day they were active.
520
- return withCache('overview-v7', range.from, range.to, async () => {
521
- const [activeMembersSeries, postsSeries, likesSeries, commentsSeries, postsByTypeDaily, topGroupRows, groupGrowth, topPostRows, topMemberRows, compiledAt, totalMembers, totalGroups, allTimePosts, activeMembers, prevActive, prevPosts, prevTotalMembers, prevTotalGroups, prevAllTimePosts, verifiedMembers, unverifiedMembers, prevVerifiedMembers, prevUnverifiedMembers,] = await Promise.all([
521
+ return withCache('overview-v8', range.from, range.to, async () => {
522
+ // Captured once so both computeJamStats calls share the same open-session
523
+ // cap — the pass is internally consistent and does not shift as real time
524
+ // elapses between the two calls before the result is cached.
525
+ const now = Date.now();
526
+ const [activeMembersSeries, postsSeries, likesSeries, commentsSeries, postsByTypeDaily, topGroupRows, groupGrowth, topPostRows, topMemberRows, compiledAt, totalMembers, totalGroups, allTimePosts, activeMembers, prevActive, prevPosts, prevTotalMembers, prevTotalGroups, prevAllTimePosts, verifiedMembers, unverifiedMembers, prevVerifiedMembers, prevUnverifiedMembers, jamSessionsSeries, jamParticipantsSeries, jamMinutesSeries, jamRecordingsSeries, curJam, prevJam,] = await Promise.all([
522
527
  loadTotalsSeries(range.from, range.to, 'activeMembers'),
523
528
  loadTotalsSeries(range.from, range.to, 'posts'),
524
529
  loadTotalsSeries(range.from, range.to, 'likes'),
@@ -542,6 +547,12 @@ export const getAnalyticsOverview = async (query = {}) => {
542
547
  unverifiedMembersAt(range.to),
543
548
  verifiedMembersAt(range.previousTo),
544
549
  unverifiedMembersAt(range.previousTo),
550
+ loadTotalsSeries(range.from, range.to, 'jamSessions'),
551
+ loadTotalsSeries(range.from, range.to, 'jamParticipants'),
552
+ loadTotalsSeries(range.from, range.to, 'jamMinutes'),
553
+ loadTotalsSeries(range.from, range.to, 'jamRecordingsCompleted'),
554
+ computeJamStats(await database(), `${range.from}T00:00:00.000Z`, exclusiveEnd(range.to), now),
555
+ computeJamStats(await database(), `${range.previousFrom}T00:00:00.000Z`, exclusiveEnd(range.previousTo), now),
545
556
  ]);
546
557
  const totalPosts = sumSeries(postsSeries);
547
558
  const { buckets } = selectChartBuckets(range.from, range.to);
@@ -582,6 +593,7 @@ export const getAnalyticsOverview = async (query = {}) => {
582
593
  count: typeTotals[type],
583
594
  }));
584
595
  const activeUsersSeries = aggregateSeriesIntoBuckets(activeMembersSeries, buckets);
596
+ const jamsOverTime = aggregateSeriesIntoBuckets(jamSessionsSeries, buckets);
585
597
  const engagementRateSeries = postsSeries.map((p, i) => {
586
598
  const engagements = (likesSeries[i]?.value ?? 0) + (commentsSeries[i]?.value ?? 0);
587
599
  const postCount = p.value;
@@ -602,10 +614,39 @@ export const getAnalyticsOverview = async (query = {}) => {
602
614
  unverifiedMembers: metricCard('unverifiedMembers', unverifiedMembers, prevUnverifiedMembers),
603
615
  activeMembers: metricCard('activeMembers', activeMembers, prevActive, activeMembersSeries),
604
616
  totalGroups: metricCard('totalGroups', totalGroups, prevTotalGroups),
617
+ jamSessions: metricCard('jamSessions', curJam.jamSessions, prevJam.jamSessions, jamSessionsSeries),
618
+ jamParticipants: metricCard('jamParticipants', curJam.jamParticipants, prevJam.jamParticipants, jamParticipantsSeries),
619
+ jamMinutes: metricCard('jamMinutes', curJam.jamMinutes, prevJam.jamMinutes, jamMinutesSeries),
620
+ jamUniqueAttendees: metricCard('jamUniqueAttendees', curJam.jamUniqueAttendees, prevJam.jamUniqueAttendees),
621
+ jamPeakConcurrent: metricCard('jamPeakConcurrent', curJam.jamPeakConcurrent, prevJam.jamPeakConcurrent),
622
+ /**
623
+ * The jam cards intentionally mix two sources (kept, not unified, on
624
+ * purpose). jamSessions/jamParticipants/jamMinutes/jamUniqueAttendees/
625
+ * jamPeakConcurrent come from live computeJamStats; only jamRecordings
626
+ * sums the daily rollups. The split is deliberate, not an oversight:
627
+ * the daily rollup rows do not carry unique-attendees or
628
+ * peak-concurrent, and neither can be reconstructed by summing day
629
+ * rows (a person in 3 jams is 3 in rollup sums but 1 here; peak
630
+ * concurrent is a cross-day max), so those cards must stay live.
631
+ * jamRecordings is the only card whose value is a plain sum of the
632
+ * daily rollup.
633
+ *
634
+ * The same split also explains value-vs-series and value-vs-CSV
635
+ * reconciliation. For the live cards (jamSessions/jamParticipants/
636
+ * jamMinutes) the `value` is a live distinct count over the raw
637
+ * jam_events rows, while `series` (and the re-bucketed CSV columns
638
+ * jam_sessions/jam_participants/jam_minutes) is a sum of the
639
+ * pre-aggregated daily rollup — the two can legitimately disagree on
640
+ * the edges (a session whose duration or attendees span days, a close
641
+ * that lands on a different day than its start). Only jamRecordings
642
+ * has value === sum(series), because it is defined as the rollup sum.
643
+ */
644
+ jamRecordings: metricCard('jamRecordings', sumSeries(jamRecordingsSeries), prevJam.jamRecordingsCompleted, jamRecordingsSeries),
605
645
  },
606
646
  postsOverTime,
607
647
  postTypes,
608
648
  activeUsersSeries,
649
+ jamsOverTime,
609
650
  topMembers: topMemberRows,
610
651
  topPosts: topPostRows,
611
652
  activitySeries: activeMembersSeries,
@@ -618,11 +659,11 @@ export const getAnalyticsOverview = async (query = {}) => {
618
659
  };
619
660
  export const getAnalyticsGrowth = async (query = {}) => {
620
661
  const range = await resolveQueryRange(query);
621
- return withCache('growth-v7', range.from, range.to, async () => {
662
+ return withCache('growth-v8', range.from, range.to, async () => {
622
663
  const db = await database();
623
664
  const mauFrom = rollingMauFrom(range.to);
624
665
  const prevMauFrom = rollingMauFrom(range.previousTo);
625
- const [newMembersSeries, activeMembersSeries, prevNew, prevActiveSeries, mau, prevMau, compiledAt, recentRows,] = await Promise.all([
666
+ const [newMembersSeries, activeMembersSeries, prevNew, prevActiveSeries, mau, prevMau, compiledAt, recentRows, jamMinutesSeries, prevJamMinutes,] = await Promise.all([
626
667
  loadTotalsSeries(range.from, range.to, 'newMembers'),
627
668
  loadTotalsSeries(range.from, range.to, 'activeMembers'),
628
669
  sumColumn(range.previousFrom, range.previousTo, 'newMembers'),
@@ -642,6 +683,8 @@ export const getAnalyticsGrowth = async (query = {}) => {
642
683
  order by p.created_at desc
643
684
  limit 25
644
685
  `),
686
+ loadTotalsSeries(range.from, range.to, 'jamMinutes'),
687
+ sumColumn(range.previousFrom, range.previousTo, 'jamMinutes'),
645
688
  ]);
646
689
  const newSignups = sumSeries(newMembersSeries);
647
690
  const dau = averageSeries(activeMembersSeries);
@@ -667,6 +710,11 @@ export const getAnalyticsGrowth = async (query = {}) => {
667
710
  dau: metricCard('dau', dau, prevDau, activeMembersSeries),
668
711
  mau: metricCard('mau', mau, prevMau),
669
712
  dauMau: metricCard('dauMau', dauMau, prevDauMau),
713
+ // Rollup-sourced previous period, matching the rollup sumSeries(value)
714
+ // above — the overview jamMinutes card's previousValue is a live
715
+ // computeJamStats count, so the two previousPeriod values are
716
+ // intentionally different sources (see the overview JSDoc).
717
+ jamMinutes: metricCard('jamMinutes', sumSeries(jamMinutesSeries), prevJamMinutes, jamMinutesSeries),
670
718
  },
671
719
  signupsByDay,
672
720
  recentSignups,
@@ -765,8 +813,20 @@ export const getAnalyticsRetention = async (query = {}) => {
765
813
  };
766
814
  export const exportAnalyticsCsv = async (query = {}) => {
767
815
  const overview = await getAnalyticsOverview(query);
816
+ // The CSV is one row per chart bucket; the jam metric cards carry daily
817
+ // series, so re-bucket them to align with the active-users rows. This makes
818
+ // the CSV columns re-bucketed *rollup* sums while each card's value/
819
+ // previousValue is a live distinct count — different aggregations, so a CSV
820
+ // row or chart bucket can legitimately not reconcile with its card's value
821
+ // (e.g. cross-day attendees/peak). All three re-bucketed jam columns
822
+ // (jam_sessions, jam_participants, jam_minutes) carry this difference. See
823
+ // the jamRecordings JSDoc and computeJamStats for the full rationale.
824
+ const { buckets } = selectChartBuckets(overview.range.from, overview.range.to);
825
+ const jamSessionsByBucket = aggregateSeriesIntoBuckets(overview.metrics.jamSessions.series ?? [], buckets);
826
+ const jamParticipantsByBucket = aggregateSeriesIntoBuckets(overview.metrics.jamParticipants.series ?? [], buckets);
827
+ const jamMinutesByBucket = aggregateSeriesIntoBuckets(overview.metrics.jamMinutes.series ?? [], buckets);
768
828
  const lines = [
769
- 'bucket,label,active_members,posts,jams,articles,notes,polls,events,resources',
829
+ 'bucket,label,active_members,posts,jams,articles,notes,polls,events,resources,jam_sessions,jam_participants,jam_minutes',
770
830
  ...overview.activeUsersSeries.map((p, i) => {
771
831
  const posts = overview.postsOverTime[i];
772
832
  const postTotal = posts
@@ -788,6 +848,9 @@ export const exportAnalyticsCsv = async (query = {}) => {
788
848
  posts?.poll ?? 0,
789
849
  posts?.event ?? 0,
790
850
  posts?.resource ?? 0,
851
+ jamSessionsByBucket[i]?.value ?? 0,
852
+ jamParticipantsByBucket[i]?.value ?? 0,
853
+ jamMinutesByBucket[i]?.value ?? 0,
791
854
  ].join(',');
792
855
  }),
793
856
  ];
@@ -89,6 +89,66 @@ export declare const buildAnalyticsBoardReport: (query?: AnalyticsDateQuery) =>
89
89
  value: number;
90
90
  }[] | undefined;
91
91
  };
92
+ jamSessions: {
93
+ key: string;
94
+ value: number;
95
+ previousValue: number;
96
+ deltaPct: number | null;
97
+ series?: {
98
+ day: string;
99
+ value: number;
100
+ }[] | undefined;
101
+ };
102
+ jamParticipants: {
103
+ key: string;
104
+ value: number;
105
+ previousValue: number;
106
+ deltaPct: number | null;
107
+ series?: {
108
+ day: string;
109
+ value: number;
110
+ }[] | undefined;
111
+ };
112
+ jamMinutes: {
113
+ key: string;
114
+ value: number;
115
+ previousValue: number;
116
+ deltaPct: number | null;
117
+ series?: {
118
+ day: string;
119
+ value: number;
120
+ }[] | undefined;
121
+ };
122
+ jamUniqueAttendees: {
123
+ key: string;
124
+ value: number;
125
+ previousValue: number;
126
+ deltaPct: number | null;
127
+ series?: {
128
+ day: string;
129
+ value: number;
130
+ }[] | undefined;
131
+ };
132
+ jamPeakConcurrent: {
133
+ key: string;
134
+ value: number;
135
+ previousValue: number;
136
+ deltaPct: number | null;
137
+ series?: {
138
+ day: string;
139
+ value: number;
140
+ }[] | undefined;
141
+ };
142
+ jamRecordings: {
143
+ key: string;
144
+ value: number;
145
+ previousValue: number;
146
+ deltaPct: number | null;
147
+ series?: {
148
+ day: string;
149
+ value: number;
150
+ }[] | undefined;
151
+ };
92
152
  };
93
153
  postsOverTime: {
94
154
  day: string;
@@ -109,6 +169,11 @@ export declare const buildAnalyticsBoardReport: (query?: AnalyticsDateQuery) =>
109
169
  label: string;
110
170
  value: number;
111
171
  }[];
172
+ jamsOverTime: {
173
+ day: string;
174
+ label: string;
175
+ value: number;
176
+ }[];
112
177
  topMembers: {
113
178
  profileId: string;
114
179
  handle: string;
@@ -214,6 +279,16 @@ export declare const buildAnalyticsBoardReport: (query?: AnalyticsDateQuery) =>
214
279
  value: number;
215
280
  }[] | undefined;
216
281
  };
282
+ jamMinutes: {
283
+ key: string;
284
+ value: number;
285
+ previousValue: number;
286
+ deltaPct: number | null;
287
+ series?: {
288
+ day: string;
289
+ value: number;
290
+ }[] | undefined;
291
+ };
217
292
  };
218
293
  signupsByDay: {
219
294
  day: string;
@@ -52,6 +52,7 @@ export const buildAnalyticsBoardReport = async (query = {}) => {
52
52
  narrativeSentence('Posts published', overview.metrics.totalPosts.value, overview.metrics.totalPosts.deltaPct),
53
53
  narrativeSentence('Groups', overview.metrics.totalGroups.value, overview.metrics.totalGroups.deltaPct),
54
54
  narrativeSentence('Content impressions', engagement.metrics.impressions.value, engagement.metrics.impressions.deltaPct),
55
+ narrativeSentence('Jam sessions', overview.metrics.jamSessions.value, overview.metrics.jamSessions.deltaPct),
55
56
  ].join('\n');
56
57
  const pdf = await buildAnalyticsPdf({
57
58
  communityName: community.info.name,
@@ -96,12 +96,15 @@ const hashtagsSplit = (data) => {
96
96
  };
97
97
  /** Older jam events stored jamId; the column is post_id. */
98
98
  const jamEventsSplit = (data) => {
99
- const { postId, jamId, ...rest } = data;
99
+ const { postId, jamId, recurrenceId, ...rest } = data;
100
100
  const scalars = {};
101
101
  const resolvedPostId = postId ?? jamId;
102
102
  if (resolvedPostId !== undefined) {
103
103
  scalars.postId = resolvedPostId;
104
104
  }
105
+ if (recurrenceId !== undefined) {
106
+ scalars.recurrenceId = recurrenceId;
107
+ }
105
108
  return { scalars, body: { ...rest } };
106
109
  };
107
110
  /** Legacy settings docs use profile id as document id, not profileId. */
@@ -472,6 +475,13 @@ export const rowToDocument = (collection, row, keepMetadata = false) => {
472
475
  return rowToModel(row.id, {
473
476
  jamId: row.postId,
474
477
  ...(row.body ?? {}),
478
+ // recurrence_id is the denormalized source of truth; a stale body
479
+ // value from a pre-migration write must not shadow it. The column is
480
+ // null for one-off jams, so only a real occurrence id overrides the
481
+ // body (an explicit null would fail the optional-string schema).
482
+ ...(typeof row.recurrenceId === 'string'
483
+ ? { recurrenceId: row.recurrenceId }
484
+ : {}),
475
485
  }, timestamps);
476
486
  case 'processingStats':
477
487
  return rowToModel(row.id, {
@@ -241,6 +241,74 @@ export declare const analyticsDailyTotals: import("drizzle-orm/pg-core").PgTable
241
241
  identity: undefined;
242
242
  generated: undefined;
243
243
  }, {}, {}>;
244
+ jamMinutes: import("drizzle-orm/pg-core").PgColumn<{
245
+ name: "jam_minutes";
246
+ tableName: "analytics_daily_totals";
247
+ dataType: "number";
248
+ columnType: "PgInteger";
249
+ data: number;
250
+ driverParam: string | number;
251
+ notNull: true;
252
+ hasDefault: true;
253
+ isPrimaryKey: false;
254
+ isAutoincrement: false;
255
+ hasRuntimeDefault: false;
256
+ enumValues: undefined;
257
+ baseColumn: never;
258
+ identity: undefined;
259
+ generated: undefined;
260
+ }, {}, {}>;
261
+ jamUniqueAttendees: import("drizzle-orm/pg-core").PgColumn<{
262
+ name: "jam_unique_attendees";
263
+ tableName: "analytics_daily_totals";
264
+ dataType: "number";
265
+ columnType: "PgInteger";
266
+ data: number;
267
+ driverParam: string | number;
268
+ notNull: true;
269
+ hasDefault: true;
270
+ isPrimaryKey: false;
271
+ isAutoincrement: false;
272
+ hasRuntimeDefault: false;
273
+ enumValues: undefined;
274
+ baseColumn: never;
275
+ identity: undefined;
276
+ generated: undefined;
277
+ }, {}, {}>;
278
+ jamPeakConcurrent: import("drizzle-orm/pg-core").PgColumn<{
279
+ name: "jam_peak_concurrent";
280
+ tableName: "analytics_daily_totals";
281
+ dataType: "number";
282
+ columnType: "PgInteger";
283
+ data: number;
284
+ driverParam: string | number;
285
+ notNull: true;
286
+ hasDefault: true;
287
+ isPrimaryKey: false;
288
+ isAutoincrement: false;
289
+ hasRuntimeDefault: false;
290
+ enumValues: undefined;
291
+ baseColumn: never;
292
+ identity: undefined;
293
+ generated: undefined;
294
+ }, {}, {}>;
295
+ jamRecordingsCompleted: import("drizzle-orm/pg-core").PgColumn<{
296
+ name: "jam_recordings_completed";
297
+ tableName: "analytics_daily_totals";
298
+ dataType: "number";
299
+ columnType: "PgInteger";
300
+ data: number;
301
+ driverParam: string | number;
302
+ notNull: true;
303
+ hasDefault: true;
304
+ isPrimaryKey: false;
305
+ isAutoincrement: false;
306
+ hasRuntimeDefault: false;
307
+ enumValues: undefined;
308
+ baseColumn: never;
309
+ identity: undefined;
310
+ generated: undefined;
311
+ }, {}, {}>;
244
312
  compiledAt: import("drizzle-orm/pg-core").PgColumn<{
245
313
  name: "compiled_at";
246
314
  tableName: "analytics_daily_totals";
@@ -17,6 +17,16 @@ export const analyticsDailyTotals = pgTable('analytics_daily_totals', {
17
17
  viewEvents: integer('view_events').notNull().default(0),
18
18
  jamSessions: integer('jam_sessions').notNull().default(0),
19
19
  jamParticipants: integer('jam_participants').notNull().default(0),
20
+ /** Sum of per-occurrence (close − start) minutes, attributed to the start day. */
21
+ jamMinutes: integer('jam_minutes').notNull().default(0),
22
+ /** Distinct profiles with a persisted join event on the day. */
23
+ jamUniqueAttendees: integer('jam_unique_attendees').notNull().default(0),
24
+ /** Max overlap of the day's per-occurrence start…close intervals. */
25
+ jamPeakConcurrent: integer('jam_peak_concurrent').notNull().default(0),
26
+ /** jam_recordings edges reaching status 'completed' on the day. */
27
+ jamRecordingsCompleted: integer('jam_recordings_completed')
28
+ .notNull()
29
+ .default(0),
20
30
  compiledAt: timestamp('compiled_at', { withTimezone: true, mode: 'string' })
21
31
  .notNull()
22
32
  .default(sql `now()`),
@@ -1799,6 +1799,23 @@ export declare const jamEvents: import("drizzle-orm/pg-core").PgTableWithColumns
1799
1799
  identity: undefined;
1800
1800
  generated: undefined;
1801
1801
  }, {}, {}>;
1802
+ recurrenceId: import("drizzle-orm/pg-core").PgColumn<{
1803
+ name: "recurrence_id";
1804
+ tableName: "jam_events";
1805
+ dataType: "string";
1806
+ columnType: "PgText";
1807
+ data: string;
1808
+ driverParam: string;
1809
+ notNull: false;
1810
+ hasDefault: false;
1811
+ isPrimaryKey: false;
1812
+ isAutoincrement: false;
1813
+ hasRuntimeDefault: false;
1814
+ enumValues: [string, ...string[]];
1815
+ baseColumn: never;
1816
+ identity: undefined;
1817
+ generated: undefined;
1818
+ }, {}, {}>;
1802
1819
  body: import("drizzle-orm/pg-core").PgColumn<{
1803
1820
  name: "body";
1804
1821
  tableName: "jam_events";