@open-mercato/core 0.6.6-develop.6126.1.0b9392fdae → 0.6.6-develop.6133.1.f01540250e

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.
@@ -1,5 +1,6 @@
1
1
  import { NextResponse } from "next/server";
2
2
  import { z } from "zod";
3
+ import { sql } from "kysely";
3
4
  import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
4
5
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
5
6
  import { findOneWithDecryption, findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
@@ -63,21 +64,20 @@ async function GET(req, context) {
63
64
  dscope
64
65
  );
65
66
  const conversationIds = conversations.map((c) => c.id).filter(Boolean);
66
- let links = [];
67
+ const counts = { sent: 0, delivered: 0, read: 0, failed: 0, pending: 0, queued: 0, other: 0 };
68
+ let totalsLast24h = 0;
67
69
  let recentFailures = [];
68
70
  if (conversationIds.length > 0) {
69
71
  const since = new Date(Date.now() - WINDOW_HOURS * 60 * 60 * 1e3);
70
- links = await findWithDecryption(
71
- em,
72
- MessageChannelLink,
73
- {
74
- externalConversationId: { $in: conversationIds },
75
- tenantId: auth.tenantId,
76
- createdAt: { $gte: since }
77
- },
78
- void 0,
79
- dscope
80
- );
72
+ const db = em.getKysely();
73
+ const statusRows = await db.selectFrom("message_channel_links").select(["delivery_status", sql`count(*)`.as("count")]).where("external_conversation_id", "in", conversationIds).where("tenant_id", "=", auth.tenantId).where("created_at", ">=", since).groupBy("delivery_status").execute();
74
+ for (const row of statusRows) {
75
+ const value = Number(row.count) || 0;
76
+ totalsLast24h += value;
77
+ const key = row.delivery_status;
78
+ if (key && key in counts) counts[key] += value;
79
+ else counts.other += value;
80
+ }
81
81
  recentFailures = await findWithDecryption(
82
82
  em,
83
83
  MessageChannelLink,
@@ -90,19 +90,13 @@ async function GET(req, context) {
90
90
  dscope
91
91
  );
92
92
  }
93
- const counts = { sent: 0, delivered: 0, read: 0, failed: 0, pending: 0, queued: 0, other: 0 };
94
- for (const link of links) {
95
- const key = link.deliveryStatus;
96
- if (key in counts) counts[key] += 1;
97
- else counts.other += 1;
98
- }
99
93
  return NextResponse.json({
100
94
  channelId: channel.id,
101
95
  providerKey: channel.providerKey,
102
96
  channelType: channel.channelType,
103
97
  windowHours: WINDOW_HOURS,
104
98
  counts,
105
- totalsLast24h: links.length,
99
+ totalsLast24h,
106
100
  recentFailures: recentFailures.map((link) => ({
107
101
  id: link.id,
108
102
  messageId: link.messageId,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../../../src/modules/communication_channels/api/get/channels/%5Bid%5D/health/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { CommunicationChannel, ExternalConversation, MessageChannelLink } from '../../../../../data/entities'\nimport { ChannelAccessDeniedError, assertCanAccessChannel } from '../../../../../lib/access-control'\n\ntype RbacServiceLike = {\n loadAcl: (\n userId: string,\n scope: { tenantId: string | null; organizationId: string | null },\n ) => Promise<{ isSuperAdmin: boolean; features: string[]; organizations: string[] | null }>\n}\n\nexport const metadata = {\n path: '/communication_channels/channels/[id]/health',\n GET: { requireAuth: true, requireFeatures: ['communication_channels.view'] },\n}\n\ntype RouteContext = {\n params: Promise<{ id: string }> | { id: string }\n}\n\nconst WINDOW_HOURS = 24\nconst RECENT_FAILURES_LIMIT = 10\n\n/**\n * Channel health snapshot \u2014 live aggregates from `message_channel_links` rather\n * than a dedicated `HealthLog` table.\n *\n * Returns counts of `sent` / `failed` / `pending` deliveries in the trailing\n * 24-hour window, plus the most recent failed links with last-error context.\n *\n * Per-user isolation: aggregates are scoped to **this channel only** via the\n * `external_conversations.channelId` join (a MessageChannelLink does not have a\n * direct channelId column \u2014 the link goes through ExternalConversation). Before\n * any DB read for aggregates, the channel must pass `assertCanAccessChannel`\n * so a non-admin caller cannot inspect another user's channel telemetry.\n */\nexport async function GET(req: Request, context: RouteContext): Promise<Response> {\n const { id } = await context.params\n if (!z.string().uuid().safeParse(id).success) {\n return NextResponse.json({ error: 'Invalid channel id' }, { status: 400 })\n }\n\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const em = (container.resolve('em') as EntityManager).fork()\n\n const dscope = {\n tenantId: auth.tenantId as string,\n organizationId: (auth as { orgId?: string | null }).orgId ?? null,\n }\n const channel = await findOneWithDecryption(\n em,\n CommunicationChannel,\n { id, tenantId: auth.tenantId, organizationId: dscope.organizationId, deletedAt: null },\n undefined,\n dscope,\n )\n if (!channel) {\n return NextResponse.json({ error: 'Channel not found' }, { status: 404 })\n }\n\n let userFeatures: string[] = []\n try {\n const rbac = container.resolve('rbacService') as RbacServiceLike\n const acl = await rbac.loadAcl(auth.sub as string, {\n tenantId: auth.tenantId as string,\n organizationId: dscope.organizationId,\n })\n userFeatures = acl?.isSuperAdmin ? ['*'] : Array.isArray(acl?.features) ? acl.features : []\n } catch {\n userFeatures = []\n }\n try {\n assertCanAccessChannel(channel, auth.sub as string, userFeatures)\n } catch (err) {\n if (err instanceof ChannelAccessDeniedError) {\n return NextResponse.json({ error: 'Channel not found' }, { status: 404 })\n }\n throw err\n }\n\n // ExternalConversation is append-only on the hub side \u2014 no soft-delete column.\n // Scope by channel + tenant so aggregates stay isolated even when the same\n // provider is connected by multiple users in the same tenant.\n const conversations = await findWithDecryption(\n em,\n ExternalConversation,\n { channelId: channel.id, tenantId: auth.tenantId },\n undefined,\n dscope,\n )\n const conversationIds = conversations.map((c) => c.id).filter(Boolean) as string[]\n\n let links: MessageChannelLink[] = []\n let recentFailures: MessageChannelLink[] = []\n if (conversationIds.length > 0) {\n const since = new Date(Date.now() - WINDOW_HOURS * 60 * 60 * 1000)\n links = await findWithDecryption(\n em,\n MessageChannelLink,\n {\n externalConversationId: { $in: conversationIds },\n tenantId: auth.tenantId,\n createdAt: { $gte: since },\n },\n undefined,\n dscope,\n )\n recentFailures = await findWithDecryption(\n em,\n MessageChannelLink,\n {\n externalConversationId: { $in: conversationIds },\n tenantId: auth.tenantId,\n deliveryStatus: 'failed',\n },\n { limit: RECENT_FAILURES_LIMIT, orderBy: { createdAt: 'desc' } },\n dscope,\n )\n }\n\n const counts = { sent: 0, delivered: 0, read: 0, failed: 0, pending: 0, queued: 0, other: 0 }\n for (const link of links) {\n const key = link.deliveryStatus as keyof typeof counts\n if (key in counts) counts[key] += 1\n else counts.other += 1\n }\n\n return NextResponse.json({\n channelId: channel.id,\n providerKey: channel.providerKey,\n channelType: channel.channelType,\n windowHours: WINDOW_HOURS,\n counts,\n totalsLast24h: links.length,\n recentFailures: recentFailures.map((link) => ({\n id: link.id,\n messageId: link.messageId,\n direction: link.direction,\n createdAt: link.createdAt?.toISOString?.() ?? null,\n lastError:\n (link.channelMetadata as Record<string, unknown> | null)?.lastError ?? null,\n transient:\n (link.channelMetadata as Record<string, unknown> | null)?.transient ?? null,\n })),\n })\n}\n\nexport const openApi = {\n tags: ['CommunicationChannels'],\n methods: {\n GET: {\n summary: 'Snapshot of channel delivery health (last 24h)',\n tags: ['CommunicationChannels'],\n responses: [\n { status: 200, description: 'Health snapshot' },\n { status: 400, description: 'Invalid channel id' },\n { status: 401, description: 'Unauthorized' },\n { status: 404, description: 'Channel not found' },\n ],\n },\n },\n}\nexport default GET\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAEvC,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,sBAAsB,sBAAsB,0BAA0B;AAC/E,SAAS,0BAA0B,8BAA8B;AAS1D,MAAM,WAAW;A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,UAAM,MAAM,KAAK;AACjB,QAAI,OAAO,OAAQ,QAAO,GAAG,KAAK;AAAA,QAC7B,QAAO,SAAS;AAAA,EACvB;AAEA,SAAO,aAAa,KAAK;AAAA,IACvB,WAAW,QAAQ;AAAA,IACnB,aAAa,QAAQ;AAAA,IACrB,aAAa,QAAQ;AAAA,IACrB,aAAa;AAAA,IACb;AAAA,IACA,eAAe,MAAM;AAAA,IACrB,gBAAgB,eAAe,IAAI,CAAC,UAAU;AAAA,MAC5C,IAAI,KAAK;AAAA,MACT,WAAW,KAAK;AAAA,MAChB,WAAW,KAAK;AAAA,MAChB,WAAW,KAAK,WAAW,cAAc,KAAK;AAAA,MAC9C,WACG,KAAK,iBAAoD,aAAa;AAAA,MACzE,WACG,KAAK,iBAAoD,aAAa;AAAA,IAC3E,EAAE;AAAA,EACJ,CAAC;AACH;AAEO,MAAM,UAAU;AAAA,EACrB,MAAM,CAAC,uBAAuB;AAAA,EAC9B,SAAS;AAAA,IACP,KAAK;AAAA,MACH,SAAS;AAAA,MACT,MAAM,CAAC,uBAAuB;AAAA,MAC9B,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,kBAAkB;AAAA,QAC9C,EAAE,QAAQ,KAAK,aAAa,qBAAqB;AAAA,QACjD,EAAE,QAAQ,KAAK,aAAa,eAAe;AAAA,QAC3C,EAAE,QAAQ,KAAK,aAAa,oBAAoB;AAAA,MAClD;AAAA,IACF;AAAA,EACF;AACF;AACA,IAAO,gBAAQ;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { sql } from 'kysely'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { CommunicationChannel, ExternalConversation, MessageChannelLink } from '../../../../../data/entities'\nimport { ChannelAccessDeniedError, assertCanAccessChannel } from '../../../../../lib/access-control'\n\ntype RbacServiceLike = {\n loadAcl: (\n userId: string,\n scope: { tenantId: string | null; organizationId: string | null },\n ) => Promise<{ isSuperAdmin: boolean; features: string[]; organizations: string[] | null }>\n}\n\nexport const metadata = {\n path: '/communication_channels/channels/[id]/health',\n GET: { requireAuth: true, requireFeatures: ['communication_channels.view'] },\n}\n\ntype RouteContext = {\n params: Promise<{ id: string }> | { id: string }\n}\n\nconst WINDOW_HOURS = 24\nconst RECENT_FAILURES_LIMIT = 10\n\n/**\n * Channel health snapshot \u2014 live aggregates from `message_channel_links` rather\n * than a dedicated `HealthLog` table.\n *\n * Returns counts of `sent` / `failed` / `pending` deliveries in the trailing\n * 24-hour window, plus the most recent failed links with last-error context.\n *\n * Per-user isolation: aggregates are scoped to **this channel only** via the\n * `external_conversations.channelId` join (a MessageChannelLink does not have a\n * direct channelId column \u2014 the link goes through ExternalConversation). Before\n * any DB read for aggregates, the channel must pass `assertCanAccessChannel`\n * so a non-admin caller cannot inspect another user's channel telemetry.\n */\nexport async function GET(req: Request, context: RouteContext): Promise<Response> {\n const { id } = await context.params\n if (!z.string().uuid().safeParse(id).success) {\n return NextResponse.json({ error: 'Invalid channel id' }, { status: 400 })\n }\n\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const em = (container.resolve('em') as EntityManager).fork()\n\n const dscope = {\n tenantId: auth.tenantId as string,\n organizationId: (auth as { orgId?: string | null }).orgId ?? null,\n }\n const channel = await findOneWithDecryption(\n em,\n CommunicationChannel,\n { id, tenantId: auth.tenantId, organizationId: dscope.organizationId, deletedAt: null },\n undefined,\n dscope,\n )\n if (!channel) {\n return NextResponse.json({ error: 'Channel not found' }, { status: 404 })\n }\n\n let userFeatures: string[] = []\n try {\n const rbac = container.resolve('rbacService') as RbacServiceLike\n const acl = await rbac.loadAcl(auth.sub as string, {\n tenantId: auth.tenantId as string,\n organizationId: dscope.organizationId,\n })\n userFeatures = acl?.isSuperAdmin ? ['*'] : Array.isArray(acl?.features) ? acl.features : []\n } catch {\n userFeatures = []\n }\n try {\n assertCanAccessChannel(channel, auth.sub as string, userFeatures)\n } catch (err) {\n if (err instanceof ChannelAccessDeniedError) {\n return NextResponse.json({ error: 'Channel not found' }, { status: 404 })\n }\n throw err\n }\n\n // ExternalConversation is append-only on the hub side \u2014 no soft-delete column.\n // Scope by channel + tenant so aggregates stay isolated even when the same\n // provider is connected by multiple users in the same tenant.\n const conversations = await findWithDecryption(\n em,\n ExternalConversation,\n { channelId: channel.id, tenantId: auth.tenantId },\n undefined,\n dscope,\n )\n const conversationIds = conversations.map((c) => c.id).filter(Boolean) as string[]\n\n const counts = { sent: 0, delivered: 0, read: 0, failed: 0, pending: 0, queued: 0, other: 0 }\n let totalsLast24h = 0\n let recentFailures: MessageChannelLink[] = []\n if (conversationIds.length > 0) {\n const since = new Date(Date.now() - WINDOW_HOURS * 60 * 60 * 1000)\n\n // Aggregate the delivery-status counts in the database so the response stays\n // a small fixed shape regardless of how much traffic the channel saw in the\n // window. `delivery_status`, `external_conversation_id`, `tenant_id` and\n // `created_at` are plaintext columns (see encryption.ts \u2014 only\n // `channel_ingest_dead_letter.raw_body` is encrypted on this module), so a\n // grouped count is safe without the decryption helpers.\n const db = em.getKysely<any>() as any\n const statusRows = (await db\n .selectFrom('message_channel_links')\n .select(['delivery_status', sql<string>`count(*)`.as('count')])\n .where('external_conversation_id', 'in', conversationIds)\n .where('tenant_id', '=', auth.tenantId)\n .where('created_at', '>=', since)\n .groupBy('delivery_status')\n .execute()) as Array<{ delivery_status: string | null; count: string | number }>\n\n for (const row of statusRows) {\n const value = Number(row.count) || 0\n totalsLast24h += value\n const key = row.delivery_status as keyof typeof counts\n if (key && key in counts) counts[key] += value\n else counts.other += value\n }\n\n recentFailures = await findWithDecryption(\n em,\n MessageChannelLink,\n {\n externalConversationId: { $in: conversationIds },\n tenantId: auth.tenantId,\n deliveryStatus: 'failed',\n },\n { limit: RECENT_FAILURES_LIMIT, orderBy: { createdAt: 'desc' } },\n dscope,\n )\n }\n\n return NextResponse.json({\n channelId: channel.id,\n providerKey: channel.providerKey,\n channelType: channel.channelType,\n windowHours: WINDOW_HOURS,\n counts,\n totalsLast24h,\n recentFailures: recentFailures.map((link) => ({\n id: link.id,\n messageId: link.messageId,\n direction: link.direction,\n createdAt: link.createdAt?.toISOString?.() ?? null,\n lastError:\n (link.channelMetadata as Record<string, unknown> | null)?.lastError ?? null,\n transient:\n (link.channelMetadata as Record<string, unknown> | null)?.transient ?? null,\n })),\n })\n}\n\nexport const openApi = {\n tags: ['CommunicationChannels'],\n methods: {\n GET: {\n summary: 'Snapshot of channel delivery health (last 24h)',\n tags: ['CommunicationChannels'],\n responses: [\n { status: 200, description: 'Health snapshot' },\n { status: 400, description: 'Invalid channel id' },\n { status: 401, description: 'Unauthorized' },\n { status: 404, description: 'Channel not found' },\n ],\n },\n },\n}\nexport default GET\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,WAAW;AACpB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAEvC,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,sBAAsB,sBAAsB,0BAA0B;AAC/E,SAAS,0BAA0B,8BAA8B;AAS1D,MAAM,WAAW;AAAA,EACtB,MAAM;AAAA,EACN,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,6BAA6B,EAAE;AAC7E;AAMA,MAAM,eAAe;AACrB,MAAM,wBAAwB;AAe9B,eAAsB,IAAI,KAAc,SAA0C;AAChF,QAAM,EAAE,GAAG,IAAI,MAAM,QAAQ;AAC7B,MAAI,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,EAAE,SAAS;AAC5C,WAAO,aAAa,KAAK,EAAE,OAAO,qBAAqB,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC3E;AAEA,QA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A,IACA,gBAAgB,eAAe,IAAI,CAAC,UAAU;AAAA,MAC5C,IAAI,KAAK;AAAA,MACT,WAAW,KAAK;AAAA,MAChB,WAAW,KAAK;AAAA,MAChB,WAAW,KAAK,WAAW,cAAc,KAAK;AAAA,MAC9C,WACG,KAAK,iBAAoD,aAAa;AAAA,MACzE,WACG,KAAK,iBAAoD,aAAa;AAAA,IAC3E,EAAE;AAAA,EACJ,CAAC;AACH;AAEO,MAAM,UAAU;AAAA,EACrB,MAAM,CAAC,uBAAuB;AAAA,EAC9B,SAAS;AAAA,IACP,KAAK;AAAA,MACH,SAAS;AAAA,MACT,MAAM,CAAC,uBAAuB;AAAA,MAC9B,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,kBAAkB;AAAA,QAC9C,EAAE,QAAQ,KAAK,aAAa,qBAAqB;AAAA,QACjD,EAAE,QAAQ,KAAK,aAAa,eAAe;AAAA,QAC3C,EAAE,QAAQ,KAAK,aAAa,oBAAoB;AAAA,MAClD;AAAA,IACF;AAAA,EACF;AACF;AACA,IAAO,gBAAQ;",
6
6
  "names": []
7
7
  }
@@ -5,48 +5,6 @@ import {
5
5
  MessageChannelLink,
6
6
  MessageReaction
7
7
  } from "./entities.js";
8
- async function resolveChannelsByMessageId(em, links, tenantId, organizationId) {
9
- if (links.length === 0) return /* @__PURE__ */ new Map();
10
- const conversationIds = Array.from(
11
- new Set(
12
- links.map((l) => l.externalConversationId).filter(
13
- (id) => typeof id === "string" && id.length > 0
14
- )
15
- )
16
- );
17
- if (conversationIds.length === 0) return /* @__PURE__ */ new Map();
18
- const dscope = { tenantId, organizationId };
19
- const conversations = await findWithDecryption(
20
- em,
21
- ExternalConversation,
22
- { id: { $in: conversationIds }, tenantId, organizationId },
23
- void 0,
24
- dscope
25
- );
26
- const channelIdByConversation = /* @__PURE__ */ new Map();
27
- for (const conv of conversations) {
28
- channelIdByConversation.set(conv.id, conv.channelId);
29
- }
30
- const channelIds = Array.from(new Set(Array.from(channelIdByConversation.values())));
31
- if (channelIds.length === 0) return /* @__PURE__ */ new Map();
32
- const channels = await findWithDecryption(
33
- em,
34
- CommunicationChannel,
35
- { id: { $in: channelIds }, tenantId, organizationId, deletedAt: null },
36
- void 0,
37
- dscope
38
- );
39
- const channelsById = new Map(
40
- channels.map((c) => [c.id, c])
41
- );
42
- const result = /* @__PURE__ */ new Map();
43
- for (const link of links) {
44
- const channelId = link.externalConversationId ? channelIdByConversation.get(link.externalConversationId) : void 0;
45
- const channel = channelId ? channelsById.get(channelId) : void 0;
46
- if (channel) result.set(link.messageId, channel);
47
- }
48
- return result;
49
- }
50
8
  function ctxEm(ctx) {
51
9
  return ctx.em;
52
10
  }
@@ -55,8 +13,8 @@ const messageChannelEnricher = {
55
13
  targetEntity: "messages.message",
56
14
  features: ["communication_channels.view"],
57
15
  priority: 30,
58
- timeout: 1500,
59
- fallback: { _channel: null },
16
+ timeout: 2e3,
17
+ fallback: { _channel: null, _channelPayload: null, _channelContact: null },
60
18
  critical: false,
61
19
  async enrichOne(record, ctx) {
62
20
  const [out] = await this.enrichMany([record], ctx);
@@ -66,84 +24,95 @@ const messageChannelEnricher = {
66
24
  if (records.length === 0) return records;
67
25
  const messageIds = records.map((r) => r.id);
68
26
  const em = ctxEm(ctx);
69
- const dscope = { tenantId: ctx.tenantId, organizationId: ctx.organizationId ?? null };
27
+ const tenantId = ctx.tenantId;
28
+ const organizationId = ctx.organizationId ?? null;
29
+ const dscope = { tenantId, organizationId };
70
30
  const links = await findWithDecryption(
71
31
  em,
72
32
  MessageChannelLink,
73
33
  {
74
34
  messageId: { $in: messageIds },
75
- tenantId: ctx.tenantId,
76
- organizationId: ctx.organizationId ?? null
35
+ tenantId,
36
+ organizationId
77
37
  },
78
- // Result set is already bounded by the `messageId $in messageIds` filter
79
- // (the host list endpoint caps the page at 100), matching the other
80
- // enrichers — no separate row limit needed.
81
38
  void 0,
82
39
  dscope
83
40
  );
84
- const channelByMessageId = await resolveChannelsByMessageId(
85
- em,
86
- links,
87
- ctx.tenantId,
88
- ctx.organizationId ?? null
89
- );
90
41
  const linksByMessage = /* @__PURE__ */ new Map();
91
42
  for (const link of links) linksByMessage.set(link.messageId, link);
43
+ const conversationIds = Array.from(
44
+ new Set(
45
+ links.map((l) => l.externalConversationId).filter((id) => typeof id === "string" && id.length > 0)
46
+ )
47
+ );
48
+ const conversationsById = /* @__PURE__ */ new Map();
49
+ if (conversationIds.length > 0) {
50
+ const conversations = await findWithDecryption(
51
+ em,
52
+ ExternalConversation,
53
+ { id: { $in: conversationIds }, tenantId, organizationId },
54
+ void 0,
55
+ dscope
56
+ );
57
+ for (const conversation of conversations) {
58
+ conversationsById.set(conversation.id, conversation);
59
+ }
60
+ }
61
+ const channelIds = Array.from(
62
+ new Set(
63
+ Array.from(conversationsById.values()).map((conversation) => conversation.channelId).filter((id) => typeof id === "string" && id.length > 0)
64
+ )
65
+ );
66
+ const channelsById = /* @__PURE__ */ new Map();
67
+ if (channelIds.length > 0) {
68
+ const channels = await findWithDecryption(
69
+ em,
70
+ CommunicationChannel,
71
+ { id: { $in: channelIds }, tenantId, organizationId, deletedAt: null },
72
+ void 0,
73
+ dscope
74
+ );
75
+ for (const channel of channels) channelsById.set(channel.id, channel);
76
+ }
77
+ const channelByMessageId = /* @__PURE__ */ new Map();
78
+ for (const link of links) {
79
+ if (!link.externalConversationId) continue;
80
+ const conversation = conversationsById.get(link.externalConversationId);
81
+ if (!conversation) continue;
82
+ const channel = conversation.channelId ? channelsById.get(conversation.channelId) : void 0;
83
+ if (channel) channelByMessageId.set(link.messageId, channel);
84
+ }
92
85
  return records.map((r) => {
93
86
  const link = linksByMessage.get(r.id);
94
- if (!link) return { ...r, _channel: null };
87
+ if (!link) {
88
+ return { ...r, _channel: null, _channelPayload: null, _channelContact: null };
89
+ }
95
90
  const channel = channelByMessageId.get(r.id);
96
- const enrichment = {
91
+ const channelEnrichment = {
97
92
  providerKey: link.providerKey,
98
93
  channelType: link.channelType,
99
94
  direction: link.direction,
100
95
  deliveryStatus: link.deliveryStatus ?? null,
101
96
  capabilities: channel?.capabilities ?? null
102
97
  };
103
- return { ...r, _channel: enrichment };
104
- });
105
- }
106
- };
107
- const messageChannelPayloadEnricher = {
108
- id: "communication_channels.message-channel-payload",
109
- targetEntity: "messages.message",
110
- features: ["communication_channels.view"],
111
- priority: 20,
112
- timeout: 1500,
113
- fallback: { _channelPayload: null },
114
- critical: false,
115
- async enrichOne(record, ctx) {
116
- const [out] = await this.enrichMany([record], ctx);
117
- return out;
118
- },
119
- async enrichMany(records, ctx) {
120
- if (records.length === 0) return records;
121
- const messageIds = records.map((r) => r.id);
122
- const em = ctxEm(ctx);
123
- const dscope = { tenantId: ctx.tenantId, organizationId: ctx.organizationId ?? null };
124
- const links = await findWithDecryption(
125
- em,
126
- MessageChannelLink,
127
- {
128
- messageId: { $in: messageIds },
129
- tenantId: ctx.tenantId,
130
- organizationId: ctx.organizationId ?? null
131
- },
132
- void 0,
133
- dscope
134
- );
135
- const byMessage = /* @__PURE__ */ new Map();
136
- for (const link of links) byMessage.set(link.messageId, link);
137
- return records.map((r) => {
138
- const link = byMessage.get(r.id);
139
- if (!link) return { ...r, _channelPayload: null };
140
- const enrichment = {
98
+ const payloadEnrichment = {
141
99
  channelContentType: link.channelContentType ?? null,
142
100
  channelPayload: link.channelPayload ?? null,
143
101
  interactiveState: link.interactiveState ?? null,
144
102
  channelMetadata: link.channelMetadata ?? null
145
103
  };
146
- return { ...r, _channelPayload: enrichment };
104
+ const conversation = link.externalConversationId ? conversationsById.get(link.externalConversationId) : void 0;
105
+ const contactEnrichment = conversation ? {
106
+ contactPersonId: conversation.contactPersonId ?? null,
107
+ assignedUserId: conversation.assignedUserId ?? null,
108
+ subject: conversation.subject ?? null
109
+ } : null;
110
+ return {
111
+ ...r,
112
+ _channel: channelEnrichment,
113
+ _channelPayload: payloadEnrichment,
114
+ _channelContact: contactEnrichment
115
+ };
147
116
  });
148
117
  }
149
118
  };
@@ -210,73 +179,9 @@ function groupReactions(rows, currentUserId) {
210
179
  }
211
180
  return Array.from(map.values()).sort((a, b) => b.count - a.count);
212
181
  }
213
- const conversationContactEnricher = {
214
- id: "communication_channels.conversation-contact",
215
- targetEntity: "messages.message",
216
- features: ["communication_channels.view"],
217
- priority: 15,
218
- timeout: 2e3,
219
- fallback: { _channelContact: null },
220
- critical: false,
221
- async enrichOne(record, ctx) {
222
- const [out] = await this.enrichMany([record], ctx);
223
- return out;
224
- },
225
- async enrichMany(records, ctx) {
226
- if (records.length === 0) return records;
227
- const messageIds = records.map((r) => r.id);
228
- const em = ctxEm(ctx);
229
- const dscope = { tenantId: ctx.tenantId, organizationId: ctx.organizationId ?? null };
230
- const links = await findWithDecryption(
231
- em,
232
- MessageChannelLink,
233
- {
234
- messageId: { $in: messageIds },
235
- tenantId: ctx.tenantId,
236
- organizationId: ctx.organizationId ?? null
237
- },
238
- void 0,
239
- dscope
240
- );
241
- const conversationIds = Array.from(
242
- new Set(links.map((l) => l.externalConversationId).filter(Boolean))
243
- );
244
- let conversationsById = /* @__PURE__ */ new Map();
245
- if (conversationIds.length > 0) {
246
- const conversations = await findWithDecryption(
247
- em,
248
- ExternalConversation,
249
- {
250
- id: { $in: conversationIds },
251
- tenantId: ctx.tenantId,
252
- organizationId: ctx.organizationId ?? null
253
- },
254
- void 0,
255
- dscope
256
- );
257
- conversationsById = new Map(conversations.map((c) => [c.id, c]));
258
- }
259
- const linksByMessage = /* @__PURE__ */ new Map();
260
- for (const link of links) linksByMessage.set(link.messageId, link);
261
- return records.map((r) => {
262
- const link = linksByMessage.get(r.id);
263
- if (!link) return { ...r, _channelContact: null };
264
- const conversation = conversationsById.get(link.externalConversationId);
265
- if (!conversation) return { ...r, _channelContact: null };
266
- const enrichment = {
267
- contactPersonId: conversation.contactPersonId ?? null,
268
- assignedUserId: conversation.assignedUserId ?? null,
269
- subject: conversation.subject ?? null
270
- };
271
- return { ...r, _channelContact: enrichment };
272
- });
273
- }
274
- };
275
182
  const enrichers = [
276
183
  messageChannelEnricher,
277
- messageChannelPayloadEnricher,
278
- messageReactionsEnricher,
279
- conversationContactEnricher
184
+ messageReactionsEnricher
280
185
  ];
281
186
  var enrichers_default = enrichers;
282
187
  export {
@@ -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 {\n CommunicationChannel,\n ExternalConversation,\n MessageChannelLink,\n MessageReaction,\n} from './entities'\n\n/**\n * Resolve channels by `id` (not `providerKey`) \u2014 multi-user channels share the\n * same `providerKey` (e.g. two users with Gmail), so a providerKey-keyed Map\n * collapses them and returns the wrong owner's capabilities snapshot. The hop\n * goes `MessageChannelLink \u2192 ExternalConversation \u2192 CommunicationChannel`.\n *\n * Returns a Map keyed by the platform Message id so enrichers can read\n * `channelByMessageId.get(record.id)` without further joins.\n */\nasync function resolveChannelsByMessageId(\n em: EntityManager,\n links: MessageChannelLink[],\n tenantId: string,\n organizationId: string | null,\n): Promise<Map<string, CommunicationChannel>> {\n if (links.length === 0) return new Map()\n const conversationIds = Array.from(\n new Set(\n links.map((l) => (l as { externalConversationId?: string }).externalConversationId).filter(\n (id): id is string => typeof id === 'string' && id.length > 0,\n ),\n ),\n )\n if (conversationIds.length === 0) return new Map()\n const dscope = { tenantId, organizationId }\n const conversations = await findWithDecryption(\n em,\n ExternalConversation,\n { id: { $in: conversationIds }, tenantId, organizationId },\n undefined,\n dscope,\n )\n const channelIdByConversation = new Map<string, string>()\n for (const conv of conversations) {\n channelIdByConversation.set(conv.id, conv.channelId)\n }\n const channelIds = Array.from(new Set(Array.from(channelIdByConversation.values())))\n if (channelIds.length === 0) return new Map()\n const channels = await findWithDecryption(\n em,\n CommunicationChannel,\n { id: { $in: channelIds }, tenantId, organizationId, deletedAt: null },\n undefined,\n dscope,\n )\n const channelsById = new Map<string, CommunicationChannel>(\n channels.map((c) => [c.id, c]),\n )\n const result = new Map<string, CommunicationChannel>()\n for (const link of links) {\n const channelId = link.externalConversationId\n ? channelIdByConversation.get(link.externalConversationId)\n : undefined\n const channel = channelId ? channelsById.get(channelId) : undefined\n if (channel) result.set(link.messageId, channel)\n }\n return result\n}\n\n/**\n * Response enrichers for the messages.message entity.\n *\n * The hub declares 4 enrichers; downstream hosts (Messages module's `/api/messages`\n * CRUD route + future provider routes) opt in via `makeCrudRoute({ enrichers: { entityId: 'messages.message' } })`.\n *\n * - `_channel` \u2192 channel metadata + capabilities snapshot\n * - `_channelPayload` \u2192 channel-native payload (Block Kit / interactive / email MIME / \u2026)\n * - `_reactions` \u2192 grouped emoji counts + users + reactedByMe\n * - `_channelContact` \u2192 CRM person preview (email + display name)\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\n// \u2500\u2500 _channel \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\nconst messageChannelEnricher: ResponseEnricher<MessageRecord, { _channel?: ChannelEnrichment | null }> = {\n id: 'communication_channels.message-channel',\n targetEntity: 'messages.message',\n features: ['communication_channels.view'],\n priority: 30,\n timeout: 1500,\n fallback: { _channel: 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 dscope = { tenantId: ctx.tenantId, organizationId: ctx.organizationId ?? null }\n const links = await findWithDecryption(\n em,\n MessageChannelLink,\n {\n messageId: { $in: messageIds },\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n },\n // Result set is already bounded by the `messageId $in messageIds` filter\n // (the host list endpoint caps the page at 100), matching the other\n // enrichers \u2014 no separate row limit needed.\n undefined,\n dscope,\n )\n\n // Resolve channels via the `link \u2192 ExternalConversation \u2192 CommunicationChannel`\n // path. Keys are platform Message ids \u2014 direct mapping per row.\n const channelByMessageId = await resolveChannelsByMessageId(\n em,\n links,\n ctx.tenantId as string,\n ctx.organizationId ?? null,\n )\n\n const linksByMessage = new Map<string, MessageChannelLink>()\n for (const link of links) linksByMessage.set(link.messageId, link)\n\n return records.map((r) => {\n const link = linksByMessage.get(r.id)\n if (!link) return { ...r, _channel: null }\n const channel = channelByMessageId.get(r.id)\n const enrichment: 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 return { ...r, _channel: enrichment }\n })\n },\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\n// \u2500\u2500 _channelPayload \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 messageChannelPayloadEnricher: ResponseEnricher<\n MessageRecord,\n { _channelPayload?: ChannelPayloadEnrichment | null }\n> = {\n id: 'communication_channels.message-channel-payload',\n targetEntity: 'messages.message',\n features: ['communication_channels.view'],\n priority: 20,\n timeout: 1500,\n fallback: { _channelPayload: 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 dscope = { tenantId: ctx.tenantId, organizationId: ctx.organizationId ?? null }\n const links = await findWithDecryption(\n em,\n MessageChannelLink,\n {\n messageId: { $in: messageIds },\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n },\n undefined,\n dscope,\n )\n const byMessage = new Map<string, MessageChannelLink>()\n for (const link of links) byMessage.set(link.messageId, link)\n\n return records.map((r) => {\n const link = byMessage.get(r.id)\n if (!link) return { ...r, _channelPayload: null }\n const enrichment: ChannelPayloadEnrichment = {\n channelContentType: link.channelContentType ?? null,\n channelPayload: link.channelPayload ?? null,\n interactiveState: link.interactiveState ?? null,\n channelMetadata: link.channelMetadata ?? null,\n }\n return { ...r, _channelPayload: enrichment }\n })\n },\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\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 _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\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 conversationContactEnricher: ResponseEnricher<\n MessageRecord,\n { _channelContact?: ChannelContactEnrichment | null }\n> = {\n id: 'communication_channels.conversation-contact',\n targetEntity: 'messages.message',\n features: ['communication_channels.view'],\n priority: 15,\n timeout: 2000,\n fallback: { _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 dscope = { tenantId: ctx.tenantId, organizationId: ctx.organizationId ?? null }\n const links = await findWithDecryption(\n em,\n MessageChannelLink,\n {\n messageId: { $in: messageIds },\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n },\n undefined,\n dscope,\n )\n const conversationIds = Array.from(\n new Set(links.map((l) => l.externalConversationId).filter(Boolean)),\n )\n let conversationsById = new Map<string, ExternalConversation>()\n if (conversationIds.length > 0) {\n const conversations = await findWithDecryption(\n em,\n ExternalConversation,\n {\n id: { $in: conversationIds },\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n },\n undefined,\n dscope,\n )\n conversationsById = new Map(conversations.map((c) => [c.id, c]))\n }\n\n const linksByMessage = new Map<string, MessageChannelLink>()\n for (const link of links) linksByMessage.set(link.messageId, link)\n\n return records.map((r) => {\n const link = linksByMessage.get(r.id)\n if (!link) return { ...r, _channelContact: null }\n const conversation = conversationsById.get(link.externalConversationId)\n if (!conversation) return { ...r, _channelContact: null }\n const enrichment: ChannelContactEnrichment = {\n contactPersonId: conversation.contactPersonId ?? null,\n assignedUserId: conversation.assignedUserId ?? null,\n subject: conversation.subject ?? null,\n }\n return { ...r, _channelContact: enrichment }\n })\n },\n}\n\nexport type ChannelContactEnrichment = {\n contactPersonId: string | null\n assignedUserId: string | null\n subject: string | null\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 messageChannelPayloadEnricher as unknown as ResponseEnricher,\n messageReactionsEnricher as unknown as ResponseEnricher,\n conversationContactEnricher as unknown as ResponseEnricher,\n]\n\nexport default enrichers\n"],
5
- "mappings": "AAEA,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAWP,eAAe,2BACb,IACA,OACA,UACA,gBAC4C;AAC5C,MAAI,MAAM,WAAW,EAAG,QAA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AgB,aAAa,kBAAkB;AAAA,QAC/C,SAAS,aAAa,WAAW;AAAA,MACnC;AACA,aAAO,EAAE,GAAG,GAAG,iBAAiB,WAAW;AAAA,IAC7C,CAAC;AAAA,EACH;AACF;AAUO,MAAM,YAAgC;AAAA,EAC3C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,IAAO,oBAAQ;",
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 {\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\nexport type ChannelContactEnrichment = {\n contactPersonId: string | null\n assignedUserId: string | null\n subject: string | null\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 }\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;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAwCP,SAAS,MAAM,KAAqC;AAClD,SAAO,IAAI;AACb;AAyBA,MAAM,yBAOF;AAAA,EACF,IAAI;AAAA,EACJ,cAAc;AAAA,EACd,UAAU,CAAC,6BAA6B;AAAA,EACxC,UAAU;AAAA,EACV,SAAS;AAAA,EACT,UAAU,EAAE,UAAU,MAAM,iBAAiB,MAAM,iBAAiB,KAAK;AAAA,EACzE,UAAU;AAAA,EAEV,MAAM,UAAU,QAAQ,KAAK;AAC3B,UAAM,CAAC,GAAG,IAAI,MAAM,KAAK,WAAY,CAAC,MAAM,GAAG,GAAG;AAClD,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,WAAW,SAAS,KAAK;AAC7B,QAAI,QAAQ,WAAW,EAAG,QAAO;AACjC,UAAM,aAAa,QAAQ,IAAI,CAAC,MAAM,EAAE,EAAE;AAC1C,UAAM,KAAK,MAAM,GAAG;AACpB,UAAM,WAAW,IAAI;AACrB,UAAM,iBAAiB,IAAI,kBAAkB;AAC7C,UAAM,SAAS,EAAE,UAAU,eAAe;AAO1C,UAAM,QAAQ,MAAM;AAAA,MAClB;AAAA,MACA;AAAA,MACA;AAAA,QACE,WAAW,EAAE,KAAK,WAAW;AAAA,QAC7B;AAAA,QACA;AAAA,MACF;AAAA,MACA;AAAA,MACA;AAAA,IACF;AACA,UAAM,iBAAiB,oBAAI,IAAgC;AAC3D,eAAW,QAAQ,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AAM,MAAM,KAAK;AAAA,MACf,QAAQ,IAAI,mBAAmB;AAAA,MAC/B,YAAY,IAAI,uBAAuB;AAAA,MACvC,aAAa,IAAI,wBAAwB;AAAA,MACzC,aAAa,IAAI,eAAe;AAAA,IAClC,CAAC;AACD,QAAI,IAAI,mBAAmB,IAAI,oBAAoB,eAAe;AAChE,YAAM,cAAc;AACpB,UAAI,CAAC,MAAM,aAAc,OAAM,eAAe,IAAI,MAAM;AAAA,IAC1D;AAAA,EACF;AACA,SAAO,MAAM,KAAK,IAAI,OAAO,CAAC,EAAE,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK;AAClE;AAIO,MAAM,YAAgC;AAAA,EAC3C;AAAA,EACA;AACF;AAEA,IAAO,oBAAQ;",
6
6
  "names": []
7
7
  }
@@ -8,6 +8,8 @@ import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuarde
8
8
  import { flash } from "@open-mercato/ui/backend/FlashMessages";
9
9
  import { useT } from "@open-mercato/shared/lib/i18n/context";
10
10
  import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
11
+ import { hasFeature } from "@open-mercato/shared/security/features";
12
+ const MANAGE_FEATURE = "configs.cache.manage";
11
13
  const API_PATH = "/api/configs/cache";
12
14
  const CACHE_MUTATION_CONTEXT_ID = "configs-cache-panel";
13
15
  function CachePanel() {
@@ -55,7 +57,7 @@ function CachePanel() {
55
57
  {
56
58
  method: "POST",
57
59
  headers: { "content-type": "application/json" },
58
- body: JSON.stringify({ features: ["configs.cache.manage"] })
60
+ body: JSON.stringify({ features: [MANAGE_FEATURE] })
59
61
  },
60
62
  {
61
63
  errorMessage: t("configs.cache.loadError", "Failed to load cache statistics."),
@@ -64,8 +66,8 @@ function CachePanel() {
64
66
  );
65
67
  if (cancelled) return;
66
68
  const granted = Array.isArray(payload?.granted) ? payload.granted.filter((feature) => typeof feature === "string") : [];
67
- const hasFeature = payload?.ok === true || granted.includes("configs.cache.manage");
68
- setCanManage(hasFeature);
69
+ const canManageFeature = payload?.ok === true || hasFeature(granted, MANAGE_FEATURE);
70
+ setCanManage(canManageFeature);
69
71
  } catch {
70
72
  if (!cancelled) setCanManage(false);
71
73
  } finally {