Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(notifications): make the changelog newsletter an account-level preference
naveenkashaf025d576f63
diff --git a/apps/erp/app/modules/users/users.service.ts b/apps/erp/app/modules/users/users.service.tsindex ddc11f6940..8d26cd3521 100644--- a/apps/erp/app/modules/users/users.service.ts+++ b/apps/erp/app/modules/users/users.service.ts@@ -40,7 +40,12 @@ import {import { redis } from "@carbon/kv";import { sendEmail } from "@carbon/lib/email.server";import { getLogger } from "@carbon/logger";-import type { NotificationPreferenceChannel } from "@carbon/notifications";+import {+ isNotificationTopic,+ type NotificationPreferenceChannel,+ type NotificationTopic,+ notificationPreferenceCompanyId+} from "@carbon/notifications";import { datetime, getClientIp } from "@carbon/utils";import { now, parseAbsolute } from "@internationalized/date";import { render } from "@react-email/components";@@ -2427,11 +2432,25 @@ export async function getNotificationPreferences(userId: string,companyId: string) {- return client+ // This company's rows plus the user's account-level rows (companyId NULL).+ const rows = await client.from("notificationPreference")- .select("topic, channel, enabled")+ .select("companyId, topic, channel, enabled").eq("userId", userId)- .eq("companyId", companyId);+ .or(`companyId.eq.${companyId},companyId.is.null`);+ if (rows.error) return rows;+ return {+ ...rows,+ data: rows.data+ .filter(+ (row) =>+ row.companyId ===+ (isNotificationTopic(row.topic)+ ? notificationPreferenceCompanyId(row.topic, companyId)+ : companyId)+ )+ .map(({ topic, channel, enabled }) => ({ topic, channel, enabled }))+ };}export async function upsertNotificationPreference(@@ -2439,7 +2458,7 @@ export async function upsertNotificationPreference(preference: {userId: string;companyId: string;- topic: string;+ topic: NotificationTopic;channel: NotificationPreferenceChannel;enabled: boolean;}@@ -2447,6 +2466,10 @@ export async function upsertNotificationPreference(return client.from("notificationPreference").upsert({...preference,+ companyId: notificationPreferenceCompanyId(+ preference.topic,+ preference.companyId+ ),updatedAt: new Date().toISOString()},{ onConflict: "userId,companyId,channel,topic" }diff --git a/packages/database/AGENTS.md b/packages/database/AGENTS.mdindex 6a7f74fc54..ce04e6a1c9 100644--- a/packages/database/AGENTS.md+++ b/packages/database/AGENTS.md@@ -17,7 +17,12 @@ DB types, Supabase/Kysely clients, audit config, event system types, rate limiti`PRIMARY KEY ("id")` and no `createdBy`/`updatedBy`. A row belongs to one user and only thatuser writes it, so the audit columns would always repeat `userId`. They keep `companyId`(FK, `ON DELETE CASCADE`) for tenant attribution and the RLS rule `owner("userId")` +- `member("companyId")`. `pushSubscription` is unique per browser `endpoint`, not per company+ `member("companyId")`. `notificationPreference.companyId` is NULL for an account-level topic+ (only the changelog newsletter, `getNotificationTopicScope` in `@carbon/notifications`): one+ row per user, unique `NULLS NOT DISTINCT`, RLS `owner("userId")` alone for that row. No CHECK+ names the topics: `getNotificationTopicScope` is the only place that decides, and every reader+ and writer goes through `notificationPreferenceCompanyId`, so a row stored under the wrong scope+ (a per-company newsletter row from an older backup) is never read. `pushSubscription` is unique per browser `endpoint`, not per company(one browser, one owner); see `.ai/specs/2026-10-08-web-push-notifications.md`.It is intentionally NOT tenant-scoped so `selectWipeableTables` (company-backup.ts) cannotselect it and a company restore cannot erase it. A migration landing in this package isdiff --git a/packages/database/src/authz/manifest.ts b/packages/database/src/authz/manifest.tsindex 0b4cd9c6ce..3b74ffce3e 100644--- a/packages/database/src/authz/manifest.ts+++ b/packages/database/src/authz/manifest.ts@@ -1077,14 +1077,15 @@ export const manifest = {}),notification: policies({ select: owner("userId"), update: owner("userId") }),notificationDelivery: policies({ select: owner("userId") }),+ // A NULL companyId is an account-level preference (the changelog newsletter).notificationPreference: policies({- select: and(owner("userId"), member("companyId")),- insert: and(owner("userId"), member("companyId")),+ select: and(owner("userId"), or(isNull("companyId"), member("companyId"))),+ insert: and(owner("userId"), or(isNull("companyId"), member("companyId"))),update: {using: owner("userId"),- check: and(owner("userId"), member("companyId"))+ check: and(owner("userId"), or(isNull("companyId"), member("companyId")))},- delete: and(owner("userId"), member("companyId"))+ delete: and(owner("userId"), or(isNull("companyId"), member("companyId")))}),oauthClient: serviceOnly(),oauthCode: serviceOnly(),diff --git a/packages/database/supabase/migrations/20261019124417_account-notification-preferences.sql b/packages/database/supabase/migrations/20261019124417_account-notification-preferences.sqlnew file mode 100644index 0000000000..35faee9c6a--- /dev/null+++ b/packages/database/supabase/migrations/20261019124417_account-notification-preferences.sql@@ -0,0 +1,31 @@+-- The changelog newsletter is one email per person, not per company, so its+-- preference becomes one row per user with "companyId" NULL. Before this every+-- company held its own row: turning the newsletter off in one company left it+-- on in another, and the dispatcher mailed anyone with any enabled row.+-- Every other topic stays per company.+--+-- Which topics are account-level is decided in one place, the app's+-- getNotificationTopicScope (@carbon/notifications), not by a CHECK here, so a+-- later account-level topic needs no schema change: a row stored under the+-- wrong scope (a per-company newsletter row from an older backup) is never read.++ALTER TABLE "notificationPreference" ALTER COLUMN "companyId" DROP NOT NULL;++-- NULLS NOT DISTINCT, so a user has at most one account-level row per+-- (channel, topic); the upsert's ON CONFLICT relies on it.+ALTER TABLE "notificationPreference"+ DROP CONSTRAINT "notificationPreference_userId_companyId_channel_topic_key";+ALTER TABLE "notificationPreference"+ ADD CONSTRAINT "notificationPreference_userId_companyId_channel_topic_key"+ UNIQUE NULLS NOT DISTINCT ("userId", "companyId", "channel", "topic");++-- Each user keeps the switch they flipped last, from whichever company.+INSERT INTO "notificationPreference" ("userId", "companyId", "channel", "topic", "enabled", "updatedAt")+SELECT DISTINCT ON ("userId", "channel")+ "userId", NULL, "channel", "topic", "enabled", "updatedAt"+FROM "notificationPreference"+WHERE "topic" = 'changelog' AND "companyId" IS NOT NULL+ORDER BY "userId", "channel", "updatedAt" DESC, "id" DESC;++DELETE FROM "notificationPreference"+WHERE "topic" = 'changelog' AND "companyId" IS NOT NULL;diff --git a/packages/database/supabase/migrations/20261019124426_account-notification-preferences-rls.sql b/packages/database/supabase/migrations/20261019124426_account-notification-preferences-rls.sqlnew file mode 100644index 0000000000..d211203a7c--- /dev/null+++ b/packages/database/supabase/migrations/20261019124426_account-notification-preferences-rls.sql@@ -0,0 +1,18 @@+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.++-- Ships these rules to databases where `authz sync` does not run after migrations yet.++-- notificationPreference+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'notificationPreference' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'notificationPreference');+ END LOOP;+END+$authz$;+ALTER TABLE public."notificationPreference" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "public"."notificationPreference" FOR SELECT USING (("userId" = ((SELECT auth.uid()))::text AND ("companyId" IS NULL OR "companyId" IN (SELECT "userToCompany"."companyId" FROM "public"."userToCompany" WHERE "userId" = ((SELECT auth.uid()))::text))));+CREATE POLICY "INSERT" ON "public"."notificationPreference" FOR INSERT WITH CHECK (("userId" = ((SELECT auth.uid()))::text AND ("companyId" IS NULL OR "companyId" IN (SELECT "userToCompany"."companyId" FROM "public"."userToCompany" WHERE "userId" = ((SELECT auth.uid()))::text))));+CREATE POLICY "UPDATE" ON "public"."notificationPreference" FOR UPDATE USING ("userId" = ((SELECT auth.uid()))::text) WITH CHECK (("userId" = ((SELECT auth.uid()))::text AND ("companyId" IS NULL OR "companyId" IN (SELECT "userToCompany"."companyId" FROM "public"."userToCompany" WHERE "userId" = ((SELECT auth.uid()))::text))));+CREATE POLICY "DELETE" ON "public"."notificationPreference" FOR DELETE USING (("userId" = ((SELECT auth.uid()))::text AND ("companyId" IS NULL OR "companyId" IN (SELECT "userToCompany"."companyId" FROM "public"."userToCompany" WHERE "userId" = ((SELECT auth.uid()))::text))));diff --git a/packages/database/supabase/tests/notification-preference-account-topic.test.sql b/packages/database/supabase/tests/notification-preference-account-topic.test.sqlnew file mode 100644index 0000000000..9758b86b2c--- /dev/null+++ b/packages/database/supabase/tests/notification-preference-account-topic.test.sql@@ -0,0 +1,71 @@+-- Run from the repository root against an existing local database:+-- pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/notification-preference-account-topic.test.sql+-- All fixtures and role changes are confined to the rolled-back transaction.+\set ON_ERROR_STOP on+BEGIN;+SET LOCAL statement_timeout = '30s';++DO $proof$+DECLARE+ group_a text; company_a text; company_b text;+ user_id text := gen_random_uuid()::text;+ other_id text := gen_random_uuid()::text;+ n int;+BEGIN+ INSERT INTO "companyGroup" (name,"createdBy") VALUES ('Preference A '||id(),'system') RETURNING id INTO group_a;+ INSERT INTO company (name,"companyGroupId","baseCurrencyCode",timezone)+ VALUES ('Preference A',group_a,'USD','America/New_York') RETURNING id INTO company_a;+ INSERT INTO company (name,"companyGroupId","baseCurrencyCode",timezone)+ VALUES ('Preference B',group_a,'USD','America/New_York') RETURNING id INTO company_b;+ INSERT INTO "user" (id,email) VALUES+ (user_id, user_id||'@preference.invalid'),+ (other_id, other_id||'@preference.invalid');+ -- The user belongs to A only.+ INSERT INTO "userToCompany" ("userId","companyId",role) VALUES (user_id,company_a,'employee');++ -- A per-company newsletter row (an older backup's) is still accepted.+ INSERT INTO "notificationPreference" ("userId","companyId",channel,topic,enabled)+ VALUES (user_id,company_a,'email','changelog',true);++ PERFORM set_config('request.jwt.claims',jsonb_build_object('sub',user_id,'role','authenticated')::text,true);+ SET LOCAL ROLE authenticated;++ -- The upsert the account page sends, twice: one row, holding the last value.+ INSERT INTO "notificationPreference" ("userId","companyId",channel,topic,enabled)+ VALUES (user_id,NULL,'email','changelog',true)+ ON CONFLICT ("userId","companyId",channel,topic) DO UPDATE SET enabled = EXCLUDED.enabled;+ INSERT INTO "notificationPreference" ("userId","companyId",channel,topic,enabled)+ VALUES (user_id,NULL,'email','changelog',false)+ ON CONFLICT ("userId","companyId",channel,topic) DO UPDATE SET enabled = EXCLUDED.enabled;+ SELECT count(*) INTO n FROM "notificationPreference"+ WHERE "userId" = user_id AND "companyId" IS NULL AND topic = 'changelog' AND NOT enabled;+ ASSERT n = 1, 'The account-level newsletter row is one row per user';+ RAISE NOTICE 'PASS the newsletter upsert keeps one row per user';++ BEGIN+ INSERT INTO "notificationPreference" ("userId","companyId",channel,topic,enabled)+ VALUES (user_id,company_b,'email','job',false);+ RAISE EXCEPTION 'A preference was written for a company the user does not belong to';+ EXCEPTION WHEN insufficient_privilege THEN NULL;+ END;+ BEGIN+ INSERT INTO "notificationPreference" ("userId","companyId",channel,topic,enabled)+ VALUES (other_id,NULL,'email','changelog',true);+ RAISE EXCEPTION 'A user wrote another user''s newsletter preference';+ EXCEPTION WHEN insufficient_privilege THEN NULL;+ END;+ RAISE NOTICE 'PASS a user writes only their own rows, in their own companies';++ RESET ROLE;+ INSERT INTO "notificationPreference" ("userId","companyId",channel,topic,enabled)+ VALUES (other_id,NULL,'email','changelog',true);+ PERFORM set_config('request.jwt.claims',jsonb_build_object('sub',user_id,'role','authenticated')::text,true);+ SET LOCAL ROLE authenticated;+ SELECT count(*) INTO n FROM "notificationPreference" WHERE "userId" = other_id;+ ASSERT n = 0, 'Another user''s newsletter row is not readable';+ RAISE NOTICE 'PASS another user''s newsletter row is not readable';+ RESET ROLE;+END+$proof$;++ROLLBACK;diff --git a/packages/jobs/src/inngest/functions/notifications/notify.ts b/packages/jobs/src/inngest/functions/notifications/notify.tsindex b35881ba3d..febea7efff 100644--- a/packages/jobs/src/inngest/functions/notifications/notify.ts+++ b/packages/jobs/src/inngest/functions/notifications/notify.ts@@ -27,6 +27,7 @@ import {isRecurringNotificationEvent,NotificationDestination,NotificationEvent,+ notificationPreferenceCompanyId,renderInlineLinks,renderSlackMrkdwn} from "@carbon/notifications";@@ -380,20 +381,30 @@ export const notifyFunction = inngest.createFunction(// Per-user channel opt-outs: absence of a row = enabled; enabled=false// mutes that (topic, channel). In-app delivery is never filtered.+ // An account-level topic's row has no company.+ const preferenceCompanyId = notificationPreferenceCompanyId(+ topic,+ payload.companyId+ );const { emailRecipientIds, slackRecipientIds } =wantsEmail || wantsSlack? await step.run("filter-recipients-by-preference", async () => {const { data: prefs, error } = await fetchAllByIds(userIds,- (batch) =>- client+ (batch) => {+ const query = client.from("notificationPreference").select("userId, channel, enabled").in("userId", batch)- .eq("companyId", payload.companyId)- .eq("topic", topic)+ .eq("topic", topic);+ return (+ preferenceCompanyId === null+ ? query.is("companyId", null)+ : query.eq("companyId", preferenceCompanyId)+ ).order("userId")- .order("channel")+ .order("channel");+ });if (error) {console.error("Failed to load notification preferences", error);diff --git a/packages/jobs/src/inngest/functions/tasks/changelog-dispatch.ts b/packages/jobs/src/inngest/functions/tasks/changelog-dispatch.tsindex 4ca31c746e..513cdac2e1 100644--- a/packages/jobs/src/inngest/functions/tasks/changelog-dispatch.ts+++ b/packages/jobs/src/inngest/functions/tasks/changelog-dispatch.ts@@ -41,8 +41,8 @@ const MANAGE_URL = `${ERP_URL.replace(/\/$/, "")}/x/account/notifications`;type DispatchPlan = ReturnType<typeof planDispatch>;-// The preference is per company but the newsletter is not, so a user opted in-// from two companies still gets one email.+// The newsletter preference is account-level: one row per user with+// "companyId" NULL, whichever company they turned it on from.async function getNewsletterRecipients(): Promise<string[]> {const db = getJobDatabaseClient();const rows = await db@@ -51,6 +51,7 @@ async function getNewsletterRecipients(): Promise<string[]> {.select(["user.email as email"]).where("notificationPreference.topic", "=", NotificationTopic.Changelog).where("notificationPreference.channel", "=", "email")+ .where("notificationPreference.companyId", "is", null).where("notificationPreference.enabled", "=", true).where("user.active", "=", true).distinct()diff --git a/packages/notifications/AGENTS.md b/packages/notifications/AGENTS.mdindex ffe2c4dbf4..1c91c0999d 100644--- a/packages/notifications/AGENTS.md+++ b/packages/notifications/AGENTS.md@@ -27,7 +27,7 @@ pnpm --filter @carbon/notifications typecheck # tsgo --noEmit## Key Patterns-- **Enums + pure mapping helpers, no I/O** — `NotificationEvent`, `NotificationTopic`, `NotificationDestination`; `getNotificationTopic`, email heading/CTA helpers, and `USER_FACING_NOTIFICATION_TOPICS` (display order for the account notification-settings page — when adding a `NotificationTopic`, add it here too or it won't appear on that page), plus `getNotificationTopicChannels` (which switches a topic's row offers) and `isNotificationTopicEnabledByDefault` (what no preference row means — `false` only for the opt-in, email-only `Changelog` newsletter)+- **Enums + pure mapping helpers, no I/O** — `NotificationEvent`, `NotificationTopic`, `NotificationDestination`; `getNotificationTopic`, email heading/CTA helpers, and `USER_FACING_NOTIFICATION_TOPICS` (display order for the account notification-settings page — when adding a `NotificationTopic`, add it here too or it won't appear on that page), plus `getNotificationTopicChannels` (which switches a topic's row offers) and `isNotificationTopicEnabledByDefault` (what no preference row means — `false` only for the opt-in, email-only `Changelog` newsletter), `getNotificationTopicScope` (`account` only for `Changelog`: one setting across all the user's companies) and `notificationPreferenceCompanyId` (the `companyId` a topic's `notificationPreference` row is stored under — `null` for an account topic — used by every reader and writer: `users.service.ts` and the `notify` fan-out). Both take a `NotificationTopic`; narrow a stored `topic` (a TEXT column) with `isNotificationTopic` first. **Making a topic account-level** is one arm in `getNotificationTopicScope` plus a data migration that folds its per-company rows into one NULL row per user (copy the backfill in `20261019124417_account-notification-preferences.sql`); no schema, RLS or reader change. The changelog dispatcher is the one reader that names its topic- **Body rendering lives here, all three renditions together** — `renderInlineLinks` (the strict `[label](https://origin/…)` matcher; a security boundary, since a workflow's message body is customer-authored) plus `renderSlackMrkdwn` / `escapeSlackText` for the Slack rendition. The in-app topbar and `NotificationEmail.tsx` consume the segments directly. A fourth channel adds its rendition beside these, not in the fan-out job- **`NotificationEvent.Workflow` is the payload-text kind** — every other event's content is read from its source document; this one carries `title` / `body` on the `carbon/notify` payload and reads nothing. Raised by the workflows notify action (`packages/jobs/src/workflows/actions/notify.ts`), topic `General`- **inApp is always included** — regardless of caller-specified destinationsdiff --git a/packages/notifications/src/index.test.ts b/packages/notifications/src/index.test.tsindex 435359ea24..8bc0096b49 100644--- a/packages/notifications/src/index.test.ts+++ b/packages/notifications/src/index.test.ts@@ -5,8 +5,11 @@import { describe, expect, it } from "vitest";import {getNotificationTopicChannels,+ getNotificationTopicScope,+ isNotificationTopic,isNotificationTopicEnabledByDefault,NotificationTopic,+ notificationPreferenceCompanyId,renderInlineLinks,renderSlackMrkdwn,USER_FACING_NOTIFICATION_TOPICS@@ -115,6 +118,13 @@ describe("notification topic settings", () => {]);});+ it("scopes only the newsletter to the account", () => {+ expect(getNotificationTopicScope(NotificationTopic.Changelog)).toBe(+ "account"+ );+ expect(getNotificationTopicScope(NotificationTopic.Job)).toBe("company");+ });+it("treats a missing preference as off only for the opt-in newsletter", () => {expect(isNotificationTopicEnabledByDefault(NotificationTopic.Changelog)@@ -125,3 +135,27 @@ describe("notification topic settings", () => {}});});++describe("notificationPreferenceCompanyId", () => {+ it("stores the newsletter once per person", () => {+ expect(+ notificationPreferenceCompanyId(NotificationTopic.Changelog, "c1")+ ).toBeNull();+ });++ it("stores every other topic per company", () => {+ for (const topic of USER_FACING_NOTIFICATION_TOPICS) {+ if (topic === NotificationTopic.Changelog) continue;+ expect(notificationPreferenceCompanyId(topic, "c1")).toBe("c1");+ }+ });+});++describe("isNotificationTopic", () => {+ it("accepts every topic and nothing else", () => {+ for (const topic of Object.values(NotificationTopic)) {+ expect(isNotificationTopic(topic)).toBe(true);+ }+ expect(isNotificationTopic("not-a-topic")).toBe(false);+ });+});diff --git a/packages/notifications/src/index.ts b/packages/notifications/src/index.tsindex e8363f5247..9174b1cac0 100644--- a/packages/notifications/src/index.ts+++ b/packages/notifications/src/index.ts@@ -134,6 +134,41 @@ export function isNotificationTopicEnabledByDefault(}}+// Who a topic's preference belongs to. A company topic is set per company. An+// account topic belongs to the person (the newsletter is the same email from+// every company), so one switch covers every company they belong to.+export type NotificationTopicScope = "company" | "account";++export function getNotificationTopicScope(+ topic: NotificationTopic+): NotificationTopicScope {+ switch (topic) {+ case NotificationTopic.Changelog:+ return "account";+ default:+ return "company";+ }+}++// The companyId a topic's preference row is stored under, read and written:+// null for an account topic, the current company otherwise. A per-company row+// of an account topic (left by a backup older than the change) is never read.+export function notificationPreferenceCompanyId(+ topic: NotificationTopic,+ companyId: string+): string | null {+ return getNotificationTopicScope(topic) === "account" ? null : companyId;+}++const NOTIFICATION_TOPICS: ReadonlySet<string> = new Set(+ Object.values(NotificationTopic)+);++// Narrows a stored `topic` (a TEXT column) to the enum.+export function isNotificationTopic(value: string): value is NotificationTopic {+ return NOTIFICATION_TOPICS.has(value);+}+// What a Recurring invoicing notification lists, which decides where its link// lands: the sales invoices the run posted or held, or the lease purchase// invoices it drafted. The two are never mixed in one notification.