@rocapine/community 0.18.0 → 0.21.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/lib/index.js CHANGED
File without changes
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Replaces the `__SUPABASE_PROJECT_URL__` / `__SUPABASE_ANON_KEY__` placeholders
3
+ * baked into the shipped migration SQL (see core/003, push/002, reaction/001)
4
+ * with the values for the app's own Supabase project.
5
+ *
6
+ * Throws if any `__SUPABASE...` token remains after substitution — a guard
7
+ * against a third, unhandled placeholder silently reaching the app's
8
+ * migrations directory (the migration's own DO block re-checks this at
9
+ * `db push` time, but failing fast here gives a clearer error before any
10
+ * SQL is written to disk).
11
+ */
12
+ export declare function substitutePlaceholders(sql: string, values: {
13
+ projectUrl: string;
14
+ anonKey: string;
15
+ }): string;
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.substitutePlaceholders = substitutePlaceholders;
4
+ /**
5
+ * Replaces the `__SUPABASE_PROJECT_URL__` / `__SUPABASE_ANON_KEY__` placeholders
6
+ * baked into the shipped migration SQL (see core/003, push/002, reaction/001)
7
+ * with the values for the app's own Supabase project.
8
+ *
9
+ * Throws if any `__SUPABASE...` token remains after substitution — a guard
10
+ * against a third, unhandled placeholder silently reaching the app's
11
+ * migrations directory (the migration's own DO block re-checks this at
12
+ * `db push` time, but failing fast here gives a clearer error before any
13
+ * SQL is written to disk).
14
+ */
15
+ function substitutePlaceholders(sql, values) {
16
+ const result = sql
17
+ .split("__SUPABASE_PROJECT_URL__")
18
+ .join(values.projectUrl)
19
+ .split("__SUPABASE_ANON_KEY__")
20
+ .join(values.anonKey);
21
+ if (result.includes("__SUPABASE")) {
22
+ throw new Error("community-sdk: unsubstituted __SUPABASE placeholder remains after substitution");
23
+ }
24
+ return result;
25
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rocapine/community",
3
- "version": "0.18.0",
3
+ "version": "0.21.0",
4
4
  "description": "CLI to install, upgrade and adopt the Rocapine Community SDK's Supabase backend (migrations, Edge Functions) into a project.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -1,7 +1,7 @@
1
1
  // Locale-aware push copy for notify-comment / notify-like / notify-reaction.
2
2
  //
3
- // Every string below is a neutral built-in for the 9 locales the UI package
4
- // ships. An app with its own voice overrides ANY of them — per locale, per
3
+ // Every string below is a neutral built-in for each of the 23 locales the UI
4
+ // package ships. An app with its own voice overrides ANY of them — per locale, per
5
5
  // key — through ONE JSON secret instead of forking the function bodies (the
6
6
  // way one host app had to before this existed):
7
7
  //
@@ -18,8 +18,9 @@
18
18
  // Placeholders: `{name}` (actor display name) and `{count}` (the number of
19
19
  // OTHER people in a coalesced push). A `*.many` value is either a string or a
20
20
  // `{ one, few, many, other }` object picked by the CLDR plural category of
21
- // `{count}` for the recipient's locale (Polish needs all three; Ukrainian and
22
- // Romanian one/few/other; French treats 0 like 1; everything else is one/other).
21
+ // `{count}` for the recipient's locale (Polish needs all three; Ukrainian,
22
+ // Russian, Croatian, Czech, Slovak and Romanian one/few/other; French treats 0
23
+ // like 1; everything else is one/other).
23
24
  //
24
25
  // Legacy single-string secrets still apply, below the JSON and above the
25
26
  // built-ins: COMMUNITY_FALLBACK_NAME (every locale's fallbackName) and
@@ -186,6 +187,242 @@ const BUILTIN: Record<string, LocaleCopy> = {
186
187
  other: "{name} und {count} weitere Personen denken an dich",
187
188
  },
188
189
  },
