@rocapine/community 0.14.0 → 0.15.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/README.md CHANGED
@@ -13,7 +13,7 @@ version. The binary is named `community`.
13
13
  ## `init`
14
14
 
15
15
  ```bash
16
- npx @rocapine/community init [--modules core,push,polls,reaction,inbox,translation,images,streaks] [--project-url <url>] [--anon-key <key>] [--dir supabase]
16
+ npx @rocapine/community init [--modules core,push,polls,reaction,inbox,translation,images,attachments,badges,streaks] [--project-url <url>] [--anon-key <key>] [--dir supabase]
17
17
  ```
18
18
 
19
19
  Copies the migrations and Edge Functions for the requested modules into
@@ -21,13 +21,13 @@ Copies the migrations and Edge Functions for the requested modules into
21
21
  relative to the current directory), and writes a `community-sdk.json`
22
22
  manifest at the repo root recording what was installed.
23
23
 
24
- - `--modules` — comma-separated (`core,push,polls,reaction,inbox,translation,images,streaks`). `core`
24
+ - `--modules` — comma-separated (`core,push,polls,reaction,inbox,translation,images,attachments,badges,streaks`). `core`
25
25
  is always implied even if omitted. Omit the flag entirely to install every
26
26
  module. Regardless of the order you type them, modules are installed
27
- `core → push → polls → reaction → inbox → translation → images → streaks` — this order is load-bearing:
27
+ `core → push → polls → reaction → inbox → translation → images → attachments → badges → streaks` — this order is load-bearing:
28
28
  the inbox module's reaction trigger is guarded at install time and must
29
29
  find the reaction module's table already present, so reaction has to land
30
- first. Requesting `inbox` without `reaction`, or `translation` without `polls`, prints a (non-fatal) warning (reactions missing from the inbox; poll labels left untranslated).
30
+ first. `streaks` (deprecated: it moves an existing streak install onto badges) always brings `badges`. Requesting `inbox` without `reaction`, or `translation` without `polls`, prints a (non-fatal) warning (reactions missing from the inbox; poll labels left untranslated).
31
31
  - `--project-url` / `--anon-key` — needed only if a migration in the
32
32
  selected modules carries a placeholder (see "Placeholder guard" below).
33
33
  If omitted, the CLI tries to read the project URL from
