@open-mercato/core 0.10.1-develop.7768.1.90fa052c11 → 0.10.1-develop.7769.1.0e6458bb99

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -260,8 +260,12 @@ function createNotificationService(deps) {
260
260
  }
261
261
  return notification;
262
262
  },
263
- async createBatch(input, ctx) {
263
+ async createBatch(input, ctx, options) {
264
+ if (options?.skipExistingGroup && !input.groupKey?.trim()) {
265
+ throw new Error("[internal] Notification group key is required for deduplicated batch delivery");
266
+ }
264
267
  const recipientUserIds = Array.from(new Set(input.recipientUserIds));
268
+ if (options?.skipExistingGroup) recipientUserIds.sort((left, right) => left.localeCompare(right));
265
269
  const { recipientUserIds: _recipientUserIds, ...content } = input;
266
270
  const notifications = [];
267
271
  const resolved = await resolveChannelsForRecipients(content, recipientUserIds, ctx);
@@ -269,11 +273,25 @@ function createNotificationService(deps) {
269
273
  await writeEm.transactional(async (tx) => {
270
274
  await assertNotificationRecipientsInScope(tx, recipientUserIds, ctx);
271
275
  for (const { recipientUserId, channels } of resolved) {
276
+ if (options?.skipExistingGroup) {
277
+ const organizationId = normalizeOrgScope(ctx.organizationId);
278
+ const lockKey = `notifications:${ctx.tenantId}:${organizationId ?? "global"}:${recipientUserId}:${content.type}:${content.groupKey}`;
279
+ await sql`select pg_advisory_xact_lock(hashtext(${lockKey}))`.execute(getDb(tx));
280
+ const existing = await tx.findOne(Notification, {
281
+ recipientUserId,
282
+ tenantId: ctx.tenantId,
283
+ organizationId,
284
+ type: content.type,
285
+ groupKey: content.groupKey
286
+ });
287
+ if (existing) continue;
288
+ }
272
289
  const notification = await createOrRefreshNotification(tx, content, recipientUserId, ctx, channels);
273
290
  notifications.push(notification);
274
291
  }
275
292
  await tx.flush();
276
293
  });
294
+ if (options?.skipExistingGroup && notifications.length === 0) return [];
277
295
  await invalidateNotificationCache(container, ctx, "created");
278
296
  await emitNotificationCreatedBatch(eventBus, notifications, ctx);
279
297
  await emitNotificationSseEvents(eventBus, notifications, ctx);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/notifications/lib/notificationService.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { type Kysely, sql } from 'kysely'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { invalidateCrudCache } from '@open-mercato/shared/lib/crud/cache'\nimport { Notification, type NotificationStatus } from '../data/entities'\nimport type { CreateNotificationInput, CreateBatchNotificationInput, CreateRoleNotificationInput, CreateFeatureNotificationInput, ExecuteActionInput } from '../data/validators'\nimport {\n NOTIFICATION_ACTION_ALREADY_EXECUTED_ERROR_CODE,\n NOTIFICATION_ACTION_FORBIDDEN_ERROR_CODE,\n type NotificationAction,\n type NotificationPollData,\n type NotificationTypeAction,\n} from '@open-mercato/shared/modules/notifications/types'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\nimport { NOTIFICATION_EVENTS, NOTIFICATION_SSE_EVENTS } from './events'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n buildNotificationEntity,\n emitNotificationCreated,\n emitNotificationCreatedBatch,\n type NotificationContentInput,\n type NotificationTenantContext,\n} from './notificationFactory'\nimport { toNotificationDto } from './notificationMapper'\nimport { buildNotificationReadScopeWhere } from './notificationScope'\nimport {\n getRecipientUserIdsForFeature,\n getRecipientUserIdsForRole,\n getScopedNotificationRecipientUserIds,\n} from './notificationRecipients'\nimport { assertSafeNotificationHref, sanitizeNotificationActions } from './safeHref'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getNotificationType } from './notification-type-registry'\nimport { getNotificationTypeOverrides, type NotificationTypeOverrides } from './typeOverrides'\nimport { getNotificationDeliveryStrategies } from './deliveryStrategies'\nimport { resolveEffectiveChannels } from './shouldDeliver'\nimport {\n createNotificationPreferenceService,\n type NotificationPreferenceService,\n} from './notificationPreferenceService'\nimport { inAppVisibleFilter, inAppVisibleSql, isInAppVisible } from './notificationVisibility'\n\nconst logger = createLogger('notifications').child({ component: 'service' })\n\nfunction debug(message: string, ...details: unknown[]): void {\n logger.debug(message, details.length ? { details } : undefined)\n}\n\nfunction getDb(em: EntityManager): Kysely<any> {\n return em.getKysely<any>()\n}\n\nconst UNIQUE_NOTIFICATION_ACTIVE_STATUSES: NotificationStatus[] = ['unread', 'read', 'actioned']\nconst NOTIFICATION_RESOURCE_KIND = 'notifications.notification'\n\nfunction normalizeOrgScope(organizationId: string | null | undefined): string | null {\n return organizationId ?? null\n}\n\nasync function invalidateNotificationCache(\n container: NotificationServiceDeps['container'],\n ctx: Pick<NotificationServiceContext, 'tenantId' | 'organizationId'>,\n reason: string,\n notificationId?: string,\n): Promise<void> {\n if (!container) return\n await invalidateCrudCache(\n container as Parameters<typeof invalidateCrudCache>[0],\n NOTIFICATION_RESOURCE_KIND,\n {\n id: notificationId,\n tenantId: ctx.tenantId,\n organizationId: normalizeOrgScope(ctx.organizationId),\n },\n ctx.tenantId,\n reason,\n )\n}\n\nasync function assertNotificationRecipientsInScope(\n em: EntityManager,\n recipientUserIds: string[],\n ctx: NotificationServiceContext,\n): Promise<void> {\n const scopedRecipientUserIds = await getScopedNotificationRecipientUserIds(\n getDb(em),\n ctx.tenantId,\n normalizeOrgScope(ctx.organizationId),\n recipientUserIds,\n )\n\n if (scopedRecipientUserIds.length !== recipientUserIds.length) {\n throw new CrudHttpError(404, { error: 'Notification recipient not found' })\n }\n}\n\nfunction actionAlreadyExecuted(): CrudHttpError {\n return new CrudHttpError(409, {\n error: 'Notification action already executed',\n code: NOTIFICATION_ACTION_ALREADY_EXECUTED_ERROR_CODE,\n })\n}\n\nasync function actionForbidden(): Promise<CrudHttpError> {\n const { translate } = await resolveTranslations()\n return new CrudHttpError(403, {\n error: translate('notifications.error.actionForbidden', 'You are not allowed to run this notification action'),\n code: NOTIFICATION_ACTION_FORBIDDEN_ERROR_CODE,\n })\n}\n\n/**\n * The command action the notification's registered type declares for a stored action: same action\n * id (across `actions` and `optionalActions`) and same `commandId`. Anything else is not dispatched.\n */\nfunction findDeclaredCommandAction(type: string, action: NotificationAction): NotificationTypeAction | null {\n const definition = getNotificationType(type)\n if (!definition) return null\n const declared = [...definition.actions, ...(definition.optionalActions ?? [])]\n .find((candidate) => candidate.id === action.id)\n if (!declared?.commandId || declared.commandId !== action.commandId) return null\n return declared\n}\n\nfunction applyNotificationContent(\n notification: Notification,\n input: NotificationContentInput,\n recipientUserId: string,\n ctx: NotificationTenantContext,\n channels: string[] | null,\n) {\n const actions = sanitizeNotificationActions(input.actions)\n const linkHref = assertSafeNotificationHref(input.linkHref)\n\n notification.recipientUserId = recipientUserId\n notification.type = input.type\n notification.titleKey = input.titleKey\n notification.bodyKey = input.bodyKey\n notification.titleVariables = input.titleVariables\n notification.bodyVariables = input.bodyVariables\n notification.title = input.title || input.titleKey || ''\n notification.body = input.body\n notification.icon = input.icon\n notification.severity = input.severity ?? 'info'\n notification.actionData = actions\n ? {\n actions,\n primaryActionId: input.primaryActionId,\n }\n : null\n notification.sourceModule = input.sourceModule\n notification.sourceEntityType = input.sourceEntityType\n notification.sourceEntityId = input.sourceEntityId\n notification.linkHref = linkHref\n notification.groupKey = input.groupKey\n notification.channels = channels\n notification.expiresAt = input.expiresAt ? new Date(input.expiresAt) : null\n notification.tenantId = ctx.tenantId\n notification.organizationId = normalizeOrgScope(ctx.organizationId)\n notification.status = 'unread'\n notification.readAt = null\n notification.actionedAt = null\n notification.dismissedAt = null\n notification.actionTaken = null\n notification.actionResult = null\n notification.createdAt = new Date()\n}\n\nasync function findScopedNotificationOrThrow(\n em: EntityManager,\n notificationId: string,\n ctx: NotificationServiceContext,\n): Promise<Notification> {\n const notification = await findOneWithDecryption(\n em,\n Notification,\n {\n id: notificationId,\n recipientUserId: ctx.userId,\n tenantId: ctx.tenantId,\n },\n undefined,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n },\n )\n if (!notification) {\n throw new CrudHttpError(404, { error: 'Notification not found' })\n }\n return notification\n}\n\nasync function emitNotificationSseEvents(\n eventBus: { emit: (event: string, payload: unknown) => Promise<void> },\n notifications: Notification[],\n ctx: NotificationServiceContext,\n): Promise<void> {\n // Live bell updates only for notifications actually delivered to the in-app channel; the others\n // exist as records but must not bump anyone's badge/inbox.\n const visible = notifications.filter((notification) => isInAppVisible(notification.channels))\n if (visible.length === 0) return\n\n const visibleRecipientUserIds = Array.from(new Set(visible.map((n) => n.recipientUserId)))\n await eventBus.emit(NOTIFICATION_SSE_EVENTS.BATCH_CREATED, {\n tenantId: ctx.tenantId,\n organizationId: normalizeOrgScope(ctx.organizationId),\n recipientUserIds: visibleRecipientUserIds,\n count: visible.length,\n })\n\n for (const notification of visible) {\n await eventBus.emit(NOTIFICATION_SSE_EVENTS.CREATED, {\n tenantId: notification.tenantId,\n organizationId: notification.organizationId ?? null,\n recipientUserId: notification.recipientUserId,\n notification: toNotificationDto(notification),\n })\n }\n}\n\nasync function createOrRefreshNotification(\n em: EntityManager,\n input: NotificationContentInput,\n recipientUserId: string,\n ctx: NotificationTenantContext,\n channels: string[] | null,\n): Promise<Notification> {\n if (input.groupKey && input.groupKey.trim().length > 0) {\n const orgScope = normalizeOrgScope(ctx.organizationId) ?? 'global'\n const lockKey = `notifications:${ctx.tenantId}:${orgScope}:${recipientUserId}:${input.type}:${input.groupKey}`\n try {\n const db = getDb(em)\n await sql`select pg_advisory_xact_lock(hashtext(${lockKey}))`.execute(db)\n } catch {\n // If advisory locks are unavailable, continue with best-effort dedupe.\n }\n\n const existing = await em.findOne(Notification, {\n recipientUserId,\n tenantId: ctx.tenantId,\n organizationId: normalizeOrgScope(ctx.organizationId),\n type: input.type,\n groupKey: input.groupKey,\n status: { $in: UNIQUE_NOTIFICATION_ACTIVE_STATUSES },\n }, {\n orderBy: { createdAt: 'desc' },\n })\n\n if (existing) {\n applyNotificationContent(existing, input, recipientUserId, ctx, channels)\n return existing\n }\n }\n\n return buildNotificationEntity(em, input, recipientUserId, ctx, channels)\n}\n\nexport interface NotificationServiceContext {\n tenantId: string\n organizationId?: string | null\n organizationIds?: string[] | null\n userId?: string | null\n}\n\nexport type CreateFeatureNotificationServiceInput = CreateFeatureNotificationInput & {\n restrictRecipientsToOrganization?: boolean\n}\n\nexport interface NotificationService {\n create(input: CreateNotificationInput, ctx: NotificationServiceContext): Promise<Notification>\n createBatch(input: CreateBatchNotificationInput, ctx: NotificationServiceContext): Promise<Notification[]>\n createForRole(input: CreateRoleNotificationInput, ctx: NotificationServiceContext): Promise<Notification[]>\n createForFeature(input: CreateFeatureNotificationServiceInput, ctx: NotificationServiceContext): Promise<Notification[]>\n markAsRead(notificationId: string, ctx: NotificationServiceContext): Promise<Notification>\n markAllAsRead(ctx: NotificationServiceContext): Promise<number>\n dismiss(notificationId: string, ctx: NotificationServiceContext): Promise<Notification>\n restoreDismissed(\n notificationId: string,\n status: 'read' | 'unread' | undefined,\n ctx: NotificationServiceContext\n ): Promise<Notification>\n executeAction(\n notificationId: string,\n input: ExecuteActionInput,\n ctx: NotificationServiceContext\n ): Promise<{ notification: Notification; result: unknown }>\n getUnreadCount(ctx: NotificationServiceContext): Promise<number>\n getPollData(ctx: NotificationServiceContext, since?: string): Promise<NotificationPollData>\n cleanupExpired(): Promise<number>\n deleteBySource(\n sourceEntityType: string,\n sourceEntityId: string,\n ctx: NotificationServiceContext\n ): Promise<number>\n}\n\nexport interface NotificationServiceDeps {\n em: EntityManager\n eventBus: { emit: (event: string, payload: unknown) => Promise<void> }\n commandBus?: {\n execute: (\n commandId: string,\n options: { input: unknown; ctx: unknown; metadata?: unknown }\n ) => Promise<{ result: unknown }>\n }\n container?: { resolve: (name: string) => unknown }\n}\n\nexport function createNotificationService(deps: NotificationServiceDeps): NotificationService {\n const { em: rootEm, eventBus, commandBus, container } = deps\n\n /**\n * Whether the clicking user holds every feature a declared notification action requires.\n * Fails closed: no user, no container, or a failing RBAC check denies the action.\n */\n const userHoldsActionFeatures = async (\n requiredFeatures: string[] | undefined,\n scopeCtx: NotificationServiceContext,\n ): Promise<boolean> => {\n if (!requiredFeatures || requiredFeatures.length === 0) return true\n if (!scopeCtx.userId || !container) return false\n try {\n const rbacService = container.resolve('rbacService') as {\n userHasAllFeatures: (\n userId: string,\n features: string[],\n scope: { tenantId: string | null; organizationId: string | null },\n ) => Promise<boolean>\n }\n const allowed = await rbacService.userHasAllFeatures(\n scopeCtx.userId,\n requiredFeatures,\n { tenantId: scopeCtx.tenantId, organizationId: scopeCtx.organizationId ?? null },\n )\n return allowed === true\n } catch (err) {\n getTelemetryRuntime()?.reportError(err, {\n module: 'notifications',\n code: 'notifications.action_feature_check_failed',\n })\n return false\n }\n }\n\n /**\n * Resolves the authoritative delivery-channel set for one recipient at create time \u2014 the single\n * gate that folds per-send target, per-type eligibility, registered strategies, and the\n * recipient's per-channel preferences (`nonOptOut` bypasses opt-out). Stored on the row and\n * replayed by the dispatcher; `in_app` membership also drives bell/inbox visibility.\n *\n * Returns `null` (\u21D2 \"all channels\", legacy behavior) when no delivery strategies are registered\n * (e.g. a minimal bootstrap/test), so notifications never become silently undeliverable/invisible\n * in an environment that simply hasn't wired the seam.\n */\n const resolveChannelsFor = async (\n content: NotificationContentInput,\n recipientUserId: string,\n scopeCtx: NotificationServiceContext,\n preferences: NotificationPreferenceService = createNotificationPreferenceService({ em: rootEm.fork() }),\n typeOverrides?: NotificationTypeOverrides | null,\n ): Promise<string[] | null> => {\n const registeredChannels = getNotificationDeliveryStrategies().map((strategy) => strategy.id)\n if (registeredChannels.length === 0) return null\n // Treat an empty target as \"no restriction\" (all channels) rather than \"no deliverable channel\":\n // a programmatic caller that computed an empty array should not silently black-hole the\n // notification. The HTTP layer rejects an empty `channels` outright (see validators.ts).\n const targetChannels = content.channels && content.channels.length > 0 ? content.channels : null\n const overrides = typeOverrides === undefined\n ? (await getNotificationTypeOverrides(rootEm.fork(), scopeCtx.tenantId, [content.type])).get(content.type) ?? null\n : typeOverrides\n return resolveEffectiveChannels({\n typeId: content.type,\n type: getNotificationType(content.type),\n scope: { tenantId: scopeCtx.tenantId, userId: recipientUserId },\n targetChannels,\n registeredChannels,\n preferences,\n channelsOverride: overrides?.channels ?? null,\n nonOptOutOverride: overrides?.nonOptOut ?? null,\n })\n }\n\n /**\n * Broadcast counterpart of {@link resolveChannelsFor}: resolves the channel set for every recipient\n * up front, BEFORE the write transaction opens, reusing a single forked EM / preference service\n * across the whole set. This keeps the preference reads out of the write transaction (matching\n * `create`, which resolves before its transaction) and avoids one EM fork per recipient on large\n * role/feature broadcasts.\n */\n const resolveChannelsForRecipients = async (\n content: NotificationContentInput,\n recipientUserIds: string[],\n scopeCtx: NotificationServiceContext,\n ): Promise<Array<{ recipientUserId: string; channels: string[] | null }>> => {\n const preferences = createNotificationPreferenceService({ em: rootEm.fork() })\n // Stored overrides are per-type (not per-recipient) \u2014 read once for the whole broadcast.\n const typeOverrides =\n (await getNotificationTypeOverrides(rootEm.fork(), scopeCtx.tenantId, [content.type])).get(content.type) ?? null\n const resolved: Array<{ recipientUserId: string; channels: string[] | null }> = []\n for (const recipientUserId of recipientUserIds) {\n resolved.push({\n recipientUserId,\n channels: await resolveChannelsFor(content, recipientUserId, scopeCtx, preferences, typeOverrides),\n })\n }\n return resolved\n }\n\n return {\n async create(input, ctx) {\n const { recipientUserId, ...content } = input\n const channels = await resolveChannelsFor(content, recipientUserId, ctx)\n const writeEm = rootEm.fork()\n const notification = await writeEm.transactional(async (tx) => {\n await assertNotificationRecipientsInScope(tx, [recipientUserId], ctx)\n const entity = await createOrRefreshNotification(tx, content, recipientUserId, ctx, channels)\n await tx.flush()\n return entity\n })\n\n await invalidateNotificationCache(container, ctx, 'created')\n // Always emit the domain event (drives the deliver subscriber \u2192 push/email/\u2026). Only bump the\n // live in-app bell when this notification is actually visible in-app.\n await emitNotificationCreated(eventBus, notification, ctx)\n if (isInAppVisible(notification.channels)) {\n await eventBus.emit(NOTIFICATION_SSE_EVENTS.CREATED, {\n tenantId: notification.tenantId,\n organizationId: notification.organizationId ?? null,\n recipientUserId: notification.recipientUserId,\n notification: toNotificationDto(notification),\n })\n }\n\n return notification\n },\n\n async createBatch(input, ctx) {\n const recipientUserIds = Array.from(new Set(input.recipientUserIds))\n const { recipientUserIds: _recipientUserIds, ...content } = input\n const notifications: Notification[] = []\n const resolved = await resolveChannelsForRecipients(content, recipientUserIds, ctx)\n const writeEm = rootEm.fork()\n\n await writeEm.transactional(async (tx) => {\n await assertNotificationRecipientsInScope(tx, recipientUserIds, ctx)\n for (const { recipientUserId, channels } of resolved) {\n const notification = await createOrRefreshNotification(tx, content, recipientUserId, ctx, channels)\n notifications.push(notification)\n }\n await tx.flush()\n })\n\n await invalidateNotificationCache(container, ctx, 'created')\n await emitNotificationCreatedBatch(eventBus, notifications, ctx)\n await emitNotificationSseEvents(eventBus, notifications, ctx)\n\n return notifications\n },\n\n async createForRole(input, ctx) {\n const em = rootEm.fork()\n\n const db = getDb(em)\n const recipientUserIds = await getRecipientUserIdsForRole(db, ctx.tenantId, input.roleId)\n if (recipientUserIds.length === 0) {\n return []\n }\n\n const { roleId: _roleId, ...content } = input\n const notifications: Notification[] = []\n const uniqueRecipientUserIds = Array.from(new Set(recipientUserIds))\n const resolved = await resolveChannelsForRecipients(content, uniqueRecipientUserIds, ctx)\n const writeEm = rootEm.fork()\n\n await writeEm.transactional(async (tx) => {\n for (const { recipientUserId, channels } of resolved) {\n const notification = await createOrRefreshNotification(tx, content, recipientUserId, ctx, channels)\n notifications.push(notification)\n }\n await tx.flush()\n })\n\n await invalidateNotificationCache(container, ctx, 'created')\n await emitNotificationCreatedBatch(eventBus, notifications, ctx)\n await emitNotificationSseEvents(eventBus, notifications, ctx)\n\n return notifications\n },\n\n async createForFeature(input, ctx) {\n const em = rootEm.fork()\n const db = getDb(em)\n const recipientUserIds = await getRecipientUserIdsForFeature(db, ctx.tenantId, input.requiredFeature)\n\n if (recipientUserIds.length === 0) {\n debug('No users found with feature:', input.requiredFeature, 'in tenant:', ctx.tenantId)\n return []\n }\n\n let authorizedRecipientUserIds = recipientUserIds\n if (input.restrictRecipientsToOrganization) {\n const uniqueCandidateUserIds = Array.from(new Set(recipientUserIds))\n if (!ctx.organizationId) {\n logger.warn('Organization-restricted feature fan-out skipped because organization scope is missing', {\n tenantId: ctx.tenantId,\n requiredFeature: input.requiredFeature,\n })\n return []\n }\n\n if (uniqueCandidateUserIds.length > 200) {\n logger.warn('Organization-restricted feature fan-out skipped because the candidate cap was exceeded', {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n requiredFeature: input.requiredFeature,\n candidateCount: uniqueCandidateUserIds.length,\n candidateCap: 200,\n })\n return []\n }\n\n if (!container) {\n logger.warn('Organization-restricted feature fan-out skipped because the DI container is unavailable', {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n requiredFeature: input.requiredFeature,\n })\n return []\n }\n\n try {\n const rbacService = container.resolve('rbacService') as {\n userHasAllFeatures: (\n userId: string,\n features: string[],\n scope: { tenantId: string | null; organizationId: string | null },\n ) => Promise<boolean>\n }\n const allowedRecipientUserIds: string[] = []\n for (let offset = 0; offset < uniqueCandidateUserIds.length; offset += 10) {\n const candidates = uniqueCandidateUserIds.slice(offset, offset + 10)\n const results = await Promise.all(candidates.map(async (recipientUserId) => ({\n recipientUserId,\n allowed: await rbacService.userHasAllFeatures(\n recipientUserId,\n [input.requiredFeature],\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId ?? null },\n ),\n })))\n for (const result of results) {\n if (result.allowed) allowedRecipientUserIds.push(result.recipientUserId)\n }\n }\n authorizedRecipientUserIds = allowedRecipientUserIds\n } catch (err) {\n logger.warn('Organization-restricted feature fan-out skipped because RBAC filtering failed', {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n requiredFeature: input.requiredFeature,\n err,\n })\n return []\n }\n\n if (authorizedRecipientUserIds.length === 0) {\n debug('No users found with feature in organization:', input.requiredFeature, ctx.organizationId)\n return []\n }\n }\n\n debug('Creating notifications for', authorizedRecipientUserIds.length, 'user(s) with feature:', input.requiredFeature)\n\n const {\n requiredFeature: _requiredFeature,\n restrictRecipientsToOrganization: _restrictRecipientsToOrganization,\n ...content\n } = input\n const notifications: Notification[] = []\n const uniqueRecipientUserIds = Array.from(new Set(authorizedRecipientUserIds))\n const resolved = await resolveChannelsForRecipients(content, uniqueRecipientUserIds, ctx)\n const writeEm = rootEm.fork()\n\n await writeEm.transactional(async (tx) => {\n for (const { recipientUserId, channels } of resolved) {\n const notification = await createOrRefreshNotification(tx, content, recipientUserId, ctx, channels)\n notifications.push(notification)\n }\n await tx.flush()\n })\n\n await invalidateNotificationCache(container, ctx, 'created')\n await emitNotificationCreatedBatch(eventBus, notifications, ctx)\n await emitNotificationSseEvents(eventBus, notifications, ctx)\n\n return notifications\n },\n\n async markAsRead(notificationId, ctx) {\n const em = rootEm.fork()\n const notification = await findScopedNotificationOrThrow(em, notificationId, ctx)\n\n if (notification.status === 'unread') {\n notification.status = 'read'\n notification.readAt = new Date()\n await em.flush()\n\n await invalidateNotificationCache(container, ctx, 'updated', notification.id)\n await eventBus.emit(NOTIFICATION_EVENTS.READ, {\n notificationId: notification.id,\n userId: ctx.userId,\n tenantId: ctx.tenantId,\n })\n }\n\n return notification\n },\n\n async markAllAsRead(ctx) {\n const em = rootEm.fork()\n const db = getDb(em)\n const applyScope = <QB extends { where: (...args: any[]) => QB }>(q: QB): QB => {\n let chain = q\n .where('recipient_user_id' as any, '=', ctx.userId as any)\n .where('tenant_id' as any, '=', ctx.tenantId)\n .where('status' as any, '=', 'unread')\n // Only in-app-visible rows count toward the badge (see getUnreadCount),\n // so \"mark all as read\" must scope to the SAME set \u2014 otherwise it flips\n // push/email-only rows the user never saw and SSE-broadcasts a read for\n // notifications that were never in the bell, inflating the returned\n // count past what the badge showed.\n .where(inAppVisibleSql() as any)\n if (ctx.organizationId) {\n chain = chain.where('organization_id' as any, '=', ctx.organizationId)\n }\n return chain\n }\n\n const targetRows = await applyScope(\n db\n .selectFrom('notifications' as any)\n .select([\n 'id' as any,\n 'organization_id' as any,\n 'recipient_user_id' as any,\n ]),\n ).execute() as Array<{ id: string }>\n\n if (!targetRows.length) {\n return 0\n }\n\n const updateResult = await applyScope(\n db.updateTable('notifications' as any).set({\n status: 'read',\n read_at: sql`now()`,\n } as any) as any,\n ).executeTakeFirst() as { numUpdatedRows?: bigint | number } | undefined\n const result = Number(updateResult?.numUpdatedRows ?? targetRows.length)\n\n await invalidateNotificationCache(container, ctx, 'updated')\n\n const notifications = await findWithDecryption(em, Notification, {\n id: { $in: targetRows.map((row) => row.id) },\n }, undefined, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n })\n\n for (const notification of notifications) {\n await eventBus.emit(NOTIFICATION_EVENTS.READ, {\n notificationId: notification.id,\n userId: ctx.userId,\n tenantId: ctx.tenantId,\n })\n\n await eventBus.emit(NOTIFICATION_SSE_EVENTS.CREATED, {\n tenantId: notification.tenantId,\n organizationId: notification.organizationId ?? null,\n recipientUserId: notification.recipientUserId,\n notification: toNotificationDto(notification),\n })\n }\n\n return result\n },\n\n async dismiss(notificationId, ctx) {\n const em = rootEm.fork()\n const notification = await findScopedNotificationOrThrow(em, notificationId, ctx)\n\n notification.status = 'dismissed'\n notification.dismissedAt = new Date()\n await em.flush()\n\n await invalidateNotificationCache(container, ctx, 'updated', notification.id)\n await eventBus.emit(NOTIFICATION_EVENTS.DISMISSED, {\n notificationId: notification.id,\n userId: ctx.userId,\n tenantId: ctx.tenantId,\n })\n\n return notification\n },\n\n async restoreDismissed(notificationId, status, ctx) {\n const em = rootEm.fork()\n const notification = await findScopedNotificationOrThrow(em, notificationId, ctx)\n\n if (notification.status !== 'dismissed') {\n return notification\n }\n\n // A dismissed notification whose action already ran comes back as `actioned`,\n // whatever the caller asked for: `actioned_at` outlives the dismissal.\n const targetStatus: NotificationStatus = notification.actionedAt != null ? 'actioned' : status ?? 'read'\n notification.status = targetStatus\n notification.dismissedAt = null\n\n if (targetStatus === 'unread') {\n notification.readAt = null\n } else if (!notification.readAt) {\n notification.readAt = new Date()\n }\n\n await em.flush()\n\n await invalidateNotificationCache(container, ctx, 'updated', notification.id)\n await eventBus.emit(NOTIFICATION_EVENTS.RESTORED, {\n notificationId: notification.id,\n userId: ctx.userId,\n tenantId: ctx.tenantId,\n status: targetStatus,\n })\n\n return notification\n },\n\n async executeAction(notificationId, input, ctx) {\n const em = rootEm.fork()\n const notification = await findScopedNotificationOrThrow(em, notificationId, ctx)\n\n const actionData = notification.actionData\n const action = actionData?.actions?.find((a) => a.id === input.actionId)\n\n if (!action) {\n throw new Error('Action not found')\n }\n\n // Reject an already-actioned notification before dispatching the command,\n // so a retry or double-click cannot re-run the side effect. `actioned_at` is\n // the durable marker: `status` is overwritten by a dismissal.\n if (notification.status === 'actioned' || notification.actionedAt != null) {\n throw actionAlreadyExecuted()\n }\n\n if (action.commandId) {\n const declared = findDeclaredCommandAction(notification.type, action)\n if (!declared || !(await userHoldsActionFeatures(declared.requiredFeatures, ctx))) {\n throw await actionForbidden()\n }\n }\n\n const actionedAt = new Date()\n const previousStatus = notification.status\n const previousActionedAt = notification.actionedAt ?? null\n const previousActionTaken = notification.actionTaken ?? null\n\n // Atomically claim the notification so only one concurrent request can run\n // the side-effecting command. The conditional UPDATE matches only while the\n // notification has not been actioned yet; a losing request updates 0 rows.\n const claimResult = (await getDb(em)\n .updateTable('notifications' as any)\n .set({\n status: 'actioned',\n actioned_at: actionedAt,\n action_taken: input.actionId,\n } as any)\n .where('id' as any, '=', notification.id)\n .where('recipient_user_id' as any, '=', ctx.userId as any)\n .where('tenant_id' as any, '=', ctx.tenantId)\n .where('status' as any, '!=', 'actioned')\n .where('actioned_at' as any, 'is', null)\n .executeTakeFirst()) as { numUpdatedRows?: bigint | number } | undefined\n\n if (Number(claimResult?.numUpdatedRows ?? 0) === 0) {\n throw actionAlreadyExecuted()\n }\n\n // The claim is provisional: if the side-effecting command fails, the action\n // never actually completed, so release the claim to its prior state. This\n // lets the user retry the action instead of the notification being locked as\n // `actioned` forever. The claim is owned through its own `actioned_at` and\n // `action_taken`, not through `status`: a dismissal that lands while the\n // command runs overwrites `status`, and the release must still clear the\n // claim then \u2014 while leaving that dismissal in place.\n const releaseClaim = async () => {\n await getDb(em)\n .updateTable('notifications' as any)\n .set({\n status: sql`case when status = 'actioned' then ${previousStatus} else status end`,\n actioned_at: previousActionedAt,\n action_taken: previousActionTaken,\n } as any)\n .where('id' as any, '=', notification.id)\n .where('recipient_user_id' as any, '=', ctx.userId as any)\n .where('tenant_id' as any, '=', ctx.tenantId)\n .where('actioned_at' as any, '=', actionedAt)\n .where('action_taken' as any, '=', input.actionId)\n .executeTakeFirst()\n }\n\n let result: unknown = null\n\n if (action.commandId && commandBus && container) {\n const commandInput = {\n ...input.payload,\n id: notification.sourceEntityId,\n }\n\n // Build a CommandRuntimeContext from the notification service context\n const commandCtx = {\n container,\n auth: {\n sub: ctx.userId,\n tenantId: ctx.tenantId,\n orgId: ctx.organizationId,\n },\n organizationScope: null,\n selectedOrganizationId: ctx.organizationId ?? null,\n organizationIds: ctx.organizationId ? [ctx.organizationId] : null,\n }\n\n let commandResult: { result: unknown }\n try {\n commandResult = await commandBus.execute(action.commandId, {\n input: commandInput,\n ctx: commandCtx,\n metadata: {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n resourceKind: 'notifications',\n },\n })\n } catch (err) {\n // Never let a rollback failure mask the original command error \u2014 the\n // caller needs the real failure to decide whether to retry.\n try {\n await releaseClaim()\n } catch (releaseErr) {\n debug('failed to release notification action claim', releaseErr)\n }\n throw err\n }\n\n result = commandResult.result\n }\n\n notification.status = 'actioned'\n notification.actionedAt = actionedAt\n notification.actionTaken = input.actionId\n notification.actionResult = result as Record<string, unknown>\n\n if (!notification.readAt) {\n notification.readAt = new Date()\n }\n\n await em.flush()\n\n await invalidateNotificationCache(container, ctx, 'updated', notification.id)\n await eventBus.emit(NOTIFICATION_EVENTS.ACTIONED, {\n notificationId: notification.id,\n actionId: input.actionId,\n userId: ctx.userId,\n tenantId: ctx.tenantId,\n })\n\n return { notification, result }\n },\n\n async getUnreadCount(ctx) {\n const em = rootEm.fork()\n return em.count(Notification, {\n recipientUserId: ctx.userId,\n tenantId: ctx.tenantId,\n status: 'unread',\n $and: [\n buildNotificationReadScopeWhere(ctx),\n inAppVisibleFilter(),\n ],\n })\n },\n\n async getPollData(ctx, since) {\n const em = rootEm.fork()\n const filters: Record<string, unknown> = {\n recipientUserId: ctx.userId,\n tenantId: ctx.tenantId,\n $and: [\n buildNotificationReadScopeWhere(ctx),\n inAppVisibleFilter(),\n ],\n }\n\n if (since) {\n filters.createdAt = { $gt: new Date(since) }\n }\n\n const [notifications, unreadCount] = await Promise.all([\n em.find(Notification, filters, {\n orderBy: { createdAt: 'desc' },\n limit: 50,\n }),\n em.count(Notification, {\n recipientUserId: ctx.userId,\n tenantId: ctx.tenantId,\n status: 'unread',\n $and: [\n buildNotificationReadScopeWhere(ctx),\n inAppVisibleFilter(),\n ],\n }),\n ])\n\n const recent = notifications.map(toNotificationDto)\n const hasNew = since ? recent.length > 0 : false\n\n return {\n unreadCount,\n recent,\n hasNew,\n lastId: recent[0]?.id,\n }\n },\n\n async cleanupExpired() {\n const em = rootEm.fork()\n const db = getDb(em)\n\n const affectedScopes = await db\n .selectFrom('notifications' as any)\n .select([\n 'tenant_id' as any,\n 'organization_id' as any,\n ])\n .where('expires_at' as any, '<', sql`now()`)\n .where('status' as any, 'not in', ['actioned', 'dismissed'])\n .distinct()\n .execute() as Array<{ tenant_id: string; organization_id: string | null }>\n\n if (!affectedScopes.length) return 0\n\n const updateResult = await db\n .updateTable('notifications' as any)\n .set({\n status: 'dismissed',\n dismissed_at: sql`now()`,\n } as any)\n .where('expires_at' as any, '<', sql`now()`)\n .where('status' as any, 'not in', ['actioned', 'dismissed'])\n .executeTakeFirst() as { numUpdatedRows?: bigint | number } | undefined\n\n for (const scope of affectedScopes) {\n await invalidateNotificationCache(container, {\n tenantId: scope.tenant_id,\n organizationId: scope.organization_id,\n }, 'updated')\n }\n\n return Number(updateResult?.numUpdatedRows ?? 0)\n },\n\n async deleteBySource(sourceEntityType, sourceEntityId, ctx) {\n const em = rootEm.fork()\n const db = getDb(em)\n\n const deleteResult = await db\n .deleteFrom('notifications' as any)\n .where('source_entity_type' as any, '=', sourceEntityType)\n .where('source_entity_id' as any, '=', sourceEntityId)\n .where('tenant_id' as any, '=', ctx.tenantId)\n .executeTakeFirst() as { numDeletedRows?: bigint | number } | undefined\n\n const deletedCount = Number(deleteResult?.numDeletedRows ?? 0)\n if (deletedCount > 0) {\n await invalidateNotificationCache(container, ctx, 'deleted')\n }\n\n return deletedCount\n },\n }\n}\n\n/**\n * Helper to create notification service from a DI container.\n * Use this in API routes and commands to avoid DI resolution issues.\n */\nexport function resolveNotificationService(container: {\n resolve: (name: string) => unknown\n}): NotificationService {\n const em = container.resolve('em') as EntityManager\n const eventBus = container.resolve('eventBus') as { emit: (event: string, payload: unknown) => Promise<void> }\n\n // commandBus may not be registered in all contexts, so resolve it safely\n let commandBus: NotificationServiceDeps['commandBus']\n try {\n commandBus = container.resolve('commandBus') as typeof commandBus\n } catch {\n // commandBus not available - actions with commandId won't work\n commandBus = undefined\n }\n\n return createNotificationService({ em, eventBus, commandBus, container })\n}\n"],
5
- "mappings": "AACA,SAAsB,WAAW;AACjC,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC,SAAS,oBAA6C;AAEtD;AAAA,EACE;AAAA,EACA;AAAA,OAIK;AACP,SAAS,2BAA2B;AACpC,SAAS,2BAA2B;AACpC,SAAS,qBAAqB,+BAA+B;AAC7D,SAAS,uBAAuB,0BAA0B;AAC1D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP,SAAS,yBAAyB;AAClC,SAAS,uCAAuC;AAChD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,4BAA4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,aAAoB,KAAK,IAAI,QAAQ,EAC3C,iBAAiB;AAEpB,YAAM,eAAe,OAAO,cAAc,kBAAkB,CAAC;AAC7D,UAAI,eAAe,GAAG;AACpB,cAAM,4BAA4B,WAAW,KAAK,SAAS;AAAA,MAC7D;AAEA,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAMO,SAAS,2BAA2B,WAEnB;AACtB,QAAM,KAAK,UAAU,QAAQ,IAAI;AACjC,QAAM,WAAW,UAAU,QAAQ,UAAU;AAG7C,MAAI;AACJ,MAAI;AACF,iBAAa,UAAU,QAAQ,YAAY;AAAA,EAC7C,QAAQ;AAEN,iBAAa;AAAA,EACf;AAEA,SAAO,0BAA0B,EAAE,IAAI,UAAU,YAAY,UAAU,CAAC;AAC1E;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { type Kysely, sql } from 'kysely'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { invalidateCrudCache } from '@open-mercato/shared/lib/crud/cache'\nimport { Notification, type NotificationStatus } from '../data/entities'\nimport type { CreateNotificationInput, CreateBatchNotificationInput, CreateRoleNotificationInput, CreateFeatureNotificationInput, ExecuteActionInput } from '../data/validators'\nimport {\n NOTIFICATION_ACTION_ALREADY_EXECUTED_ERROR_CODE,\n NOTIFICATION_ACTION_FORBIDDEN_ERROR_CODE,\n type NotificationAction,\n type NotificationPollData,\n type NotificationTypeAction,\n} from '@open-mercato/shared/modules/notifications/types'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\nimport { NOTIFICATION_EVENTS, NOTIFICATION_SSE_EVENTS } from './events'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n buildNotificationEntity,\n emitNotificationCreated,\n emitNotificationCreatedBatch,\n type NotificationContentInput,\n type NotificationTenantContext,\n} from './notificationFactory'\nimport { toNotificationDto } from './notificationMapper'\nimport { buildNotificationReadScopeWhere } from './notificationScope'\nimport {\n getRecipientUserIdsForFeature,\n getRecipientUserIdsForRole,\n getScopedNotificationRecipientUserIds,\n} from './notificationRecipients'\nimport { assertSafeNotificationHref, sanitizeNotificationActions } from './safeHref'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getNotificationType } from './notification-type-registry'\nimport { getNotificationTypeOverrides, type NotificationTypeOverrides } from './typeOverrides'\nimport { getNotificationDeliveryStrategies } from './deliveryStrategies'\nimport { resolveEffectiveChannels } from './shouldDeliver'\nimport {\n createNotificationPreferenceService,\n type NotificationPreferenceService,\n} from './notificationPreferenceService'\nimport { inAppVisibleFilter, inAppVisibleSql, isInAppVisible } from './notificationVisibility'\n\nconst logger = createLogger('notifications').child({ component: 'service' })\n\nfunction debug(message: string, ...details: unknown[]): void {\n logger.debug(message, details.length ? { details } : undefined)\n}\n\nfunction getDb(em: EntityManager): Kysely<any> {\n return em.getKysely<any>()\n}\n\nconst UNIQUE_NOTIFICATION_ACTIVE_STATUSES: NotificationStatus[] = ['unread', 'read', 'actioned']\nconst NOTIFICATION_RESOURCE_KIND = 'notifications.notification'\n\nfunction normalizeOrgScope(organizationId: string | null | undefined): string | null {\n return organizationId ?? null\n}\n\nasync function invalidateNotificationCache(\n container: NotificationServiceDeps['container'],\n ctx: Pick<NotificationServiceContext, 'tenantId' | 'organizationId'>,\n reason: string,\n notificationId?: string,\n): Promise<void> {\n if (!container) return\n await invalidateCrudCache(\n container as Parameters<typeof invalidateCrudCache>[0],\n NOTIFICATION_RESOURCE_KIND,\n {\n id: notificationId,\n tenantId: ctx.tenantId,\n organizationId: normalizeOrgScope(ctx.organizationId),\n },\n ctx.tenantId,\n reason,\n )\n}\n\nasync function assertNotificationRecipientsInScope(\n em: EntityManager,\n recipientUserIds: string[],\n ctx: NotificationServiceContext,\n): Promise<void> {\n const scopedRecipientUserIds = await getScopedNotificationRecipientUserIds(\n getDb(em),\n ctx.tenantId,\n normalizeOrgScope(ctx.organizationId),\n recipientUserIds,\n )\n\n if (scopedRecipientUserIds.length !== recipientUserIds.length) {\n throw new CrudHttpError(404, { error: 'Notification recipient not found' })\n }\n}\n\nfunction actionAlreadyExecuted(): CrudHttpError {\n return new CrudHttpError(409, {\n error: 'Notification action already executed',\n code: NOTIFICATION_ACTION_ALREADY_EXECUTED_ERROR_CODE,\n })\n}\n\nasync function actionForbidden(): Promise<CrudHttpError> {\n const { translate } = await resolveTranslations()\n return new CrudHttpError(403, {\n error: translate('notifications.error.actionForbidden', 'You are not allowed to run this notification action'),\n code: NOTIFICATION_ACTION_FORBIDDEN_ERROR_CODE,\n })\n}\n\n/**\n * The command action the notification's registered type declares for a stored action: same action\n * id (across `actions` and `optionalActions`) and same `commandId`. Anything else is not dispatched.\n */\nfunction findDeclaredCommandAction(type: string, action: NotificationAction): NotificationTypeAction | null {\n const definition = getNotificationType(type)\n if (!definition) return null\n const declared = [...definition.actions, ...(definition.optionalActions ?? [])]\n .find((candidate) => candidate.id === action.id)\n if (!declared?.commandId || declared.commandId !== action.commandId) return null\n return declared\n}\n\nfunction applyNotificationContent(\n notification: Notification,\n input: NotificationContentInput,\n recipientUserId: string,\n ctx: NotificationTenantContext,\n channels: string[] | null,\n) {\n const actions = sanitizeNotificationActions(input.actions)\n const linkHref = assertSafeNotificationHref(input.linkHref)\n\n notification.recipientUserId = recipientUserId\n notification.type = input.type\n notification.titleKey = input.titleKey\n notification.bodyKey = input.bodyKey\n notification.titleVariables = input.titleVariables\n notification.bodyVariables = input.bodyVariables\n notification.title = input.title || input.titleKey || ''\n notification.body = input.body\n notification.icon = input.icon\n notification.severity = input.severity ?? 'info'\n notification.actionData = actions\n ? {\n actions,\n primaryActionId: input.primaryActionId,\n }\n : null\n notification.sourceModule = input.sourceModule\n notification.sourceEntityType = input.sourceEntityType\n notification.sourceEntityId = input.sourceEntityId\n notification.linkHref = linkHref\n notification.groupKey = input.groupKey\n notification.channels = channels\n notification.expiresAt = input.expiresAt ? new Date(input.expiresAt) : null\n notification.tenantId = ctx.tenantId\n notification.organizationId = normalizeOrgScope(ctx.organizationId)\n notification.status = 'unread'\n notification.readAt = null\n notification.actionedAt = null\n notification.dismissedAt = null\n notification.actionTaken = null\n notification.actionResult = null\n notification.createdAt = new Date()\n}\n\nasync function findScopedNotificationOrThrow(\n em: EntityManager,\n notificationId: string,\n ctx: NotificationServiceContext,\n): Promise<Notification> {\n const notification = await findOneWithDecryption(\n em,\n Notification,\n {\n id: notificationId,\n recipientUserId: ctx.userId,\n tenantId: ctx.tenantId,\n },\n undefined,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n },\n )\n if (!notification) {\n throw new CrudHttpError(404, { error: 'Notification not found' })\n }\n return notification\n}\n\nasync function emitNotificationSseEvents(\n eventBus: { emit: (event: string, payload: unknown) => Promise<void> },\n notifications: Notification[],\n ctx: NotificationServiceContext,\n): Promise<void> {\n // Live bell updates only for notifications actually delivered to the in-app channel; the others\n // exist as records but must not bump anyone's badge/inbox.\n const visible = notifications.filter((notification) => isInAppVisible(notification.channels))\n if (visible.length === 0) return\n\n const visibleRecipientUserIds = Array.from(new Set(visible.map((n) => n.recipientUserId)))\n await eventBus.emit(NOTIFICATION_SSE_EVENTS.BATCH_CREATED, {\n tenantId: ctx.tenantId,\n organizationId: normalizeOrgScope(ctx.organizationId),\n recipientUserIds: visibleRecipientUserIds,\n count: visible.length,\n })\n\n for (const notification of visible) {\n await eventBus.emit(NOTIFICATION_SSE_EVENTS.CREATED, {\n tenantId: notification.tenantId,\n organizationId: notification.organizationId ?? null,\n recipientUserId: notification.recipientUserId,\n notification: toNotificationDto(notification),\n })\n }\n}\n\nasync function createOrRefreshNotification(\n em: EntityManager,\n input: NotificationContentInput,\n recipientUserId: string,\n ctx: NotificationTenantContext,\n channels: string[] | null,\n): Promise<Notification> {\n if (input.groupKey && input.groupKey.trim().length > 0) {\n const orgScope = normalizeOrgScope(ctx.organizationId) ?? 'global'\n const lockKey = `notifications:${ctx.tenantId}:${orgScope}:${recipientUserId}:${input.type}:${input.groupKey}`\n try {\n const db = getDb(em)\n await sql`select pg_advisory_xact_lock(hashtext(${lockKey}))`.execute(db)\n } catch {\n // If advisory locks are unavailable, continue with best-effort dedupe.\n }\n\n const existing = await em.findOne(Notification, {\n recipientUserId,\n tenantId: ctx.tenantId,\n organizationId: normalizeOrgScope(ctx.organizationId),\n type: input.type,\n groupKey: input.groupKey,\n status: { $in: UNIQUE_NOTIFICATION_ACTIVE_STATUSES },\n }, {\n orderBy: { createdAt: 'desc' },\n })\n\n if (existing) {\n applyNotificationContent(existing, input, recipientUserId, ctx, channels)\n return existing\n }\n }\n\n return buildNotificationEntity(em, input, recipientUserId, ctx, channels)\n}\n\nexport interface NotificationServiceContext {\n tenantId: string\n organizationId?: string | null\n organizationIds?: string[] | null\n userId?: string | null\n}\n\nexport type CreateFeatureNotificationServiceInput = CreateFeatureNotificationInput & {\n restrictRecipientsToOrganization?: boolean\n}\n\nexport type CreateBatchNotificationOptions = {\n skipExistingGroup?: boolean\n}\n\nexport interface NotificationService {\n create(input: CreateNotificationInput, ctx: NotificationServiceContext): Promise<Notification>\n createBatch(input: CreateBatchNotificationInput, ctx: NotificationServiceContext, options?: CreateBatchNotificationOptions): Promise<Notification[]>\n createForRole(input: CreateRoleNotificationInput, ctx: NotificationServiceContext): Promise<Notification[]>\n createForFeature(input: CreateFeatureNotificationServiceInput, ctx: NotificationServiceContext): Promise<Notification[]>\n markAsRead(notificationId: string, ctx: NotificationServiceContext): Promise<Notification>\n markAllAsRead(ctx: NotificationServiceContext): Promise<number>\n dismiss(notificationId: string, ctx: NotificationServiceContext): Promise<Notification>\n restoreDismissed(\n notificationId: string,\n status: 'read' | 'unread' | undefined,\n ctx: NotificationServiceContext\n ): Promise<Notification>\n executeAction(\n notificationId: string,\n input: ExecuteActionInput,\n ctx: NotificationServiceContext\n ): Promise<{ notification: Notification; result: unknown }>\n getUnreadCount(ctx: NotificationServiceContext): Promise<number>\n getPollData(ctx: NotificationServiceContext, since?: string): Promise<NotificationPollData>\n cleanupExpired(): Promise<number>\n deleteBySource(\n sourceEntityType: string,\n sourceEntityId: string,\n ctx: NotificationServiceContext\n ): Promise<number>\n}\n\nexport interface NotificationServiceDeps {\n em: EntityManager\n eventBus: { emit: (event: string, payload: unknown) => Promise<void> }\n commandBus?: {\n execute: (\n commandId: string,\n options: { input: unknown; ctx: unknown; metadata?: unknown }\n ) => Promise<{ result: unknown }>\n }\n container?: { resolve: (name: string) => unknown }\n}\n\nexport function createNotificationService(deps: NotificationServiceDeps): NotificationService {\n const { em: rootEm, eventBus, commandBus, container } = deps\n\n /**\n * Whether the clicking user holds every feature a declared notification action requires.\n * Fails closed: no user, no container, or a failing RBAC check denies the action.\n */\n const userHoldsActionFeatures = async (\n requiredFeatures: string[] | undefined,\n scopeCtx: NotificationServiceContext,\n ): Promise<boolean> => {\n if (!requiredFeatures || requiredFeatures.length === 0) return true\n if (!scopeCtx.userId || !container) return false\n try {\n const rbacService = container.resolve('rbacService') as {\n userHasAllFeatures: (\n userId: string,\n features: string[],\n scope: { tenantId: string | null; organizationId: string | null },\n ) => Promise<boolean>\n }\n const allowed = await rbacService.userHasAllFeatures(\n scopeCtx.userId,\n requiredFeatures,\n { tenantId: scopeCtx.tenantId, organizationId: scopeCtx.organizationId ?? null },\n )\n return allowed === true\n } catch (err) {\n getTelemetryRuntime()?.reportError(err, {\n module: 'notifications',\n code: 'notifications.action_feature_check_failed',\n })\n return false\n }\n }\n\n /**\n * Resolves the authoritative delivery-channel set for one recipient at create time \u2014 the single\n * gate that folds per-send target, per-type eligibility, registered strategies, and the\n * recipient's per-channel preferences (`nonOptOut` bypasses opt-out). Stored on the row and\n * replayed by the dispatcher; `in_app` membership also drives bell/inbox visibility.\n *\n * Returns `null` (\u21D2 \"all channels\", legacy behavior) when no delivery strategies are registered\n * (e.g. a minimal bootstrap/test), so notifications never become silently undeliverable/invisible\n * in an environment that simply hasn't wired the seam.\n */\n const resolveChannelsFor = async (\n content: NotificationContentInput,\n recipientUserId: string,\n scopeCtx: NotificationServiceContext,\n preferences: NotificationPreferenceService = createNotificationPreferenceService({ em: rootEm.fork() }),\n typeOverrides?: NotificationTypeOverrides | null,\n ): Promise<string[] | null> => {\n const registeredChannels = getNotificationDeliveryStrategies().map((strategy) => strategy.id)\n if (registeredChannels.length === 0) return null\n // Treat an empty target as \"no restriction\" (all channels) rather than \"no deliverable channel\":\n // a programmatic caller that computed an empty array should not silently black-hole the\n // notification. The HTTP layer rejects an empty `channels` outright (see validators.ts).\n const targetChannels = content.channels && content.channels.length > 0 ? content.channels : null\n const overrides = typeOverrides === undefined\n ? (await getNotificationTypeOverrides(rootEm.fork(), scopeCtx.tenantId, [content.type])).get(content.type) ?? null\n : typeOverrides\n return resolveEffectiveChannels({\n typeId: content.type,\n type: getNotificationType(content.type),\n scope: { tenantId: scopeCtx.tenantId, userId: recipientUserId },\n targetChannels,\n registeredChannels,\n preferences,\n channelsOverride: overrides?.channels ?? null,\n nonOptOutOverride: overrides?.nonOptOut ?? null,\n })\n }\n\n /**\n * Broadcast counterpart of {@link resolveChannelsFor}: resolves the channel set for every recipient\n * up front, BEFORE the write transaction opens, reusing a single forked EM / preference service\n * across the whole set. This keeps the preference reads out of the write transaction (matching\n * `create`, which resolves before its transaction) and avoids one EM fork per recipient on large\n * role/feature broadcasts.\n */\n const resolveChannelsForRecipients = async (\n content: NotificationContentInput,\n recipientUserIds: string[],\n scopeCtx: NotificationServiceContext,\n ): Promise<Array<{ recipientUserId: string; channels: string[] | null }>> => {\n const preferences = createNotificationPreferenceService({ em: rootEm.fork() })\n // Stored overrides are per-type (not per-recipient) \u2014 read once for the whole broadcast.\n const typeOverrides =\n (await getNotificationTypeOverrides(rootEm.fork(), scopeCtx.tenantId, [content.type])).get(content.type) ?? null\n const resolved: Array<{ recipientUserId: string; channels: string[] | null }> = []\n for (const recipientUserId of recipientUserIds) {\n resolved.push({\n recipientUserId,\n channels: await resolveChannelsFor(content, recipientUserId, scopeCtx, preferences, typeOverrides),\n })\n }\n return resolved\n }\n\n return {\n async create(input, ctx) {\n const { recipientUserId, ...content } = input\n const channels = await resolveChannelsFor(content, recipientUserId, ctx)\n const writeEm = rootEm.fork()\n const notification = await writeEm.transactional(async (tx) => {\n await assertNotificationRecipientsInScope(tx, [recipientUserId], ctx)\n const entity = await createOrRefreshNotification(tx, content, recipientUserId, ctx, channels)\n await tx.flush()\n return entity\n })\n\n await invalidateNotificationCache(container, ctx, 'created')\n // Always emit the domain event (drives the deliver subscriber \u2192 push/email/\u2026). Only bump the\n // live in-app bell when this notification is actually visible in-app.\n await emitNotificationCreated(eventBus, notification, ctx)\n if (isInAppVisible(notification.channels)) {\n await eventBus.emit(NOTIFICATION_SSE_EVENTS.CREATED, {\n tenantId: notification.tenantId,\n organizationId: notification.organizationId ?? null,\n recipientUserId: notification.recipientUserId,\n notification: toNotificationDto(notification),\n })\n }\n\n return notification\n },\n\n async createBatch(input, ctx, options) {\n if (options?.skipExistingGroup && !input.groupKey?.trim()) {\n throw new Error('[internal] Notification group key is required for deduplicated batch delivery')\n }\n const recipientUserIds = Array.from(new Set(input.recipientUserIds))\n if (options?.skipExistingGroup) recipientUserIds.sort((left, right) => left.localeCompare(right))\n const { recipientUserIds: _recipientUserIds, ...content } = input\n const notifications: Notification[] = []\n const resolved = await resolveChannelsForRecipients(content, recipientUserIds, ctx)\n const writeEm = rootEm.fork()\n\n await writeEm.transactional(async (tx) => {\n await assertNotificationRecipientsInScope(tx, recipientUserIds, ctx)\n for (const { recipientUserId, channels } of resolved) {\n if (options?.skipExistingGroup) {\n const organizationId = normalizeOrgScope(ctx.organizationId)\n const lockKey = `notifications:${ctx.tenantId}:${organizationId ?? 'global'}:${recipientUserId}:${content.type}:${content.groupKey}`\n await sql`select pg_advisory_xact_lock(hashtext(${lockKey}))`.execute(getDb(tx))\n const existing = await tx.findOne(Notification, {\n recipientUserId,\n tenantId: ctx.tenantId,\n organizationId,\n type: content.type,\n groupKey: content.groupKey,\n })\n if (existing) continue\n }\n const notification = await createOrRefreshNotification(tx, content, recipientUserId, ctx, channels)\n notifications.push(notification)\n }\n await tx.flush()\n })\n\n if (options?.skipExistingGroup && notifications.length === 0) return []\n await invalidateNotificationCache(container, ctx, 'created')\n await emitNotificationCreatedBatch(eventBus, notifications, ctx)\n await emitNotificationSseEvents(eventBus, notifications, ctx)\n\n return notifications\n },\n\n async createForRole(input, ctx) {\n const em = rootEm.fork()\n\n const db = getDb(em)\n const recipientUserIds = await getRecipientUserIdsForRole(db, ctx.tenantId, input.roleId)\n if (recipientUserIds.length === 0) {\n return []\n }\n\n const { roleId: _roleId, ...content } = input\n const notifications: Notification[] = []\n const uniqueRecipientUserIds = Array.from(new Set(recipientUserIds))\n const resolved = await resolveChannelsForRecipients(content, uniqueRecipientUserIds, ctx)\n const writeEm = rootEm.fork()\n\n await writeEm.transactional(async (tx) => {\n for (const { recipientUserId, channels } of resolved) {\n const notification = await createOrRefreshNotification(tx, content, recipientUserId, ctx, channels)\n notifications.push(notification)\n }\n await tx.flush()\n })\n\n await invalidateNotificationCache(container, ctx, 'created')\n await emitNotificationCreatedBatch(eventBus, notifications, ctx)\n await emitNotificationSseEvents(eventBus, notifications, ctx)\n\n return notifications\n },\n\n async createForFeature(input, ctx) {\n const em = rootEm.fork()\n const db = getDb(em)\n const recipientUserIds = await getRecipientUserIdsForFeature(db, ctx.tenantId, input.requiredFeature)\n\n if (recipientUserIds.length === 0) {\n debug('No users found with feature:', input.requiredFeature, 'in tenant:', ctx.tenantId)\n return []\n }\n\n let authorizedRecipientUserIds = recipientUserIds\n if (input.restrictRecipientsToOrganization) {\n const uniqueCandidateUserIds = Array.from(new Set(recipientUserIds))\n if (!ctx.organizationId) {\n logger.warn('Organization-restricted feature fan-out skipped because organization scope is missing', {\n tenantId: ctx.tenantId,\n requiredFeature: input.requiredFeature,\n })\n return []\n }\n\n if (uniqueCandidateUserIds.length > 200) {\n logger.warn('Organization-restricted feature fan-out skipped because the candidate cap was exceeded', {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n requiredFeature: input.requiredFeature,\n candidateCount: uniqueCandidateUserIds.length,\n candidateCap: 200,\n })\n return []\n }\n\n if (!container) {\n logger.warn('Organization-restricted feature fan-out skipped because the DI container is unavailable', {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n requiredFeature: input.requiredFeature,\n })\n return []\n }\n\n try {\n const rbacService = container.resolve('rbacService') as {\n userHasAllFeatures: (\n userId: string,\n features: string[],\n scope: { tenantId: string | null; organizationId: string | null },\n ) => Promise<boolean>\n }\n const allowedRecipientUserIds: string[] = []\n for (let offset = 0; offset < uniqueCandidateUserIds.length; offset += 10) {\n const candidates = uniqueCandidateUserIds.slice(offset, offset + 10)\n const results = await Promise.all(candidates.map(async (recipientUserId) => ({\n recipientUserId,\n allowed: await rbacService.userHasAllFeatures(\n recipientUserId,\n [input.requiredFeature],\n { tenantId: ctx.tenantId, organizationId: ctx.organizationId ?? null },\n ),\n })))\n for (const result of results) {\n if (result.allowed) allowedRecipientUserIds.push(result.recipientUserId)\n }\n }\n authorizedRecipientUserIds = allowedRecipientUserIds\n } catch (err) {\n logger.warn('Organization-restricted feature fan-out skipped because RBAC filtering failed', {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n requiredFeature: input.requiredFeature,\n err,\n })\n return []\n }\n\n if (authorizedRecipientUserIds.length === 0) {\n debug('No users found with feature in organization:', input.requiredFeature, ctx.organizationId)\n return []\n }\n }\n\n debug('Creating notifications for', authorizedRecipientUserIds.length, 'user(s) with feature:', input.requiredFeature)\n\n const {\n requiredFeature: _requiredFeature,\n restrictRecipientsToOrganization: _restrictRecipientsToOrganization,\n ...content\n } = input\n const notifications: Notification[] = []\n const uniqueRecipientUserIds = Array.from(new Set(authorizedRecipientUserIds))\n const resolved = await resolveChannelsForRecipients(content, uniqueRecipientUserIds, ctx)\n const writeEm = rootEm.fork()\n\n await writeEm.transactional(async (tx) => {\n for (const { recipientUserId, channels } of resolved) {\n const notification = await createOrRefreshNotification(tx, content, recipientUserId, ctx, channels)\n notifications.push(notification)\n }\n await tx.flush()\n })\n\n await invalidateNotificationCache(container, ctx, 'created')\n await emitNotificationCreatedBatch(eventBus, notifications, ctx)\n await emitNotificationSseEvents(eventBus, notifications, ctx)\n\n return notifications\n },\n\n async markAsRead(notificationId, ctx) {\n const em = rootEm.fork()\n const notification = await findScopedNotificationOrThrow(em, notificationId, ctx)\n\n if (notification.status === 'unread') {\n notification.status = 'read'\n notification.readAt = new Date()\n await em.flush()\n\n await invalidateNotificationCache(container, ctx, 'updated', notification.id)\n await eventBus.emit(NOTIFICATION_EVENTS.READ, {\n notificationId: notification.id,\n userId: ctx.userId,\n tenantId: ctx.tenantId,\n })\n }\n\n return notification\n },\n\n async markAllAsRead(ctx) {\n const em = rootEm.fork()\n const db = getDb(em)\n const applyScope = <QB extends { where: (...args: any[]) => QB }>(q: QB): QB => {\n let chain = q\n .where('recipient_user_id' as any, '=', ctx.userId as any)\n .where('tenant_id' as any, '=', ctx.tenantId)\n .where('status' as any, '=', 'unread')\n // Only in-app-visible rows count toward the badge (see getUnreadCount),\n // so \"mark all as read\" must scope to the SAME set \u2014 otherwise it flips\n // push/email-only rows the user never saw and SSE-broadcasts a read for\n // notifications that were never in the bell, inflating the returned\n // count past what the badge showed.\n .where(inAppVisibleSql() as any)\n if (ctx.organizationId) {\n chain = chain.where('organization_id' as any, '=', ctx.organizationId)\n }\n return chain\n }\n\n const targetRows = await applyScope(\n db\n .selectFrom('notifications' as any)\n .select([\n 'id' as any,\n 'organization_id' as any,\n 'recipient_user_id' as any,\n ]),\n ).execute() as Array<{ id: string }>\n\n if (!targetRows.length) {\n return 0\n }\n\n const updateResult = await applyScope(\n db.updateTable('notifications' as any).set({\n status: 'read',\n read_at: sql`now()`,\n } as any) as any,\n ).executeTakeFirst() as { numUpdatedRows?: bigint | number } | undefined\n const result = Number(updateResult?.numUpdatedRows ?? targetRows.length)\n\n await invalidateNotificationCache(container, ctx, 'updated')\n\n const notifications = await findWithDecryption(em, Notification, {\n id: { $in: targetRows.map((row) => row.id) },\n }, undefined, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n })\n\n for (const notification of notifications) {\n await eventBus.emit(NOTIFICATION_EVENTS.READ, {\n notificationId: notification.id,\n userId: ctx.userId,\n tenantId: ctx.tenantId,\n })\n\n await eventBus.emit(NOTIFICATION_SSE_EVENTS.CREATED, {\n tenantId: notification.tenantId,\n organizationId: notification.organizationId ?? null,\n recipientUserId: notification.recipientUserId,\n notification: toNotificationDto(notification),\n })\n }\n\n return result\n },\n\n async dismiss(notificationId, ctx) {\n const em = rootEm.fork()\n const notification = await findScopedNotificationOrThrow(em, notificationId, ctx)\n\n notification.status = 'dismissed'\n notification.dismissedAt = new Date()\n await em.flush()\n\n await invalidateNotificationCache(container, ctx, 'updated', notification.id)\n await eventBus.emit(NOTIFICATION_EVENTS.DISMISSED, {\n notificationId: notification.id,\n userId: ctx.userId,\n tenantId: ctx.tenantId,\n })\n\n return notification\n },\n\n async restoreDismissed(notificationId, status, ctx) {\n const em = rootEm.fork()\n const notification = await findScopedNotificationOrThrow(em, notificationId, ctx)\n\n if (notification.status !== 'dismissed') {\n return notification\n }\n\n // A dismissed notification whose action already ran comes back as `actioned`,\n // whatever the caller asked for: `actioned_at` outlives the dismissal.\n const targetStatus: NotificationStatus = notification.actionedAt != null ? 'actioned' : status ?? 'read'\n notification.status = targetStatus\n notification.dismissedAt = null\n\n if (targetStatus === 'unread') {\n notification.readAt = null\n } else if (!notification.readAt) {\n notification.readAt = new Date()\n }\n\n await em.flush()\n\n await invalidateNotificationCache(container, ctx, 'updated', notification.id)\n await eventBus.emit(NOTIFICATION_EVENTS.RESTORED, {\n notificationId: notification.id,\n userId: ctx.userId,\n tenantId: ctx.tenantId,\n status: targetStatus,\n })\n\n return notification\n },\n\n async executeAction(notificationId, input, ctx) {\n const em = rootEm.fork()\n const notification = await findScopedNotificationOrThrow(em, notificationId, ctx)\n\n const actionData = notification.actionData\n const action = actionData?.actions?.find((a) => a.id === input.actionId)\n\n if (!action) {\n throw new Error('Action not found')\n }\n\n // Reject an already-actioned notification before dispatching the command,\n // so a retry or double-click cannot re-run the side effect. `actioned_at` is\n // the durable marker: `status` is overwritten by a dismissal.\n if (notification.status === 'actioned' || notification.actionedAt != null) {\n throw actionAlreadyExecuted()\n }\n\n if (action.commandId) {\n const declared = findDeclaredCommandAction(notification.type, action)\n if (!declared || !(await userHoldsActionFeatures(declared.requiredFeatures, ctx))) {\n throw await actionForbidden()\n }\n }\n\n const actionedAt = new Date()\n const previousStatus = notification.status\n const previousActionedAt = notification.actionedAt ?? null\n const previousActionTaken = notification.actionTaken ?? null\n\n // Atomically claim the notification so only one concurrent request can run\n // the side-effecting command. The conditional UPDATE matches only while the\n // notification has not been actioned yet; a losing request updates 0 rows.\n const claimResult = (await getDb(em)\n .updateTable('notifications' as any)\n .set({\n status: 'actioned',\n actioned_at: actionedAt,\n action_taken: input.actionId,\n } as any)\n .where('id' as any, '=', notification.id)\n .where('recipient_user_id' as any, '=', ctx.userId as any)\n .where('tenant_id' as any, '=', ctx.tenantId)\n .where('status' as any, '!=', 'actioned')\n .where('actioned_at' as any, 'is', null)\n .executeTakeFirst()) as { numUpdatedRows?: bigint | number } | undefined\n\n if (Number(claimResult?.numUpdatedRows ?? 0) === 0) {\n throw actionAlreadyExecuted()\n }\n\n // The claim is provisional: if the side-effecting command fails, the action\n // never actually completed, so release the claim to its prior state. This\n // lets the user retry the action instead of the notification being locked as\n // `actioned` forever. The claim is owned through its own `actioned_at` and\n // `action_taken`, not through `status`: a dismissal that lands while the\n // command runs overwrites `status`, and the release must still clear the\n // claim then \u2014 while leaving that dismissal in place.\n const releaseClaim = async () => {\n await getDb(em)\n .updateTable('notifications' as any)\n .set({\n status: sql`case when status = 'actioned' then ${previousStatus} else status end`,\n actioned_at: previousActionedAt,\n action_taken: previousActionTaken,\n } as any)\n .where('id' as any, '=', notification.id)\n .where('recipient_user_id' as any, '=', ctx.userId as any)\n .where('tenant_id' as any, '=', ctx.tenantId)\n .where('actioned_at' as any, '=', actionedAt)\n .where('action_taken' as any, '=', input.actionId)\n .executeTakeFirst()\n }\n\n let result: unknown = null\n\n if (action.commandId && commandBus && container) {\n const commandInput = {\n ...input.payload,\n id: notification.sourceEntityId,\n }\n\n // Build a CommandRuntimeContext from the notification service context\n const commandCtx = {\n container,\n auth: {\n sub: ctx.userId,\n tenantId: ctx.tenantId,\n orgId: ctx.organizationId,\n },\n organizationScope: null,\n selectedOrganizationId: ctx.organizationId ?? null,\n organizationIds: ctx.organizationId ? [ctx.organizationId] : null,\n }\n\n let commandResult: { result: unknown }\n try {\n commandResult = await commandBus.execute(action.commandId, {\n input: commandInput,\n ctx: commandCtx,\n metadata: {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n resourceKind: 'notifications',\n },\n })\n } catch (err) {\n // Never let a rollback failure mask the original command error \u2014 the\n // caller needs the real failure to decide whether to retry.\n try {\n await releaseClaim()\n } catch (releaseErr) {\n debug('failed to release notification action claim', releaseErr)\n }\n throw err\n }\n\n result = commandResult.result\n }\n\n notification.status = 'actioned'\n notification.actionedAt = actionedAt\n notification.actionTaken = input.actionId\n notification.actionResult = result as Record<string, unknown>\n\n if (!notification.readAt) {\n notification.readAt = new Date()\n }\n\n await em.flush()\n\n await invalidateNotificationCache(container, ctx, 'updated', notification.id)\n await eventBus.emit(NOTIFICATION_EVENTS.ACTIONED, {\n notificationId: notification.id,\n actionId: input.actionId,\n userId: ctx.userId,\n tenantId: ctx.tenantId,\n })\n\n return { notification, result }\n },\n\n async getUnreadCount(ctx) {\n const em = rootEm.fork()\n return em.count(Notification, {\n recipientUserId: ctx.userId,\n tenantId: ctx.tenantId,\n status: 'unread',\n $and: [\n buildNotificationReadScopeWhere(ctx),\n inAppVisibleFilter(),\n ],\n })\n },\n\n async getPollData(ctx, since) {\n const em = rootEm.fork()\n const filters: Record<string, unknown> = {\n recipientUserId: ctx.userId,\n tenantId: ctx.tenantId,\n $and: [\n buildNotificationReadScopeWhere(ctx),\n inAppVisibleFilter(),\n ],\n }\n\n if (since) {\n filters.createdAt = { $gt: new Date(since) }\n }\n\n const [notifications, unreadCount] = await Promise.all([\n em.find(Notification, filters, {\n orderBy: { createdAt: 'desc' },\n limit: 50,\n }),\n em.count(Notification, {\n recipientUserId: ctx.userId,\n tenantId: ctx.tenantId,\n status: 'unread',\n $and: [\n buildNotificationReadScopeWhere(ctx),\n inAppVisibleFilter(),\n ],\n }),\n ])\n\n const recent = notifications.map(toNotificationDto)\n const hasNew = since ? recent.length > 0 : false\n\n return {\n unreadCount,\n recent,\n hasNew,\n lastId: recent[0]?.id,\n }\n },\n\n async cleanupExpired() {\n const em = rootEm.fork()\n const db = getDb(em)\n\n const affectedScopes = await db\n .selectFrom('notifications' as any)\n .select([\n 'tenant_id' as any,\n 'organization_id' as any,\n ])\n .where('expires_at' as any, '<', sql`now()`)\n .where('status' as any, 'not in', ['actioned', 'dismissed'])\n .distinct()\n .execute() as Array<{ tenant_id: string; organization_id: string | null }>\n\n if (!affectedScopes.length) return 0\n\n const updateResult = await db\n .updateTable('notifications' as any)\n .set({\n status: 'dismissed',\n dismissed_at: sql`now()`,\n } as any)\n .where('expires_at' as any, '<', sql`now()`)\n .where('status' as any, 'not in', ['actioned', 'dismissed'])\n .executeTakeFirst() as { numUpdatedRows?: bigint | number } | undefined\n\n for (const scope of affectedScopes) {\n await invalidateNotificationCache(container, {\n tenantId: scope.tenant_id,\n organizationId: scope.organization_id,\n }, 'updated')\n }\n\n return Number(updateResult?.numUpdatedRows ?? 0)\n },\n\n async deleteBySource(sourceEntityType, sourceEntityId, ctx) {\n const em = rootEm.fork()\n const db = getDb(em)\n\n const deleteResult = await db\n .deleteFrom('notifications' as any)\n .where('source_entity_type' as any, '=', sourceEntityType)\n .where('source_entity_id' as any, '=', sourceEntityId)\n .where('tenant_id' as any, '=', ctx.tenantId)\n .executeTakeFirst() as { numDeletedRows?: bigint | number } | undefined\n\n const deletedCount = Number(deleteResult?.numDeletedRows ?? 0)\n if (deletedCount > 0) {\n await invalidateNotificationCache(container, ctx, 'deleted')\n }\n\n return deletedCount\n },\n }\n}\n\n/**\n * Helper to create notification service from a DI container.\n * Use this in API routes and commands to avoid DI resolution issues.\n */\nexport function resolveNotificationService(container: {\n resolve: (name: string) => unknown\n}): NotificationService {\n const em = container.resolve('em') as EntityManager\n const eventBus = container.resolve('eventBus') as { emit: (event: string, payload: unknown) => Promise<void> }\n\n // commandBus may not be registered in all contexts, so resolve it safely\n let commandBus: NotificationServiceDeps['commandBus']\n try {\n commandBus = container.resolve('commandBus') as typeof commandBus\n } catch {\n // commandBus not available - actions with commandId won't work\n commandBus = undefined\n }\n\n return createNotificationService({ em, eventBus, commandBus, container })\n}\n"],
5
+ "mappings": "AACA,SAAsB,WAAW;AACjC,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC,SAAS,oBAA6C;AAEtD;AAAA,EACE;AAAA,EACA;AAAA,OAIK;AACP,SAAS,2BAA2B;AACpC,SAAS,2BAA2B;AACpC,SAAS,qBAAqB,+BAA+B;AAC7D,SAAS,uBAAuB,0BAA0B;AAC1D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP,SAAS,yBAAyB;AAClC,SAAS,uCAAuC;AAChD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,4BAA4B,mCAAmC;AACxE,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AACpC,SAAS,oCAAoE;AAC7E,SAAS,yCAAyC;AAClD,SAAS,gCAAgC;AACzC;AAAA,EACE;AAAA,OAEK;AACP,SAAS,oBAAoB,iBAAiB,sBAAsB;AAEpE,MAAM,SAAS,aAAa,eAAe,EAAE,MAAM,EAAE,WAAW,UAAU,CAAC;AAE3E,SAAS,MAAM,YAAoB,SAA0B;AAC3D,SAAO,MAAM,SAAS,QAAQ,SAAS,EAAE,QAAQ,IAAI,MAAS;AAChE;AA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MAAM;AAAA,QACxB,GAAG,SAAS;AAAA,MACd;AAEA,aAAO,OAAO,cAAc,kBAAkB,CAAC;AAAA,IACjD;AAAA,IAEA,MAAM,eAAe,kBAAkB,gBAAgB,KAAK;AAC1D,YAAM,KAAK,OAAO,KAAK;AACvB,YAAM,KAAK,MAAM,EAAE;AAEnB,YAAM,eAAe,MAAM,GACxB,WAAW,eAAsB,EACjC,MAAM,sBAA6B,KAAK,gBAAgB,EACxD,MAAM,oBAA2B,KAAK,cAAc,EACpD,MAAM,aAAoB,KAAK,IAAI,QAAQ,EAC3C,iBAAiB;AAEpB,YAAM,eAAe,OAAO,cAAc,kBAAkB,CAAC;AAC7D,UAAI,eAAe,GAAG;AACpB,cAAM,4BAA4B,WAAW,KAAK,SAAS;AAAA,MAC7D;AAEA,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAMO,SAAS,2BAA2B,WAEnB;AACtB,QAAM,KAAK,UAAU,QAAQ,IAAI;AACjC,QAAM,WAAW,UAAU,QAAQ,UAAU;AAG7C,MAAI;AACJ,MAAI;AACF,iBAAa,UAAU,QAAQ,YAAY;AAAA,EAC7C,QAAQ;AAEN,iBAAa;AAAA,EACf;AAEA,SAAO,0BAA0B,EAAE,IAAI,UAAU,YAAY,UAAU,CAAC;AAC1E;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/core",
3
- "version": "0.10.1-develop.7768.1.90fa052c11",
3
+ "version": "0.10.1-develop.7769.1.0e6458bb99",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -266,16 +266,16 @@
266
266
  "zod": "^4.4.3"