190
+ "fr-vous": {
191
+ fallbackName: "Quelqu'un",
192
+ photo: "📷 Photo",
193
+ "comment.title": "Vous avez reçu un commentaire",
194
+ "reply.title": "Vous avez reçu une réponse",
195
+ "like.one": "{name} a aimé votre publication",
196
+ "like.many": {
197
+ one: "{name} et {count} autre personne ont aimé votre publication",
198
+ other: "{name} et {count} autres personnes ont aimé votre publication",
199
+ },
200
+ "reaction.one": "{name} pense à vous",
201
+ "reaction.many": {
202
+ one: "{name} et {count} autre personne pensent à vous",
203
+ other: "{name} et {count} autres personnes pensent à vous",
204
+ },
205
+ },
206
+ ko: {
207
+ fallbackName: "누군가",
208
+ photo: "📷 사진",
209
+ "comment.title": "새 댓글이 달렸어요",
210
+ "reply.title": "새 답글이 달렸어요",
211
+ "like.one": "{name}님이 내 게시글을 좋아해요",
212
+ "like.many": {
213
+ one: "{name}님 외 {count}명이 내 게시글을 좋아해요",
214
+ other: "{name}님 외 {count}명이 내 게시글을 좋아해요",
215
+ },
216
+ "reaction.one": "{name}님이 나를 생각하고 있어요",
217
+ "reaction.many": {
218
+ one: "{name}님 외 {count}명이 나를 생각하고 있어요",
219
+ other: "{name}님 외 {count}명이 나를 생각하고 있어요",
220
+ },
221
+ },
222
+ ro: {
223
+ fallbackName: "Cineva",
224
+ photo: "📷 Fotografie",
225
+ "comment.title": "Ai primit un comentariu",
226
+ "reply.title": "Ai primit un răspuns",
227
+ "like.one": "{name} a apreciat postarea ta",
228
+ "like.many": {
229
+ one: "{name} și încă o persoană au apreciat postarea ta",
230
+ few: "{name} și încă {count} persoane au apreciat postarea ta",
231
+ other: "{name} și încă {count} de persoane au apreciat postarea ta",
232
+ },
233
+ "reaction.one": "{name} se gândește la tine",
234
+ "reaction.many": {
235
+ one: "{name} și încă o persoană se gândesc la tine",
236
+ few: "{name} și încă {count} persoane se gândesc la tine",
237
+ other: "{name} și încă {count} de persoane se gândesc la tine",
238
+ },
239
+ },
240
+ uk: {
241
+ fallbackName: "Хтось",
242
+ photo: "📷 Фото",
243
+ "comment.title": "У тебе новий коментар",
244
+ "reply.title": "У тебе нова відповідь",
245
+ "like.one": "{name} вподобав(ла) твій допис",
246
+ "like.many": {
247
+ one: "{name} і ще {count} людина вподобали твій допис",
248
+ few: "{name} і ще {count} людини вподобали твій допис",
249
+ other: "{name} і ще {count} людей вподобали твій допис",
250
+ },
251
+ "reaction.one": "{name} думає про тебе",
252
+ "reaction.many": {
253
+ one: "{name} і ще {count} людина думають про тебе",
254
+ few: "{name} і ще {count} людини думають про тебе",
255
+ other: "{name} і ще {count} людей думають про тебе",
256
+ },
257
+ },
258
+ nl: {
259
+ fallbackName: "Iemand",
260
+ photo: "📷 Foto",
261
+ "comment.title": "Je hebt een reactie ontvangen",
262
+ "reply.title": "Je hebt een antwoord ontvangen",
263
+ "like.one": "{name} vindt je post leuk",
264
+ "like.many": {
265
+ one: "{name} en {count} ander vinden je post leuk",
266
+ other: "{name} en {count} anderen vinden je post leuk",
267
+ },
268
+ "reaction.one": "{name} denkt aan je",
269
+ "reaction.many": {
270
+ one: "{name} en {count} ander denken aan je",
271
+ other: "{name} en {count} anderen denken aan je",
272
+ },
273
+ },
274
+ ru: {
275
+ fallbackName: "Кто-то",
276
+ photo: "📷 Фото",
277
+ "comment.title": "У тебя новый комментарий",
278
+ "reply.title": "У тебя новый ответ",
279
+ "like.one": "{name} оценил(а) твой пост",
280
+ "like.many": {
281
+ one: "{name} и ещё {count} человек оценили твой пост",
282
+ few: "{name} и ещё {count} человека оценили твой пост",
283
+ other: "{name} и ещё {count} человек оценили твой пост",
284
+ },
285
+ "reaction.one": "{name} думает о тебе",
286
+ "reaction.many": {
287
+ one: "{name} и ещё {count} человек думают о тебе",
288
+ few: "{name} и ещё {count} человека думают о тебе",
289
+ other: "{name} и ещё {count} человек думают о тебе",
290
+ },
291
+ },
292
+ el: {
293
+ fallbackName: "Κάποιος",
294
+ photo: "📷 Φωτογραφία",
295
+ "comment.title": "Έλαβες ένα σχόλιο",
296
+ "reply.title": "Έλαβες μια απάντηση",
297
+ "like.one": "{name} έκανε like στη δημοσίευσή σου",
298
+ "like.many": {
299
+ one: "{name} και {count} ακόμα άτομο έκαναν like στη δημοσίευσή σου",
300
+ other: "{name} και {count} ακόμα άτομα έκαναν like στη δημοσίευσή σου",
301
+ },
302
+ "reaction.one": "{name} σε σκέφτεται",
303
+ "reaction.many": {
304
+ one: "{name} και {count} ακόμα άτομο σε σκέφτονται",
305
+ other: "{name} και {count} ακόμα άτομα σε σκέφτονται",
306
+ },
307
+ },
308
+ hu: {
309
+ fallbackName: "Valaki",
310
+ photo: "📷 Fotó",
311
+ "comment.title": "Hozzászólást kaptál",
312
+ "reply.title": "Választ kaptál",
313
+ "like.one": "{name} kedvelte a bejegyzésedet",
314
+ "like.many": {
315
+ one: "{name} és még {count} ember kedvelte a bejegyzésedet",
316
+ other: "{name} és még {count} ember kedvelte a bejegyzésedet",
317
+ },
318
+ "reaction.one": "{name} gondol rád",
319
+ "reaction.many": {
320
+ one: "{name} és még {count} ember gondol rád",
321
+ other: "{name} és még {count} ember gondol rád",
322
+ },
323
+ },
324
+ sv: {
325
+ fallbackName: "Någon",
326
+ photo: "📷 Foto",
327
+ "comment.title": "Du har fått en kommentar",
328
+ "reply.title": "Du har fått ett svar",
329
+ "like.one": "{name} gillade ditt inlägg",
330
+ "like.many": {
331
+ one: "{name} och {count} annan gillade ditt inlägg",
332
+ other: "{name} och {count} andra gillade ditt inlägg",
333
+ },
334
+ "reaction.one": "{name} tänker på dig",
335
+ "reaction.many": {
336
+ one: "{name} och {count} annan tänker på dig",
337
+ other: "{name} och {count} andra tänker på dig",
338
+ },
339
+ },
340
+ nb: {
341
+ fallbackName: "Noen",
342
+ photo: "📷 Bilde",
343
+ "comment.title": "Du har fått en kommentar",
344
+ "reply.title": "Du har fått et svar",
345
+ "like.one": "{name} likte innlegget ditt",
346
+ "like.many": {
347
+ one: "{name} og {count} annen likte innlegget ditt",
348
+ other: "{name} og {count} andre likte innlegget ditt",
349
+ },
350
+ "reaction.one": "{name} tenker på deg",
351
+ "reaction.many": {
352
+ one: "{name} og {count} annen tenker på deg",
353
+ other: "{name} og {count} andre tenker på deg",
354
+ },
355
+ },
356
+ da: {
357
+ fallbackName: "Nogen",
358
+ photo: "📷 Foto",
359
+ "comment.title": "Du har fået en kommentar",
360
+ "reply.title": "Du har fået et svar",
361
+ "like.one": "{name} synes godt om dit opslag",
362
+ "like.many": {
363
+ one: "{name} og {count} anden synes godt om dit opslag",
364
+ other: "{name} og {count} andre synes godt om dit opslag",
365
+ },
366
+ "reaction.one": "{name} tænker på dig",
367
+ "reaction.many": {
368
+ one: "{name} og {count} anden tænker på dig",
369
+ other: "{name} og {count} andre tænker på dig",
370
+ },
371
+ },
372
+ hr: {
373
+ fallbackName: "Netko",
374
+ photo: "📷 Fotografija",
375
+ "comment.title": "Imaš novi komentar",
376
+ "reply.title": "Imaš novi odgovor",
377
+ "like.one": "{name} je lajkao/la tvoju objavu",
378
+ "like.many": {
379
+ one: "{name} i još {count} osoba lajkali su tvoju objavu",
380
+ few: "{name} i još {count} osobe lajkali su tvoju objavu",
381
+ other: "{name} i još {count} osoba lajkali su tvoju objavu",
382
+ },
383
+ "reaction.one": "{name} misli na tebe",
384
+ "reaction.many": {
385
+ one: "{name} i još {count} osoba misle na tebe",
386
+ few: "{name} i još {count} osobe misle na tebe",
387
+ other: "{name} i još {count} osoba misle na tebe",
388
+ },
389
+ },
390
+ sk: {
391
+ fallbackName: "Niekto",
392
+ photo: "📷 Fotka",
393
+ "comment.title": "Máš nový komentár",
394
+ "reply.title": "Máš novú odpoveď",
395
+ "like.one": "{name} dal(a) like tvojmu príspevku",
396
+ "like.many": {
397
+ one: "{name} a {count} ďalší dali like tvojmu príspevku",
398
+ few: "{name} a {count} ďalší dali like tvojmu príspevku",
399
+ other: "{name} a {count} ďalších dali like tvojmu príspevku",
400
+ },
401
+ "reaction.one": "{name} myslí na teba",
402
+ "reaction.many": {
403
+ one: "{name} a {count} ďalší myslia na teba",
404
+ few: "{name} a {count} ďalší myslia na teba",
405
+ other: "{name} a {count} ďalších myslia na teba",
406
+ },
407
+ },
408
+ cs: {
409
+ fallbackName: "Někdo",
410
+ photo: "📷 Fotka",
411
+ "comment.title": "Máš nový komentář",
412
+ "reply.title": "Máš novou odpověď",
413
+ "like.one": "{name} ocenil(a) tvůj příspěvek",
414
+ "like.many": {
415
+ one: "{name} a {count} další ocenili tvůj příspěvek",
416
+ few: "{name} a {count} další ocenili tvůj příspěvek",
417
+ other: "{name} a {count} dalších ocenili tvůj příspěvek",
418
+ },
419
+ "reaction.one": "{name} myslí na tebe",
420
+ "reaction.many": {
421
+ one: "{name} a {count} další myslí na tebe",
422
+ few: "{name} a {count} další myslí na tebe",
423
+ other: "{name} a {count} dalších myslí na tebe",
424
+ },
425
+ },
189
426
  };