@@ -58,9 +58,14 @@ async function runUpgrade(options = {}) {
58
58
  // rules `init --modules` uses; left empty/undefined, behaviour here must stay
59
59
  // byte-identical to the pre-`addModules` path (no resolveModules call, no
60
60
  // spurious warnings for e.g. an existing inbox-without-reaction install).
61
+ // One implication still applies: streaks/002 moves the streak onto badges, so an
62
+ // install that has streaks gets badges too.
63
+ const installed = manifest.modules.includes("streaks")
64
+ ? [...manifest.modules, "badges"]
65
+ : manifest.modules;
61
66
  const canonicalModules = options.addModules && options.addModules.length > 0
62
- ? (0, install_shared_1.resolveModules)([...manifest.modules, ...options.addModules], onWarn)
63
- : install_shared_1.MODULE_ORDER.filter((m) => manifest.modules.includes(m));
67
+ ? (0, install_shared_1.resolveModules)([...installed, ...options.addModules], onWarn)
68
+ : install_shared_1.MODULE_ORDER.filter((m) => installed.includes(m));
64
69
  const addedModules = canonicalModules.filter((m) => !manifest.modules.includes(m));
65
70
  const installedTemplateIds = new Set(manifest.installedTemplates ?? reconstructInstalledTemplateIds(manifest.installedFiles));
66
71
  const pending = [];
@@ -189,9 +194,12 @@ async function runUpgrade(options = {}) {
189
194
  const updatedManifest = {
190
195
  schemaVersion: manifest_1.CURRENT_SCHEMA_VERSION,
191
196
  sdkVersion: (0, install_shared_1.readOwnPackageVersion)(),
192
- // Only --add-modules rewrites the module list; a plain upgrade keeps the
193
- // manifest's own (order and any entry this CLI doesn't know).
194
- modules: options.addModules && options.addModules.length > 0 ? canonicalModules : manifest.modules,
197
+ // Only --add-modules (or a module brought along, like badges with streaks)
198
+ // rewrites the module list; a plain upgrade keeps the manifest's own (order
199
+ // and any entry this CLI doesn't know).
200
+ modules: (options.addModules && options.addModules.length > 0) || addedModules.length > 0
201
+ ? canonicalModules
202
+ : manifest.modules,
195
203
  installedFiles,
196
204
  installedTemplates: [...newInstalledTemplateIds].sort(),
197
205
  };
package/lib/index.js CHANGED
@@ -60,7 +60,7 @@ program
60
60
  program
61
61
  .command("init")
62
62
  .description("Copy the community backend into a Supabase project: migrations, Edge Functions, and a community-sdk.json manifest")
63
- .option("--modules <modules>", "comma-separated module list (core,push,polls,reaction,inbox,translation,images,streaks) — core is always implied; defaults to all modules")
63
+ .option("--modules <modules>", "comma-separated module list (core,push,polls,reaction,inbox,translation,images,attachments,badges,streaks) — core is always implied; defaults to all modules")
64
64
  .option("--project-url <url>", "Supabase project URL, e.g. https://<ref>.supabase.co — optional, only fills in the printed settings seed statement")
65
65
  .option("--anon-key <key>", "Supabase anon key — optional, only fills in the printed settings seed statement")
66
66
  .option("--dir <dir>", "target Supabase directory, relative to the current directory", "supabase")
@@ -103,7 +103,7 @@ program
103
103
  .command("adopt")
104
104
  .description("Register an already-live community backend (e.g. an app that hand-rolled its own before this SDK existed) with community-sdk.json, without copying any files")
105
105
  .requiredOption("--schema-version <n>", "the community-sdk schema version this app's live backend corresponds to")
106
- .requiredOption("--modules <modules>", "comma-separated module list (core,push,polls,reaction,inbox,translation,images,streaks) — core is always implied")
106
+ .requiredOption("--modules <modules>", "comma-separated module list (core,push,polls,reaction,inbox,translation,images,attachments,badges,streaks) — core is always implied")
107
107
  .option("--dir <dir>", "Supabase directory this app would use, relative to the current directory", "supabase")
108
108
  .action(async (opts) => {
109
109
  try {
@@ -10,7 +10,7 @@
10
10
  * single source of truth for module names, order, and the function sets
11
11
  * each module pulls in.
12
12
  */
13
- export declare const MODULE_ORDER: readonly ["core", "push", "polls", "reaction", "inbox", "translation", "images", "streaks"];
13
+ export declare const MODULE_ORDER: readonly ["core", "push", "polls", "reaction", "inbox", "translation", "images", "attachments", "badges", "streaks"];
14
14
  export type Module = (typeof MODULE_ORDER)[number];
15
15
  export declare function functionsForModules(modules: readonly Module[]): string[];
16
16
  /**
@@ -73,6 +73,9 @@ exports.MODULE_ORDER = [
73
73
  "inbox",
74
74
  "translation",
75
75
  "images",
76
+ "attachments",
77
+ "badges",
78
+ // Deprecated: kept to move existing streaks onto badges (streaks/002). Implies badges.
76
79
  "streaks",
77
80
  ];
78
81
  const ALWAYS_FUNCTIONS = [
@@ -111,8 +114,10 @@ function resolveModules(requested, onWarn) {
111
114
  throw new Error(`community-sdk: unknown module "${m}" (expected one of ${exports.MODULE_ORDER.join(", ")})`);
112
115
  }
113
116
  }
114
- // core is always required/implied.
117
+ // core is always required/implied; streaks/002 moves the streak onto badges.
115
118
  requestedSet.add("core");
119
+ if (requestedSet.has("streaks"))
120
+ requestedSet.add("badges");
116
121
  const canonicalModules = exports.MODULE_ORDER.filter((m) => requestedSet.has(m));
117
122
  if (canonicalModules.includes("inbox") && !canonicalModules.includes("reaction")) {
118
123
  onWarn("community-sdk: module 'inbox' selected without 'reaction' — reaction notifications won't appear in the inbox until the reaction module is also installed.");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rocapine/community",
3
- "version": "0.14.0",
3
+ "version": "0.15.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": {
@@ -2,6 +2,6 @@
2
2
  // deploys unchanged to every app. Push copy (actor fallback name, like /
3
3
  // comment / reaction titles) lives in _shared/copy.ts (COMMUNITY_PUSH_COPY).
4
4
 
5
- // Push title fallback for official broadcast posts whose author has no
6
- // username (normally the official account's display name).
5
+ // Push title fallback for admin broadcast posts whose author has no
6
+ // username (normally the admin account's display name).
7
7
  export const BROADCAST_FALLBACK_TITLE = Deno.env.get("COMMUNITY_APP_NAME") ?? "Community";
@@ -1,8 +1,11 @@
1
- // Broadcast push for an official dashboard post: Rocactopus invokes this with
2
- // the service-role key after composing a post with "Send push notification"
3
- // checked. Sends an Expo push to every registered token (batches of 100).
4
- // Guarded by a service-role check — the public anon key passes the platform's
5
- // verify_jwt but must NOT be able to trigger a broadcast.
1
+ // Broadcast push for an admin post. Two callers: the push module's trigger once a
2
+ // post an admin asked to send to everyone is visible (push/005_broadcast_trigger.sql,
3
+ // with the public anon key), or a dashboard with the service-role key. The anon key
4
+ // passes the platform's verify_jwt, so the body is untrusted: only `post_id` is
5
+ // read, and an anon call sends nothing unless the post's admin author asked for it
6
+ // (core/013_post_broadcasts.sql). `broadcast_at` is claimed before sending, so a
7
+ // post goes out once and the inbox lists exactly the posts that were sent.
8
+ // Sends an Expo push to every registered token (batches of 100) but the author's.
6
9
 
7
10
  import { adminClient, fetchAllRows, isServiceCaller } from "../_shared/client.ts";
8
11
  import { excerptOrPhoto, pushCopy } from "../_shared/copy.ts";
@@ -13,25 +16,32 @@ import { ensureTranslations, resolveTargetLocale, TARGET_LOCALES } from "../_sha
13
16
  const supabase = adminClient();
14
17
 
15
18
  Deno.serve(async (req) => {
16
- if (!isServiceCaller(req)) {
17
- return new Response("unauthorized", { status: 401 });
18
- }
19
-
20
- const { post_id } = (await req.json()) as { post_id?: string };
19
+ const service = isServiceCaller(req);
20
+ const { post_id } = (await req.json().catch(() => ({}))) as { post_id?: string };
21
21
  if (!post_id) return new Response("missing post_id", { status: 400 });
22
22
 
23
23
  const { data: post } = await supabase
24
24
  .from("posts")
25
- .select("id, author_id, content, status")
25
+ .select("id, author_id, content, status, broadcast_requested")
26
26
  .eq("id", post_id)
27
27
  .single();
28
28
  if (!post || post.status !== "visible") return new Response("skip: post not visible");
29
29
 
30
30
  const { data: author } = await supabase
31
31
  .from("profiles")
32
- .select("username")
32
+ .select("username, is_admin")
33
33
  .eq("id", post.author_id)
34
34
  .single();
35
+ if (!service && !(post.broadcast_requested && author?.is_admin)) {
36
+ return new Response("forbidden", { status: 403 });
37
+ }
38
+ const { data: claimed } = await supabase
39
+ .from("posts")
40
+ .update({ broadcast_at: new Date().toISOString() })
41
+ .eq("id", post.id)
42
+ .is("broadcast_at", null)
43
+ .select("id");
44
+ if (!claimed?.length) return new Response("skip: already sent");
35
45
  const title = author?.username?.trim() || BROADCAST_FALLBACK_TITLE;
36
46
 
37
47
  // waitMs: when translate-one holds the claim (it fires on the same insert),
@@ -61,7 +71,10 @@ Deno.serve(async (req) => {
61
71
  .order("user_id")
62
72
  .range(from, to),
63
73
  );
64
- const seen = new Set<string>();
74
+ // The author's own devices: their center never lists their own post.
75
+ const seen = new Set<string>(
76
+ rows.filter((r) => r.user_id === post.author_id).map((r) => r.expo_push_token as string),
77
+ );
65
78
  const messages = rows
66
79
  .map((r) => {
67
80
  const profile = Array.isArray(r.profiles) ? r.profiles[0] : r.profiles;
@@ -81,7 +94,7 @@ Deno.serve(async (req) => {
81
94
  to,
82
95
  title,
83
96
  body: excerptFor(locale, profileLocale),
84
- data: { route: "/community", kind: "community_official_post", postId: post.id },
97
+ data: { route: "/community", kind: "community_admin_post", postId: post.id },
85
98
  badge: 1,
86
99
  }));
87
100
  await sendExpoPushBatch(messages);
@@ -0,0 +1,28 @@
1
+ -- community-sdk attachments/001_attachments.sql (schema v1)
2
+ -- Attachments module: one reference to the app's own content per post (a verse, a
3
+ -- recipe, a session), `{ "type": "verse", "id": "43.3.16" }`. The post never stores a
4
+ -- URL, a title or an image: each reader's app draws the card from its own data, and
5
+ -- its button opens that content in the app. Which types exist, and who may attach,
6
+ -- is the app's configuration. Client-written: a shape and size check is the only
7
+ -- guard. Fully idempotent.
8
+
9
+ alter table public.posts add column if not exists attachment jsonb;
10
+
11
+ alter table public.posts drop constraint if exists posts_attachment_check;
12
+ alter table public.posts add constraint posts_attachment_check check (
13
+ attachment is null or (
14
+ jsonb_typeof(attachment) = 'object'
15
+ -- `?` first: a missing key would make jsonb_typeof null, which a check lets pass.
16
+ and attachment ? 'type'
17
+ and attachment ? 'id'
18
+ and jsonb_typeof(attachment -> 'type') = 'string'
19
+ and jsonb_typeof(attachment -> 'id') = 'string'
20
+ and octet_length(attachment::text) <= 512
21
+ )
22
+ );
23
+
24
+ -- The text stays required: pushes and inbox rows read an empty post as a photo.
25
+
26
+ -- Posts use column-scoped insert grants (core/002_rls.sql); extend them.
27
+ grant insert (attachment) on table public.posts to authenticated;
28
+ grant select (attachment) on table public.posts to anon, authenticated;
@@ -0,0 +1,25 @@
1
+ -- community-sdk badges/001_badges.sql (schema v1)
2
+ -- Badges module: app-defined badges on each profile (a streak, a pregnancy month,
3
+ -- a rank…), shown next to the author on posts and comments and on the profile.
4
+ -- The app writes `badges` (JSON keyed by its badge ids) for its own member; the
5
+ -- member writes `hidden_badges`, the ids they chose to hide. Readers only ever see
6
+ -- the generated `visible_badges`, so a hidden badge never leaves the database.
7
+ -- Client-written by design (the app computes the values on the device): a size and
8
+ -- shape check is the only guard. Fully idempotent.
9
+
10
+ alter table public.profiles
11
+ add column if not exists badges jsonb not null default '{}'::jsonb,
12
+ add column if not exists hidden_badges text[] not null default '{}';
13
+
14
+ alter table public.profiles drop constraint if exists profiles_badges_check;
15
+ alter table public.profiles add constraint profiles_badges_check
16
+ check (jsonb_typeof(badges) = 'object' and octet_length(badges::text) <= 2048);
17
+
18
+ alter table public.profiles
19
+ add column if not exists visible_badges jsonb
20
+ generated always as (badges - hidden_badges) stored;
21
+
22
+ -- Owners write their own row (RLS "update own profile"); the raw values stay
23
+ -- unreadable, everyone reads the visible ones and the hidden ids (the toggles).
24
+ grant update (badges, hidden_badges) on table public.profiles to authenticated;
25
+ grant select (visible_badges, hidden_badges) on public.profiles to anon, authenticated;
@@ -0,0 +1,35 @@
1
+ -- community-sdk core/011_admins.sql (schema v1)
2
+ -- "Official" accounts become admin accounts (`profiles.is_admin`), and the
3
+ -- posts insert policy no longer reserves the 'news' topic: which topics only
4
+ -- admins post in is the app's `adminOnly` config, applied by the SDK's UI.
5
+ --
6
+ -- Expand step, for app versions on SDK 0.14 or older:
7
+ -- - `is_official` stays, read-only and always equal to `is_admin`;
8
+ -- - list_notifications still names admin posts `official_post` (the only kind
9
+ -- those versions know); SDK 0.15 reads it as `admin_post`.
10
+ -- Contract step, once no such version is in use: drop `is_official`, and return
11
+ -- `admin_post` from list_notifications.
12
+
13
+ alter table public.profiles rename column is_official to is_admin;
14
+ alter table public.profiles
15
+ add column is_official boolean generated always as (is_admin) stored;
16
+ -- `is_admin` keeps the column grant `is_official` had (002_rls.sql).
17
+ grant select (is_official) on public.profiles to anon, authenticated;
18
+
19
+ create or replace function public.current_user_admin()
20
+ returns boolean
21
+ language sql stable security definer set search_path = public
22
+ as $$
23
+ select coalesce((select is_admin from profiles where id = auth.uid()), false);
24
+ $$;
25
+
26
+ drop policy "insert own posts if not banned" on public.posts;
27
+ create policy "insert own posts if not banned"
28
+ on public.posts for insert to authenticated
29
+ with check (
30
+ author_id = auth.uid()
31
+ and not public.current_user_banned()
32
+ and status = 'pending'
33
+ );
34
+
35
+ drop function public.current_user_official();
@@ -0,0 +1,19 @@
1
+ -- community-sdk core/012_pin_posts.sql (schema v1)
2
+ -- Admins pin and unpin posts from the app. `pinned_at` stays out of the client's
3
+ -- column grants; this function is the only client path to it. A pinned post leads
4
+ -- its feeds (newest pin first) until unpinned.
5
+
6
+ create or replace function public.set_post_pinned(p_post_id uuid, p_pinned boolean)
7
+ returns void
8
+ language plpgsql security definer set search_path = public
9
+ as $$
10
+ begin
11
+ if not public.current_user_admin() then
12
+ raise exception 'only admins pin posts' using errcode = '42501';
13
+ end if;
14
+ update posts set pinned_at = case when p_pinned then now() end where id = p_post_id;
15
+ end;
16
+ $$;
17
+
18
+ revoke execute on function public.set_post_pinned(uuid, boolean) from public, anon;
19
+ grant execute on function public.set_post_pinned(uuid, boolean) to authenticated;
@@ -0,0 +1,27 @@
1
+ -- community-sdk core/013_post_broadcasts.sql (schema v1)
2
+ -- "Notify everyone" for admin posts. An admin asks for it on their own post
3
+ -- (request_post_broadcast); the push module's broadcast-post sends it once the post
4
+ -- is visible, even when moderation publishes it later, and stamps `broadcast_at`.
5
+ -- The inbox lists an admin post only once it is stamped, so the notification
6
+ -- center shows exactly the admin posts that were pushed.
7
+ -- Both columns stay out of the client's grants; this function is the only client path.
8
+
9
+ alter table public.posts
10
+ add column if not exists broadcast_requested boolean not null default false,
11
+ add column if not exists broadcast_at timestamptz;
12
+
13
+ create or replace function public.request_post_broadcast(p_post_id uuid)
14
+ returns void
15
+ language plpgsql security definer set search_path = public
16
+ as $$
17
+ begin
18
+ if not public.current_user_admin() then
19
+ raise exception 'only admins notify everyone' using errcode = '42501';
20
+ end if;
21
+ update posts set broadcast_requested = true
22
+ where id = p_post_id and author_id = auth.uid();
23
+ end;
24
+ $$;
25
+
26
+ revoke execute on function public.request_post_broadcast(uuid) from public, anon;
27
+ grant execute on function public.request_post_broadcast(uuid) to authenticated;
@@ -0,0 +1,40 @@
1
+ -- community-sdk inbox/003_pushed_admin_posts.sql (schema v1)
2
+ -- The notification center is the history of the pushes: an admin post is listed
3
+ -- only once it was sent to everyone (`posts.broadcast_at`, core/013), dated when it
4
+ -- was sent. Admin posts that were never pushed leave the center. Same return shape
5
+ -- as before, so installed app versions read it unchanged.
6
+
7
+ create or replace function public.list_notifications(p_limit int default 50)
8
+ returns table (
9
+ id uuid,
10
+ kind text,
11
+ actor_id uuid,
12
+ actor_username text,
13
+ post_id uuid,
14
+ post_excerpt text,
15
+ created_at timestamptz
16
+ )
17
+ language sql stable security definer set search_path = public
18
+ as $$
19
+ (
20
+ select n.id, n.kind, n.actor_id, pr.username, n.post_id,
21
+ left(p.content, 140), n.created_at
22
+ from notifications n
23
+ left join profiles pr on pr.id = n.actor_id
24
+ left join posts p on p.id = n.post_id
25
+ where n.user_id = auth.uid()
26
+ and (n.post_id is null or p.status in ('visible', 'pending'))
27
+ )
28
+ union all
29
+ (
30
+ select p.id, 'official_post', p.author_id, pr.username, p.id,
31
+ left(p.content, 140), p.broadcast_at
32
+ from posts p
33
+ join profiles pr on pr.id = p.author_id
34
+ where p.status = 'visible' and p.broadcast_at is not null
35
+ and p.author_id <> auth.uid()
36
+ and p.broadcast_at > now() - interval '90 days'
37
+ )
38
+ order by created_at desc
39
+ limit p_limit;
40
+ $$;
@@ -0,0 +1,18 @@
1
+ -- community-sdk push/005_broadcast_trigger.sql (schema v1)
2
+ -- Sends an admin post to everyone (broadcast-post) once it is visible and was asked
3
+ -- for (core/013_post_broadcasts.sql): on a visible insert, on publication by
4
+ -- moderation, or when asked after publication. broadcast-post stamps `broadcast_at`
5
+ -- before sending, so a post goes out at most once.
6
+
7
+ create or replace function public.broadcast_post_webhook()
8
+ returns trigger language plpgsql security definer set search_path = public as $$
9
+ begin
10
+ perform public.community_call_function('broadcast-post', jsonb_build_object('post_id', new.id));
11
+ return new;
12
+ end; $$;
13
+
14
+ create or replace trigger on_post_broadcast_ready
15
+ after insert or update of status, broadcast_requested on public.posts
16
+ for each row
17
+ when (new.status = 'visible' and new.broadcast_requested and new.broadcast_at is null)
18
+ execute function public.broadcast_post_webhook();
@@ -0,0 +1,87 @@
1
+ -- community-sdk streaks/002_to_badges.sql (schema v1)
2
+ -- Moves the streak onto the badges module (badges/001 must run first): the current
3
+ -- streak becomes the `streak` badge ({ since }), the best one `bestStreak`
4
+ -- ({ days }), their toggles `hidden_badges`.
5
+ -- Expand step: the legacy columns stay, and a trigger keeps both forms equal in both
6
+ -- directions, so app builds still writing and reading the legacy columns keep
7
+ -- working next to the new ones. streaks/003 drops them once those builds are gone.
8
+ -- Fully idempotent.
9
+
10
+ update public.profiles set
11
+ badges = badges
12
+ || case when streak_started_at is not null
13
+ then jsonb_build_object('streak', jsonb_build_object('since', to_jsonb(streak_started_at)))
14
+ else '{}'::jsonb end
15
+ || case when best_streak_days is not null
16
+ then jsonb_build_object('bestStreak', jsonb_build_object('days', best_streak_days))
17
+ else '{}'::jsonb end,
18
+ hidden_badges = array(
19
+ select distinct h from unnest(
20
+ hidden_badges
21
+ || case when not show_streak then array['streak'] else '{}'::text[] end
22
+ || case when not show_best_streak then array['bestStreak'] else '{}'::text[] end
23
+ ) h
24
+ )
25
+ where streak_started_at is not null
26
+ or best_streak_days is not null
27
+ or not show_streak
28
+ or not show_best_streak;
29
+
30
+ create or replace function public.profiles_sync_legacy_streak()
31
+ returns trigger
32
+ language plpgsql
33
+ set search_path = ''
34
+ as $$
35
+ declare
36
+ legacy_changed boolean :=
37
+ (new.streak_started_at, new.best_streak_days) is distinct from (old.streak_started_at, old.best_streak_days);
38
+ legacy_shown_changed boolean :=
39
+ (new.show_streak, new.show_best_streak) is distinct from (old.show_streak, old.show_best_streak);
40
+ badges_changed boolean := new.badges is distinct from old.badges;
41
+ hidden_changed boolean := new.hidden_badges is distinct from old.hidden_badges;
42
+ begin
43
+ -- A new build wrote the badges: keep the legacy columns in step for old readers.
44
+ -- The badges win when one write carries both forms. A value that does not read as
45
+ -- a date or a day count leaves the legacy column empty rather than failing the write.
46
+ if badges_changed then
47
+ begin
48
+ new.streak_started_at := case when jsonb_typeof(new.badges -> 'streak' -> 'since') = 'string'
49
+ then (new.badges -> 'streak' ->> 'since')::timestamptz end;
50
+ exception when data_exception then
51
+ new.streak_started_at := null;
52
+ end;
53
+ begin
54
+ new.best_streak_days := case when jsonb_typeof(new.badges -> 'bestStreak' -> 'days') = 'number'
55
+ then greatest((new.badges -> 'bestStreak' ->> 'days')::numeric, 0)::int end;
56
+ exception when data_exception then
57
+ new.best_streak_days := null;
58
+ end;
59
+ -- An old build wrote the legacy values: rewrite the two streak badges.
60
+ elsif legacy_changed then
61
+ new.badges := (new.badges - 'streak' - 'bestStreak')
62
+ || case when new.streak_started_at is not null
63
+ then jsonb_build_object('streak', jsonb_build_object('since', to_jsonb(new.streak_started_at)))
64
+ else '{}'::jsonb end
65
+ || case when new.best_streak_days is not null
66
+ then jsonb_build_object('bestStreak', jsonb_build_object('days', new.best_streak_days))
67
+ else '{}'::jsonb end;
68
+ end if;
69
+
70
+ if hidden_changed then
71
+ new.show_streak := not ('streak' = any (new.hidden_badges));
72
+ new.show_best_streak := not ('bestStreak' = any (new.hidden_badges));
73
+ elsif legacy_shown_changed then
74
+ new.hidden_badges := array(
75
+ select h from unnest(new.hidden_badges) h where h not in ('streak', 'bestStreak')
76
+ )
77
+ || case when not new.show_streak then array['streak'] else '{}'::text[] end
78
+ || case when not new.show_best_streak then array['bestStreak'] else '{}'::text[] end;
79
+ end if;
80
+ return new;
81
+ end;
82
+ $$;
83
+
84
+ drop trigger if exists profiles_sync_legacy_streak on public.profiles;
85
+ create trigger profiles_sync_legacy_streak
86
+ before update on public.profiles
87
+ for each row execute function public.profiles_sync_legacy_streak();