267
267
  },
268
268
  "peerDependencies": {
269
- "@open-mercato/ai-assistant": "0.10.1-develop.7768.1.90fa052c11",
270
- "@open-mercato/shared": "0.10.1-develop.7768.1.90fa052c11",
271
- "@open-mercato/ui": "0.10.1-develop.7768.1.90fa052c11",
269
+ "@open-mercato/ai-assistant": "0.10.1-develop.7769.1.0e6458bb99",
270
+ "@open-mercato/shared": "0.10.1-develop.7769.1.0e6458bb99",
271
+ "@open-mercato/ui": "0.10.1-develop.7769.1.0e6458bb99",
272
272
  "react": "^19.0.0",
273
273
  "react-dom": "^19.0.0"
274
274
  },
275
275
  "devDependencies": {
276
- "@open-mercato/ai-assistant": "0.10.1-develop.7768.1.90fa052c11",
277
- "@open-mercato/shared": "0.10.1-develop.7768.1.90fa052c11",
278
- "@open-mercato/ui": "0.10.1-develop.7768.1.90fa052c11",
276
+ "@open-mercato/ai-assistant": "0.10.1-develop.7769.1.0e6458bb99",
277
+ "@open-mercato/shared": "0.10.1-develop.7769.1.0e6458bb99",
278
+ "@open-mercato/ui": "0.10.1-develop.7769.1.0e6458bb99",
279
279
  "@testing-library/dom": "^10.4.1",
280
280
  "@testing-library/jest-dom": "^7.0.1",
281
281
  "@testing-library/react": "^16.3.3",
@@ -268,9 +268,13 @@ export type CreateFeatureNotificationServiceInput = CreateFeatureNotificationInp
268
268
  restrictRecipientsToOrganization?: boolean
269
269
  }