190
427
 
191
428
  // Same rule set as the UI package's `pluralCategory` (packages/ui/src/i18n.ts).
@@ -198,11 +435,16 @@ export function pluralCategory(locale: string, n: number): keyof Forms {
198
435
  if (m10 >= 2 && m10 <= 4 && !(m100 >= 12 && m100 <= 14)) return "few";
199
436
  return "many";
200
437
  }
201
- if (lang === "uk") {
438
+ if (lang === "uk" || lang === "ru" || lang === "hr") {
202
439
  if (m10 === 1 && m100 !== 11) return "one";
203
440
  if (m10 >= 2 && m10 <= 4 && !(m100 >= 12 && m100 <= 14)) return "few";
204
441
  return "other";
205
442
  }
443
+ if (lang === "cs" || lang === "sk") {
444
+ if (n === 1) return "one";
445
+ if (n >= 2 && n <= 4) return "few";
446
+ return "other";
447
+ }
206
448
  if (lang === "ro") {
207
449
  if (n === 1) return "one";
208
450
  if (n === 0 || (m100 >= 2 && m100 <= 19)) return "few";
@@ -228,7 +470,7 @@ const OVERRIDES = parseOverrides();
228
470
  const LEGACY_FALLBACK_NAME = Deno.env.get("COMMUNITY_FALLBACK_NAME");
229
471
  const LEGACY_REACTION_ONE = Deno.env.get("COMMUNITY_REACTION_PUSH_TEXT");
230
472
 
231
- /** `es-MX` → `es-ES`, `pt-AO` → `pt-PT`, `fr-CA` → `fr`; unknown → `en`. */
473
+ /** `es-MX` → `es-ES`, `pt-AO` → `pt-PT`, `fr-CA` → `fr`, `no` → `nb`; unknown → `en`. */
232
474
  function resolveLocale(locale: string | null | undefined): string {
233
475
  if (!locale) return "en";
234
476
  if (BUILTIN[locale]) return locale;
@@ -236,6 +478,7 @@ function resolveLocale(locale: string | null | undefined): string {
236
478
  if (BUILTIN[lang]) return lang;
237
479
  if (lang === "es") return "es-ES";
238
480
  if (lang === "pt") return "pt-PT";
481
+ if (lang === "no") return "nb";
239
482
  return "en";
240
483
  }
241
484
 
@@ -0,0 +1,284 @@
1
+ -- community-sdk core/017_activity_metrics.sql (schema v1)
2
+ -- admin_daily_metrics, fixed for the dashboard's Activity section (service role only):
3
+ -- days in the team's zone (tz, an IANA name; two arguments mean UTC), house accounts out of
4
+ -- every count, posts and comments of any status but deleted, the reply rate per day (a reply is
5
+ -- a comment not deleted by someone other than the author within 24 h; posts under 24 h old are
6
+ -- left out), new posters on their first post that isn't deleted, and likes, poll votes,
7
+ -- reactions, unanswered posts, contributors and reactors. Poll votes and reactions are null
8
+ -- when the polls / reaction module is not installed. Also: new members (profiles created in the
9
+ -- window, per day and in all), active members (distinct members with any post, comment, like,
10
+ -- comment like, poll vote or reaction, per day and over the period), members_total (profiles
11
+ -- created before the window's end) and median_first_reply_minutes (median minutes to the first
12
+ -- non-deleted reply by someone else, over posts at least 24 h old; null when none was replied).
13
+ -- created_at indexes keep the window scans cheap. Replaces the two-argument version of core/004.
14
+ -- Also admin_activity_breakdown(from_date, to_date, tz): the Activity page's breakdowns in one
15
+ -- call (service role only): a 7 x 24 heatmap (Monday first, hours in tz) of member posts and
16
+ -- comments, those by author language (profiles.locale, from the push module; null when the
17
+ -- column is absent: then languages is null), moderation counts (reports by members, items the AI hid whatever their status or review now,
18
+ -- team moderation actions) against the previous period of the same length, how many of the previous period's
19
+ -- contributors came back, and the five top posts (whole content, image, verse, poll with votes). Same zone check and window as above.
20
+ -- Requires core/004. Fully idempotent.
21
+
22
+ create index if not exists posts_created_at_idx on public.posts (created_at);
23
+ create index if not exists comments_created_at_idx on public.comments (created_at);
24
+ create index if not exists likes_created_at_idx on public.likes (created_at);
25
+ create index if not exists comment_likes_created_at_idx on public.comment_likes (created_at);
26
+ create index if not exists profiles_created_at_idx on public.profiles (created_at);
27
+ create index if not exists reports_created_at_idx on public.reports (created_at);
28
+ do $$
29
+ begin
30
+ if to_regclass('public.poll_votes') is not null then
31
+ create index if not exists poll_votes_created_at_idx on public.poll_votes (created_at);
32
+ end if;
33
+ if to_regclass('public.post_reactions') is not null then
34
+ create index if not exists post_reactions_created_at_idx on public.post_reactions (created_at);
35
+ end if;
36
+ end $$;
37
+
38
+ drop function if exists public.admin_daily_metrics(date, date);
39
+
40
+ create or replace function public.admin_daily_metrics(from_date date, to_date date, tz text default 'UTC')
41
+ returns jsonb
42
+ language plpgsql
43
+ stable
44
+ set search_path = public
45
+ as $$
46
+ declare
47
+ t0 timestamptz;
48
+ t1 timestamptz;
49
+ -- Member rows of an optional module in the window: per-day counts and the distinct [user, day] pairs.
50
+ extra text := $q$
51
+ with r as (
52
+ select x.user_id, (x.created_at at time zone $3)::date as day
53
+ from %I x join profiles a on a.id = x.user_id and not a.is_house
54
+ where x.created_at >= $1 and x.created_at < $2)
55
+ select coalesce((select jsonb_object_agg(day, n) from (select day, count(*) as n from r group by day) s), '{}'),
56
+ coalesce((select jsonb_agg(distinct jsonb_build_array(user_id, day)) from r), '[]')$q$;
57
+ vote_days jsonb;
58
+ vote_pairs jsonb := '[]';
59
+ reaction_days jsonb;
60
+ reaction_pairs jsonb := '[]';
61
+ result jsonb;
62
+ begin
63
+ if tz is null or tz not in (select name from pg_timezone_names) then
64
+ raise exception 'invalid_time_zone' using errcode = '22023';
65
+ end if;
66
+ t0 := from_date::timestamp at time zone tz;
67
+ t1 := (to_date + 1)::timestamp at time zone tz;
68
+
69
+ if to_regclass('public.poll_votes') is not null then
70
+ execute format(extra, 'poll_votes') into vote_days, vote_pairs using t0, t1, tz;
71
+ end if;
72
+ if to_regclass('public.post_reactions') is not null then
73
+ execute format(extra, 'post_reactions') into reaction_days, reaction_pairs using t0, t1, tz;
74
+ end if;
75
+
76
+ with
77
+ days as (select generate_series(from_date, to_date, interval '1 day')::date as day),
78
+ -- first_reply_min: minutes to the first non-deleted comment by someone other than the author.
79
+ m_posts as (
80
+ select author_id, topic, day, eligible, coalesce(first_reply_min <= 1440, false) as replied,
81
+ first_reply_min is not null as answered, first_reply_min
82
+ from (
83
+ select p.author_id, p.topic, (p.created_at at time zone tz)::date as day,
84
+ p.created_at <= now() - interval '24 hours' as eligible,
85
+ (select extract(epoch from min(c.created_at) - p.created_at) / 60 from comments c
86
+ where c.post_id = p.id and c.status <> 'deleted' and c.author_id <> p.author_id) as first_reply_min
87
+ from posts p join profiles a on a.id = p.author_id and not a.is_house
88
+ where p.status <> 'deleted' and p.created_at >= t0 and p.created_at < t1) q),
89
+ m_comments as (
90
+ select c.author_id, (c.created_at at time zone tz)::date as day
91
+ from comments c join profiles a on a.id = c.author_id and not a.is_house
92
+ where c.status <> 'deleted' and c.created_at >= t0 and c.created_at < t1),
93
+ m_likes as (
94
+ select l.user_id, (l.created_at at time zone tz)::date as day
95
+ from likes l join profiles a on a.id = l.user_id and not a.is_house
96
+ where l.created_at >= t0 and l.created_at < t1
97
+ union all
98
+ select l.user_id, (l.created_at at time zone tz)::date
99
+ from comment_likes l join profiles a on a.id = l.user_id and not a.is_house
100
+ where l.created_at >= t0 and l.created_at < t1),
101
+ writes as (select author_id, day from m_posts union all select author_id, day from m_comments),
102
+ extra_pairs as (
103
+ select (e->>0)::uuid as who, (e->>1)::date as day
104
+ from jsonb_array_elements(vote_pairs || reaction_pairs) e),
105
+ activity as (
106
+ select author_id as who, day from writes
107
+ union all select user_id, day from m_likes
108
+ union all select who, day from extra_pairs),
109
+ active_by_day as (select day, count(distinct who) as n from activity group by day),
110
+ new_by_day as (
111
+ select (created_at at time zone tz)::date as day, count(*) as n
112
+ from profiles where not is_house and created_at >= t0 and created_at < t1 group by 1),
113
+ -- A new poster has a post in the window, so only those authors are looked up.
114
+ new_posters as (
115
+ select (min(p.created_at) at time zone tz)::date as day
116
+ from posts p
117
+ where p.status <> 'deleted' and p.author_id in (select author_id from m_posts)
118
+ group by p.author_id
119
+ having min(p.created_at) >= t0),
120
+ hidden as (
121
+ select (p.moderated_at at time zone tz)::date as day
122
+ from posts p join profiles a on a.id = p.author_id and not a.is_house
123
+ where p.status = 'hidden' and p.moderated_at >= t0 and p.moderated_at < t1),
124
+ contributions as (select author_id, count(*) as n from writes group by author_id),
125
+ -- One pass per day: every row tagged with its kind, then counted by kind.
126
+ events as (
127
+ select day, 'post' as kind, author_id as who, eligible, eligible and replied as replied from m_posts
128
+ union all select day, 'comment', author_id, false, false from m_comments
129
+ union all select day, 'like', user_id, false, false from m_likes
130
+ union all select day, 'new_poster', null, false, false from new_posters
131
+ union all select day, 'hidden', null, false, false from hidden),
132
+ per_day as (
133
+ select day,
134
+ count(*) filter (where kind = 'post') as posts,
135
+ count(*) filter (where kind = 'comment') as comments,
136
+ count(*) filter (where kind = 'new_poster') as new_posters,
137
+ count(*) filter (where kind = 'hidden') as hidden,
138
+ count(*) filter (where kind = 'like') as likes,
139
+ count(*) filter (where replied) as replied,
140
+ count(*) filter (where eligible) as eligible,
141
+ count(distinct who) filter (where kind in ('post', 'comment')) as contributors
142
+ from events group by day)
143
+ select jsonb_build_object(
144
+ 'tz', tz,
145
+ 'daily', (select coalesce(jsonb_agg(jsonb_build_object(
146
+ 'day', d.day,
147
+ 'posts', coalesce(x.posts, 0),
148
+ 'comments', coalesce(x.comments, 0),
149
+ 'new_posters', coalesce(x.new_posters, 0),
150
+ 'hidden', coalesce(x.hidden, 0),
151
+ 'likes', coalesce(x.likes, 0),
152
+ 'poll_votes', case when vote_days is not null then coalesce((vote_days->>d.day::text)::int, 0) end,
153
+ 'reactions', case when reaction_days is not null then coalesce((reaction_days->>d.day::text)::int, 0) end,
154
+ 'replied_24h', coalesce(x.replied, 0),
155
+ 'reply_eligible', coalesce(x.eligible, 0),
156
+ 'contributors', coalesce(x.contributors, 0),
157
+ 'new_members', coalesce(nm.n, 0),
158
+ 'active_members', coalesce(am.n, 0)
159
+ ) order by d.day), '[]'::jsonb) from days d left join per_day x on x.day = d.day
160
+ left join new_by_day nm on nm.day = d.day left join active_by_day am on am.day = d.day),
161
+ 'topics', (select coalesce(jsonb_agg(jsonb_build_object('topic', topic, 'count', n) order by n desc, topic), '[]')
162
+ from (select coalesce(topic, '(sans)') as topic, count(*) as n from m_posts group by 1) t),
163
+ 'reply_rate', (select coalesce(count(*) filter (where replied)::float / nullif(count(*), 0), 0)
164
+ from m_posts where eligible),
165
+ 'unanswered', (select count(*) from m_posts where eligible and not answered),
166
+ 'contributors', (select count(*) from contributions),
167
+ 'new_members', (select coalesce(sum(n), 0) from new_by_day),
168
+ 'active_members', (select count(distinct who) from activity),
169
+ 'members_total', (select count(*) from profiles where not is_house and created_at < t1),
170
+ 'median_first_reply_minutes', (select percentile_cont(0.5) within group (order by first_reply_min)
171
+ from m_posts where eligible and first_reply_min is not null),
172
+ 'reactors', (select count(distinct u) from (
173
+ select user_id as u from m_likes
174
+ union all select (e->>0)::uuid from jsonb_array_elements(vote_pairs) e
175
+ union all select (e->>0)::uuid from jsonb_array_elements(reaction_pairs) e) r
176
+ where u not in (select author_id from contributions)),
177
+ 'contribution_buckets', (select jsonb_build_object(
178
+ '1', count(*) filter (where n = 1),
179
+ '2-3', count(*) filter (where n between 2 and 3),
180
+ '4-7', count(*) filter (where n between 4 and 7),
181
+ '8+', count(*) filter (where n >= 8)) from contributions))
182
+ into result;
183
+ return result;
184
+ end;
185
+ $$;
186
+
187
+ revoke execute on function public.admin_daily_metrics(date, date, text) from public, anon, authenticated;
188
+
189
+ create or replace function public.admin_activity_breakdown(from_date date, to_date date, tz text default 'UTC')
190
+ returns jsonb
191
+ language plpgsql
192
+ stable
193
+ set search_path = public
194
+ as $$
195
+ declare
196
+ t0 timestamptz;
197
+ t1 timestamptz;
198
+ pt0 timestamptz; -- the previous period: as many days, right before from_date
199
+ polls jsonb;
200
+ -- profiles.locale comes from the push module: without it, languages is null.
201
+ has_locale boolean := exists (select 1 from pg_attribute
202
+ where attrelid = 'public.profiles'::regclass and attname = 'locale' and not attisdropped);
203
+ result jsonb;
204
+ begin
205
+ if tz is null or tz not in (select name from pg_timezone_names) then
206
+ raise exception 'invalid_time_zone' using errcode = '22023';
207
+ end if;
208
+ t0 := from_date::timestamp at time zone tz;
209
+ t1 := (to_date + 1)::timestamp at time zone tz;
210
+ pt0 := (from_date - greatest(to_date - from_date + 1, 0))::timestamp at time zone tz;
211
+
212
+ with
213
+ -- Member posts and comments (not deleted) of both periods; locale is read through to_jsonb
214
+ -- so the function also compiles where the push module's column does not exist.
215
+ writes as (
216
+ select p.author_id, p.created_at, case when has_locale then to_jsonb(a)->>'locale' end as locale
217
+ from posts p join profiles a on a.id = p.author_id and not a.is_house
218
+ where p.status <> 'deleted' and p.created_at >= pt0 and p.created_at < t1
219
+ union all
220
+ select c.author_id, c.created_at, case when has_locale then to_jsonb(a)->>'locale' end
221
+ from comments c join profiles a on a.id = c.author_id and not a.is_house
222
+ where c.status <> 'deleted' and c.created_at >= pt0 and c.created_at < t1),
223
+ cur as (select * from writes where created_at >= t0),
224
+ heat as (
225
+ select extract(isodow from created_at at time zone tz)::int - 1 as dow,
226
+ extract(hour from created_at at time zone tz)::int as hr, count(*) as n
227
+ from cur group by 1, 2),
228
+ mod as (
229
+ select w.k,
230
+ (select count(*) from reports r join profiles a on a.id = r.reporter_id and not a.is_house
231
+ where r.created_at >= w.a and r.created_at < w.b) as reports,
232
+ (select count(*) from (
233
+ select 1 from posts p join profiles a on a.id = p.author_id and not a.is_house
234
+ where p.moderation_reason is not null and p.moderated_at >= w.a and p.moderated_at < w.b
235
+ union all
236
+ select 1 from comments c join profiles a on a.id = c.author_id and not a.is_house
237
+ where c.moderation_reason is not null and c.moderated_at >= w.a and c.moderated_at < w.b) q) as ai_hidden,
238
+ (select count(*) from moderation_actions m where m.created_at >= w.a and m.created_at < w.b
239
+ and m.action in ('hide','restore','confirm_hide','reject_report','ban','unban')) as team_actions
240
+ from (values ('cur', t0, t1), ('prev', pt0, t0)) w(k, a, b)),
241
+ top as (select * from (
242
+ -- image_path and attachment come from optional modules: read through to_jsonb so their absence is null.
243
+ select p.id, p.content, to_jsonb(p)->>'image_path' as image_path, to_jsonb(p)->'attachment' as attachment, p.topic, p.author_id, a.username as author_name, p.created_at,
244
+ (select count(*) from likes l join profiles u on u.id = l.user_id and not u.is_house where l.post_id = p.id) as likes,
245
+ (select count(*) from comments c join profiles u on u.id = c.author_id and not u.is_house
246
+ where c.post_id = p.id and c.status <> 'deleted') as comments
247
+ from posts p join profiles a on a.id = p.author_id and not a.is_house
248
+ where p.status <> 'deleted' and p.created_at >= t0 and p.created_at < t1) q
249
+ order by likes + comments desc, created_at desc, id limit 5)
250
+ select jsonb_build_object(
251
+ 'tz', tz,
252
+ 'heatmap', (select jsonb_agg((select jsonb_agg(coalesce((select n from heat where heat.dow = d and heat.hr = hh), 0) order by hh)
253
+ from generate_series(0, 23) hh) order by d) from generate_series(0, 6) d),
254
+ 'languages', case when has_locale then (select coalesce(jsonb_agg(jsonb_build_object('locale', locale, 'count', n)
255
+ order by n desc, locale), '[]') from (select locale, count(*) as n from cur group by locale) l) end,
256
+ 'moderation', (select jsonb_build_object('reports', c.reports, 'ai_hidden', c.ai_hidden, 'team_actions', c.team_actions,
257
+ 'previous', jsonb_build_object('reports', v.reports, 'ai_hidden', v.ai_hidden, 'team_actions', v.team_actions))
258
+ from mod c, mod v where c.k = 'cur' and v.k = 'prev'),
259
+ 'returning', jsonb_build_object(
260
+ 'previous_contributors', (select count(distinct author_id) from writes where created_at < t0),
261
+ 'returned', (select count(distinct author_id) from cur
262
+ where author_id in (select author_id from writes where created_at < t0))),
263
+ 'top_posts', (select coalesce(jsonb_agg(jsonb_build_object('id', id, 'content', content, 'image_path', image_path,
264
+ 'attachment', attachment, 'poll', null, 'topic', topic,
265
+ 'author_id', author_id, 'author_name', author_name, 'likes', likes, 'comments', comments,
266
+ 'created_at', to_char(created_at at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'))
267
+ order by likes + comments desc, created_at desc, id), '[]') from top))
268
+ into result;
269
+ -- A top post's poll (polls module): its options in order with their vote counts.
270
+ if to_regclass('public.poll_options') is not null and jsonb_array_length(result->'top_posts') > 0 then
271
+ execute $q$select coalesce(jsonb_object_agg(post_id, opts), '{}') from (
272
+ select o.post_id, jsonb_agg(jsonb_build_object('label', o.label,
273
+ 'votes', (select count(*) from public.poll_votes v where v.option_id = o.id)) order by o.idx) as opts
274
+ from public.poll_options o where o.post_id = any($1) group by o.post_id) x$q$
275
+ into polls
276
+ using (select array_agg((e->>'id')::uuid) from jsonb_array_elements(result->'top_posts') e);
277
+ result := jsonb_set(result, '{top_posts}', (select jsonb_agg(jsonb_set(e, '{poll}', coalesce(polls->(e->>'id'), 'null'))
278
+ order by n) from jsonb_array_elements(result->'top_posts') with ordinality t(e, n)));
279
+ end if;
280
+ return result;
281
+ end;
282
+ $$;
283
+
284
+ revoke execute on function public.admin_activity_breakdown(date, date, text) from public, anon, authenticated;