@openpeepshq/core 0.28.1 → 0.30.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.
- package/dist/analytics/compile.js +15 -7
- package/dist/analytics/jamMetrics.d.ts +47 -0
- package/dist/analytics/jamMetrics.js +93 -0
- package/dist/analytics/pdfReport.js +40 -1
- package/dist/analytics/read.js +68 -5
- package/dist/analytics/report.d.ts +75 -0
- package/dist/analytics/report.js +1 -0
- package/dist/auditLog/finders.d.ts +27 -0
- package/dist/auditLog/finders.js +40 -0
- package/dist/auditLog/index.d.ts +3 -0
- package/dist/auditLog/index.js +3 -0
- package/dist/auditLog/mapping.d.ts +4 -0
- package/dist/auditLog/mapping.js +18 -0
- package/dist/auditLog/mutations.d.ts +42 -0
- package/dist/auditLog/mutations.js +43 -0
- package/dist/db/pg/map/registry.js +11 -1
- package/dist/db/pg/schema/analytics.d.ts +68 -0
- package/dist/db/pg/schema/analytics.js +10 -0
- package/dist/db/pg/schema/auditLogs.d.ts +183 -0
- package/dist/db/pg/schema/auditLogs.js +30 -0
- package/dist/db/pg/schema/documents.d.ts +17 -0
- package/dist/db/pg/schema/documents.js +10 -1
- package/dist/db/pg/schema/index.d.ts +263 -0
- package/dist/db/pg/schema/index.js +3 -0
- package/dist/db/pg/sql/0020_add_audit_logs.sql +16 -0
- package/dist/db/pg/sql/0021_jam_occurrence_recurrence_id.sql +10 -0
- package/dist/db/pg/sql/meta/0020_snapshot.json +4816 -0
- package/dist/db/pg/sql/meta/0021_snapshot.json +4718 -0
- package/dist/db/pg/sql/meta/0022_snapshot.json +182 -1
- package/dist/db/pg/sql/meta/_journal.json +15 -1
- package/dist/jams/export.d.ts +17 -4
- package/dist/jams/export.js +36 -6
- package/dist/jams/finders.js +5 -1
- package/dist/jams/index.js +3 -0
- package/dist/jams/livekit.d.ts +18 -3
- package/dist/jams/livekit.js +37 -5
- package/dist/jams/mapping.d.ts +0 -27
- package/dist/jams/mapping.js +0 -15
- package/dist/jams/token.js +14 -6
- package/dist/stats/finders.js +34 -7
- 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
|
-
|
|
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
|
|
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
|
-
|
|
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);
|
package/dist/analytics/read.js
CHANGED
|
@@ -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-
|
|
521
|
-
|
|
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-
|
|
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;
|
package/dist/analytics/report.js
CHANGED
|
@@ -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,
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { AuditLogRow } from '../db/pg/schema';
|
|
2
|
+
export interface ListAuditEntriesOptions {
|
|
3
|
+
/**
|
|
4
|
+
* Cursor: only entries strictly older than `(before, beforeId)`.
|
|
5
|
+
* `before` is the `created_at` (ISO string) and `beforeId` is the `id` of
|
|
6
|
+
* the last row of the previous page; both are used together so that rows
|
|
7
|
+
* tying on `created_at` with the boundary row are not skipped. `before`
|
|
8
|
+
* alone (no `beforeId`) degrades to "older than this timestamp".
|
|
9
|
+
*/
|
|
10
|
+
before?: string;
|
|
11
|
+
beforeId?: string;
|
|
12
|
+
limit?: number;
|
|
13
|
+
actorProfileId?: string;
|
|
14
|
+
targetType?: string;
|
|
15
|
+
targetId?: string;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Newest-first, cursor-paginated listing. `before` is the `created_at` of the
|
|
19
|
+
* last row of the previous page ("older page"); rows are immutable, and tied
|
|
20
|
+
* timestamps are ordered by `id desc` for deterministic pages.
|
|
21
|
+
*
|
|
22
|
+
* `limit` is clamped defensively with an explicit `Number()` so the bound
|
|
23
|
+
* holds whether the value arrived as a number or a numeric string (the direct
|
|
24
|
+
* `.handle()` call path bypasses Riddl's query coercion, which a real request
|
|
25
|
+
* would have already applied).
|
|
26
|
+
*/
|
|
27
|
+
export declare const listAuditEntries: (options?: ListAuditEntriesOptions) => Promise<AuditLogRow[]>;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { and, desc, eq, lt, or } from 'drizzle-orm';
|
|
2
|
+
import { auditLogs } from '../db/pg/schema/index.js';
|
|
3
|
+
import { allpeepDb } from '../db/index.js';
|
|
4
|
+
const DEFAULT_LIMIT = 100;
|
|
5
|
+
const MAX_LIMIT = 1000;
|
|
6
|
+
/**
|
|
7
|
+
* Newest-first, cursor-paginated listing. `before` is the `created_at` of the
|
|
8
|
+
* last row of the previous page ("older page"); rows are immutable, and tied
|
|
9
|
+
* timestamps are ordered by `id desc` for deterministic pages.
|
|
10
|
+
*
|
|
11
|
+
* `limit` is clamped defensively with an explicit `Number()` so the bound
|
|
12
|
+
* holds whether the value arrived as a number or a numeric string (the direct
|
|
13
|
+
* `.handle()` call path bypasses Riddl's query coercion, which a real request
|
|
14
|
+
* would have already applied).
|
|
15
|
+
*/
|
|
16
|
+
export const listAuditEntries = async (options = {}) => {
|
|
17
|
+
const limit = Math.min(Math.max(Number(options.limit ?? DEFAULT_LIMIT), 1), MAX_LIMIT);
|
|
18
|
+
const cursor = options.before && options.beforeId
|
|
19
|
+
? or(lt(auditLogs.createdAt, options.before), and(eq(auditLogs.createdAt, options.before), lt(auditLogs.id, options.beforeId)))
|
|
20
|
+
: options.before
|
|
21
|
+
? lt(auditLogs.createdAt, options.before)
|
|
22
|
+
: undefined;
|
|
23
|
+
const conditions = [
|
|
24
|
+
cursor,
|
|
25
|
+
options.actorProfileId
|
|
26
|
+
? eq(auditLogs.actorProfileId, options.actorProfileId)
|
|
27
|
+
: undefined,
|
|
28
|
+
options.targetType
|
|
29
|
+
? eq(auditLogs.targetType, options.targetType)
|
|
30
|
+
: undefined,
|
|
31
|
+
options.targetId ? eq(auditLogs.targetId, options.targetId) : undefined,
|
|
32
|
+
].filter(Boolean);
|
|
33
|
+
const { db } = await allpeepDb();
|
|
34
|
+
return db
|
|
35
|
+
.select()
|
|
36
|
+
.from(auditLogs)
|
|
37
|
+
.where(conditions.length ? and(...conditions) : undefined)
|
|
38
|
+
.orderBy(desc(auditLogs.createdAt), desc(auditLogs.id))
|
|
39
|
+
.limit(limit);
|
|
40
|
+
};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { AuditLogEntry } from '@openpeepshq/common/types';
|
|
2
|
+
import type { AuditLogRow } from '../db/pg/schema';
|
|
3
|
+
export declare const mapAuditLogRow: (row: AuditLogRow) => AuditLogEntry;
|
|
4
|
+
export declare const mapAuditLogRows: (rows: AuditLogRow[]) => AuditLogEntry[];
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { normalizeIsoDatetime } from '../db/pg/mappers.js';
|
|
2
|
+
export const mapAuditLogRow = (row) => ({
|
|
3
|
+
id: row.id,
|
|
4
|
+
actorProfileId: row.actorProfileId,
|
|
5
|
+
actorAccountId: row.actorAccountId,
|
|
6
|
+
actorIp: row.actorIp,
|
|
7
|
+
action: row.action,
|
|
8
|
+
targetType: row.targetType,
|
|
9
|
+
targetId: row.targetId,
|
|
10
|
+
targetLabel: row.targetLabel,
|
|
11
|
+
// `jsonb` columns have no type mode, so drizzle infers `unknown` on read.
|
|
12
|
+
metadata: row.metadata,
|
|
13
|
+
// The pg driver returns timestamptz as an offset string
|
|
14
|
+
// (`"2026-11-26 12:00:00.123+00"`); normalize to ISO UTC so the
|
|
15
|
+
// `z.string().datetime()` output schemas accept it.
|
|
16
|
+
createdAt: normalizeIsoDatetime(row.createdAt),
|
|
17
|
+
});
|
|
18
|
+
export const mapAuditLogRows = (rows) => rows.map(mapAuditLogRow);
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { ProfileWithMeta } from '@openpeepshq/common/types';
|
|
2
|
+
export interface AuditEntryData {
|
|
3
|
+
/** Id of the profile performing the action. */
|
|
4
|
+
actorProfileId: string;
|
|
5
|
+
actorAccountId?: string | null;
|
|
6
|
+
actorIp?: string | null;
|
|
7
|
+
/** e.g. `profile.delete`, `report.resolve`, `role.update`. */
|
|
8
|
+
action: string;
|
|
9
|
+
/** e.g. `profile`, `account`, `report`, `role`, `group`. */
|
|
10
|
+
targetType: string;
|
|
11
|
+
targetId?: string | null;
|
|
12
|
+
/** Human-readable target detail (handle, email, role key…). */
|
|
13
|
+
targetLabel?: string | null;
|
|
14
|
+
/** Action-specific detail; never credentials or full request bodies. */
|
|
15
|
+
metadata?: Record<string, unknown> | null;
|
|
16
|
+
}
|
|
17
|
+
/** Plain insert — throws on failure. */
|
|
18
|
+
export declare const createAuditEntry: (data: AuditEntryData) => Promise<{
|
|
19
|
+
id: string;
|
|
20
|
+
metadata: unknown;
|
|
21
|
+
createdAt: string;
|
|
22
|
+
actorProfileId: string;
|
|
23
|
+
actorAccountId: string | null;
|
|
24
|
+
actorIp: string | null;
|
|
25
|
+
action: string;
|
|
26
|
+
targetType: string;
|
|
27
|
+
targetId: string | null;
|
|
28
|
+
targetLabel: string | null;
|
|
29
|
+
}>;
|
|
30
|
+
export interface AuditContext {
|
|
31
|
+
/** The actor (already loaded by the auth middleware). */
|
|
32
|
+
profile?: ProfileWithMeta | null;
|
|
33
|
+
/** Client IP at request time (behind the TLS proxy: first XFF hop). */
|
|
34
|
+
ip?: string | null;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Fire-and-forget audit write: resolves the actor (profile + owning
|
|
38
|
+
* account), inserts one row and swallows its own errors. A failed audit
|
|
39
|
+
* write must never fail the admin action that triggered it — it is logged
|
|
40
|
+
* as a server error.
|
|
41
|
+
*/
|
|
42
|
+
export declare const recordAuditEntry: (data: Omit<AuditEntryData, "actorAccountId" | "actorProfileId" | "actorIp"> & Partial<Pick<AuditEntryData, "actorProfileId">>, ctx: AuditContext) => Promise<void>;
|