@open-mercato/core 0.6.6-develop.6507.1.cc8b36505d → 0.6.6-develop.6515.1.01911d00e2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/modules/communication_channels/data/enrichers.js +22 -1
- package/dist/modules/communication_channels/data/enrichers.js.map +2 -2
- package/dist/modules/inbox_ops/api/proposals/[id]/translate/route.js +1 -1
- package/dist/modules/inbox_ops/api/proposals/[id]/translate/route.js.map +2 -2
- package/dist/modules/integrations/lib/credentials-field-validation.js +1 -0
- package/dist/modules/integrations/lib/credentials-field-validation.js.map +2 -2
- package/dist/modules/integrations/lib/credentials-masking.js +16 -0
- package/dist/modules/integrations/lib/credentials-masking.js.map +2 -2
- package/dist/modules/notifications/lib/notificationRecipients.js +11 -1
- package/dist/modules/notifications/lib/notificationRecipients.js.map +2 -2
- package/dist/modules/notifications/lib/notificationService.js +18 -1
- package/dist/modules/notifications/lib/notificationService.js.map +2 -2
- package/dist/modules/sales/commands/returns.js +48 -17
- package/dist/modules/sales/commands/returns.js.map +3 -3
- package/package.json +7 -7
- package/src/modules/communication_channels/data/enrichers.ts +55 -1
- package/src/modules/inbox_ops/api/proposals/[id]/translate/route.ts +1 -1
- package/src/modules/integrations/AGENTS.md +1 -0
- package/src/modules/integrations/lib/credentials-field-validation.ts +1 -0
- package/src/modules/integrations/lib/credentials-masking.ts +17 -0
- package/src/modules/notifications/lib/notificationRecipients.ts +24 -0
- package/src/modules/notifications/lib/notificationService.ts +24 -1
- package/src/modules/sales/commands/returns.ts +49 -2
|
@@ -34,11 +34,29 @@ const messageChannelEnricher = {
|
|
|
34
34
|
const tenantId = ctx.tenantId;
|
|
35
35
|
const organizationId = ctx.organizationId ?? null;
|
|
36
36
|
const dscope = { tenantId, organizationId };
|
|
37
|
+
const userId = typeof ctx.userId === "string" ? ctx.userId : null;
|
|
38
|
+
if (!userId) {
|
|
39
|
+
return records.map((record) => ({
|
|
40
|
+
...record,
|
|
41
|
+
_channel: null,
|
|
42
|
+
_channelPayload: null,
|
|
43
|
+
_channelContact: null
|
|
44
|
+
}));
|
|
45
|
+
}
|
|
46
|
+
const db = em.getKysely();
|
|
47
|
+
let participantQuery = db.selectFrom("messages as m").leftJoin("message_recipients as r", (join) => join.onRef("m.id", "=", "r.message_id").on("r.recipient_user_id", "=", userId).on("r.deleted_at", "is", null)).select("m.id").distinct().where("m.id", "in", messageIds).where("m.tenant_id", "=", tenantId).where("m.deleted_at", "is", null).where((eb) => eb.or([
|
|
48
|
+
eb("m.sender_user_id", "=", userId),
|
|
49
|
+
eb("r.message_id", "is not", null)
|
|
50
|
+
]));
|
|
51
|
+
participantQuery = organizationId !== null ? participantQuery.where("m.organization_id", "=", organizationId) : participantQuery.where("m.organization_id", "is", null);
|
|
52
|
+
const participantRows = await participantQuery.execute();
|
|
53
|
+
const participantMessageIds = participantRows.map((row) => row.id);
|
|
54
|
+
const participantMessageIdSet = new Set(participantMessageIds);
|
|
37
55
|
const links = await findWithDecryption(
|
|
38
56
|
em,
|
|
39
57
|
MessageChannelLink,
|
|
40
58
|
{
|
|
41
|
-
messageId: { $in:
|
|
59
|
+
messageId: { $in: participantMessageIds },
|
|
42
60
|
tenantId,
|
|
43
61
|
organizationId
|
|
44
62
|
},
|
|
@@ -90,6 +108,9 @@ const messageChannelEnricher = {
|
|
|
90
108
|
if (channel) channelByMessageId.set(link.messageId, channel);
|
|
91
109
|
}
|
|
92
110
|
return records.map((r) => {
|
|
111
|
+
if (!participantMessageIdSet.has(r.id)) {
|
|
112
|
+
return { ...r, _channel: null, _channelPayload: null, _channelContact: null };
|
|
113
|
+
}
|
|
93
114
|
const link = linksByMessage.get(r.id);
|
|
94
115
|
if (!link) {
|
|
95
116
|
return { ...r, _channel: null, _channelPayload: null, _channelContact: null };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/communication_channels/data/enrichers.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { EnricherContext, ResponseEnricher } from '@open-mercato/shared/lib/crud/response-enricher'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { sanitizeChannelHtml } from '../lib/sanitize-channel-html'\nimport {\n CommunicationChannel,\n ExternalConversation,\n MessageChannelLink,\n MessageReaction,\n} from './entities'\n\n/**\n * Response enrichers for the messages.message entity.\n *\n * The hub declares 2 enrichers; downstream hosts (Messages module's `/api/messages`\n * CRUD route + future provider routes) opt in via `makeCrudRoute({ enrichers: { entityId: 'messages.message' } })`.\n *\n * - `messageChannelEnricher` \u2192 `_channel`, `_channelPayload`, `_channelContact`\n * - `messageReactionsEnricher` \u2192 `_reactions`\n *\n * The channel/payload/contact enrichments were three separate enrichers, each\n * independently issuing its own `MessageChannelLink` `$in` query (and two of them\n * an `ExternalConversation` query) for the same message page. Because the shared\n * enricher runner executes active enrichers sequentially with no per-pass shared\n * context, those lookups were repeated for every page (#3183). They are merged\n * into one batched enricher so the link batch (and the conversation batch) is\n * loaded once per pass, while preserving the public enriched field names:\n *\n * - `_channel` \u2192 channel metadata + capabilities snapshot\n * - `_channelPayload` \u2192 channel-native payload (Block Kit / interactive / email MIME / \u2026)\n * - `_channelContact` \u2192 CRM person preview (email + display name)\n * - `_reactions` \u2192 grouped emoji counts + users + reactedByMe\n *\n * Per `packages/shared/lib/crud/response-enricher` rules:\n * - `enrichMany` is implemented for every enricher (N+1 prevention).\n * - Enriched fields are namespaced with `_channel*` / `_reactions` prefixes.\n * - Enrichers are read-only; no writes via the EntityManager.\n * - Each enricher is feature-gated by `communication_channels.view`.\n */\n\ntype MessageRecord = Record<string, unknown> & {\n id: string\n threadId?: string | null\n}\n\ntype ResolvedCtx = EnricherContext & {\n em: EntityManager\n}\n\nfunction ctxEm(ctx: EnricherContext): EntityManager {\n return ctx.em as EntityManager\n}\n\nexport type ChannelEnrichment = {\n providerKey: string\n channelType: string\n direction: 'inbound' | 'outbound' | string\n deliveryStatus: string | null\n capabilities: Record<string, unknown> | null\n}\n\nexport type ChannelPayloadEnrichment = {\n channelContentType: string | null\n channelPayload: Record<string, unknown> | null\n interactiveState: Record<string, unknown> | null\n channelMetadata: Record<string, unknown> | null\n /**\n * Server-sanitized email HTML, safe for `dangerouslySetInnerHTML`. Populated\n * for `email/*` payloads that carry an html body, `null` otherwise. Sanitizing\n * here keeps `sanitize-html` off the client render path.\n */\n sanitizedHtml: string | null\n}\n\nexport type ChannelContactEnrichment = {\n contactPersonId: string | null\n assignedUserId: string | null\n subject: string | null\n}\n\n/**\n * Sanitize channel-supplied email HTML on the server so the client widget never\n * has to pull `sanitize-html` into the browser bundle or run sanitization on the\n * render path. Returns the sanitized HTML for `email/*` payloads that carry an\n * html body, and `null` otherwise. The raw `channelPayload` is left untouched so\n * provider-package widget overrides keep their existing data contract.\n */\nfunction sanitizeEmailPayloadHtml(\n contentType: string | null | undefined,\n payload: Record<string, unknown> | null | undefined,\n): string | null {\n if (!contentType || !contentType.startsWith('email/')) return null\n const html = payload?.html\n if (typeof html !== 'string' || html.length === 0) return null\n return sanitizeChannelHtml(html)\n}\n\n// \u2500\u2500 _channel + _channelPayload + _channelContact \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst messageChannelEnricher: ResponseEnricher<\n MessageRecord,\n {\n _channel?: ChannelEnrichment | null\n _channelPayload?: ChannelPayloadEnrichment | null\n _channelContact?: ChannelContactEnrichment | null\n }\n> = {\n id: 'communication_channels.message-channel',\n targetEntity: 'messages.message',\n features: ['communication_channels.view'],\n priority: 30,\n timeout: 2000,\n fallback: { _channel: null, _channelPayload: null, _channelContact: null },\n critical: false,\n\n async enrichOne(record, ctx) {\n const [out] = await this.enrichMany!([record], ctx)\n return out\n },\n\n async enrichMany(records, ctx) {\n if (records.length === 0) return records\n const messageIds = records.map((r) => r.id)\n const em = ctxEm(ctx)\n const tenantId = ctx.tenantId as string\n const organizationId = ctx.organizationId ?? null\n const dscope = { tenantId, organizationId }\n\n // 1) MessageChannelLink \u2014 one bounded `$in` query for the whole page, shared by\n // all three enrichments (channel metadata, channel payload, conversation\n // contact). The result set is already bounded by the `messageId $in messageIds`\n // filter (the host list endpoint caps the page at 100), so no separate row\n // limit is needed.\n const links = await findWithDecryption(\n em,\n MessageChannelLink,\n {\n messageId: { $in: messageIds },\n tenantId,\n organizationId,\n },\n undefined,\n dscope,\n )\n const linksByMessage = new Map<string, MessageChannelLink>()\n for (const link of links) linksByMessage.set(link.messageId, link)\n\n // 2) ExternalConversation \u2014 one query, shared by the channel-capabilities hop and\n // the conversation-contact enrichment.\n const conversationIds = Array.from(\n new Set(\n links\n .map((l) => l.externalConversationId)\n .filter((id): id is string => typeof id === 'string' && id.length > 0),\n ),\n )\n const conversationsById = new Map<string, ExternalConversation>()\n if (conversationIds.length > 0) {\n const conversations = await findWithDecryption(\n em,\n ExternalConversation,\n { id: { $in: conversationIds }, tenantId, organizationId },\n undefined,\n dscope,\n )\n for (const conversation of conversations) {\n conversationsById.set(conversation.id, conversation)\n }\n }\n\n // 3) CommunicationChannel \u2014 capabilities snapshot. Resolve by `id` (not\n // `providerKey`): multi-user channels share the same `providerKey` (e.g. two\n // users with Gmail), so a providerKey-keyed map collapses them and returns the\n // wrong owner's capabilities. The hop is `link \u2192 ExternalConversation \u2192 CommunicationChannel`.\n const channelIds = Array.from(\n new Set(\n Array.from(conversationsById.values())\n .map((conversation) => conversation.channelId)\n .filter((id): id is string => typeof id === 'string' && id.length > 0),\n ),\n )\n const channelsById = new Map<string, CommunicationChannel>()\n if (channelIds.length > 0) {\n const channels = await findWithDecryption(\n em,\n CommunicationChannel,\n { id: { $in: channelIds }, tenantId, organizationId, deletedAt: null },\n undefined,\n dscope,\n )\n for (const channel of channels) channelsById.set(channel.id, channel)\n }\n\n const channelByMessageId = new Map<string, CommunicationChannel>()\n for (const link of links) {\n if (!link.externalConversationId) continue\n const conversation = conversationsById.get(link.externalConversationId)\n if (!conversation) continue\n const channel = conversation.channelId ? channelsById.get(conversation.channelId) : undefined\n if (channel) channelByMessageId.set(link.messageId, channel)\n }\n\n return records.map((r) => {\n const link = linksByMessage.get(r.id)\n if (!link) {\n return { ...r, _channel: null, _channelPayload: null, _channelContact: null }\n }\n\n const channel = channelByMessageId.get(r.id)\n const channelEnrichment: ChannelEnrichment = {\n providerKey: link.providerKey,\n channelType: link.channelType,\n direction: link.direction,\n deliveryStatus: link.deliveryStatus ?? null,\n capabilities: (channel?.capabilities as Record<string, unknown> | null) ?? null,\n }\n\n const payloadEnrichment: ChannelPayloadEnrichment = {\n channelContentType: link.channelContentType ?? null,\n channelPayload: link.channelPayload ?? null,\n interactiveState: link.interactiveState ?? null,\n channelMetadata: link.channelMetadata ?? null,\n sanitizedHtml: sanitizeEmailPayloadHtml(link.channelContentType, link.channelPayload),\n }\n\n const conversation = link.externalConversationId\n ? conversationsById.get(link.externalConversationId)\n : undefined\n const contactEnrichment: ChannelContactEnrichment | null = conversation\n ? {\n contactPersonId: conversation.contactPersonId ?? null,\n assignedUserId: conversation.assignedUserId ?? null,\n subject: conversation.subject ?? null,\n }\n : null\n\n return {\n ...r,\n _channel: channelEnrichment,\n _channelPayload: payloadEnrichment,\n _channelContact: contactEnrichment,\n }\n })\n },\n}\n\n// \u2500\u2500 _reactions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst messageReactionsEnricher: ResponseEnricher<\n MessageRecord,\n { _reactions?: ReactionGroup[] }\n> = {\n id: 'communication_channels.message-reactions',\n targetEntity: 'messages.message',\n features: ['communication_channels.view'],\n priority: 25,\n timeout: 1500,\n fallback: { _reactions: [] },\n critical: false,\n\n async enrichOne(record, ctx) {\n const [out] = await this.enrichMany!([record], ctx)\n return out\n },\n\n async enrichMany(records, ctx) {\n if (records.length === 0) return records\n const messageIds = records.map((r) => r.id)\n const em = ctxEm(ctx)\n const dscope = { tenantId: ctx.tenantId, organizationId: ctx.organizationId ?? null }\n const reactions = await findWithDecryption(\n em,\n MessageReaction,\n {\n messageId: { $in: messageIds },\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n },\n undefined,\n dscope,\n )\n\n const byMessage = new Map<string, MessageReaction[]>()\n for (const reaction of reactions) {\n const existing = byMessage.get(reaction.messageId) ?? []\n existing.push(reaction)\n byMessage.set(reaction.messageId, existing)\n }\n\n return records.map((r) => {\n const rows = byMessage.get(r.id) ?? []\n const grouped = groupReactions(rows, ctx.userId)\n return { ...r, _reactions: grouped }\n })\n },\n}\n\nexport type ReactionGroup = {\n emoji: string\n count: number\n users: Array<{\n userId?: string | null\n externalId?: string | null\n displayName?: string | null\n providerKey?: string | null\n }>\n reactedByMe: boolean\n /**\n * MessageReaction.id of the current user's reaction row, if any. Exposed so\n * the reaction-bar UI can issue\n * `DELETE /api/communication_channels/messages/{messageId}/reactions/{myReactionId}`\n * when the user toggles their own reaction off. Null when `reactedByMe` is\n * false or the row was added by an external participant (provider-side).\n */\n myReactionId: string | null\n}\n\nfunction groupReactions(rows: MessageReaction[], currentUserId: string): ReactionGroup[] {\n const map = new Map<string, ReactionGroup>()\n for (const row of rows) {\n const key = row.emoji\n if (!map.has(key)) {\n map.set(key, { emoji: key, count: 0, users: [], reactedByMe: false, myReactionId: null })\n }\n const group = map.get(key)!\n group.count += 1\n group.users.push({\n userId: row.reactedByUserId ?? null,\n externalId: row.reactedByExternalId ?? null,\n displayName: row.reactedByDisplayName ?? null,\n providerKey: row.providerKey ?? null,\n })\n if (row.reactedByUserId && row.reactedByUserId === currentUserId) {\n group.reactedByMe = true\n if (!group.myReactionId) group.myReactionId = row.id ?? null\n }\n }\n return Array.from(map.values()).sort((a, b) => b.count - a.count)\n}\n\n// \u2500\u2500 Export \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport const enrichers: ResponseEnricher[] = [\n messageChannelEnricher as unknown as ResponseEnricher,\n messageReactionsEnricher as unknown as ResponseEnricher,\n]\n\nexport default enrichers\n"],
|
|
5
|
-
"mappings": "AAEA,SAAS,0BAA0B;AACnC,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { EnricherContext, ResponseEnricher } from '@open-mercato/shared/lib/crud/response-enricher'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { sanitizeChannelHtml } from '../lib/sanitize-channel-html'\nimport {\n CommunicationChannel,\n ExternalConversation,\n MessageChannelLink,\n MessageReaction,\n} from './entities'\n\n/**\n * Response enrichers for the messages.message entity.\n *\n * The hub declares 2 enrichers; downstream hosts (Messages module's `/api/messages`\n * CRUD route + future provider routes) opt in via `makeCrudRoute({ enrichers: { entityId: 'messages.message' } })`.\n *\n * - `messageChannelEnricher` \u2192 `_channel`, `_channelPayload`, `_channelContact`\n * - `messageReactionsEnricher` \u2192 `_reactions`\n *\n * The channel/payload/contact enrichments were three separate enrichers, each\n * independently issuing its own `MessageChannelLink` `$in` query (and two of them\n * an `ExternalConversation` query) for the same message page. Because the shared\n * enricher runner executes active enrichers sequentially with no per-pass shared\n * context, those lookups were repeated for every page (#3183). They are merged\n * into one batched enricher so the link batch (and the conversation batch) is\n * loaded once per pass, while preserving the public enriched field names:\n *\n * - `_channel` \u2192 channel metadata + capabilities snapshot\n * - `_channelPayload` \u2192 channel-native payload (Block Kit / interactive / email MIME / \u2026)\n * - `_channelContact` \u2192 CRM person preview (email + display name)\n * - `_reactions` \u2192 grouped emoji counts + users + reactedByMe\n *\n * Per `packages/shared/lib/crud/response-enricher` rules:\n * - `enrichMany` is implemented for every enricher (N+1 prevention).\n * - Enriched fields are namespaced with `_channel*` / `_reactions` prefixes.\n * - Enrichers are read-only; no writes via the EntityManager.\n * - Each enricher is feature-gated by `communication_channels.view`.\n */\n\ntype MessageRecord = Record<string, unknown> & {\n id: string\n threadId?: string | null\n}\n\ntype MessageParticipantDatabase = {\n messages: {\n id: string\n tenant_id: string\n organization_id: string | null\n sender_user_id: string\n deleted_at: Date | null\n }\n message_recipients: {\n message_id: string\n recipient_user_id: string\n deleted_at: Date | null\n }\n}\n\ntype ResolvedCtx = EnricherContext & {\n em: EntityManager\n}\n\nfunction ctxEm(ctx: EnricherContext): EntityManager {\n return ctx.em as EntityManager\n}\n\nexport type ChannelEnrichment = {\n providerKey: string\n channelType: string\n direction: 'inbound' | 'outbound' | string\n deliveryStatus: string | null\n capabilities: Record<string, unknown> | null\n}\n\nexport type ChannelPayloadEnrichment = {\n channelContentType: string | null\n channelPayload: Record<string, unknown> | null\n interactiveState: Record<string, unknown> | null\n channelMetadata: Record<string, unknown> | null\n /**\n * Server-sanitized email HTML, safe for `dangerouslySetInnerHTML`. Populated\n * for `email/*` payloads that carry an html body, `null` otherwise. Sanitizing\n * here keeps `sanitize-html` off the client render path.\n */\n sanitizedHtml: string | null\n}\n\nexport type ChannelContactEnrichment = {\n contactPersonId: string | null\n assignedUserId: string | null\n subject: string | null\n}\n\n/**\n * Sanitize channel-supplied email HTML on the server so the client widget never\n * has to pull `sanitize-html` into the browser bundle or run sanitization on the\n * render path. Returns the sanitized HTML for `email/*` payloads that carry an\n * html body, and `null` otherwise. The raw `channelPayload` is left untouched so\n * provider-package widget overrides keep their existing data contract.\n */\nfunction sanitizeEmailPayloadHtml(\n contentType: string | null | undefined,\n payload: Record<string, unknown> | null | undefined,\n): string | null {\n if (!contentType || !contentType.startsWith('email/')) return null\n const html = payload?.html\n if (typeof html !== 'string' || html.length === 0) return null\n return sanitizeChannelHtml(html)\n}\n\n// \u2500\u2500 _channel + _channelPayload + _channelContact \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst messageChannelEnricher: ResponseEnricher<\n MessageRecord,\n {\n _channel?: ChannelEnrichment | null\n _channelPayload?: ChannelPayloadEnrichment | null\n _channelContact?: ChannelContactEnrichment | null\n }\n> = {\n id: 'communication_channels.message-channel',\n targetEntity: 'messages.message',\n features: ['communication_channels.view'],\n priority: 30,\n timeout: 2000,\n fallback: { _channel: null, _channelPayload: null, _channelContact: null },\n critical: false,\n\n async enrichOne(record, ctx) {\n const [out] = await this.enrichMany!([record], ctx)\n return out\n },\n\n async enrichMany(records, ctx) {\n if (records.length === 0) return records\n const messageIds = records.map((r) => r.id)\n const em = ctxEm(ctx)\n const tenantId = ctx.tenantId as string\n const organizationId = ctx.organizationId ?? null\n const dscope = { tenantId, organizationId }\n\n const userId = typeof ctx.userId === 'string' ? ctx.userId : null\n if (!userId) {\n return records.map((record) => ({\n ...record,\n _channel: null,\n _channelPayload: null,\n _channelContact: null,\n }))\n }\n\n const db = em.getKysely<MessageParticipantDatabase>()\n let participantQuery = db\n .selectFrom('messages as m')\n .leftJoin('message_recipients as r', (join) => join\n .onRef('m.id', '=', 'r.message_id')\n .on('r.recipient_user_id', '=', userId)\n .on('r.deleted_at', 'is', null))\n .select('m.id')\n .distinct()\n .where('m.id', 'in', messageIds)\n .where('m.tenant_id', '=', tenantId)\n .where('m.deleted_at', 'is', null)\n .where((eb) => eb.or([\n eb('m.sender_user_id', '=', userId),\n eb('r.message_id', 'is not', null),\n ]))\n\n participantQuery = organizationId !== null\n ? participantQuery.where('m.organization_id', '=', organizationId)\n : participantQuery.where('m.organization_id', 'is', null)\n\n const participantRows = await participantQuery.execute()\n const participantMessageIds = participantRows.map((row) => row.id)\n const participantMessageIdSet = new Set(participantMessageIds)\n\n // 1) MessageChannelLink \u2014 one bounded `$in` query for the whole page, shared by\n // all three enrichments (channel metadata, channel payload, conversation\n // contact). The result set is already bounded by the `messageId $in messageIds`\n // filter (the host list endpoint caps the page at 100), so no separate row\n // limit is needed.\n const links = await findWithDecryption(\n em,\n MessageChannelLink,\n {\n messageId: { $in: participantMessageIds },\n tenantId,\n organizationId,\n },\n undefined,\n dscope,\n )\n const linksByMessage = new Map<string, MessageChannelLink>()\n for (const link of links) linksByMessage.set(link.messageId, link)\n\n // 2) ExternalConversation \u2014 one query, shared by the channel-capabilities hop and\n // the conversation-contact enrichment.\n const conversationIds = Array.from(\n new Set(\n links\n .map((l) => l.externalConversationId)\n .filter((id): id is string => typeof id === 'string' && id.length > 0),\n ),\n )\n const conversationsById = new Map<string, ExternalConversation>()\n if (conversationIds.length > 0) {\n const conversations = await findWithDecryption(\n em,\n ExternalConversation,\n { id: { $in: conversationIds }, tenantId, organizationId },\n undefined,\n dscope,\n )\n for (const conversation of conversations) {\n conversationsById.set(conversation.id, conversation)\n }\n }\n\n // 3) CommunicationChannel \u2014 capabilities snapshot. Resolve by `id` (not\n // `providerKey`): multi-user channels share the same `providerKey` (e.g. two\n // users with Gmail), so a providerKey-keyed map collapses them and returns the\n // wrong owner's capabilities. The hop is `link \u2192 ExternalConversation \u2192 CommunicationChannel`.\n const channelIds = Array.from(\n new Set(\n Array.from(conversationsById.values())\n .map((conversation) => conversation.channelId)\n .filter((id): id is string => typeof id === 'string' && id.length > 0),\n ),\n )\n const channelsById = new Map<string, CommunicationChannel>()\n if (channelIds.length > 0) {\n const channels = await findWithDecryption(\n em,\n CommunicationChannel,\n { id: { $in: channelIds }, tenantId, organizationId, deletedAt: null },\n undefined,\n dscope,\n )\n for (const channel of channels) channelsById.set(channel.id, channel)\n }\n\n const channelByMessageId = new Map<string, CommunicationChannel>()\n for (const link of links) {\n if (!link.externalConversationId) continue\n const conversation = conversationsById.get(link.externalConversationId)\n if (!conversation) continue\n const channel = conversation.channelId ? channelsById.get(conversation.channelId) : undefined\n if (channel) channelByMessageId.set(link.messageId, channel)\n }\n\n return records.map((r) => {\n if (!participantMessageIdSet.has(r.id)) {\n return { ...r, _channel: null, _channelPayload: null, _channelContact: null }\n }\n\n const link = linksByMessage.get(r.id)\n if (!link) {\n return { ...r, _channel: null, _channelPayload: null, _channelContact: null }\n }\n\n const channel = channelByMessageId.get(r.id)\n const channelEnrichment: ChannelEnrichment = {\n providerKey: link.providerKey,\n channelType: link.channelType,\n direction: link.direction,\n deliveryStatus: link.deliveryStatus ?? null,\n capabilities: (channel?.capabilities as Record<string, unknown> | null) ?? null,\n }\n\n const payloadEnrichment: ChannelPayloadEnrichment = {\n channelContentType: link.channelContentType ?? null,\n channelPayload: link.channelPayload ?? null,\n interactiveState: link.interactiveState ?? null,\n channelMetadata: link.channelMetadata ?? null,\n sanitizedHtml: sanitizeEmailPayloadHtml(link.channelContentType, link.channelPayload),\n }\n\n const conversation = link.externalConversationId\n ? conversationsById.get(link.externalConversationId)\n : undefined\n const contactEnrichment: ChannelContactEnrichment | null = conversation\n ? {\n contactPersonId: conversation.contactPersonId ?? null,\n assignedUserId: conversation.assignedUserId ?? null,\n subject: conversation.subject ?? null,\n }\n : null\n\n return {\n ...r,\n _channel: channelEnrichment,\n _channelPayload: payloadEnrichment,\n _channelContact: contactEnrichment,\n }\n })\n },\n}\n\n// \u2500\u2500 _reactions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst messageReactionsEnricher: ResponseEnricher<\n MessageRecord,\n { _reactions?: ReactionGroup[] }\n> = {\n id: 'communication_channels.message-reactions',\n targetEntity: 'messages.message',\n features: ['communication_channels.view'],\n priority: 25,\n timeout: 1500,\n fallback: { _reactions: [] },\n critical: false,\n\n async enrichOne(record, ctx) {\n const [out] = await this.enrichMany!([record], ctx)\n return out\n },\n\n async enrichMany(records, ctx) {\n if (records.length === 0) return records\n const messageIds = records.map((r) => r.id)\n const em = ctxEm(ctx)\n const dscope = { tenantId: ctx.tenantId, organizationId: ctx.organizationId ?? null }\n const reactions = await findWithDecryption(\n em,\n MessageReaction,\n {\n messageId: { $in: messageIds },\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n },\n undefined,\n dscope,\n )\n\n const byMessage = new Map<string, MessageReaction[]>()\n for (const reaction of reactions) {\n const existing = byMessage.get(reaction.messageId) ?? []\n existing.push(reaction)\n byMessage.set(reaction.messageId, existing)\n }\n\n return records.map((r) => {\n const rows = byMessage.get(r.id) ?? []\n const grouped = groupReactions(rows, ctx.userId)\n return { ...r, _reactions: grouped }\n })\n },\n}\n\nexport type ReactionGroup = {\n emoji: string\n count: number\n users: Array<{\n userId?: string | null\n externalId?: string | null\n displayName?: string | null\n providerKey?: string | null\n }>\n reactedByMe: boolean\n /**\n * MessageReaction.id of the current user's reaction row, if any. Exposed so\n * the reaction-bar UI can issue\n * `DELETE /api/communication_channels/messages/{messageId}/reactions/{myReactionId}`\n * when the user toggles their own reaction off. Null when `reactedByMe` is\n * false or the row was added by an external participant (provider-side).\n */\n myReactionId: string | null\n}\n\nfunction groupReactions(rows: MessageReaction[], currentUserId: string): ReactionGroup[] {\n const map = new Map<string, ReactionGroup>()\n for (const row of rows) {\n const key = row.emoji\n if (!map.has(key)) {\n map.set(key, { emoji: key, count: 0, users: [], reactedByMe: false, myReactionId: null })\n }\n const group = map.get(key)!\n group.count += 1\n group.users.push({\n userId: row.reactedByUserId ?? null,\n externalId: row.reactedByExternalId ?? null,\n displayName: row.reactedByDisplayName ?? null,\n providerKey: row.providerKey ?? null,\n })\n if (row.reactedByUserId && row.reactedByUserId === currentUserId) {\n group.reactedByMe = true\n if (!group.myReactionId) group.myReactionId = row.id ?? null\n }\n }\n return Array.from(map.values()).sort((a, b) => b.count - a.count)\n}\n\n// \u2500\u2500 Export \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport const enrichers: ResponseEnricher[] = [\n messageChannelEnricher as unknown as ResponseEnricher,\n messageReactionsEnricher as unknown as ResponseEnricher,\n]\n\nexport default enrichers\n"],
|
|
5
|
+
"mappings": "AAEA,SAAS,0BAA0B;AACnC,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAuDP,SAAS,MAAM,KAAqC;AAClD,SAAO,IAAI;AACb;AAoCA,SAAS,yBACP,aACA,SACe;AACf,MAAI,CAAC,eAAe,CAAC,YAAY,WAAW,QAAQ,EAAG,QAAO;AAC9D,QAAM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AgC;AAAA,EAC3C;AAAA,EACA;AACF;AAEA,IAAO,oBAAQ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -10,7 +10,7 @@ import {
|
|
|
10
10
|
isErrorResponse
|
|
11
11
|
} from "../../../routeHelpers.js";
|
|
12
12
|
const metadata = {
|
|
13
|
-
POST: { requireAuth: true, requireFeatures: ["inbox_ops.proposals.
|
|
13
|
+
POST: { requireAuth: true, requireFeatures: ["inbox_ops.proposals.manage"] }
|
|
14
14
|
};
|
|
15
15
|
async function POST(req) {
|
|
16
16
|
try {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../src/modules/inbox_ops/api/proposals/%5Bid%5D/translate/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { InboxProposalAction } from '../../../../data/entities'\nimport type { ProposalTranslationEntry } from '../../../../data/entities'\nimport { translateProposalSchema } from '../../../../data/validators'\nimport { translateProposalContent } from '../../../../lib/translationProvider'\nimport {\n resolveRequestContext,\n resolveProposal,\n handleRouteError,\n isErrorResponse,\n} from '../../../routeHelpers'\n\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: ['inbox_ops.proposals.
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAE7B,SAAS,0BAA0B;AACnC,SAAS,2BAA2B;AAEpC,SAAS,+BAA+B;AACxC,SAAS,gCAAgC;AACzC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEA,MAAM,WAAW;AAAA,EACtB,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { InboxProposalAction } from '../../../../data/entities'\nimport type { ProposalTranslationEntry } from '../../../../data/entities'\nimport { translateProposalSchema } from '../../../../data/validators'\nimport { translateProposalContent } from '../../../../lib/translationProvider'\nimport {\n resolveRequestContext,\n resolveProposal,\n handleRouteError,\n isErrorResponse,\n} from '../../../routeHelpers'\n\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: ['inbox_ops.proposals.manage'] },\n}\n\nexport async function POST(req: Request) {\n try {\n const ctx = await resolveRequestContext(req)\n const proposal = await resolveProposal(new URL(req.url), ctx)\n if (isErrorResponse(proposal)) return proposal\n\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 })\n }\n const parsed = translateProposalSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid request', details: parsed.error.issues }, { status: 400 })\n }\n\n const { targetLocale } = parsed.data\n const proposalLanguage = proposal.workingLanguage || 'en'\n\n if (proposalLanguage === targetLocale) {\n return NextResponse.json({ error: 'Proposal is already in the requested language' }, { status: 400 })\n }\n\n // Return cached translation if available\n const cached = proposal.translations?.[targetLocale]\n if (cached) {\n return NextResponse.json({ translation: cached, cached: true })\n }\n\n // Load actions for translation\n const actions = await findWithDecryption(\n ctx.em,\n InboxProposalAction,\n { proposalId: proposal.id, organizationId: ctx.organizationId, tenantId: ctx.tenantId, deletedAt: null },\n { orderBy: { sortOrder: 'ASC' } },\n ctx.scope,\n )\n\n const actionDescriptions: Record<string, string> = {}\n for (const action of actions) {\n actionDescriptions[action.id] = action.description\n }\n\n const result = await translateProposalContent({\n summary: proposal.summary,\n actionDescriptions,\n sourceLanguage: proposalLanguage,\n targetLocale,\n })\n\n const entry: ProposalTranslationEntry = {\n summary: result.summary,\n actions: result.actions,\n translatedAt: new Date().toISOString(),\n }\n\n // Cache the translation on the proposal entity\n const translations = proposal.translations || {}\n translations[targetLocale] = entry\n proposal.translations = translations\n await ctx.em.flush()\n\n return NextResponse.json({ translation: entry, cached: false })\n } catch (err) {\n return handleRouteError(err, 'translate proposal')\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'InboxOps',\n summary: 'Translate proposal',\n methods: {\n POST: {\n summary: 'Translate proposal content',\n description: 'Translates the proposal summary and action descriptions to the target locale. Results are cached.',\n responses: [\n { status: 200, description: 'Translation result' },\n { status: 400, description: 'Invalid target locale or same language' },\n { status: 404, description: 'Proposal not found' },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAE7B,SAAS,0BAA0B;AACnC,SAAS,2BAA2B;AAEpC,SAAS,+BAA+B;AACxC,SAAS,gCAAgC;AACzC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEA,MAAM,WAAW;AAAA,EACtB,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,4BAA4B,EAAE;AAC7E;AAEA,eAAsB,KAAK,KAAc;AACvC,MAAI;AACF,UAAM,MAAM,MAAM,sBAAsB,GAAG;AAC3C,UAAM,WAAW,MAAM,gBAAgB,IAAI,IAAI,IAAI,GAAG,GAAG,GAAG;AAC5D,QAAI,gBAAgB,QAAQ,EAAG,QAAO;AAEtC,QAAI;AACJ,QAAI;AACF,aAAO,MAAM,IAAI,KAAK;AAAA,IACxB,QAAQ;AACN,aAAO,aAAa,KAAK,EAAE,OAAO,oBAAoB,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IAC1E;AACA,UAAM,SAAS,wBAAwB,UAAU,IAAI;AACrD,QAAI,CAAC,OAAO,SAAS;AACnB,aAAO,aAAa,KAAK,EAAE,OAAO,mBAAmB,SAAS,OAAO,MAAM,OAAO,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IACtG;AAEA,UAAM,EAAE,aAAa,IAAI,OAAO;AAChC,UAAM,mBAAmB,SAAS,mBAAmB;AAErD,QAAI,qBAAqB,cAAc;AACrC,aAAO,aAAa,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,yCAAyC;AAAA,QACrE,EAAE,QAAQ,KAAK,aAAa,qBAAqB;AAAA,MACnD;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -8,6 +8,7 @@ function isValidCredentialUrl(value) {
|
|
|
8
8
|
}
|
|
9
9
|
if (!ALLOWED_CREDENTIAL_URL_PROTOCOLS.has(parsed.protocol)) return false;
|
|
10
10
|
if (!parsed.hostname) return false;
|
|
11
|
+
if (parsed.username || parsed.password) return false;
|
|
11
12
|
return true;
|
|
12
13
|
}
|
|
13
14
|
const defaultUrlMessageBuilder = (field) => `${field.label || field.key} must be a valid http(s) URL.`;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/integrations/lib/credentials-field-validation.ts"],
|
|
4
|
-
"sourcesContent": ["import type { IntegrationCredentialsSchema } from '@open-mercato/shared/modules/integrations/types'\n\nconst ALLOWED_CREDENTIAL_URL_PROTOCOLS = new Set(['http:', 'https:'])\n\n/**\n * Validates that a credential value declared as `type: 'url'` is a syntactically\n * valid http(s) URL. Rejects free text, script fragments, and malformed URLs such as\n * `<script>alert(1)</script>` or `http://example.com<script>alert(1)</script>` \u2014 the\n * WHATWG URL parser refuses forbidden host code points (`<`, `>`) and missing schemes.\n */\nexport function isValidCredentialUrl(value: string): boolean {\n let parsed: URL\n try {\n parsed = new URL(value)\n } catch {\n return false\n }\n if (!ALLOWED_CREDENTIAL_URL_PROTOCOLS.has(parsed.protocol)) return false\n if (!parsed.hostname) return false\n return true\n}\n\nexport type CredentialUrlMessageBuilder = (field: { key: string; label: string }) => string\n\nconst defaultUrlMessageBuilder: CredentialUrlMessageBuilder = (field) =>\n `${field.label || field.key} must be a valid http(s) URL.`\n\n/**\n * Collects field-level validation errors for `url`-typed credential fields against the\n * supplied integration credentials schema. Empty/absent values are skipped (required-ness\n * is enforced separately); only non-empty string values are checked for URL validity.\n *\n * Used by both the server-side credentials route (security enforcement) and the\n * client-side credential form (immediate feedback) so the rule stays single-sourced.\n */\nexport function collectCredentialUrlValidationErrors(\n schema: IntegrationCredentialsSchema | undefined,\n credentials: Record<string, unknown>,\n buildMessage: CredentialUrlMessageBuilder = defaultUrlMessageBuilder,\n): Record<string, string> {\n const fieldErrors: Record<string, string> = {}\n if (!schema?.fields) return fieldErrors\n for (const field of schema.fields) {\n if (field.type !== 'url') continue\n const value = credentials[field.key]\n if (typeof value !== 'string') continue\n if (value.trim().length === 0) continue\n if (!isValidCredentialUrl(value)) {\n fieldErrors[field.key] = buildMessage({ key: field.key, label: field.label })\n }\n }\n return fieldErrors\n}\n"],
|
|
5
|
-
"mappings": "AAEA,MAAM,mCAAmC,oBAAI,IAAI,CAAC,SAAS,QAAQ,CAAC;AAQ7D,SAAS,qBAAqB,OAAwB;AAC3D,MAAI;AACJ,MAAI;AACF,aAAS,IAAI,IAAI,KAAK;AAAA,EACxB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI,CAAC,iCAAiC,IAAI,OAAO,QAAQ,EAAG,QAAO;AACnE,MAAI,CAAC,OAAO,SAAU,QAAO;AAC7B,SAAO;AACT;AAIA,MAAM,2BAAwD,CAAC,UAC7D,GAAG,MAAM,SAAS,MAAM,GAAG;AAUtB,SAAS,qCACd,QACA,aACA,eAA4C,0BACpB;AACxB,QAAM,cAAsC,CAAC;AAC7C,MAAI,CAAC,QAAQ,OAAQ,QAAO;AAC5B,aAAW,SAAS,OAAO,QAAQ;AACjC,QAAI,MAAM,SAAS,MAAO;AAC1B,UAAM,QAAQ,YAAY,MAAM,GAAG;AACnC,QAAI,OAAO,UAAU,SAAU;AAC/B,QAAI,MAAM,KAAK,EAAE,WAAW,EAAG;AAC/B,QAAI,CAAC,qBAAqB,KAAK,GAAG;AAChC,kBAAY,MAAM,GAAG,IAAI,aAAa,EAAE,KAAK,MAAM,KAAK,OAAO,MAAM,MAAM,CAAC;AAAA,IAC9E;AAAA,EACF;AACA,SAAO;AACT;",
|
|
4
|
+
"sourcesContent": ["import type { IntegrationCredentialsSchema } from '@open-mercato/shared/modules/integrations/types'\n\nconst ALLOWED_CREDENTIAL_URL_PROTOCOLS = new Set(['http:', 'https:'])\n\n/**\n * Validates that a credential value declared as `type: 'url'` is a syntactically\n * valid http(s) URL. Rejects free text, script fragments, and malformed URLs such as\n * `<script>alert(1)</script>` or `http://example.com<script>alert(1)</script>` \u2014 the\n * WHATWG URL parser refuses forbidden host code points (`<`, `>`) and missing schemes.\n */\nexport function isValidCredentialUrl(value: string): boolean {\n let parsed: URL\n try {\n parsed = new URL(value)\n } catch {\n return false\n }\n if (!ALLOWED_CREDENTIAL_URL_PROTOCOLS.has(parsed.protocol)) return false\n if (!parsed.hostname) return false\n if (parsed.username || parsed.password) return false\n return true\n}\n\nexport type CredentialUrlMessageBuilder = (field: { key: string; label: string }) => string\n\nconst defaultUrlMessageBuilder: CredentialUrlMessageBuilder = (field) =>\n `${field.label || field.key} must be a valid http(s) URL.`\n\n/**\n * Collects field-level validation errors for `url`-typed credential fields against the\n * supplied integration credentials schema. Empty/absent values are skipped (required-ness\n * is enforced separately); only non-empty string values are checked for URL validity.\n *\n * Used by both the server-side credentials route (security enforcement) and the\n * client-side credential form (immediate feedback) so the rule stays single-sourced.\n */\nexport function collectCredentialUrlValidationErrors(\n schema: IntegrationCredentialsSchema | undefined,\n credentials: Record<string, unknown>,\n buildMessage: CredentialUrlMessageBuilder = defaultUrlMessageBuilder,\n): Record<string, string> {\n const fieldErrors: Record<string, string> = {}\n if (!schema?.fields) return fieldErrors\n for (const field of schema.fields) {\n if (field.type !== 'url') continue\n const value = credentials[field.key]\n if (typeof value !== 'string') continue\n if (value.trim().length === 0) continue\n if (!isValidCredentialUrl(value)) {\n fieldErrors[field.key] = buildMessage({ key: field.key, label: field.label })\n }\n }\n return fieldErrors\n}\n"],
|
|
5
|
+
"mappings": "AAEA,MAAM,mCAAmC,oBAAI,IAAI,CAAC,SAAS,QAAQ,CAAC;AAQ7D,SAAS,qBAAqB,OAAwB;AAC3D,MAAI;AACJ,MAAI;AACF,aAAS,IAAI,IAAI,KAAK;AAAA,EACxB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI,CAAC,iCAAiC,IAAI,OAAO,QAAQ,EAAG,QAAO;AACnE,MAAI,CAAC,OAAO,SAAU,QAAO;AAC7B,MAAI,OAAO,YAAY,OAAO,SAAU,QAAO;AAC/C,SAAO;AACT;AAIA,MAAM,2BAAwD,CAAC,UAC7D,GAAG,MAAM,SAAS,MAAM,GAAG;AAUtB,SAAS,qCACd,QACA,aACA,eAA4C,0BACpB;AACxB,QAAM,cAAsC,CAAC;AAC7C,MAAI,CAAC,QAAQ,OAAQ,QAAO;AAC5B,aAAW,SAAS,OAAO,QAAQ;AACjC,QAAI,MAAM,SAAS,MAAO;AAC1B,UAAM,QAAQ,YAAY,MAAM,GAAG;AACnC,QAAI,OAAO,UAAU,SAAU;AAC/B,QAAI,MAAM,KAAK,EAAE,WAAW,EAAG;AAC/B,QAAI,CAAC,qBAAqB,KAAK,GAAG;AAChC,kBAAY,MAAM,GAAG,IAAI,aAAa,EAAE,KAAK,MAAM,KAAK,OAAO,MAAM,MAAM,CAAC;AAAA,IAC9E;AAAA,EACF;AACA,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -7,6 +7,18 @@ const MASKED_SECRET_VALUE = "__om_secret_unchanged__";
|
|
|
7
7
|
function isSecretField(type) {
|
|
8
8
|
return SECRET_CREDENTIAL_FIELD_TYPES.has(type);
|
|
9
9
|
}
|
|
10
|
+
function redactUrlUserinfo(value) {
|
|
11
|
+
if (typeof value !== "string") return value;
|
|
12
|
+
try {
|
|
13
|
+
const parsed = new URL(value);
|
|
14
|
+
if (!parsed.username && !parsed.password) return value;
|
|
15
|
+
parsed.username = "";
|
|
16
|
+
parsed.password = "";
|
|
17
|
+
return parsed.toString();
|
|
18
|
+
} catch {
|
|
19
|
+
return value;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
10
22
|
function hasPresentValue(value) {
|
|
11
23
|
if (value === void 0 || value === null) return false;
|
|
12
24
|
if (typeof value === "string") return value.length > 0;
|
|
@@ -17,6 +29,10 @@ function maskSecretCredentials(schema, values) {
|
|
|
17
29
|
const credentials = { ...values };
|
|
18
30
|
const secretFieldsConfigured = {};
|
|
19
31
|
for (const field of schema?.fields ?? []) {
|
|
32
|
+
if (field.type === "url") {
|
|
33
|
+
credentials[field.key] = redactUrlUserinfo(credentials[field.key]);
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
20
36
|
if (!isSecretField(field.type)) continue;
|
|
21
37
|
const configured = hasPresentValue(credentials[field.key]);
|
|
22
38
|
secretFieldsConfigured[field.key] = configured;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/integrations/lib/credentials-masking.ts"],
|
|
4
|
-
"sourcesContent": ["import type {\n CredentialFieldType,\n IntegrationCredentialsSchema,\n} from '@open-mercato/shared/modules/integrations/types'\n\n/**\n * Credential field types whose stored value is a secret (API keys, OAuth client\n * secrets/tokens, SSH private keys). These MUST never be returned in plaintext\n * from the credentials API \u2014 they are masked on read and treated as write-only.\n */\nexport const SECRET_CREDENTIAL_FIELD_TYPES: ReadonlySet<CredentialFieldType> = new Set<CredentialFieldType>([\n 'secret',\n 'oauth',\n 'ssh_keypair',\n])\n\n/**\n * Opaque sentinel returned in place of a configured secret value. The client\n * round-trips this value back on save when the user did not change the field;\n * the PUT handler then preserves the existing stored secret instead of writing\n * the sentinel. Chosen to be extremely unlikely to collide with a real secret.\n */\nexport const MASKED_SECRET_VALUE = '__om_secret_unchanged__'\n\nfunction isSecretField(type: CredentialFieldType): boolean {\n return SECRET_CREDENTIAL_FIELD_TYPES.has(type)\n}\n\nfunction hasPresentValue(value: unknown): boolean {\n if (value === undefined || value === null) return false\n if (typeof value === 'string') return value.length > 0\n if (typeof value === 'object') return Object.keys(value as Record<string, unknown>).length > 0\n return true\n}\n\nexport type MaskSecretCredentialsResult = {\n credentials: Record<string, unknown>\n secretFieldsConfigured: Record<string, boolean>\n}\n\n/**\n * Replace every configured secret-typed field with an opaque sentinel so the\n * decrypted plaintext never reaches the API response (and therefore the\n * browser, devtools, proxies, or editable DOM inputs). Non-secret config fields\n * pass through unchanged. A `secretFieldsConfigured` map reports which secret\n * fields currently hold a value without exposing it.\n */\nexport function maskSecretCredentials(\n schema: IntegrationCredentialsSchema | undefined,\n values: Record<string, unknown>,\n): MaskSecretCredentialsResult {\n const credentials: Record<string, unknown> = { ...values }\n const secretFieldsConfigured: Record<string, boolean> = {}\n\n for (const field of schema?.fields ?? []) {\n if (!isSecretField(field.type)) continue\n const configured = hasPresentValue(credentials[field.key])\n secretFieldsConfigured[field.key] = configured\n if (configured) {\n credentials[field.key] = MASKED_SECRET_VALUE\n } else {\n delete credentials[field.key]\n }\n }\n\n return { credentials, secretFieldsConfigured }\n}\n\n/**\n * Reverse of {@link maskSecretCredentials} for the save path. When the client\n * submits the mask sentinel for a secret field it means \"leave it unchanged\":\n * restore the existing stored secret, or drop the field entirely when nothing\n * was previously stored (so the literal sentinel is never persisted). Any other\n * value (including an empty string, which clears the secret) is written as-is.\n */\nexport function mergeMaskedSecretCredentials(\n schema: IntegrationCredentialsSchema | undefined,\n incoming: Record<string, unknown>,\n existing: Record<string, unknown>,\n): Record<string, unknown> {\n const merged: Record<string, unknown> = { ...incoming }\n\n for (const field of schema?.fields ?? []) {\n if (!isSecretField(field.type)) continue\n if (merged[field.key] !== MASKED_SECRET_VALUE) continue\n\n if (hasPresentValue(existing[field.key])) {\n merged[field.key] = existing[field.key]\n } else {\n delete merged[field.key]\n }\n }\n\n return merged\n}\n"],
|
|
5
|
-
"mappings": "AAUO,MAAM,gCAAkE,oBAAI,IAAyB;AAAA,EAC1G;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAQM,MAAM,sBAAsB;AAEnC,SAAS,cAAc,MAAoC;AACzD,SAAO,8BAA8B,IAAI,IAAI;AAC/C;AAEA,SAAS,gBAAgB,OAAyB;AAChD,MAAI,UAAU,UAAa,UAAU,KAAM,QAAO;AAClD,MAAI,OAAO,UAAU,SAAU,QAAO,MAAM,SAAS;AACrD,MAAI,OAAO,UAAU,SAAU,QAAO,OAAO,KAAK,KAAgC,EAAE,SAAS;AAC7F,SAAO;AACT;AAcO,SAAS,sBACd,QACA,QAC6B;AAC7B,QAAM,cAAuC,EAAE,GAAG,OAAO;AACzD,QAAM,yBAAkD,CAAC;AAEzD,aAAW,SAAS,QAAQ,UAAU,CAAC,GAAG;AACxC,QAAI,CAAC,cAAc,MAAM,IAAI,EAAG;AAChC,UAAM,aAAa,gBAAgB,YAAY,MAAM,GAAG,CAAC;AACzD,2BAAuB,MAAM,GAAG,IAAI;AACpC,QAAI,YAAY;AACd,kBAAY,MAAM,GAAG,IAAI;AAAA,IAC3B,OAAO;AACL,aAAO,YAAY,MAAM,GAAG;AAAA,IAC9B;AAAA,EACF;AAEA,SAAO,EAAE,aAAa,uBAAuB;AAC/C;AASO,SAAS,6BACd,QACA,UACA,UACyB;AACzB,QAAM,SAAkC,EAAE,GAAG,SAAS;AAEtD,aAAW,SAAS,QAAQ,UAAU,CAAC,GAAG;AACxC,QAAI,CAAC,cAAc,MAAM,IAAI,EAAG;AAChC,QAAI,OAAO,MAAM,GAAG,MAAM,oBAAqB;AAE/C,QAAI,gBAAgB,SAAS,MAAM,GAAG,CAAC,GAAG;AACxC,aAAO,MAAM,GAAG,IAAI,SAAS,MAAM,GAAG;AAAA,IACxC,OAAO;AACL,aAAO,OAAO,MAAM,GAAG;AAAA,IACzB;AAAA,EACF;AAEA,SAAO;AACT;",
|
|
4
|
+
"sourcesContent": ["import type {\n CredentialFieldType,\n IntegrationCredentialsSchema,\n} from '@open-mercato/shared/modules/integrations/types'\n\n/**\n * Credential field types whose stored value is a secret (API keys, OAuth client\n * secrets/tokens, SSH private keys). These MUST never be returned in plaintext\n * from the credentials API \u2014 they are masked on read and treated as write-only.\n */\nexport const SECRET_CREDENTIAL_FIELD_TYPES: ReadonlySet<CredentialFieldType> = new Set<CredentialFieldType>([\n 'secret',\n 'oauth',\n 'ssh_keypair',\n])\n\n/**\n * Opaque sentinel returned in place of a configured secret value. The client\n * round-trips this value back on save when the user did not change the field;\n * the PUT handler then preserves the existing stored secret instead of writing\n * the sentinel. Chosen to be extremely unlikely to collide with a real secret.\n */\nexport const MASKED_SECRET_VALUE = '__om_secret_unchanged__'\n\nfunction isSecretField(type: CredentialFieldType): boolean {\n return SECRET_CREDENTIAL_FIELD_TYPES.has(type)\n}\n\nfunction redactUrlUserinfo(value: unknown): unknown {\n if (typeof value !== 'string') return value\n try {\n const parsed = new URL(value)\n if (!parsed.username && !parsed.password) return value\n parsed.username = ''\n parsed.password = ''\n return parsed.toString()\n } catch {\n return value\n }\n}\n\nfunction hasPresentValue(value: unknown): boolean {\n if (value === undefined || value === null) return false\n if (typeof value === 'string') return value.length > 0\n if (typeof value === 'object') return Object.keys(value as Record<string, unknown>).length > 0\n return true\n}\n\nexport type MaskSecretCredentialsResult = {\n credentials: Record<string, unknown>\n secretFieldsConfigured: Record<string, boolean>\n}\n\n/**\n * Replace every configured secret-typed field with an opaque sentinel so the\n * decrypted plaintext never reaches the API response (and therefore the\n * browser, devtools, proxies, or editable DOM inputs). Non-secret config fields\n * pass through unchanged. A `secretFieldsConfigured` map reports which secret\n * fields currently hold a value without exposing it.\n */\nexport function maskSecretCredentials(\n schema: IntegrationCredentialsSchema | undefined,\n values: Record<string, unknown>,\n): MaskSecretCredentialsResult {\n const credentials: Record<string, unknown> = { ...values }\n const secretFieldsConfigured: Record<string, boolean> = {}\n\n for (const field of schema?.fields ?? []) {\n if (field.type === 'url') {\n credentials[field.key] = redactUrlUserinfo(credentials[field.key])\n continue\n }\n if (!isSecretField(field.type)) continue\n const configured = hasPresentValue(credentials[field.key])\n secretFieldsConfigured[field.key] = configured\n if (configured) {\n credentials[field.key] = MASKED_SECRET_VALUE\n } else {\n delete credentials[field.key]\n }\n }\n\n return { credentials, secretFieldsConfigured }\n}\n\n/**\n * Reverse of {@link maskSecretCredentials} for the save path. When the client\n * submits the mask sentinel for a secret field it means \"leave it unchanged\":\n * restore the existing stored secret, or drop the field entirely when nothing\n * was previously stored (so the literal sentinel is never persisted). Any other\n * value (including an empty string, which clears the secret) is written as-is.\n */\nexport function mergeMaskedSecretCredentials(\n schema: IntegrationCredentialsSchema | undefined,\n incoming: Record<string, unknown>,\n existing: Record<string, unknown>,\n): Record<string, unknown> {\n const merged: Record<string, unknown> = { ...incoming }\n\n for (const field of schema?.fields ?? []) {\n if (!isSecretField(field.type)) continue\n if (merged[field.key] !== MASKED_SECRET_VALUE) continue\n\n if (hasPresentValue(existing[field.key])) {\n merged[field.key] = existing[field.key]\n } else {\n delete merged[field.key]\n }\n }\n\n return merged\n}\n"],
|
|
5
|
+
"mappings": "AAUO,MAAM,gCAAkE,oBAAI,IAAyB;AAAA,EAC1G;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAQM,MAAM,sBAAsB;AAEnC,SAAS,cAAc,MAAoC;AACzD,SAAO,8BAA8B,IAAI,IAAI;AAC/C;AAEA,SAAS,kBAAkB,OAAyB;AAClD,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,MAAI;AACF,UAAM,SAAS,IAAI,IAAI,KAAK;AAC5B,QAAI,CAAC,OAAO,YAAY,CAAC,OAAO,SAAU,QAAO;AACjD,WAAO,WAAW;AAClB,WAAO,WAAW;AAClB,WAAO,OAAO,SAAS;AAAA,EACzB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAAS,gBAAgB,OAAyB;AAChD,MAAI,UAAU,UAAa,UAAU,KAAM,QAAO;AAClD,MAAI,OAAO,UAAU,SAAU,QAAO,MAAM,SAAS;AACrD,MAAI,OAAO,UAAU,SAAU,QAAO,OAAO,KAAK,KAAgC,EAAE,SAAS;AAC7F,SAAO;AACT;AAcO,SAAS,sBACd,QACA,QAC6B;AAC7B,QAAM,cAAuC,EAAE,GAAG,OAAO;AACzD,QAAM,yBAAkD,CAAC;AAEzD,aAAW,SAAS,QAAQ,UAAU,CAAC,GAAG;AACxC,QAAI,MAAM,SAAS,OAAO;AACxB,kBAAY,MAAM,GAAG,IAAI,kBAAkB,YAAY,MAAM,GAAG,CAAC;AACjE;AAAA,IACF;AACA,QAAI,CAAC,cAAc,MAAM,IAAI,EAAG;AAChC,UAAM,aAAa,gBAAgB,YAAY,MAAM,GAAG,CAAC;AACzD,2BAAuB,MAAM,GAAG,IAAI;AACpC,QAAI,YAAY;AACd,kBAAY,MAAM,GAAG,IAAI;AAAA,IAC3B,OAAO;AACL,aAAO,YAAY,MAAM,GAAG;AAAA,IAC9B;AAAA,EACF;AAEA,SAAO,EAAE,aAAa,uBAAuB;AAC/C;AASO,SAAS,6BACd,QACA,UACA,UACyB;AACzB,QAAM,SAAkC,EAAE,GAAG,SAAS;AAEtD,aAAW,SAAS,QAAQ,UAAU,CAAC,GAAG;AACxC,QAAI,CAAC,cAAc,MAAM,IAAI,EAAG;AAChC,QAAI,OAAO,MAAM,GAAG,MAAM,oBAAqB;AAE/C,QAAI,gBAAgB,SAAS,MAAM,GAAG,CAAC,GAAG;AACxC,aAAO,MAAM,GAAG,IAAI,SAAS,MAAM,GAAG;AAAA,IACxC,OAAO;AACL,aAAO,OAAO,MAAM,GAAG;AAAA,IACzB;AAAA,EACF;AAEA,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -16,6 +16,15 @@ function collectUsersWithFeature(userIdsSet, rows, requiredFeature) {
|
|
|
16
16
|
}
|
|
17
17
|
}
|
|
18
18
|
}
|
|
19
|
+
async function getScopedNotificationRecipientUserIds(db, tenantId, organizationId, recipientUserIds) {
|
|
20
|
+
const builder = db;
|
|
21
|
+
let query = builder.selectFrom("users").where("users.id", "in", recipientUserIds).where("users.deleted_at", "is", null).where("users.tenant_id", "=", tenantId);
|
|
22
|
+
if (organizationId) {
|
|
23
|
+
query = query.where("users.organization_id", "=", organizationId);
|
|
24
|
+
}
|
|
25
|
+
const users = await query.select("users.id as user_id").execute();
|
|
26
|
+
return users.map((user) => user.user_id);
|
|
27
|
+
}
|
|
19
28
|
async function getRecipientUserIdsForRole(db, tenantId, roleId) {
|
|
20
29
|
const builder = db;
|
|
21
30
|
const userRoles = await builder.selectFrom("user_roles").innerJoin("users", "user_roles.user_id", "users.id").where("user_roles.role_id", "=", roleId).where("user_roles.deleted_at", "is", null).where("users.deleted_at", "is", null).where("users.tenant_id", "=", tenantId).select("users.id as user_id").execute();
|
|
@@ -40,6 +49,7 @@ async function getRecipientUserIdsForFeature(db, tenantId, requiredFeature) {
|
|
|
40
49
|
}
|
|
41
50
|
export {
|
|
42
51
|
getRecipientUserIdsForFeature,
|
|
43
|
-
getRecipientUserIdsForRole
|
|
52
|
+
getRecipientUserIdsForRole,
|
|
53
|
+
getScopedNotificationRecipientUserIds
|
|
44
54
|
};
|
|
45
55
|
//# sourceMappingURL=notificationRecipients.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/notifications/lib/notificationRecipients.ts"],
|
|
4
|
-
"sourcesContent": ["import type { Kysely } from 'kysely'\nimport { hasFeature } from '@open-mercato/shared/security/features'\n\ninterface AclRow {\n user_id: string\n features_json: unknown\n is_super_admin: boolean\n}\n\nfunction normalizeFeatures(features: unknown): string[] | undefined {\n if (!Array.isArray(features)) return undefined\n const normalized = features.filter((feature): feature is string => typeof feature === 'string')\n return normalized.length ? normalized : undefined\n}\n\n/**\n * Extract user IDs from ACL rows that have the required feature or are super admins.\n */\nfunction collectUsersWithFeature(\n userIdsSet: Set<string>,\n rows: AclRow[],\n requiredFeature: string\n): void {\n for (const row of rows) {\n if (row.is_super_admin) {\n userIdsSet.add(row.user_id)\n continue\n }\n\n const features = normalizeFeatures(row.features_json)\n if (features && hasFeature(features, requiredFeature)) {\n userIdsSet.add(row.user_id)\n }\n }\n}\n\nexport async function getRecipientUserIdsForRole(\n db: Kysely<any>,\n tenantId: string,\n roleId: string\n): Promise<string[]> {\n const builder: any = db\n const userRoles = await builder\n .selectFrom('user_roles')\n .innerJoin('users', 'user_roles.user_id', 'users.id')\n .where('user_roles.role_id', '=', roleId)\n .where('user_roles.deleted_at', 'is', null)\n .where('users.deleted_at', 'is', null)\n .where('users.tenant_id', '=', tenantId)\n .select('users.id as user_id')\n .execute() as Array<{ user_id: string }>\n\n return userRoles.map((row) => row.user_id)\n}\n\nexport async function getRecipientUserIdsForFeature(\n db: Kysely<any>,\n tenantId: string,\n requiredFeature: string\n): Promise<string[]> {\n const userIdsSet = new Set<string>()\n const builder: any = db\n\n const userAcls = await builder\n .selectFrom('user_acls')\n .innerJoin('users', 'user_acls.user_id', 'users.id')\n .where('user_acls.tenant_id', '=', tenantId)\n .where('user_acls.deleted_at', 'is', null)\n .where('users.deleted_at', 'is', null)\n .where('users.tenant_id', '=', tenantId)\n .select([\n 'users.id as user_id',\n 'user_acls.features_json',\n 'user_acls.is_super_admin',\n ])\n .execute() as AclRow[]\n\n collectUsersWithFeature(userIdsSet, userAcls, requiredFeature)\n\n const roleAcls = await builder\n .selectFrom('role_acls')\n .innerJoin('user_roles', 'role_acls.role_id', 'user_roles.role_id')\n .innerJoin('users', 'user_roles.user_id', 'users.id')\n .where('role_acls.tenant_id', '=', tenantId)\n .where('role_acls.deleted_at', 'is', null)\n .where('user_roles.deleted_at', 'is', null)\n .where('users.deleted_at', 'is', null)\n .where('users.tenant_id', '=', tenantId)\n .select([\n 'users.id as user_id',\n 'role_acls.features_json',\n 'role_acls.is_super_admin',\n ])\n .execute() as AclRow[]\n\n collectUsersWithFeature(userIdsSet, roleAcls, requiredFeature)\n\n return Array.from(userIdsSet)\n}\n"],
|
|
5
|
-
"mappings": "AACA,SAAS,kBAAkB;AAQ3B,SAAS,kBAAkB,UAAyC;AAClE,MAAI,CAAC,MAAM,QAAQ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UAAU,SAAS,sBAAsB,UAAU,EACnD,MAAM,uBAAuB,KAAK,QAAQ,EAC1C,MAAM,wBAAwB,MAAM,IAAI,EACxC,MAAM,yBAAyB,MAAM,IAAI,EACzC,MAAM,oBAAoB,MAAM,IAAI,EACpC,MAAM,mBAAmB,KAAK,QAAQ,EACtC,OAAO;AAAA,IACN;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC,EACA,QAAQ;AAEX,0BAAwB,YAAY,UAAU,eAAe;AAE7D,SAAO,MAAM,KAAK,UAAU;AAC9B;",
|
|
4
|
+
"sourcesContent": ["import type { Kysely } from 'kysely'\nimport { hasFeature } from '@open-mercato/shared/security/features'\n\ninterface AclRow {\n user_id: string\n features_json: unknown\n is_super_admin: boolean\n}\n\nfunction normalizeFeatures(features: unknown): string[] | undefined {\n if (!Array.isArray(features)) return undefined\n const normalized = features.filter((feature): feature is string => typeof feature === 'string')\n return normalized.length ? normalized : undefined\n}\n\n/**\n * Extract user IDs from ACL rows that have the required feature or are super admins.\n */\nfunction collectUsersWithFeature(\n userIdsSet: Set<string>,\n rows: AclRow[],\n requiredFeature: string\n): void {\n for (const row of rows) {\n if (row.is_super_admin) {\n userIdsSet.add(row.user_id)\n continue\n }\n\n const features = normalizeFeatures(row.features_json)\n if (features && hasFeature(features, requiredFeature)) {\n userIdsSet.add(row.user_id)\n }\n }\n}\n\nexport async function getScopedNotificationRecipientUserIds(\n db: Kysely<any>,\n tenantId: string,\n organizationId: string | null,\n recipientUserIds: string[],\n): Promise<string[]> {\n const builder: any = db\n let query = builder\n .selectFrom('users')\n .where('users.id', 'in', recipientUserIds)\n .where('users.deleted_at', 'is', null)\n .where('users.tenant_id', '=', tenantId)\n\n if (organizationId) {\n query = query.where('users.organization_id', '=', organizationId)\n }\n\n const users = await query\n .select('users.id as user_id')\n .execute() as Array<{ user_id: string }>\n\n return users.map((user) => user.user_id)\n}\n\nexport async function getRecipientUserIdsForRole(\n db: Kysely<any>,\n tenantId: string,\n roleId: string\n): Promise<string[]> {\n const builder: any = db\n const userRoles = await builder\n .selectFrom('user_roles')\n .innerJoin('users', 'user_roles.user_id', 'users.id')\n .where('user_roles.role_id', '=', roleId)\n .where('user_roles.deleted_at', 'is', null)\n .where('users.deleted_at', 'is', null)\n .where('users.tenant_id', '=', tenantId)\n .select('users.id as user_id')\n .execute() as Array<{ user_id: string }>\n\n return userRoles.map((row) => row.user_id)\n}\n\nexport async function getRecipientUserIdsForFeature(\n db: Kysely<any>,\n tenantId: string,\n requiredFeature: string\n): Promise<string[]> {\n const userIdsSet = new Set<string>()\n const builder: any = db\n\n const userAcls = await builder\n .selectFrom('user_acls')\n .innerJoin('users', 'user_acls.user_id', 'users.id')\n .where('user_acls.tenant_id', '=', tenantId)\n .where('user_acls.deleted_at', 'is', null)\n .where('users.deleted_at', 'is', null)\n .where('users.tenant_id', '=', tenantId)\n .select([\n 'users.id as user_id',\n 'user_acls.features_json',\n 'user_acls.is_super_admin',\n ])\n .execute() as AclRow[]\n\n collectUsersWithFeature(userIdsSet, userAcls, requiredFeature)\n\n const roleAcls = await builder\n .selectFrom('role_acls')\n .innerJoin('user_roles', 'role_acls.role_id', 'user_roles.role_id')\n .innerJoin('users', 'user_roles.user_id', 'users.id')\n .where('role_acls.tenant_id', '=', tenantId)\n .where('role_acls.deleted_at', 'is', null)\n .where('user_roles.deleted_at', 'is', null)\n .where('users.deleted_at', 'is', null)\n .where('users.tenant_id', '=', tenantId)\n .select([\n 'users.id as user_id',\n 'role_acls.features_json',\n 'role_acls.is_super_admin',\n ])\n .execute() as AclRow[]\n\n collectUsersWithFeature(userIdsSet, roleAcls, requiredFeature)\n\n return Array.from(userIdsSet)\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,kBAAkB;AAQ3B,SAAS,kBAAkB,UAAyC;AAClE,MAAI,CAAC,MAAM,QAAQ,QAAQ,EAAG,QAAO;AACrC,QAAM,aAAa,SAAS,OAAO,CAAC,YAA+B,OAAO,YAAY,QAAQ;AAC9F,SAAO,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,EAC1C,MAAM,wBAAwB,MAAM,IAAI,EACxC,MAAM,oBAAoB,MAAM,IAAI,EACpC,MAAM,mBAAmB,KAAK,QAAQ,EACtC,OAAO;AAAA,IACN;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC,EACA,QAAQ;AAEX,0BAAwB,YAAY,UAAU,eAAe;AAE7D,QAAM,WAAW,MAAM,QACpB,WAAW,WAAW,EACtB,UAAU,cAAc,qBAAqB,oBAAoB,EACjE,UAAU,SAAS,sBAAsB,UAAU,EACnD,MAAM,uBAAuB,KAAK,QAAQ,EAC1C,MAAM,wBAAwB,MAAM,IAAI,EACxC,MAAM,yBAAyB,MAAM,IAAI,EACzC,MAAM,oBAAoB,MAAM,IAAI,EACpC,MAAM,mBAAmB,KAAK,QAAQ,EACtC,OAAO;AAAA,IACN;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC,EACA,QAAQ;AAEX,0BAAwB,YAAY,UAAU,eAAe;AAE7D,SAAO,MAAM,KAAK,UAAU;AAC9B;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -9,7 +9,11 @@ import {
|
|
|
9
9
|
emitNotificationCreatedBatch
|
|
10
10
|
} from "./notificationFactory.js";
|
|
11
11
|
import { toNotificationDto } from "./notificationMapper.js";
|
|
12
|
-
import {
|
|
12
|
+
import {
|
|
13
|
+
getRecipientUserIdsForFeature,
|
|
14
|
+
getRecipientUserIdsForRole,
|
|
15
|
+
getScopedNotificationRecipientUserIds
|
|
16
|
+
} from "./notificationRecipients.js";
|
|
13
17
|
import { assertSafeNotificationHref, sanitizeNotificationActions } from "./safeHref.js";
|
|
14
18
|
import { createLogger } from "@open-mercato/shared/lib/logger";
|
|
15
19
|
const logger = createLogger("notifications").child({ component: "service" });
|
|
@@ -23,6 +27,17 @@ const UNIQUE_NOTIFICATION_ACTIVE_STATUSES = ["unread", "read", "actioned"];
|
|
|
23
27
|
function normalizeOrgScope(organizationId) {
|
|
24
28
|
return organizationId ?? null;
|
|
25
29
|
}
|
|
30
|
+
async function assertNotificationRecipientsInScope(em, recipientUserIds, ctx) {
|
|
31
|
+
const scopedRecipientUserIds = await getScopedNotificationRecipientUserIds(
|
|
32
|
+
getDb(em),
|
|
33
|
+
ctx.tenantId,
|
|
34
|
+
normalizeOrgScope(ctx.organizationId),
|
|
35
|
+
recipientUserIds
|
|
36
|
+
);
|
|
37
|
+
if (scopedRecipientUserIds.length !== recipientUserIds.length) {
|
|
38
|
+
throw new CrudHttpError(404, { error: "Notification recipient not found" });
|
|
39
|
+
}
|
|
40
|
+
}
|
|
26
41
|
function applyNotificationContent(notification, input, recipientUserId, ctx) {
|
|
27
42
|
const actions = sanitizeNotificationActions(input.actions);
|
|
28
43
|
const linkHref = assertSafeNotificationHref(input.linkHref);
|
|
@@ -125,6 +140,7 @@ function createNotificationService(deps) {
|
|
|
125
140
|
const { recipientUserId, ...content } = input;
|
|
126
141
|
const writeEm = rootEm.fork();
|
|
127
142
|
const notification = await writeEm.transactional(async (tx) => {
|
|
143
|
+
await assertNotificationRecipientsInScope(tx, [recipientUserId], ctx);
|
|
128
144
|
const entity = await createOrRefreshNotification(tx, content, recipientUserId, ctx);
|
|
129
145
|
await tx.flush();
|
|
130
146
|
return entity;
|
|
@@ -144,6 +160,7 @@ function createNotificationService(deps) {
|
|
|
144
160
|
const notifications = [];
|
|
145
161
|
const writeEm = rootEm.fork();
|
|
146
162
|
await writeEm.transactional(async (tx) => {
|
|
163
|
+
await assertNotificationRecipientsInScope(tx, recipientUserIds, ctx);
|
|
147
164
|
for (const recipientUserId of recipientUserIds) {
|
|
148
165
|
const notification = await createOrRefreshNotification(tx, content, recipientUserId, ctx);
|
|
149
166
|
notifications.push(notification);
|
|
@@ -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, conflict } from '@open-mercato/shared/lib/crud/errors'\nimport { Notification, type NotificationStatus } from '../data/entities'\nimport type { CreateNotificationInput, CreateBatchNotificationInput, CreateRoleNotificationInput, CreateFeatureNotificationInput, ExecuteActionInput } from '../data/validators'\nimport type { NotificationPollData } from '@open-mercato/shared/modules/notifications/types'\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 { getRecipientUserIdsForFeature, getRecipientUserIdsForRole } from './notificationRecipients'\nimport { assertSafeNotificationHref, sanitizeNotificationActions } from './safeHref'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\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']\n\nfunction normalizeOrgScope(organizationId: string | null | undefined): string | null {\n return organizationId ?? null\n}\n\nfunction applyNotificationContent(\n notification: Notification,\n input: NotificationContentInput,\n recipientUserId: string,\n ctx: NotificationTenantContext,\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.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 recipientUserIds: string[],\n): Promise<void> {\n await eventBus.emit(NOTIFICATION_SSE_EVENTS.BATCH_CREATED, {\n tenantId: ctx.tenantId,\n organizationId: normalizeOrgScope(ctx.organizationId),\n recipientUserIds,\n count: notifications.length,\n })\n\n for (const notification of notifications) {\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): 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)\n return existing\n }\n }\n\n return buildNotificationEntity(em, input, recipientUserId, ctx)\n}\n\nexport interface NotificationServiceContext {\n tenantId: string\n organizationId?: string | null\n userId?: string | null\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: CreateFeatureNotificationInput, 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 return {\n async create(input, ctx) {\n const { recipientUserId, ...content } = input\n const writeEm = rootEm.fork()\n const notification = await writeEm.transactional(async (tx) => {\n const entity = await createOrRefreshNotification(tx, content, recipientUserId, ctx)\n await tx.flush()\n return entity\n })\n\n await emitNotificationCreated(eventBus, notification, ctx)\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 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 writeEm = rootEm.fork()\n\n await writeEm.transactional(async (tx) => {\n for (const recipientUserId of recipientUserIds) {\n const notification = await createOrRefreshNotification(tx, content, recipientUserId, ctx)\n notifications.push(notification)\n }\n await tx.flush()\n })\n\n await emitNotificationCreatedBatch(eventBus, notifications, ctx)\n await emitNotificationSseEvents(eventBus, notifications, ctx, recipientUserIds)\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 writeEm = rootEm.fork()\n\n await writeEm.transactional(async (tx) => {\n for (const recipientUserId of uniqueRecipientUserIds) {\n const notification = await createOrRefreshNotification(tx, content, recipientUserId, ctx)\n notifications.push(notification)\n }\n await tx.flush()\n })\n\n await emitNotificationCreatedBatch(eventBus, notifications, ctx)\n await emitNotificationSseEvents(eventBus, notifications, ctx, uniqueRecipientUserIds)\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 debug('Creating notifications for', recipientUserIds.length, 'user(s) with feature:', input.requiredFeature)\n\n const { requiredFeature: _requiredFeature, ...content } = input\n const notifications: Notification[] = []\n const uniqueRecipientUserIds = Array.from(new Set(recipientUserIds))\n const writeEm = rootEm.fork()\n\n await writeEm.transactional(async (tx) => {\n for (const recipientUserId of uniqueRecipientUserIds) {\n const notification = await createOrRefreshNotification(tx, content, recipientUserId, ctx)\n notifications.push(notification)\n }\n await tx.flush()\n })\n\n await emitNotificationCreatedBatch(eventBus, notifications, ctx)\n await emitNotificationSseEvents(eventBus, notifications, ctx, uniqueRecipientUserIds)\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 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 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 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 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 const targetStatus = 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 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.\n if (notification.status === 'actioned') {\n throw conflict('Notification action already executed')\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 .executeTakeFirst()) as { numUpdatedRows?: bigint | number } | undefined\n\n if (Number(claimResult?.numUpdatedRows ?? 0) === 0) {\n throw conflict('Notification action already executed')\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. Only release while we still own the claim\n // (status = 'actioned'), so a concurrent winner's state is never clobbered.\n const releaseClaim = async () => {\n await getDb(em)\n .updateTable('notifications' as any)\n .set({\n status: previousStatus,\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('status' as any, '=', 'actioned')\n .executeTakeFirst()\n }\n\n let result: unknown = null\n\n if (action.commandId && commandBus && container) {\n const commandInput = {\n id: notification.sourceEntityId,\n ...input.payload,\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 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 })\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 }\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 }),\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 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 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 return Number(deleteResult?.numDeletedRows ?? 0)\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,eAAe,gBAAgB;AACxC,SAAS,oBAA6C;AAGtD,SAAS,qBAAqB,+BAA+B;AAC7D,SAAS,uBAAuB,0BAA0B;AAC1D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP,SAAS,yBAAyB;AAClC,SAAS,+BAA+B,kCAAkC;AAC1E,SAAS,4BAA4B,mCAAmC;AACxE,SAAS,oBAAoB;AAE7B,MAAM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U,YAAY,UAAU,CAAC;AAC1E;",
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { type Kysely, sql } from 'kysely'\nimport { CrudHttpError, conflict } from '@open-mercato/shared/lib/crud/errors'\nimport { Notification, type NotificationStatus } from '../data/entities'\nimport type { CreateNotificationInput, CreateBatchNotificationInput, CreateRoleNotificationInput, CreateFeatureNotificationInput, ExecuteActionInput } from '../data/validators'\nimport type { NotificationPollData } from '@open-mercato/shared/modules/notifications/types'\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 {\n getRecipientUserIdsForFeature,\n getRecipientUserIdsForRole,\n getScopedNotificationRecipientUserIds,\n} from './notificationRecipients'\nimport { assertSafeNotificationHref, sanitizeNotificationActions } from './safeHref'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\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']\n\nfunction normalizeOrgScope(organizationId: string | null | undefined): string | null {\n return organizationId ?? null\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 applyNotificationContent(\n notification: Notification,\n input: NotificationContentInput,\n recipientUserId: string,\n ctx: NotificationTenantContext,\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.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 recipientUserIds: string[],\n): Promise<void> {\n await eventBus.emit(NOTIFICATION_SSE_EVENTS.BATCH_CREATED, {\n tenantId: ctx.tenantId,\n organizationId: normalizeOrgScope(ctx.organizationId),\n recipientUserIds,\n count: notifications.length,\n })\n\n for (const notification of notifications) {\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): 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)\n return existing\n }\n }\n\n return buildNotificationEntity(em, input, recipientUserId, ctx)\n}\n\nexport interface NotificationServiceContext {\n tenantId: string\n organizationId?: string | null\n userId?: string | null\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: CreateFeatureNotificationInput, 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 return {\n async create(input, ctx) {\n const { recipientUserId, ...content } = input\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)\n await tx.flush()\n return entity\n })\n\n await emitNotificationCreated(eventBus, notification, ctx)\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 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 writeEm = rootEm.fork()\n\n await writeEm.transactional(async (tx) => {\n await assertNotificationRecipientsInScope(tx, recipientUserIds, ctx)\n for (const recipientUserId of recipientUserIds) {\n const notification = await createOrRefreshNotification(tx, content, recipientUserId, ctx)\n notifications.push(notification)\n }\n await tx.flush()\n })\n\n await emitNotificationCreatedBatch(eventBus, notifications, ctx)\n await emitNotificationSseEvents(eventBus, notifications, ctx, recipientUserIds)\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 writeEm = rootEm.fork()\n\n await writeEm.transactional(async (tx) => {\n for (const recipientUserId of uniqueRecipientUserIds) {\n const notification = await createOrRefreshNotification(tx, content, recipientUserId, ctx)\n notifications.push(notification)\n }\n await tx.flush()\n })\n\n await emitNotificationCreatedBatch(eventBus, notifications, ctx)\n await emitNotificationSseEvents(eventBus, notifications, ctx, uniqueRecipientUserIds)\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 debug('Creating notifications for', recipientUserIds.length, 'user(s) with feature:', input.requiredFeature)\n\n const { requiredFeature: _requiredFeature, ...content } = input\n const notifications: Notification[] = []\n const uniqueRecipientUserIds = Array.from(new Set(recipientUserIds))\n const writeEm = rootEm.fork()\n\n await writeEm.transactional(async (tx) => {\n for (const recipientUserId of uniqueRecipientUserIds) {\n const notification = await createOrRefreshNotification(tx, content, recipientUserId, ctx)\n notifications.push(notification)\n }\n await tx.flush()\n })\n\n await emitNotificationCreatedBatch(eventBus, notifications, ctx)\n await emitNotificationSseEvents(eventBus, notifications, ctx, uniqueRecipientUserIds)\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 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 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 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 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 const targetStatus = 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 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.\n if (notification.status === 'actioned') {\n throw conflict('Notification action already executed')\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 .executeTakeFirst()) as { numUpdatedRows?: bigint | number } | undefined\n\n if (Number(claimResult?.numUpdatedRows ?? 0) === 0) {\n throw conflict('Notification action already executed')\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. Only release while we still own the claim\n // (status = 'actioned'), so a concurrent winner's state is never clobbered.\n const releaseClaim = async () => {\n await getDb(em)\n .updateTable('notifications' as any)\n .set({\n status: previousStatus,\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('status' as any, '=', 'actioned')\n .executeTakeFirst()\n }\n\n let result: unknown = null\n\n if (action.commandId && commandBus && container) {\n const commandInput = {\n id: notification.sourceEntityId,\n ...input.payload,\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 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 })\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 }\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 }),\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 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 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 return Number(deleteResult?.numDeletedRows ?? 0)\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,eAAe,gBAAgB;AACxC,SAAS,oBAA6C;AAGtD,SAAS,qBAAqB,+BAA+B;AAC7D,SAAS,uBAAuB,0BAA0B;AAC1D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP,SAAS,yBAAyB;AAClC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,4BAA4B,mCAAmC;AACxE,SAAS,oBAAoB;AAE7B,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;AAEA,SAAS,MAAM,IAAgC;AAC7C,SAAO,GAAG,UAAe;AAC3B;AAEA,MAAM,sCAA4D,CAAC,UAAU,QAAQ,UAAU;AAE/F,SAAS,kBAAkB,gBAA0D;AACnF,SAAO,kBAAkB;AAC3B;AAEA,eAAe,oCACb,IACA,kBACA,KACe;AACf,QAAM,yBAAyB,MAAM;AAAA,IACnC,MAAM,EAAE;AAAA,IACR,IAAI;AAAA,IACJ,kBAAkB,IAAI,cAAc;AAAA,IACpC;AAAA,EACF;AAEA,MAAI,uBAAuB,WAAW,iBAAiB,QAAQ;AAC7D,UAAM,IAAI,cAAc,KAAK,EAAE,OAAO,mCAAmC,CAAC;AAAA,EAC5E;AACF;AAEA,SAAS,yBACP,cACA,OACA,iBACA,KACA;AACA,QAAM,UAAU,4BAA4B,MAAM,OAAO;AACzD,QAAM,WAAW,2BAA2B,MAAM,QAAQ;AAE1D,eAAa,kBAAkB;AAC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