Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

ralph(M6-005): notification module into core: service + trpc + notification queue + worker job

ralphd0ee3fc3fd55
diff --git a/apps/worker/src/jobs/notification.ts b/apps/worker/src/jobs/notification.ts
index ff78c031b..ad3161de8 100644
--- a/apps/worker/src/jobs/notification.ts
+++ b/apps/worker/src/jobs/notification.ts
@@ -1,105 +1,15 @@
-import { getServerIntegration } from '@openpanel/core';
-import { db, Prisma } from '@openpanel/db';
-import { sendEmail } from '@openpanel/email';
+// Dissolved into @openpanel/core's notification module (M6-005): the
+// dispatch/delivery body moved to
+// packages/core/src/modules/notification/notification.service.ts. This file
+// stays (DELEGATE PATTERN) — it is the BullMQ job body V1's worker registers
+// (boot-workers.ts), a thin wrapper around the core function.
+import { deliverNotification } from '@openpanel/core';
import type { NotificationQueuePayload } from '@openpanel/queue';
-import { publishEvent } from '@openpanel/redis';
import type { Job } from 'bullmq';
-function isValidJson<T>(
- value: T | Prisma.NullableJsonNullValueInput | null | undefined
-): value is T {
- return (
- value !== null &&
- value !== undefined &&
- value !== Prisma.JsonNull &&
- value !== Prisma.DbNull
- );
-}
-
-export async function notificationJob(job: Job<NotificationQueuePayload>) {
+export function notificationJob(job: Job<NotificationQueuePayload>) {
switch (job.data.type) {
- case 'sendNotification': {
- const { notification } = job.data.payload;
-
- // App + email are pseudo-integrations dispatched by flags, not real rows.
- if (notification.sendToApp) {
- publishEvent('notification', 'created', notification);
- return;
- }
-
- if (notification.sendToEmail) {
- const project = await db.project.findUniqueOrThrow({
- where: { id: notification.projectId },
- select: { name: true, organizationId: true },
- });
- const members = await db.member.findMany({
- where: {
- organizationId: project.organizationId,
- user: { deletedAt: null },
- },
- include: { user: { select: { email: true } } },
- });
- const emails = new Set(
- members.flatMap((member) =>
- member.user?.email ? [member.user.email] : []
- )
- );
- for (const to of emails) {
- // Per-recipient unsubscribe (product_alerts category) is handled
- // inside sendEmail.
- await sendEmail('notification-rule', {
- to,
- data: {
- title: notification.title,
- message: notification.message,
- projectName: project.name,
- dashboardUrl: `${process.env.DASHBOARD_URL ?? 'https://dashboard.openpanel.dev'}/${project.organizationId}/${notification.projectId}`,
- },
- });
- }
- return;
- }
-
- if (!notification.integrationId) {
- throw new Error('No integrationId provided');
- }
-
- const integration = await db.integration.findUniqueOrThrow({
- where: {
- id: notification.integrationId,
- },
- });
-
- const payload = notification.payload;
-
- if (!isValidJson(payload)) {
- return new Error('Invalid payload');
- }
-
- // An integration whose config is still empty (e.g. a Slack integration
- // before its OAuth callback fills the config) has no type yet — nothing
- // to deliver to.
- if (!integration.config?.type) {
- return;
- }
-
- // Generic registry dispatch — no per-type switch. A new notification
- // integration just registers a `notification.deliver` plugin.
- const plugin = getServerIntegration(integration.config.type);
- if (!plugin.notification) {
- throw new Error(
- `Integration ${integration.config.type} is not a notification sink`
- );
- }
-
- return plugin.notification.deliver({
- config: integration.config,
- notification: {
- title: notification.title,
- message: notification.message,
- },
- payload,
- });
- }
+ case 'sendNotification':
+ return deliverNotification(job.data.payload.notification);
}
}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index f91fbe4f2..bcfdda231 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -404,6 +404,38 @@ export {
updateOrganization,
updateOrganizationMemberAccess,
} from './modules/organization/organization.service';
+// Dissolved from @openpanel/db's services/notification.service.ts (M6-005,
+// "rules + dispatch stay together") — packages/trpc's notification router,
+// packages/db's own enqueue orchestration (createNotification et al, which
+// stays there — see that file's header for why) and apps/worker's
+// notification job all call these directly, the same way V1 reaches every
+// other dissolved service here. packages/db/src/services/notification.service.ts
+// stays a re-export shim for the pieces that moved.
+export type {
+ INotificationPayload,
+ INotificationRuleCached,
+ NotificationService,
+} from './modules/notification/notification.service';
+export {
+ APP_NOTIFICATION_INTEGRATION_ID,
+ BASE_INTEGRATIONS,
+ createNotificationService,
+ createOrUpdateNotificationRule,
+ deleteNotificationRule,
+ deliverNotification,
+ EMAIL_NOTIFICATION_INTEGRATION_ID,
+ getFunnelRules,
+ getHasFunnelRules,
+ getNotificationRuleByIdOrThrow,
+ getNotificationRulesByProjectId,
+ isBaseIntegration,
+ listNotificationRules,
+ listNotifications,
+ matchEvent,
+ matchEventFilters,
+ notificationTemplateEvent,
+ notificationTemplateFunnel,
+} from './modules/notification/notification.service';
// Dissolved from @openpanel/db's services/project.service.ts (M6-002) —
// packages/trpc's project router, apps/api's manage controller and several
// core modules' `src/access.ts` call these directly, the same way V1
diff --git a/packages/core/src/jobs.registry.test.ts b/packages/core/src/jobs.registry.test.ts
index dba1f1b26..082df1e9e 100644
--- a/packages/core/src/jobs.registry.test.ts
+++ b/packages/core/src/jobs.registry.test.ts
@@ -166,3 +166,15 @@ test('the import queue carries the import module job', () => {
name: 'import',
});
});
+
+// M6-005: the notification module's own job. No cron fragment — notifications
+// are always triggered by a rule match, never scheduled. legacyCompat.notification
+// already discriminates on this exact name (jobs/compat.ts), so this pins the
+// two in agreement.
+test('the notification queue carries the notification module job', () => {
+ expect(Object.keys(queues.notification.jobs)).toEqual(['sendNotification']);
+ expect(queues.notification.jobs.sendNotification).toMatchObject({
+ queue: 'notification',
+ name: 'sendNotification',
+ });
+});
diff --git a/packages/core/src/jobs.registry.ts b/packages/core/src/jobs.registry.ts
index e288f36b5..13ba6f32c 100644
--- a/packages/core/src/jobs.registry.ts
+++ b/packages/core/src/jobs.registry.ts
@@ -21,6 +21,7 @@ import {
insightCronJobs,
insightQueueJobs,
} from './modules/insight/insight.jobs';
+import { notificationQueueJobs } from './modules/notification/notification.jobs';
import { onboardingCronJobs } from './modules/onboarding/onboarding.jobs';
import { organizationCronJobs } from './modules/organization/organization.jobs';
@@ -69,7 +70,9 @@ const notification = defineQueue('notification', {
defaults: { removeOnComplete: 10 },
worker: { concurrency: CONCURRENCY.notification },
compat: legacyCompat.notification,
- jobs: {},
+ jobs: {
+ ...notificationQueueJobs,
+ },
});
const importQueue = defineQueue('import', {
diff --git a/packages/core/src/modules/cohort/cohort.jobs.test.ts b/packages/core/src/modules/cohort/cohort.jobs.test.ts
index 7cebe5a0f..79091c719 100644
--- a/packages/core/src/modules/cohort/cohort.jobs.test.ts
+++ b/packages/core/src/modules/cohort/cohort.jobs.test.ts
@@ -31,6 +31,7 @@ function stubLogger(): Logger {
function stubJobCtx(cohort: Partial<CohortService>, jobName = 'test'): JobCtx {
const services: Services = {
auth: {} as Services['auth'],
+ notification: {} as Services['notification'],
insight: {} as Services['insight'],
gsc: {} as Services['gsc'],
import: {} as Services['import'],
diff --git a/packages/core/src/modules/gsc/gsc.jobs.test.ts b/packages/core/src/modules/gsc/gsc.jobs.test.ts
index 2d56b0adf..ed72684bb 100644
--- a/packages/core/src/modules/gsc/gsc.jobs.test.ts
+++ b/packages/core/src/modules/gsc/gsc.jobs.test.ts
@@ -27,6 +27,7 @@ function stubLogger(): Logger {
function stubJobCtx(gsc: Partial<GscService>, jobName = 'test'): JobCtx {
const services: Services = {
auth: {} as Services['auth'],
+ notification: {} as Services['notification'],
insight: {} as Services['insight'],
cohort: {} as Services['cohort'],
import: {} as Services['import'],
@@ -121,6 +122,7 @@ test('gscSync fans out one gscProjectSync enqueue per connected project', async
queues: producers.queues,
services: {
auth: {} as Services['auth'],
+ notification: {} as Services['notification'],
insight: {} as Services['insight'],
cohort: {} as Services['cohort'],
import: {} as Services['import'],
diff --git a/packages/core/src/modules/import/import.jobs.test.ts b/packages/core/src/modules/import/import.jobs.test.ts
index a90f39943..fd40f4801 100644
--- a/packages/core/src/modules/import/import.jobs.test.ts
+++ b/packages/core/src/modules/import/import.jobs.test.ts
@@ -27,6 +27,7 @@ function stubLogger(): Logger {
function stubJobCtx(importService: Partial<ImportService>): JobCtx {
const services: Services = {
auth: {} as Services['auth'],
+ notification: {} as Services['notification'],
insight: {} as Services['insight'],
cohort: {} as Services['cohort'],
gsc: {} as Services['gsc'],
diff --git a/packages/core/src/modules/insight/insight.jobs.test.ts b/packages/core/src/modules/insight/insight.jobs.test.ts
index b99271198..bbbdc84e4 100644
--- a/packages/core/src/modules/insight/insight.jobs.test.ts
+++ b/packages/core/src/modules/insight/insight.jobs.test.ts
@@ -38,6 +38,7 @@ function stubJobCtx(
): JobCtx {
const services: Services = {
auth: {} as Services['auth'],
+ notification: {} as Services['notification'],
insight: insight as InsightService,
gsc: {} as Services['gsc'],
cohort: {} as Services['cohort'],
@@ -115,6 +116,7 @@ test('insightsDaily fans out one insightsProject enqueue per candidate, jobId de
queues: producers.queues,
services: {
auth: {} as Services['auth'],
+ notification: {} as Services['notification'],
insight: {
listDailyInsightCandidates: async (date) => [
{ projectId: 'p1', date },
diff --git a/packages/core/src/modules/notification/notification.constants.ts b/packages/core/src/modules/notification/notification.constants.ts
new file mode 100644
index 000000000..dc45d813e
--- /dev/null
+++ b/packages/core/src/modules/notification/notification.constants.ts
@@ -0,0 +1,158 @@
+// Moved from packages/validation/src/index.ts (M6-005, ADR-008's module map:
+// notification owns "C"). packages/validation/src/index.ts becomes a
+// re-export shim of this file (same shape as ./onboarding.constants.ts since
+// M6-003), so packages/trpc's notification router and apps/start's
+// notification rule form keep resolving these symbols through
+// @openpanel/validation's existing barrel unchanged.
+//
+// `zChartEvent`/`zChartEventFilter` are chart/report vocabulary that has not
+// moved to core yet (ADR-008's "report" module is a later wave), so per
+// `constants-stay-isomorphic` (zod, another `*.constants.ts`, or type-only —
+// nothing else) they cannot be value-imported from @openpanel/validation
+// here. Diverged local copy instead, same treatment as
+// ./modules/cohort/cohort.constants.ts's zChartEventFilter since M5-003 —
+// including inlining `operators`/`chartSegments`/`filterValueTypes` as
+// literal key tuples rather than importing them from @openpanel/constants.
+// TODO(report module): once report.constants.ts exists, delete this
+// duplicate and import zChartEvent from there instead.
+//
+// Isomorphic by the AGENTS.md rule otherwise: zod and nothing else.
+
+import { z } from 'zod';
+
+const CHART_EVENT_FILTER_OPERATORS = [
+ 'is',
+ 'isNot',
+ 'contains',
+ 'doesNotContain',
+ 'startsWith',
+ 'endsWith',
+ 'regex',
+ 'isNull',
+ 'isNotNull',
+ 'gt',
+ 'lt',
+ 'gte',
+ 'lte',
+ 'inCohort',
+ 'notInCohort',
+] as const;
+
+const CHART_EVENT_FILTER_VALUE_TYPES = [
+ 'string',
+ 'number',
+ 'date',
+ 'datetime',
+ 'boolean',
+] as const;
+
+const CHART_EVENT_SEGMENTS = [
+ 'event',
+ 'user',
+ 'session',
+ 'group',
+ 'user_average',
+ 'one_event_per_user',
+ 'property_sum',
+ 'property_average',
+ 'property_max',
+ 'property_min',
+] as const;
+
+const zChartEventFilter = z.object({
+ id: z.string().optional().describe('Unique identifier for the filter'),
+ name: z.string().describe('The property name to filter on'),
+ operator: z
+ .enum(CHART_EVENT_FILTER_OPERATORS)
+ .describe('The operator to use for the filter'),
+ value: z
+ .array(z.string().or(z.number()).or(z.boolean()).or(z.null()))
+ .describe('The values to filter on'),
+ type: z
+ .enum(CHART_EVENT_FILTER_VALUE_TYPES)
+ .optional()
+ .describe(
+ 'Cast type for the column/value in equality & comparison operators ' +
+ '(string/number/date/datetime/boolean). Absent = legacy behavior.'
+ ),
+ cohortId: z
+ .string()
+ .optional()
+ .describe(
+ 'DEPRECATED: legacy single-cohort id, kept for saved reports. ' +
+ 'New code reads cohortIds via getCohortIds(filter).'
+ ),
+ cohortIds: z
+ .array(z.string())
+ .optional()
+ .describe(
+ 'Cohort IDs for inCohort/notInCohort. Multiple ids OR-match ' +
+ '(matches profiles in any of the listed cohorts).'
+ ),
+});
+
+const zChartEventSegment = z
+ .enum(CHART_EVENT_SEGMENTS)
+ .default('event')
+ .describe('Defines how the event data should be segmented or aggregated');
+
+const zChartEvent = z.object({
+ id: z
+ .string()
+ .optional()
+ .describe('Unique identifier for the chart event configuration'),
+ name: z.string().describe('The name of the event as tracked in the system'),
+ displayName: z
+ .string()
+ .optional()
+ .describe('A user-friendly name for display purposes'),
+ property: z
+ .string()
+ .optional()
+ .describe(
+ 'Optional property of the event used for specific segment calculations (e.g., value for property_sum/average)'
+ ),
+ segment: zChartEventSegment,
+ filters: z
+ .array(zChartEventFilter)
+ .default([])
+ .describe('Filters applied specifically to this event'),
+});
+
+export const zNotificationRuleEventConfig = z.object({
+ type: z.literal('events'),
+ events: z.array(zChartEvent),
+});
+
+export type INotificationRuleEventConfig = z.infer<
+ typeof zNotificationRuleEventConfig
+>;
+
+export const zNotificationRuleFunnelConfig = z.object({
+ type: z.literal('funnel'),
+ events: z.array(zChartEvent).min(1),
+});
+
+export type INotificationRuleFunnelConfig = z.infer<
+ typeof zNotificationRuleFunnelConfig
+>;
+
+export const zNotificationRuleConfig = z.discriminatedUnion('type', [
+ zNotificationRuleEventConfig,
+ zNotificationRuleFunnelConfig,
+]);
+
+export type INotificationRuleConfig = z.infer<typeof zNotificationRuleConfig>;
+
+export const zCreateNotificationRule = z.object({
+ id: z.string().optional(),
+ name: z.string().min(1),
+ template: z.string().optional(),
+ config: zNotificationRuleConfig,
+ integrations: z.array(z.string()),
+ sendToApp: z.boolean(),
+ sendToEmail: z.boolean(),
+ projectId: z.string(),
+});
+
+export type ICreateNotificationRule = z.infer<typeof zCreateNotificationRule>;
diff --git a/packages/core/src/modules/notification/notification.jobs.test.ts b/packages/core/src/modules/notification/notification.jobs.test.ts
new file mode 100644
index 000000000..a638f0279
--- /dev/null
+++ b/packages/core/src/modules/notification/notification.jobs.test.ts
@@ -0,0 +1,104 @@
+// Job wiring — no ClickHouse/Postgres touched. The rule matching and
+// dispatch logic themselves are exercised in notification.service.test.ts.
+
+import { expect, test } from 'bun:test';
+import type { JobCtx } from '../../context';
+import { createRecordingProducers } from '../../jobs/testing';
+import { queues } from '../../jobs.registry';
+import type { Logger } from '../../logger';
+import type { Services } from '../../services';
+import { notificationQueueJobs } from './notification.jobs';
+import type { NotificationService } from './notification.service';
+
+function stubLogger(): Logger {
+ const noop = () => undefined;
+ const logger: Logger = {
+ fatal: noop,
+ error: noop,
+ warn: noop,
+ info: noop,
+ debug: noop,
+ trace: noop,
+ child: () => logger,
+ };
+ return logger;
+}
+
+function stubJobCtx(notification: Partial<NotificationService>): JobCtx {
+ const services: Services = {
+ auth: {} as Services['auth'],
+ notification: notification as NotificationService,
+ insight: {} as Services['insight'],
+ cohort: {} as Services['cohort'],
+ gsc: {} as Services['gsc'],
+ import: {} as Services['import'],
+ organization: {} as Services['organization'],
+ onboarding: {} as Services['onboarding'],
+ };
+ return {
+ db: {},
+ ch: {},
+ redis: {},
+ clients: {},
+ buffers: {},
+ logger: stubLogger(),
+ queues: createRecordingProducers(queues).queues,
+ services,
+ requestId: 'req_1',
+ job: { id: 'job_1', attempt: 0, queue: 'notification', name: 'sendNotification' },
+ };
+}
+
+test('the notification queue declares exactly the sendNotification job', () => {
+ expect(Object.keys(notificationQueueJobs)).toEqual(['sendNotification']);
+ expect(queues.notification.jobs.sendNotification).toMatchObject({
+ queue: 'notification',
+ name: 'sendNotification',
+ });
+});
+
+test('sendNotification validates its payload', () => {
+ expect(() =>
+ notificationQueueJobs.sendNotification.payload.parse({})
+ ).toThrow();
+ expect(
+ notificationQueueJobs.sendNotification.payload.parse({
+ notification: {
+ projectId: 'proj_1',
+ title: 'Hello',
+ message: 'World',
+ },
+ })
+ ).toEqual({
+ notification: {
+ projectId: 'proj_1',
+ title: 'Hello',
+ message: 'World',
+ },
+ });
+});
+
+test('sendNotification delegates to ctx.services.notification.dispatch', async () => {
+ const calls: unknown[] = [];
+ const ctx = stubJobCtx({
+ dispatch: async (notification) => {
+ calls.push(notification);
+ },
+ });
+
+ await notificationQueueJobs.sendNotification.handler({
+ payload: {
+ notification: {
+ projectId: 'proj_1',
+ title: 'Hello',
+ message: 'World',
+ sendToApp: true,
+ },
+ },
+ ctx,
+ });
+
+ expect(calls).toEqual([
+ { projectId: 'proj_1', title: 'Hello', message: 'World', sendToApp: true },
+ ]);
+});
diff --git a/packages/core/src/modules/notification/notification.jobs.ts b/packages/core/src/modules/notification/notification.jobs.ts
new file mode 100644
index 000000000..154a0657a
--- /dev/null
+++ b/packages/core/src/modules/notification/notification.jobs.ts
@@ -0,0 +1,43 @@
+// Ported from apps/worker/src/jobs/notification.ts (M6-005).
+//
+// `sendNotification` is this module's own queue (`notification` in the
+// registry — ADR-005's registry key). legacyCompat.notification already
+// discriminates on this exact job name (jobs/compat.ts), so this pins the two
+// in agreement. No cron fragment — notifications are always triggered by a
+// rule match, never scheduled.
+
+import type { Prisma } from '@openpanel/db/src/prisma-client';
+import { z } from 'zod';
+import { defineJob } from '../../jobs/define';
+
+// A loose mirror of `Prisma.NotificationUncheckedCreateInput` — the payload
+// is a Prisma create input on the wire (packages/queue/src/queues.ts's
+// `NotificationQueuePayload`), and BullMQ stores job data as JSON, so this
+// only needs to survive that round-trip, not model every Prisma input
+// variant.
+const notificationPayload = z.object({
+ id: z.string().optional(),
+ projectId: z.string(),
+ title: z.string(),
+ message: z.string(),
+ sendToApp: z.boolean().optional(),
+ sendToEmail: z.boolean().optional(),
+ integrationId: z.string().nullable().optional(),
+ notificationRuleId: z.string().nullable().optional(),
+ payload: z.unknown().optional(),
+});
+
+/** The `notification` queue's own job. */
+export const notificationQueueJobs = {
+ sendNotification: defineJob({
+ payload: z.object({ notification: notificationPayload }),
+ handler: async ({ payload, ctx }) => {
+ // `payload.notification` round-tripped through BullMQ's JSON storage
+ // and the loose wire schema above — the real shape is Prisma's create
+ // input, exactly what a V1 producer put on the queue.
+ await ctx.services.notification.dispatch(
+ payload.notification as Prisma.NotificationUncheckedCreateInput
+ );
+ },
+ }),
+};
diff --git a/packages/core/src/modules/notification/notification.rpc.test.ts b/packages/core/src/modules/notification/notification.rpc.test.ts
new file mode 100644
index 000000000..bd506144a
--- /dev/null
+++ b/packages/core/src/modules/notification/notification.rpc.test.ts
@@ -0,0 +1,66 @@
+// Only the "is anyone logged in" boundary is exercised here — no database.
+// The access-check + CRUD logic ride on @openpanel/db (lazy-loaded, see
+// notification.service.ts's header); wiring this router end-to-end against a
+// real Postgres is P6's (protectedProcedure) job, not this one's — see
+// notification.rpc.ts's header.
+
+import { expect, test } from 'bun:test';
+import { stubHttpCtx } from '../../../test/rpc-fixtures';
+import { makeTrpcContext } from '../../rpc/base';
+import type { CookieOptions } from '../../shared/cookie';
+import { notificationRouter } from './notification.rpc';
+
+const COOKIE_OPTIONS: CookieOptions = {
+ domain: '.openpanel.dev',
+ secure: true,
+ sameSite: 'lax',
+ httpOnly: true,
+ path: '/',
+};
+
+// EMPTY_SESSION's shape (packages/db/src/services/auth-session.service.ts) —
+// `TrpcContext.session` is never literally `null`, only its `userId` is.
+const EMPTY_SESSION = { session: null, user: null, userId: null };
+
+async function anonCaller() {
+ const { ctx } = stubHttpCtx({}, EMPTY_SESSION);
+ const trpcCtx = await makeTrpcContext(ctx, new Headers(), {
+ cookieOptions: COOKIE_OPTIONS,
+ });
+ return notificationRouter.createCaller(trpcCtx);
+}
+
+test('list rejects an unauthenticated caller', async () => {
+ const caller = await anonCaller();
+ await expect(caller.list({ projectId: 'proj_1' })).rejects.toMatchObject({
+ code: 'UNAUTHORIZED',
+ });
+});
+
+test('rules rejects an unauthenticated caller', async () => {
+ const caller = await anonCaller();
+ await expect(caller.rules({ projectId: 'proj_1' })).rejects.toMatchObject({
+ code: 'UNAUTHORIZED',
+ });
+});
+
+test('createOrUpdateRule rejects an unauthenticated caller', async () => {
+ const caller = await anonCaller();
+ await expect(
+ caller.createOrUpdateRule({
+ name: 'Rule',
+ config: { type: 'events', events: [] },
+ integrations: [],
+ sendToApp: true,
+ sendToEmail: false,
+ projectId: 'proj_1',
+ })
+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
+});
+
+test('deleteRule rejects an unauthenticated caller before looking up the rule', async () => {
+ const caller = await anonCaller();
+ await expect(caller.deleteRule({ id: 'rule_1' })).rejects.toMatchObject({
+ code: 'UNAUTHORIZED',
+ });
+});
diff --git a/packages/core/src/modules/notification/notification.rpc.ts b/packages/core/src/modules/notification/notification.rpc.ts
new file mode 100644
index 000000000..7ee60c4ab
--- /dev/null
+++ b/packages/core/src/modules/notification/notification.rpc.ts
@@ -0,0 +1,102 @@
+// Ported from packages/trpc/src/routers/notification.ts (M6-005).
+//
+// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware
+// stack — lands in core with auth (rpc/base.ts: "those need the resolved
+// Session shape and the access rules, so they land with auth (P6)"). Until
+// then this router does its own minimal "is anyone logged in" check inline,
+// exactly like V1's `enforceUserIsAuthed`. V1 keeps serving the live route
+// through packages/trpc's own `protectedProcedure` (full stack included) and
+// delegates its handler bodies to core's notification functions (DELEGATE
+// PATTERN), so nothing here is a live regression.
+//
+// `list`/`rules` have no access check here either — same gap V1's router has
+// (ported verbatim, not fixed; see notification.service.ts's header for why
+// `deleteRule` and `createOrUpdateRule` re-check access against the
+// *existing* rule's project, not just the input's).
+//
+// The per-project access ladder itself IS shared: `./src/access.ts` binds
+// core's shared/access.ts ladder to @openpanel/db's real lookups, the same
+// way packages/trpc/src/access.ts does for V1.
+
+import { z } from 'zod';
+import { createTRPCRouter, procedure } from '../../rpc/base';
+import { TRPCAccessError } from '../../rpc/errors';
+import { zCreateNotificationRule } from './notification.constants';
+import {
+ createOrUpdateNotificationRule,
+ deleteNotificationRule,
+ getNotificationRuleByIdOrThrow,
+ getNotificationRulesByProjectId,
+ listNotificationRules,
+ listNotifications,
+} from './notification.service';
+
+function loadAccessChecks() {
+ return import('./src/access');
+}
+
+function requireLogin(userId: string | null | undefined): string {
+ if (!userId) {
+ throw new TRPCAccessError('Not authenticated');
+ }
+ return userId;
+}
+
+export const notificationRouter = createTRPCRouter({
+ list: procedure
+ .input(z.object({ projectId: z.string() }))
+ .query(({ input, ctx }) => {
+ requireLogin(ctx.session.userId);
+ return listNotifications(input.projectId);
+ }),
+
+ rules: procedure
+ .input(z.object({ projectId: z.string() }))
+ .query(({ input, ctx }) => {
+ requireLogin(ctx.session.userId);
+ return listNotificationRules(input.projectId);
+ }),
+
+ createOrUpdateRule: procedure
+ .input(zCreateNotificationRule)
+ .mutation(async ({ input, ctx }) => {
+ const userId = requireLogin(ctx.session.userId);
+
+ // Clear the cache for the project
+ await getNotificationRulesByProjectId.clear(input.projectId);
+
+ const { requireProjectAccess } = await loadAccessChecks();
+ await requireProjectAccess({
+ userId,
+ projectId: input.projectId,
+ level: 'write',
+ });
+
+ if (input.id) {
+ const existing = await getNotificationRuleByIdOrThrow(input.id);
+ await requireProjectAccess({
+ userId,
+ projectId: existing.projectId,
+ level: 'write',
+ });
+ }
+
+ return createOrUpdateNotificationRule(input);
+ }),
+
+ deleteRule: procedure
+ .input(z.object({ id: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ const userId = requireLogin(ctx.session.userId);
+ const rule = await getNotificationRuleByIdOrThrow(input.id);
+
+ const { requireProjectAccess } = await loadAccessChecks();
+ await requireProjectAccess({
+ userId,
+ projectId: rule.projectId,
+ level: 'write',
+ });
+
+ return deleteNotificationRule(input.id);
+ }),
+});
diff --git a/packages/core/src/modules/notification/notification.service.test.ts b/packages/core/src/modules/notification/notification.service.test.ts
new file mode 100644
index 000000000..0899fa691
--- /dev/null
+++ b/packages/core/src/modules/notification/notification.service.test.ts
@@ -0,0 +1,323 @@
+// notification.service.ts's db access is lazy (`await import(...)` inside
+// each function — see the file's header), which is exactly what makes
+// `mock.module` work here with no import-time side effects to race: every
+// mock below is registered before the subject's first call, not before its
+// (side-effect-free) import.
+
+import { beforeAll, beforeEach, expect, mock, test } from 'bun:test';
+import type { IChartEvent } from '@openpanel/validation';
+
+interface FakeRule {
+ id: string;
+ name: string;
+ projectId: string;
+ sendToApp: boolean;
+ sendToEmail: boolean;
+ config: { type: 'events' | 'funnel'; events: IChartEvent[] };
+ template: string | null;
+ integrations: { id: string }[];
+}
+
+const ruleStore = new Map<string, FakeRule>();
+const integrationStore = new Map<
+ string,
+ { id: string; projectId: string | null; organizationId: string; config: unknown }
+>();
+
+function makeRule(overrides: Partial<FakeRule> & { id: string }): FakeRule {
+ return {
+ name: 'Rule',
+ projectId: 'proj_1',
+ sendToApp: false,
+ sendToEmail: false,
+ config: { type: 'events', events: [] },
+ template: null,
+ integrations: [],
+ ...overrides,
+ };
+}
+
+const publishedEvents: unknown[] = [];
+mock.module('@openpanel/redis', () => ({
+ cacheable: (
+ _name: string,
+ fn: (...args: unknown[]) => unknown,
+ _ttl: number
+ ) => fn,
+ publishEvent: (channel: string, type: string, event: unknown) => {
+ publishedEvents.push({ channel, type, event });
+ },
+}));
+
+const notificationRule = {
+ findMany: mock(async ({ where }: { where: { projectId: string } }) =>
+ [...ruleStore.values()].filter((r) => r.projectId === where.projectId)
+ ),
+ findUniqueOrThrow: mock(
+ async ({ where: { id } }: { where: { id: string } }) => {
+ const found = ruleStore.get(id);
+ if (!found) {
+ throw new Error(`rule ${id} not found`);
+ }
+ return found;
+ }
+ ),
+ create: mock(async ({ data }: { data: Partial<FakeRule> }) => {
+ const row = makeRule({ id: `rule_${ruleStore.size + 1}`, ...data } as never);
+ ruleStore.set(row.id, row);
+ return row;
+ }),
+ update: mock(
+ async ({
+ where: { id },
+ data,
+ }: {
+ where: { id: string };
+ data: Partial<FakeRule>;
+ }) => {
+ const existing = ruleStore.get(id);
+ if (!existing) {
+ throw new Error(`rule ${id} not found`);
+ }
+ const next = { ...existing, ...data };
+ ruleStore.set(id, next as FakeRule);
+ return next;
+ }
+ ),
+ delete: mock(async ({ where: { id } }: { where: { id: string } }) => {
+ const existing = ruleStore.get(id);
+ ruleStore.delete(id);
+ return existing;
+ }),
+};
+
+const integration = {
+ findMany: mock(async ({ where }: { where: { id: { in: string[] } } }) =>
+ [...integrationStore.values()].filter((i) => where.id.in.includes(i.id))
+ ),
+};
+
+const project = {
+ findUniqueOrThrow: mock(async () => ({ organizationId: 'org_1' })),
+};
+
+const actualPrismaClient = await import('@openpanel/db/src/prisma-client');
+mock.module('@openpanel/db/src/prisma-client', () => ({
+ ...actualPrismaClient,
+ db: { notificationRule, integration, project },
+}));
+
+let subject: typeof import('./notification.service');
+beforeAll(async () => {
+ subject = await import('./notification.service');
+});
+
+beforeEach(() => {
+ ruleStore.clear();
+ integrationStore.clear();
+ publishedEvents.length = 0;
+ notificationRule.create.mockClear();
+ notificationRule.update.mockClear();
+});
+
+const CLICK_EVENT = { name: 'click', filters: [] } as never;
+
+test('isBaseIntegration finds app and email, nothing else', () => {
+ expect(subject.isBaseIntegration('app')).toBeTruthy();
+ expect(subject.isBaseIntegration('email')).toBeTruthy();
+ expect(subject.isBaseIntegration('slack_1')).toBeUndefined();
+});
+
+test('matchEvent matches by exact name', () => {
+ const payload = { name: 'click' } as never;
+ expect(subject.matchEvent(payload, CLICK_EVENT)).toBe(true);
+ expect(
+ subject.matchEvent({ name: 'purchase' } as never, CLICK_EVENT)
+ ).toBe(false);
+});
+
+test('matchEvent matches any event name on a wildcard', () => {
+ const wildcard = { name: '*', filters: [] } as never;
+ expect(subject.matchEvent({ name: 'anything' } as never, wildcard)).toBe(
+ true
+ );
+});
+
+test('matchEventFilters: an empty value list always matches', () => {
+ expect(
+ subject.matchEventFilters({} as never, [
+ { name: 'country', operator: 'is', value: [] } as never,
+ ])
+ ).toBe(true);
+});
+
+test('matchEventFilters: "is" matches the exact property value', () => {
+ const payload = { country: 'SE' } as never;
+ expect(
+ subject.matchEventFilters(payload, [
+ { name: 'country', operator: 'is', value: ['SE'] } as never,
+ ])
+ ).toBe(true);
+ expect(
+ subject.matchEventFilters(payload, [
+ { name: 'country', operator: 'is', value: ['US'] } as never,
+ ])
+ ).toBe(false);
+});
+
+test('matchEventFilters: has_profile compares profileId against deviceId', () => {
+ const identified = { profileId: 'p1', deviceId: 'd1' } as never;
+ const anonymous = { profileId: 'd1', deviceId: 'd1' } as never;
+ const filter = {
+ name: 'has_profile',
+ operator: 'is',
+ value: ['true'],
+ } as never;
+ expect(subject.matchEventFilters(identified, [filter])).toBe(true);
+ expect(subject.matchEventFilters(anonymous, [filter])).toBe(false);
+});
+
+test('getHasFunnelRules / getFunnelRules split on config.type', () => {
+ const rules = [
+ makeRule({ id: 'r1', config: { type: 'events', events: [] } }),
+ makeRule({ id: 'r2', config: { type: 'funnel', events: [] } }),
+ ] as never;
+ expect(subject.getHasFunnelRules(rules)).toBe(true);
+ expect(subject.getFunnelRules(rules)).toHaveLength(1);
+ expect(subject.getHasFunnelRules([makeRule({ id: 'r3' })] as never)).toBe(
+ false
+ );
+});
+
+test('notificationTemplateEvent falls back to a default when no template is set', () => {
+ const rule = makeRule({ id: 'r1', template: null });
+ const result = subject.notificationTemplateEvent({
+ payload: { name: 'click' } as never,
+ rule: rule as never,
+ });
+ expect(result).toBe('You received a new "click" event');
+});
+
+test('notificationTemplateEvent substitutes $EVENT_NAME, $RULE_NAME and {{path}} placeholders', () => {
+ const rule = makeRule({
+ id: 'r1',
+ name: 'My Rule',
+ template: '$RULE_NAME saw $EVENT_NAME from {{properties.country}}',
+ });
+ const result = subject.notificationTemplateEvent({
+ payload: { name: 'click', properties: { country: 'SE' } } as never,
+ rule: rule as never,
+ });
+ expect(result).toBe('My Rule saw click from SE');
+});
+
+test('notificationTemplateFunnel joins matched event names with an arrow', () => {
+ const rule = makeRule({ id: 'r1', template: null });
+ const result = subject.notificationTemplateFunnel({
+ events: [{ name: 'view' }, { name: 'checkout' }] as never,
+ rule: rule as never,
+ });
+ expect(result).toBe('Funnel "Rule" completed');
+});
+
+test('listNotificationRules merges the app/email pseudo-integrations onto real ones', async () => {
+ ruleStore.set(
+ 'rule_1',
+ makeRule({
+ id: 'rule_1',
+ sendToApp: true,
+ sendToEmail: false,
+ integrations: [{ id: 'slack_1' }],
+ })
+ );
+
+ const result = await subject.listNotificationRules('proj_1');
+
+ expect(result).toHaveLength(1);
+ expect(result[0]?.integrations.map((i) => i.id)).toEqual([
+ 'app',
+ 'slack_1',
+ ]);
+});
+
+test('createOrUpdateNotificationRule rejects an integration from another project', async () => {
+ integrationStore.set('slack_1', {
+ id: 'slack_1',
+ projectId: 'proj_other',
+ organizationId: 'org_1',
+ config: { type: 'slack' },
+ });
+
+ await expect(
+ subject.createOrUpdateNotificationRule({
+ name: 'Rule',
+ config: { type: 'events', events: [] },
+ integrations: ['slack_1'],
+ sendToApp: false,
+ sendToEmail: false,
+ projectId: 'proj_1',
+ })
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+});
+
+test('createOrUpdateNotificationRule rejects an export-only integration', async () => {
+ integrationStore.set('s3_1', {
+ id: 's3_1',
+ projectId: 'proj_1',
+ organizationId: 'org_1',
+ config: { type: 's3_export' },
+ });
+
+ await expect(
+ subject.createOrUpdateNotificationRule({
+ name: 'Rule',
+ config: { type: 'events', events: [] },
+ integrations: ['s3_1'],
+ sendToApp: false,
+ sendToEmail: false,
+ projectId: 'proj_1',
+ })
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+});
+
+test('createOrUpdateNotificationRule creates a new rule when id is absent', async () => {
+ const created = await subject.createOrUpdateNotificationRule({
+ name: 'Rule',
+ config: { type: 'events', events: [] },
+ integrations: ['app'],
+ sendToApp: true,
+ sendToEmail: false,
+ projectId: 'proj_1',
+ });
+
+ expect(created).toMatchObject({ name: 'Rule', sendToApp: true });
+ expect(notificationRule.create).toHaveBeenCalledTimes(1);
+});
+
+test('deleteNotificationRule removes the row', async () => {
+ ruleStore.set('rule_1', makeRule({ id: 'rule_1' }));
+ await subject.deleteNotificationRule('rule_1');
+ expect(ruleStore.has('rule_1')).toBe(false);
+});
+
+test('deliverNotification publishes the app pseudo-integration instead of enqueuing an email or plugin', async () => {
+ await subject.deliverNotification({
+ projectId: 'proj_1',
+ title: 'Hello',
+ message: 'World',
+ sendToApp: true,
+ } as never);
+
+ expect(publishedEvents).toEqual([
+ {
+ channel: 'notification',
+ type: 'created',
+ event: {
+ projectId: 'proj_1',
+ title: 'Hello',
+ message: 'World',
+ sendToApp: true,
+ },
+ },
+ ]);
+});
diff --git a/packages/core/src/modules/notification/notification.service.ts b/packages/core/src/modules/notification/notification.service.ts
new file mode 100644
index 000000000..c484545b2
--- /dev/null
+++ b/packages/core/src/modules/notification/notification.service.ts
@@ -0,0 +1,519 @@
+// Moved from packages/db/src/services/notification.service.ts (M6-005,
+// ADR-008's module map: "rules + dispatch stay together"). The delivery body
+// moves here too, from apps/worker/src/jobs/notification.ts (DELEGATE
+// PATTERN: that file becomes a thin wrapper calling `deliverNotification`).
+//
+// What does NOT move: `createNotification` / `triggerNotification` /
+// `checkNotificationRulesForEvent` / `checkNotificationRulesForSessionEnd` —
+// the BullMQ-producer orchestration around a rule match. `@openpanel/queue`
+// imports `@openpanel/core` for its logger (packages/queue/src/queues.ts), so
+// core cannot import `@openpanel/queue` back without a real package cycle —
+// same constraint gsc.service.ts and cohort.service.ts document for their own
+// enqueue wrappers. Those four functions stay in
+// packages/db/src/services/notification.service.ts, now built on the rule
+// matching, templates, cache and constants exported below instead of holding
+// their own copies.
+//
+// db/ch access is LAZY (`load*` below), not a static top-level import — see
+// insight.service.ts's header for the full reasoning (jobs.registry.ts and
+// services.ts pull this module into the eager barrel chain nearly every core
+// test file reaches, and constructing @openpanel/db's clients at import time
+// would spawn a pino-pretty transport worker thread per test file).
+
+import { stripLeadingAndTrailingSlashes } from '@openpanel/common';
+import type {
+ IServiceCreateEventPayload,
+ IServiceEvent,
+} from '@openpanel/db';
+import type { Integration, Prisma } from '@openpanel/db/src/prisma-client';
+import { cacheable } from '@openpanel/redis';
+import {
+ type IChartEvent,
+ type IChartEventFilter,
+ type IIntegrationConfig,
+ isKind,
+} from '@openpanel/validation';
+import { pathOr } from 'ramda';
+import { sendEmail } from '../../clients/email';
+import { getServerIntegration } from '../../clients/integrations/registry';
+import { TRPCBadRequestError, TRPCForbiddenError } from '../../rpc/errors';
+import type { ServiceDeps } from '../../services';
+import type { ICreateNotificationRule } from './notification.constants';
+
+export const APP_NOTIFICATION_INTEGRATION_ID = 'app';
+export const EMAIL_NOTIFICATION_INTEGRATION_ID = 'email';
+
+export const BASE_INTEGRATIONS: Integration[] = [
+ {
+ id: APP_NOTIFICATION_INTEGRATION_ID,
+ name: 'Website',
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ config: { type: APP_NOTIFICATION_INTEGRATION_ID },
+ organizationId: '',
+ projectId: null,
+ },
+ {
+ id: EMAIL_NOTIFICATION_INTEGRATION_ID,
+ name: 'Email',
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ config: { type: EMAIL_NOTIFICATION_INTEGRATION_ID },
+ organizationId: '',
+ projectId: null,
+ },
+];
+
+export const isBaseIntegration = (id: string) =>
+ BASE_INTEGRATIONS.find((integration) => integration.id === id);
+
+export type INotificationPayload =
+ | { type: 'event'; event: IServiceCreateEventPayload }
+ | { type: 'funnel'; funnel: IServiceEvent[] };
+
+function loadDb() {
+ return import('@openpanel/db/src/prisma-client').then((m) => m.db);
+}
+
+function loadPrisma() {
+ return import('@openpanel/db/src/prisma-client').then((m) => m.Prisma);
+}
+
+// -- Rule cache --------------------------------------------------------
+
+export type INotificationRuleCached = Awaited<
+ ReturnType<typeof getNotificationRulesByProjectId>
+>[number];
+
+export const getNotificationRulesByProjectId = cacheable(
+ 'getNotificationRulesByProjectId',
+ async (projectId: string) => {
+ const db = await loadDb();
+ return db.notificationRule.findMany({
+ where: { projectId },
+ select: {
+ id: true,
+ name: true,
+ sendToApp: true,
+ sendToEmail: true,
+ config: true,
+ template: true,
+ integrations: { select: { id: true } },
+ },
+ });
+ },
+ 60 * 24,
+ { cacheEmptyArray: true }
+);
+
+// -- Rule matching (pure) -----------------------------------------------
+
+export function matchEventFilters(
+ payload: IServiceCreateEventPayload,
+ filters: IChartEventFilter[]
+): boolean {
+ return filters.every((filter) => {
+ const { name, value, operator } = filter;
+
+ if (value.length === 0) {
+ return true;
+ }
+
+ if (name === 'has_profile') {
+ if (value.includes('true')) {
+ return payload.profileId !== payload.deviceId;
+ }
+ return payload.profileId === payload.deviceId;
+ }
+
+ const propertyValue = (
+ name.startsWith('properties.')
+ ? pathOr('', name.split('.'), payload)
+ : pathOr('', [name], payload)
+ ).trim();
+
+ switch (operator) {
+ case 'is':
+ return value.includes(propertyValue);
+ case 'isNot':
+ return !value.includes(propertyValue);
+ case 'contains':
+ return value.some((val) => propertyValue.includes(String(val)));
+ case 'doesNotContain':
+ return !value.some((val) => propertyValue.includes(String(val)));
+ case 'startsWith':
+ return value.some((val) => propertyValue.startsWith(String(val)));
+ case 'endsWith':
+ return value.some((val) => propertyValue.endsWith(String(val)));
+ case 'regex': {
+ return value
+ .map((val) => stripLeadingAndTrailingSlashes(String(val)))
+ .some((val) => {
+ try {
+ return new RegExp(val).test(propertyValue);
+ } catch {
+ return false;
+ }
+ });
+ }
+ case 'isNull':
+ return propertyValue === '';
+ case 'isNotNull':
+ return propertyValue !== '';
+ case 'gt':
+ return value.some((val) => Number(propertyValue) > Number(val));
+ case 'lt':
+ return value.some((val) => Number(propertyValue) < Number(val));
+ case 'gte':
+ return value.some((val) => Number(propertyValue) >= Number(val));
+ case 'lte':
+ return value.some((val) => Number(propertyValue) <= Number(val));
+ default:
+ return false;
+ }
+ });
+}
+
+export function matchEvent(
+ payload: IServiceCreateEventPayload,
+ chartEvent: IChartEvent
+): boolean {
+ if (payload.name !== chartEvent.name && chartEvent.name !== '*') {
+ return false;
+ }
+
+ if (chartEvent.filters.length > 0) {
+ return matchEventFilters(payload, chartEvent.filters);
+ }
+
+ return true;
+}
+
+const isFunnelRule = (rule: INotificationRuleCached) =>
+ rule.config.type === 'funnel';
+
+export function getHasFunnelRules(rules: INotificationRuleCached[]): boolean {
+ return rules.some(isFunnelRule);
+}
+
+export function getFunnelRules(
+ rules: INotificationRuleCached[]
+): INotificationRuleCached[] {
+ return rules.filter(isFunnelRule);
+}
+
+// -- Templates (pure) -----------------------------------------------------
+
+export function notificationTemplateEvent({
+ payload,
+ rule,
+}: {
+ payload: IServiceCreateEventPayload;
+ rule: INotificationRuleCached;
+}): string {
+ if (!rule.template) {
+ return `You received a new "${payload.name}" event`;
+ }
+ let template = rule.template
+ .replaceAll('$EVENT_NAME', payload.name)
+ .replaceAll('$RULE_NAME', rule.name)
+ .replaceAll('{{rule_name}}', rule.name);
+
+ const placeholderMatches = template.match(/{{[^}]+}}/g) || [];
+ for (const match of placeholderMatches) {
+ const path = match.slice(2, -2);
+ const value = pathOr('', path.split('.'), payload);
+
+ if (value) {
+ template = template.replaceAll(
+ match,
+ typeof value === 'object' ? JSON.stringify(value) : value
+ );
+ }
+ }
+
+ return template;
+}
+
+export function notificationTemplateFunnel({
+ events,
+ rule,
+}: {
+ events: IServiceEvent[];
+ rule: INotificationRuleCached;
+}): string {
+ if (!rule.template) {
+ return `Funnel "${rule.name}" completed`;
+ }
+ return rule.template
+ .replaceAll('$EVENT_NAME', events.map((e) => e.name).join(' -> '))
+ .replaceAll('$RULE_NAME', rule.name);
+}
+
+// -- Dispatch (the delivery job body) --------------------------------------
+
+/**
+ * `Prisma.JsonNull`/`Prisma.DbNull` sentinels don't narrow away from a union
+ * through plain `!==` control flow — an explicit type predicate is what makes
+ * `payload` usable as `INotificationPayload` afterward.
+ */
+function isValidPayload<T>(
+ value: T | Prisma.NullableJsonNullValueInput | null | undefined,
+ jsonNull: unknown,
+ dbNull: unknown
+): value is T {
+ return (
+ value !== null && value !== undefined && value !== jsonNull && value !== dbNull
+ );
+}
+
+/** apps/worker/src/jobs/notification.ts's `sendNotification` job body. */
+export async function deliverNotification(
+ notification: Prisma.NotificationUncheckedCreateInput
+): Promise<unknown> {
+ const db = await loadDb();
+
+ // App + email are pseudo-integrations dispatched by flags, not real rows.
+ // Lazy: @openpanel/redis is otherwise pulled in eagerly through this
+ // module's place in the barrel (services.ts, jobs.registry.ts), and a
+ // static import here would demand `publishEvent` from every core test
+ // file's `@openpanel/redis` mock, not just this module's own.
+ if (notification.sendToApp) {
+ const { publishEvent } = await import('@openpanel/redis');
+ publishEvent('notification', 'created', notification);
+ return;
+ }
+
+ if (notification.sendToEmail) {
+ const project = await db.project.findUniqueOrThrow({
+ where: { id: notification.projectId },
+ select: { name: true, organizationId: true },
+ });
+ const members = await db.member.findMany({
+ where: {
+ organizationId: project.organizationId,
+ user: { deletedAt: null },
+ },
+ include: { user: { select: { email: true } } },
+ });
+ const emails = new Set(
+ members.flatMap((member) =>
+ member.user?.email ? [member.user.email] : []
+ )
+ );
+ for (const to of emails) {
+ // Per-recipient unsubscribe (product_alerts category) is handled
+ // inside sendEmail.
+ await sendEmail('notification-rule', {
+ to,
+ data: {
+ title: notification.title,
+ message: notification.message,
+ projectName: project.name,
+ dashboardUrl: `${process.env.DASHBOARD_URL ?? 'https://dashboard.openpanel.dev'}/${project.organizationId}/${notification.projectId}`,
+ },
+ });
+ }
+ return;
+ }
+
+ if (!notification.integrationId) {
+ throw new Error('No integrationId provided');
+ }
+
+ const integration = await db.integration.findUniqueOrThrow({
+ where: { id: notification.integrationId },
+ });
+
+ const payload = notification.payload;
+ const PrismaRuntime = await loadPrisma();
+ if (
+ !isValidPayload<INotificationPayload>(
+ payload,
+ PrismaRuntime.JsonNull,
+ PrismaRuntime.DbNull
+ )
+ ) {
+ return new Error('Invalid payload');
+ }
+
+ const config = integration.config as IIntegrationConfig | null;
+ // An integration whose config is still empty (e.g. a Slack integration
+ // before its OAuth callback fills the config) has no type yet — nothing
+ // to deliver to.
+ if (!config?.type) {
+ return;
+ }
+
+ // Generic registry dispatch — no per-type switch. A new notification
+ // integration just registers a `notification.deliver` plugin.
+ const plugin = getServerIntegration(config.type);
+ if (!plugin.notification) {
+ throw new Error(`Integration ${config.type} is not a notification sink`);
+ }
+
+ return plugin.notification.deliver({
+ config,
+ notification: {
+ title: notification.title,
+ message: notification.message,
+ },
+ payload,
+ });
+}
+
+// -- RPC-facing CRUD --------------------------------------------------------
+
+export function listNotifications(projectId: string) {
+ return loadDb().then((db) =>
+ db.notification.findMany({
+ where: { projectId },
+ orderBy: { createdAt: 'desc' },
+ include: {
+ integration: { select: { name: true } },
+ notificationRule: { select: { name: true } },
+ },
+ take: 5000,
+ })
+ );
+}
+
+export async function listNotificationRules(projectId: string) {
+ const db = await loadDb();
+ const rules = await db.notificationRule.findMany({
+ where: { projectId },
+ include: { integrations: true },
+ orderBy: { createdAt: 'desc' },
+ });
+
+ return rules.map((rule) => ({
+ ...rule,
+ integrations: [
+ ...BASE_INTEGRATIONS.filter(
+ (integration) =>
+ (integration.id === APP_NOTIFICATION_INTEGRATION_ID &&
+ rule.sendToApp) ||
+ (integration.id === EMAIL_NOTIFICATION_INTEGRATION_ID &&
+ rule.sendToEmail)
+ ),
+ ...rule.integrations,
+ ],
+ }));
+}
+
+export function getNotificationRuleByIdOrThrow(id: string) {
+ return loadDb().then((db) =>
+ db.notificationRule.findUniqueOrThrow({ where: { id } })
+ );
+}
+
+/**
+ * Authorization (`requireProjectAccess`) is the caller's job — same split as
+ * reference.service.ts. This validates that every connected integration
+ * belongs to `input.projectId` or is a legacy org-wide one in the same org,
+ * then writes the rule.
+ */
+export async function createOrUpdateNotificationRule(
+ input: ICreateNotificationRule
+) {
+ const db = await loadDb();
+ const project = await db.project.findUniqueOrThrow({
+ where: { id: input.projectId },
+ select: { organizationId: true },
+ });
+
+ const integrationIds = input.integrations.filter(
+ (id) => !isBaseIntegration(id)
+ );
+ if (integrationIds.length > 0) {
+ const integrations = await db.integration.findMany({
+ where: { id: { in: integrationIds } },
+ select: {
+ id: true,
+ projectId: true,
+ organizationId: true,
+ config: true,
+ },
+ });
+ if (integrations.length !== integrationIds.length) {
+ throw new TRPCBadRequestError('One or more integrations were not found');
+ }
+ for (const integration of integrations) {
+ const sameProject = integration.projectId === input.projectId;
+ const orgWideSameOrg =
+ integration.projectId === null &&
+ integration.organizationId === project.organizationId;
+ if (!sameProject && !orgWideSameOrg) {
+ throw new TRPCForbiddenError(
+ 'Integration does not belong to this project'
+ );
+ }
+ // Export-only integrations (s3_export, gcs_export) have no
+ // notification handler in the registry — attaching one to a rule
+ // would only surface later as a throw in the notification worker.
+ if (!isKind(integration.config, 'notification')) {
+ throw new TRPCBadRequestError(
+ 'Integration cannot be used to deliver notifications'
+ );
+ }
+ }
+ }
+
+ const data = {
+ name: input.name,
+ projectId: input.projectId,
+ sendToApp: !!input.integrations.find(
+ (id) => id === APP_NOTIFICATION_INTEGRATION_ID
+ ),
+ sendToEmail: !!input.integrations.find(
+ (id) => id === EMAIL_NOTIFICATION_INTEGRATION_ID
+ ),
+ config: input.config,
+ template: input.template || null,
+ };
+
+ if (input.id) {
+ return db.notificationRule.update({
+ where: { id: input.id },
+ data: {
+ ...data,
+ integrations: {
+ set: input.integrations
+ .filter((id) => !isBaseIntegration(id))
+ .map((id) => ({ id })),
+ },
+ },
+ });
+ }
+
+ return db.notificationRule.create({
+ data: {
+ ...data,
+ integrations: {
+ connect: input.integrations
+ .filter((id) => !isBaseIntegration(id))
+ .map((id) => ({ id })),
+ },
+ },
+ });
+}
+
+export function deleteNotificationRule(id: string) {
+ return loadDb().then((db) => db.notificationRule.delete({ where: { id } }));
+}
+
+// -- Services surface --------------------------------------------------
+
+export interface NotificationService {
+ dispatch(
+ notification: Prisma.NotificationUncheckedCreateInput
+ ): Promise<unknown>;
+}
+
+export function createNotificationService(
+ _deps: ServiceDeps
+): NotificationService {
+ return {
+ dispatch: deliverNotification,
+ };
+}
diff --git a/packages/core/src/modules/notification/src/access.ts b/packages/core/src/modules/notification/src/access.ts
new file mode 100644
index 000000000..de4a4168e
--- /dev/null
+++ b/packages/core/src/modules/notification/src/access.ts
@@ -0,0 +1,21 @@
+// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
+// this module's own router — the same binding packages/trpc/src/access.ts
+// does for V1, self-contained here because the general core -> db binding
+// itself moves with auth (P6), not this wave.
+
+import {
+ canWriteProject,
+ getOrganizationAccess,
+ getProjectAccess,
+} from '@openpanel/db/src/services/access.service';
+import { getProjectById } from '@openpanel/db/src/services/project.service';
+import { createAccessChecks } from '../../../shared/access';
+
+const checks = createAccessChecks({
+ getProjectAccess,
+ canWriteProject,
+ getOrganizationAccess,
+ getProjectById,
+});
+
+export const requireProjectAccess = checks.requireProjectAccess;
diff --git a/packages/core/src/modules/onboarding/onboarding.jobs.test.ts b/packages/core/src/modules/onboarding/onboarding.jobs.test.ts
index 611b73c43..805101b05 100644
--- a/packages/core/src/modules/onboarding/onboarding.jobs.test.ts
+++ b/packages/core/src/modules/onboarding/onboarding.jobs.test.ts
@@ -30,6 +30,7 @@ function stubJobCtx(
): JobCtx {
const services: Services = {
auth: {} as Services['auth'],
+ notification: {} as Services['notification'],
insight: {} as Services['insight'],
gsc: {} as Services['gsc'],
import: {} as Services['import'],
diff --git a/packages/core/src/modules/organization/organization.jobs.test.ts b/packages/core/src/modules/organization/organization.jobs.test.ts
index 955a5dcbe..60bbb4d23 100644
--- a/packages/core/src/modules/organization/organization.jobs.test.ts
+++ b/packages/core/src/modules/organization/organization.jobs.test.ts
@@ -33,6 +33,7 @@ function stubJobCtx(
): JobCtx {
const services: Services = {
auth: {} as Services['auth'],
+ notification: {} as Services['notification'],
insight: {} as Services['insight'],
gsc: {} as Services['gsc'],
import: {} as Services['import'],
diff --git a/packages/core/src/rpc.router.ts b/packages/core/src/rpc.router.ts
index 52a93a7bf..3627feb2b 100644
--- a/packages/core/src/rpc.router.ts
+++ b/packages/core/src/rpc.router.ts
@@ -14,6 +14,7 @@ import { gscRouter } from './modules/gsc/gsc.rpc';
import { healthRouter } from './modules/health/health.rpc';
import { importRouter } from './modules/import/import.rpc';
import { insightRouter } from './modules/insight/insight.rpc';
+import { notificationRouter } from './modules/notification/notification.rpc';
import { onboardingRouter } from './modules/onboarding/onboarding.rpc';
import { organizationRouter } from './modules/organization/organization.rpc';
import { projectRouter } from './modules/project/project.rpc';
@@ -39,6 +40,7 @@ export const appRouter = createTRPCRouter({
reference: referenceRouter,
share: shareRouter,
email: emailRouter,
+ notification: notificationRouter,
});
export type AppRouter = typeof appRouter;
diff --git a/packages/core/src/services.ts b/packages/core/src/services.ts
index efa65b2d5..bbd6c9351 100644
--- a/packages/core/src/services.ts
+++ b/packages/core/src/services.ts
@@ -20,6 +20,10 @@ import {
createInsightService,
type InsightService,
} from './modules/insight/insight.service';
+import {
+ createNotificationService,
+ type NotificationService,
+} from './modules/notification/notification.service';
import {
createOnboardingService,
type OnboardingService,
@@ -52,6 +56,7 @@ export interface Services {
import: ImportService;
organization: OrganizationService;
onboarding: OnboardingService;
+ notification: NotificationService;
}
export function createServices(deps: ServiceDeps): Services {
@@ -66,5 +71,6 @@ export function createServices(deps: ServiceDeps): Services {
import: createImportService(deps),
organization: createOrganizationService(deps),
onboarding: createOnboardingService(deps),
+ notification: createNotificationService(deps),
};
}
diff --git a/packages/db/src/services/notification.service.ts b/packages/db/src/services/notification.service.ts
index f63097214..1352cfa89 100644
--- a/packages/db/src/services/notification.service.ts
+++ b/packages/db/src/services/notification.service.ts
@@ -1,14 +1,39 @@
-import { stripLeadingAndTrailingSlashes } from '@openpanel/common';
+// Rule matching, templates, the rule cache, the base-integration constants
+// and the delivery (dispatch) body all moved into @openpanel/core's
+// notification module (M6-005, ADR-008's module map: "rules + dispatch stay
+// together"). Re-exported here for existing @openpanel/db importers
+// (packages/trpc's notification/integration routers, this file's own
+// enqueue orchestration below, apps/start via @openpanel/db) — same shape as
+// ./organization.service.ts's re-export since M6-001.
+//
+// What stays here: `createNotification` / `triggerNotification` /
+// `checkNotificationRulesForEvent` / `checkNotificationRulesForSessionEnd` —
+// the BullMQ-producer orchestration around a rule match. `@openpanel/queue`
+// imports `@openpanel/core` for its logger (packages/queue/src/queues.ts), so
+// core cannot import `@openpanel/queue` back without a real package cycle —
+// same constraint packages/trpc/src/routers/cohort.ts documents for its own
+// enqueue call (M5-003). These four functions are the one place that cycle is
+// unavoidable, so they stay on this side of the boundary, built on core's
+// rule matching instead of holding a second copy of it.
+
import { notificationQueue } from '@openpanel/queue';
-import { cacheable } from '@openpanel/redis';
-import type { IChartEvent, IChartEventFilter } from '@openpanel/validation';
-import { pathOr } from 'ramda';
import {
- db,
- type Integration,
- type Notification,
- type Prisma,
-} from '../prisma-client';
+ APP_NOTIFICATION_INTEGRATION_ID,
+ BASE_INTEGRATIONS,
+ EMAIL_NOTIFICATION_INTEGRATION_ID,
+ getFunnelRules,
+ getHasFunnelRules,
+ getNotificationRulesByProjectId,
+ isBaseIntegration,
+ matchEvent,
+ notificationTemplateEvent,
+ notificationTemplateFunnel,
+} from '@openpanel/core';
+import type {
+ INotificationPayload,
+ INotificationRuleCached,
+} from '@openpanel/core';
+import { db, type Notification, type Prisma } from '../prisma-client';
import type {
IServiceCreateEventPayload,
IServiceEvent,
@@ -16,6 +41,21 @@ import type {
import { getProfileById } from './profile.service';
import { getProjectByIdCached } from './project.service';
+export {
+ APP_NOTIFICATION_INTEGRATION_ID,
+ BASE_INTEGRATIONS,
+ EMAIL_NOTIFICATION_INTEGRATION_ID,
+ getFunnelRules,
+ getHasFunnelRules,
+ getNotificationRulesByProjectId,
+ isBaseIntegration,
+ matchEvent,
+} from '@openpanel/core';
+export type {
+ INotificationPayload,
+ INotificationRuleCached,
+} from '@openpanel/core';
+
type ICreateNotification = Pick<
Notification,
| 'projectId'
@@ -26,100 +66,6 @@ type ICreateNotification = Pick<
| 'notificationRuleId'
>;
-export type INotificationPayload =
- | {
- type: 'event';
- event: IServiceCreateEventPayload;
- }
- | {
- type: 'funnel';
- funnel: IServiceEvent[];
- };
-
-export const APP_NOTIFICATION_INTEGRATION_ID = 'app';
-export const EMAIL_NOTIFICATION_INTEGRATION_ID = 'email';
-
-export const BASE_INTEGRATIONS: Integration[] = [
- {
- id: APP_NOTIFICATION_INTEGRATION_ID,
- name: 'Website',
- createdAt: new Date(),
- updatedAt: new Date(),
- config: {
- type: APP_NOTIFICATION_INTEGRATION_ID,
- },
- organizationId: '',
- projectId: null,
- },
- {
- id: EMAIL_NOTIFICATION_INTEGRATION_ID,
- name: 'Email',
- createdAt: new Date(),
- updatedAt: new Date(),
- config: {
- type: EMAIL_NOTIFICATION_INTEGRATION_ID,
- },
- organizationId: '',
- projectId: null,
- },
-];
-
-export const isBaseIntegration = (id: string) =>
- BASE_INTEGRATIONS.find((i) => i.id === id);
-
-export type INotificationRuleCached = Awaited<
- ReturnType<typeof getNotificationRulesByProjectId>
->[number];
-export const getNotificationRulesByProjectId = cacheable(
- 'getNotificationRulesByProjectId',
- (projectId: string) => {
- return db.notificationRule.findMany({
- where: {
- projectId,
- },
- select: {
- id: true,
- name: true,
- sendToApp: true,
- sendToEmail: true,
- config: true,
- template: true,
- integrations: {
- select: {
- id: true,
- },
- },
- },
- });
- },
- 60 * 24,
- { cacheEmptyArray: true }
-);
-
-function getIntegration(integrationId: string | null) {
- if (integrationId === APP_NOTIFICATION_INTEGRATION_ID) {
- return {
- integrationId: null,
- sendToApp: true,
- sendToEmail: false,
- };
- }
-
- if (integrationId === EMAIL_NOTIFICATION_INTEGRATION_ID) {
- return {
- integrationId: null,
- sendToApp: false,
- sendToEmail: true,
- };
- }
-
- return {
- sendToApp: false,
- sendToEmail: false,
- integrationId,
- };
-}
-
function stripNullChars<T>(value: T): T {
if (typeof value === 'string') {
return value.split('\u0000').join('') as T;
@@ -138,6 +84,18 @@ function stripNullChars<T>(value: T): T {
return value;
}
+function getIntegration(integrationId: string | null) {
+ if (integrationId === APP_NOTIFICATION_INTEGRATION_ID) {
+ return { integrationId: null, sendToApp: true, sendToEmail: false };
+ }
+
+ if (integrationId === EMAIL_NOTIFICATION_INTEGRATION_ID) {
+ return { integrationId: null, sendToApp: false, sendToEmail: true };
+ }
+
+ return { sendToApp: false, sendToEmail: false, integrationId };
+}
+
export async function createNotification(notification: ICreateNotification) {
const data: Prisma.NotificationUncheckedCreateInput = {
title: notification.title,
@@ -150,9 +108,7 @@ export async function createNotification(notification: ICreateNotification) {
// Only create notifications for app
if (data.sendToApp) {
- await db.notification.create({
- data,
- });
+ await db.notification.create({ data });
}
return triggerNotification(data);
@@ -163,140 +119,10 @@ export function triggerNotification(
) {
return notificationQueue.add('sendNotification', {
type: 'sendNotification',
- payload: {
- notification,
- },
+ payload: { notification },
});
}
-function matchEventFilters(
- payload: IServiceCreateEventPayload,
- filters: IChartEventFilter[]
-) {
- return filters.every((filter) => {
- const { name, value, operator } = filter;
-
- if (value.length === 0) {
- return true;
- }
-
- if (name === 'has_profile') {
- if (value.includes('true')) {
- return payload.profileId !== payload.deviceId;
- }
- return payload.profileId === payload.deviceId;
- }
-
- const propertyValue = (
- name.startsWith('properties.')
- ? pathOr('', name.split('.'), payload)
- : pathOr('', [name], payload)
- ).trim();
-
- switch (operator) {
- case 'is':
- return value.includes(propertyValue);
- case 'isNot':
- return !value.includes(propertyValue);
- case 'contains':
- return value.some((val) => propertyValue.includes(String(val)));
- case 'doesNotContain':
- return !value.some((val) => propertyValue.includes(String(val)));
- case 'startsWith':
- return value.some((val) => propertyValue.startsWith(String(val)));
- case 'endsWith':
- return value.some((val) => propertyValue.endsWith(String(val)));
- case 'regex': {
- return value
- .map((val) => stripLeadingAndTrailingSlashes(String(val)))
- .some((val) => {
- try {
- return new RegExp(val).test(propertyValue);
- } catch {
- return false;
- }
- });
- }
- case 'isNull':
- return propertyValue === '';
- case 'isNotNull':
- return propertyValue !== '';
- case 'gt':
- return value.some((val) => Number(propertyValue) > Number(val));
- case 'lt':
- return value.some((val) => Number(propertyValue) < Number(val));
- case 'gte':
- return value.some((val) => Number(propertyValue) >= Number(val));
- case 'lte':
- return value.some((val) => Number(propertyValue) <= Number(val));
- default:
- return false;
- }
- });
-}
-
-export function matchEvent(
- payload: IServiceCreateEventPayload,
- chartEvent: IChartEvent
-) {
- if (payload.name !== chartEvent.name && chartEvent.name !== '*') {
- return false;
- }
-
- if (chartEvent.filters.length > 0) {
- return matchEventFilters(payload, chartEvent.filters);
- }
-
- return true;
-}
-
-function notificationTemplateEvent({
- payload,
- rule,
-}: {
- payload: IServiceCreateEventPayload;
- rule: INotificationRuleCached;
-}) {
- if (!rule.template) {
- return `You received a new "${payload.name}" event`;
- }
- let template = rule.template
- .replaceAll('$EVENT_NAME', payload.name)
- .replaceAll('$RULE_NAME', rule.name)
- .replaceAll('{{rule_name}}', rule.name);
-
- // Replace all {{xxx}} placeholders with their values
- const placeholderMatches = template.match(/{{[^}]+}}/g) || [];
- for (const match of placeholderMatches) {
- const path = match.slice(2, -2); // Remove {{ and }}
- const value = pathOr('', path.split('.'), payload);
-
- if (value) {
- template = template.replaceAll(
- match,
- typeof value === 'object' ? JSON.stringify(value) : value
- );
- }
- }
-
- return template;
-}
-
-function notificationTemplateFunnel({
- events,
- rule,
-}: {
- events: IServiceEvent[];
- rule: INotificationRuleCached;
-}) {
- if (!rule.template) {
- return `Funnel "${rule.name}" completed`;
- }
- return rule.template
- .replaceAll('$EVENT_NAME', events.map((e) => e.name).join(' -> '))
- .replaceAll('$RULE_NAME', rule.name);
-}
-
const PROFILE_TEMPLATE_REGEX = /{{profile\.[^}]*}}/;
export async function checkNotificationRulesForEvent(
payload: IServiceCreateEventPayload
@@ -328,16 +154,10 @@ export async function checkNotificationRulesForEvent(
}
const notification = {
- title: notificationTemplateEvent({
- payload,
- rule,
- }),
+ title: notificationTemplateEvent({ payload, rule }),
message: project?.name ? `Project: ${project?.name}` : '',
projectId: payload.projectId,
- payload: {
- type: 'event',
- event: payload,
- },
+ payload: { type: 'event', event: payload },
} as const;
const promises = rule.integrations.map((integration) =>
@@ -376,17 +196,6 @@ export async function checkNotificationRulesForEvent(
);
}
-const isFunnelRule = (rule: INotificationRuleCached) =>
- rule.config.type === 'funnel';
-
-export function getHasFunnelRules(rules: INotificationRuleCached[]) {
- return rules.some(isFunnelRule);
-}
-
-export function getFunnelRules(rules: INotificationRuleCached[]) {
- return rules.filter(isFunnelRule);
-}
-
export async function checkNotificationRulesForSessionEnd(
events: IServiceEvent[]
) {
@@ -425,10 +234,7 @@ export async function checkNotificationRulesForSessionEnd(
// Create notification object
const notification = {
- title: notificationTemplateFunnel({
- rule,
- events: matchedEvents,
- }),
+ title: notificationTemplateFunnel({ rule, events: matchedEvents }),
message: project?.name ? `Project: ${project?.name}` : '',
projectId,
payload: { type: 'funnel', funnel: matchedEvents } as const,
diff --git a/packages/trpc/src/routers/notification.ts b/packages/trpc/src/routers/notification.ts
index f4153f05d..6b83ec6ac 100644
--- a/packages/trpc/src/routers/notification.ts
+++ b/packages/trpc/src/routers/notification.ts
@@ -1,78 +1,35 @@
-import { z } from 'zod';
+// Dissolved into @openpanel/core's notification module (M6-005): the CRUD
+// and rule-write bodies moved to
+// packages/core/src/modules/notification/notification.service.ts. This
+// router stays (DELEGATE PATTERN) — it keeps V1's protectedProcedure stack
+// (session/access/logger/rate-limit middleware) and delegates every handler
+// body to core's notification functions, same as organization's router does
+// (M6-001).
import {
- APP_NOTIFICATION_INTEGRATION_ID,
- BASE_INTEGRATIONS,
- EMAIL_NOTIFICATION_INTEGRATION_ID,
- db,
+ createOrUpdateNotificationRule,
+ deleteNotificationRule,
+ getNotificationRuleByIdOrThrow,
getNotificationRulesByProjectId,
- isBaseIntegration,
-} from '@openpanel/db';
-import { isKind, zCreateNotificationRule } from '@openpanel/validation';
+ listNotificationRules,
+ listNotifications,
+} from '@openpanel/core';
+import { zCreateNotificationRule } from '@openpanel/validation';
+import { z } from 'zod';
import { requireProjectAccess } from '../access';
-import { TRPCBadRequestError, TRPCForbiddenError } from '../errors';
import { createTRPCRouter, protectedProcedure } from '../trpc';
export const notificationRouter = createTRPCRouter({
list: protectedProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input }) => {
- return db.notification.findMany({
- where: {
- projectId: input.projectId,
- },
- orderBy: {
- createdAt: 'desc',
- },
- include: {
- integration: {
- select: {
- name: true,
- },
- },
- notificationRule: {
- select: {
- name: true,
- },
- },
- },
- take: 5000,
- });
+ return listNotifications(input.projectId);
}),
rules: protectedProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input }) => {
- return db.notificationRule
- .findMany({
- where: {
- projectId: input.projectId,
- },
- include: {
- integrations: true,
- },
- orderBy: {
- createdAt: 'desc',
- },
- })
- .then((rules) => {
- return rules.map((rule) => {
- return {
- ...rule,
- integrations: [
- ...BASE_INTEGRATIONS.filter((integration) => {
- return (
- (integration.id === APP_NOTIFICATION_INTEGRATION_ID &&
- rule.sendToApp) ||
- (integration.id === EMAIL_NOTIFICATION_INTEGRATION_ID &&
- rule.sendToEmail)
- );
- }),
- ...rule.integrations,
- ],
- };
- });
- });
+ return listNotificationRules(input.projectId);
}),
createOrUpdateRule: protectedProcedure
.input(zCreateNotificationRule)
@@ -80,124 +37,31 @@ export const notificationRouter = createTRPCRouter({
// Clear the cache for the project
await getNotificationRulesByProjectId.clear(input.projectId);
- // Authorize the target project (covers both create and update; the create
- // branch previously had no access check) and verify every connected
- // integration belongs to this project or is a legacy org-wide one in the
- // same org — never another project's.
- const project = await db.project.findUniqueOrThrow({
- where: { id: input.projectId },
- select: { organizationId: true },
- });
+ // Authorize the target project (covers both create and update; the
+ // create branch previously had no access check) and verify every
+ // connected integration belongs to this project or is a legacy
+ // org-wide one in the same org — never another project's.
await requireProjectAccess({
userId: ctx.session.userId,
projectId: input.projectId,
level: 'write',
});
- const integrationIds = input.integrations.filter(
- (id) => !isBaseIntegration(id),
- );
- if (integrationIds.length > 0) {
- const integrations = await db.integration.findMany({
- where: { id: { in: integrationIds } },
- select: {
- id: true,
- projectId: true,
- organizationId: true,
- config: true,
- },
- });
- if (integrations.length !== integrationIds.length) {
- throw new TRPCBadRequestError(
- 'One or more integrations were not found',
- );
- }
- for (const integration of integrations) {
- const sameProject = integration.projectId === input.projectId;
- const orgWideSameOrg =
- integration.projectId === null &&
- integration.organizationId === project.organizationId;
- if (!sameProject && !orgWideSameOrg) {
- throw new TRPCForbiddenError(
- 'Integration does not belong to this project',
- );
- }
- // Export-only integrations (s3_export, gcs_export) have no
- // notification handler in the registry — attaching one to a rule
- // would only surface later as a throw in the notification worker.
- if (!isKind(integration.config, 'notification')) {
- throw new TRPCBadRequestError(
- 'Integration cannot be used to deliver notifications',
- );
- }
- }
- }
-
if (input.id) {
- const existing = await db.notificationRule.findUniqueOrThrow({
- where: {
- id: input.id,
- },
- });
-
+ const existing = await getNotificationRuleByIdOrThrow(input.id);
await requireProjectAccess({
userId: ctx.session.userId,
projectId: existing.projectId,
level: 'write',
});
-
- return db.notificationRule.update({
- where: {
- id: input.id,
- },
- data: {
- name: input.name,
- projectId: input.projectId,
- sendToApp: !!input.integrations.find(
- (id) => id === APP_NOTIFICATION_INTEGRATION_ID,
- ),
- sendToEmail: !!input.integrations.find(
- (id) => id === EMAIL_NOTIFICATION_INTEGRATION_ID,
- ),
- integrations: {
- set: input.integrations
- .filter((id) => !isBaseIntegration(id))
- .map((id) => ({ id })),
- },
- config: input.config,
- template: input.template || null,
- },
- });
}
- return db.notificationRule.create({
- data: {
- name: input.name,
- projectId: input.projectId,
- sendToApp: !!input.integrations.find(
- (id) => id === APP_NOTIFICATION_INTEGRATION_ID,
- ),
- sendToEmail: !!input.integrations.find(
- (id) => id === EMAIL_NOTIFICATION_INTEGRATION_ID,
- ),
- integrations: {
- connect: input.integrations
- .filter((id) => !isBaseIntegration(id))
- .map((id) => ({ id })),
- },
- config: input.config,
- template: input.template || null,
- },
- });
+ return createOrUpdateNotificationRule(input);
}),
deleteRule: protectedProcedure
.input(z.object({ id: z.string() }))
.mutation(async ({ input: { id }, ctx }) => {
- const rule = await db.notificationRule.findUniqueOrThrow({
- where: {
- id,
- },
- });
+ const rule = await getNotificationRuleByIdOrThrow(id);
await requireProjectAccess({
userId: ctx.session.userId,
@@ -205,10 +69,6 @@ export const notificationRouter = createTRPCRouter({
level: 'write',
});
- return db.notificationRule.delete({
- where: {
- id,
- },
- });
+ return deleteNotificationRule(id);
}),
});
diff --git a/packages/validation/src/index.ts b/packages/validation/src/index.ts
index 42e21e8cd..138d8cefb 100644
--- a/packages/validation/src/index.ts
+++ b/packages/validation/src/index.ts
@@ -367,41 +367,15 @@ export const zCreateReference = z.object({
export * from '@openpanel/core/modules/onboarding/onboarding.constants';
export * from './integrations';
-export const zNotificationRuleEventConfig = z.object({
- type: z.literal('events'),
- events: z.array(zChartEvent),
-});
-
-export type INotificationRuleEventConfig = z.infer<
- typeof zNotificationRuleEventConfig
->;
-
-export const zNotificationRuleFunnelConfig = z.object({
- type: z.literal('funnel'),
- events: z.array(zChartEvent).min(1),
-});
-
-export type INotificationRuleFunnelConfig = z.infer<
- typeof zNotificationRuleFunnelConfig
->;
-
-export const zNotificationRuleConfig = z.discriminatedUnion('type', [
- zNotificationRuleEventConfig,
- zNotificationRuleFunnelConfig,
-]);
-
-export type INotificationRuleConfig = z.infer<typeof zNotificationRuleConfig>;
-
-export const zCreateNotificationRule = z.object({
- id: z.string().optional(),
- name: z.string().min(1),
- template: z.string().optional(),
- config: zNotificationRuleConfig,
- integrations: z.array(z.string()),
- sendToApp: z.boolean(),
- sendToEmail: z.boolean(),
- projectId: z.string(),
-});
+// Moved into @openpanel/core's notification module (M6-005, ADR-008's module
+// map: notification owns "C"). Re-exported here for existing
+// @openpanel/validation importers (packages/trpc's notification router,
+// apps/start's notification rule form) — same shape as
+// ./onboarding.constants.ts re-export since M6-003. `zChartEvent` (used
+// above, and by notification.constants.ts itself) is defined earlier in this
+// file, so the resulting module cycle resolves at the value level: see
+// notification.constants.ts's header.
+export * from '@openpanel/core/modules/notification/notification.constants';
export const zProjectFilterIp = z.object({
type: z.literal('ip'),