270
270
 
271
+ export type CreateBatchNotificationOptions = {
272
+ skipExistingGroup?: boolean
273
+ }
274
+
271
275
  export interface NotificationService {
272
276
  create(input: CreateNotificationInput, ctx: NotificationServiceContext): Promise<Notification>
273
- createBatch(input: CreateBatchNotificationInput, ctx: NotificationServiceContext): Promise<Notification[]>
277
+ createBatch(input: CreateBatchNotificationInput, ctx: NotificationServiceContext, options?: CreateBatchNotificationOptions): Promise<Notification[]>
274
278
  createForRole(input: CreateRoleNotificationInput, ctx: NotificationServiceContext): Promise<Notification[]>
275
279
  createForFeature(input: CreateFeatureNotificationServiceInput, ctx: NotificationServiceContext): Promise<Notification[]>
276
280
  markAsRead(notificationId: string, ctx: NotificationServiceContext): Promise<Notification>
@@ -436,8 +440,12 @@ export function createNotificationService(deps: NotificationServiceDeps): Notifi
436
440
  return notification
437
441
  },
438
442
 
439
- async createBatch(input, ctx) {
443
+ async createBatch(input, ctx, options) {
444
+ if (options?.skipExistingGroup && !input.groupKey?.trim()) {
445
+ throw new Error('[internal] Notification group key is required for deduplicated batch delivery')
446
+ }
440
447
  const recipientUserIds = Array.from(new Set(input.recipientUserIds))
448
+ if (options?.skipExistingGroup) recipientUserIds.sort((left, right) => left.localeCompare(right))
441
449
  const { recipientUserIds: _recipientUserIds, ...content } = input
442
450
  const notifications: Notification[] = []
443
451
  const resolved = await resolveChannelsForRecipients(content, recipientUserIds, ctx)
@@ -446,12 +454,26 @@ export function createNotificationService(deps: NotificationServiceDeps): Notifi
446
454
  await writeEm.transactional(async (tx) => {
447
455
  await assertNotificationRecipientsInScope(tx, recipientUserIds, ctx)
448
456
  for (const { recipientUserId, channels } of resolved) {
457
+ if (options?.skipExistingGroup) {
458
+ const organizationId = normalizeOrgScope(ctx.organizationId)
459
+ const lockKey = `notifications:${ctx.tenantId}:${organizationId ?? 'global'}:${recipientUserId}:${content.type}:${content.groupKey}`
460
+ await sql`select pg_advisory_xact_lock(hashtext(${lockKey}))`.execute(getDb(tx))
461
+ const existing = await tx.findOne(Notification, {
462
+ recipientUserId,
463
+ tenantId: ctx.tenantId,
464
+ organizationId,
465
+ type: content.type,
466
+ groupKey: content.groupKey,
467
+ })
468
+ if (existing) continue
469
+ }
449
470
  const notification = await createOrRefreshNotification(tx, content, recipientUserId, ctx, channels)
450
471
  notifications.push(notification)
451
472
  }
452
473
  await tx.flush()
453
474
  })
454
475
 
476
+ if (options?.skipExistingGroup && notifications.length === 0) return []
455
477
  await invalidateNotificationCache(container, ctx, 'created')
456
478
  await emitNotificationCreatedBatch(eventBus, notifications, ctx)
457
479
  await emitNotificationSseEvents(eventBus, notifications, ctx)