@open-mercato/core 0.9.1-develop.7513.1.ae2715553f → 0.9.1-develop.7516.1.176184247d
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/.turbo/turbo-build.log +1 -1
- package/dist/modules/communication_channels/lib/send-as-user.js.map +2 -2
- package/dist/modules/customers/api/people/[id]/emails/route.js +44 -1
- package/dist/modules/customers/api/people/[id]/emails/route.js.map +2 -2
- package/dist/modules/customers/lib/personEmailThreads.js +36 -1
- package/dist/modules/customers/lib/personEmailThreads.js.map +2 -2
- package/dist/modules/messages/api/[id]/route.js +3 -9
- package/dist/modules/messages/api/[id]/route.js.map +2 -2
- package/dist/modules/messages/api/route.js +33 -16
- package/dist/modules/messages/api/route.js.map +2 -2
- package/dist/modules/messages/commands/messages.js.map +2 -2
- package/dist/modules/messages/lib/routeHelpers.js +40 -1
- package/dist/modules/messages/lib/routeHelpers.js.map +2 -2
- package/dist/modules/shipping_carriers/api/webhook/[provider]/route.js +4 -7
- package/dist/modules/shipping_carriers/api/webhook/[provider]/route.js.map +2 -2
- package/dist/modules/shipping_carriers/lib/shipping-service.js +29 -11
- package/dist/modules/shipping_carriers/lib/shipping-service.js.map +2 -2
- package/dist/modules/shipping_carriers/lib/status-sync.js +2 -2
- package/dist/modules/shipping_carriers/lib/status-sync.js.map +2 -2
- package/dist/modules/shipping_carriers/workers/webhook-processor.js +60 -33
- package/dist/modules/shipping_carriers/workers/webhook-processor.js.map +3 -3
- package/dist/modules/warranty_claims/commands/claim-lines.js +89 -68
- package/dist/modules/warranty_claims/commands/claim-lines.js.map +2 -2
- package/dist/modules/warranty_claims/commands/claims.js +14 -13
- package/dist/modules/warranty_claims/commands/claims.js.map +2 -2
- package/dist/modules/warranty_claims/commands/shared.js +8 -2
- package/dist/modules/warranty_claims/commands/shared.js.map +2 -2
- package/package.json +7 -7
- package/src/modules/communication_channels/lib/send-as-user.ts +4 -0
- package/src/modules/customers/api/people/[id]/emails/route.ts +67 -1
- package/src/modules/customers/i18n/de.json +1 -0
- package/src/modules/customers/i18n/en.json +1 -0
- package/src/modules/customers/i18n/es.json +1 -0
- package/src/modules/customers/i18n/ko.json +1 -0
- package/src/modules/customers/i18n/pl.json +1 -0
- package/src/modules/customers/lib/personEmailThreads.ts +61 -0
- package/src/modules/messages/api/[id]/route.ts +2 -9
- package/src/modules/messages/api/route.ts +42 -20
- package/src/modules/messages/commands/messages.ts +7 -0
- package/src/modules/messages/i18n/de.json +1 -0
- package/src/modules/messages/i18n/en.json +1 -0
- package/src/modules/messages/i18n/es.json +1 -0
- package/src/modules/messages/i18n/ko.json +1 -0
- package/src/modules/messages/i18n/pl.json +1 -0
- package/src/modules/messages/lib/routeHelpers.ts +84 -1
- package/src/modules/shipping_carriers/api/webhook/[provider]/route.ts +4 -7
- package/src/modules/shipping_carriers/lib/shipping-service.ts +29 -11
- package/src/modules/shipping_carriers/lib/status-sync.ts +2 -2
- package/src/modules/shipping_carriers/workers/webhook-processor.ts +71 -39
- package/src/modules/warranty_claims/commands/claim-lines.ts +107 -66
- package/src/modules/warranty_claims/commands/claims.ts +14 -13
- package/src/modules/warranty_claims/commands/shared.ts +7 -1
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/communication_channels/lib/send-as-user.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n ChannelThreadMapping,\n CommunicationChannel,\n ExternalConversation,\n MessageChannelLink,\n} from '../data/entities'\nimport { ChannelMutationBlockedError, guardOutboundCreate } from './mutation-guards'\nimport { COMMUNICATION_CHANNELS_QUEUES, getCommunicationChannelsQueue } from './queue'\nimport type { OutboundDeliveryPayload } from '../workers/outbound-delivery'\nimport { htmlToText } from './email-mime'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('communication_channels')\n\nexport type SendAsUserActor = {\n userId: string\n tenantId: string\n organizationId: string | null\n /** Forwarded as the messages compose command `ctx.auth`. */\n auth?: unknown\n}\n\nexport type SendAsUserInput = {\n userChannelId: string\n to: string[]\n cc?: string[]\n bcc?: string[]\n subject: string\n body: { plain?: string; html?: string; bodyFormat?: 'text' | 'markdown' }\n inReplyTo?: string\n references?: string[]\n /**\n * Open Mercato `messages.message` id of the message being replied to. When\n * set, the composed message joins that message's thread (the messages module\n * derives `threadId` from the parent), so a CRM reply continues the existing\n * conversation instead of starting a new thread. Optional \u2014 omitted for new\n * threads.\n */\n parentMessageId?: string\n /**\n * Free-form metadata persisted on the resulting MessageChannelLink. Used by\n * downstream subscribers (e.g. the customers module's link-channel-message\n * subscriber) to anchor the sent message back to a CRM Person or honor a\n * caller-specified visibility flag. The hub does not interpret these keys.\n */\n channelMetadata?: Record<string, unknown>\n}\n\nexport type SendAsUserResult =\n | {\n ok: true\n messageId: string\n threadId: string\n channelId: string\n providerKey: string\n }\n | { ok: false; status: number; error: string; fieldErrors?: Record<string, string> }\n\n/**\n * In-process send-as-user facade.\n *\n * Validates the actor owns `userChannelId`, composes the Message via the\n * messages module command, persists the outbound MessageChannelLink + thread\n * mapping, and enqueues delivery. Returns a discriminated result instead of an\n * HTTP Response so it can be invoked both by the `/send-as-user` route and by\n * other modules via DI (`container.resolve('communicationChannelsSendAsUser')`)\n * \u2014 no HTTP self-call required.\n */\nexport async function sendAsUser(\n container: AppContainer,\n actor: SendAsUserActor,\n input: SendAsUserInput,\n): Promise<SendAsUserResult> {\n if (!input.body.plain && !input.body.html) {\n return { ok: false, status: 422, error: 'Either body.plain or body.html is required' }\n }\n // Re-validate here (not only in the HTTP route's zod schema) because this\n // facade is also reachable via DI; `input.to[0]` below would otherwise become\n // `undefined` for an empty recipient list.\n if (!Array.isArray(input.to) || input.to.length === 0) {\n return { ok: false, status: 422, error: 'At least one recipient is required' }\n }\n\n const em = (container.resolve('em') as EntityManager).fork()\n const { tenantId } = actor\n const organizationId = actor.organizationId\n const dscope = { tenantId, organizationId }\n\n const channel = await findOneWithDecryption(\n em,\n CommunicationChannel,\n { id: input.userChannelId, tenantId, organizationId, deletedAt: null },\n undefined,\n dscope,\n )\n if (!channel) return { ok: false, status: 404, error: 'Channel not found' }\n if (channel.userId !== actor.userId) {\n return { ok: false, status: 403, error: 'You can only send through channels you own' }\n }\n\n // Hub mutation guard: map known non-deliverable states (`requires_reauth`,\n // `disconnected`) to a 422 with field-level errors; other transitional states\n // fall through to the 409 below.\n try {\n await guardOutboundCreate(em, { channelId: channel.id, scope: dscope })\n } catch (err) {\n if (err instanceof ChannelMutationBlockedError) {\n return { ok: false, status: 422, error: err.message, fieldErrors: err.errors }\n }\n throw err\n }\n if (!channel.isActive || channel.status !== 'connected') {\n return {\n ok: false,\n status: 409,\n error: `Channel is in status '${channel.status}' (not connected)`,\n }\n }\n\n // Create the Message via the messages module compose command. The outbound\n // subscriber picks it up via `messages.message.sent` and routes through the\n // adapter chain.\n const commandBus = container.resolve('commandBus') as CommandBus\n const messageBody = input.body.plain ?? htmlToText(input.body.html ?? '')\n const composeInput = {\n type: `channel.${channel.providerKey}`,\n visibility: 'public' as const,\n sourceEntityType: 'communication_channels.send_as_user',\n sourceEntityId: channel.id,\n externalEmail: input.to[0],\n externalName: input.subject,\n recipients: [],\n subject: input.subject,\n body: messageBody,\n bodyFormat: input.body.bodyFormat === 'markdown' ? ('markdown' as const) : ('text' as const),\n priority: 'normal' as const,\n sendViaEmail: false,\n parentMessageId: input.parentMessageId,\n isDraft: false,\n tenantId,\n organizationId,\n userId: actor.userId,\n }\n let result\n try {\n result = await commandBus.execute<typeof composeInput, { id: string; threadId: string | null }>(\n 'messages.messages.compose',\n {\n input: composeInput,\n ctx: {\n container,\n auth: actor.auth as never,\n organizationScope: null,\n selectedOrganizationId: organizationId,\n organizationIds: organizationId ? [organizationId] : null,\n },\n },\n )\n } catch (err) {\n logger.error('communication_channels send-as-user compose failed', { err })\n return { ok: false, status: 500, error: '[internal] compose failed' }\n }\n\n const messageId = result.result.id\n const messageThreadId = result.result.threadId ?? messageId\n const externalThreadRef = `outbound:${messageThreadId}`\n\n // Persist the conversation, thread mapping, and channel link as one unit. The\n // conversation's id is DB-generated (`gen_random_uuid()`), so it must be\n // flushed before the mapping/link can reference it \u2014 hence the eager flushes\n // rather than `withAtomicFlush` (single trailing flush). `em.transactional`\n // wraps the whole sequence so a mid-way failure rolls back all three writes\n // instead of leaving an orphaned conversation row.\n await em.transactional(async () => {\n let conversation = await findOneWithDecryption(\n em,\n ExternalConversation,\n {\n channelId: channel.id,\n externalConversationId: externalThreadRef,\n tenantId,\n organizationId,\n },\n undefined,\n dscope,\n )\n if (!conversation) {\n conversation = em.create(ExternalConversation, {\n channelId: channel.id,\n externalConversationId: externalThreadRef,\n subject: input.subject,\n assignedUserId: actor.userId,\n tenantId,\n organizationId,\n lastMessageAt: new Date(),\n })\n em.persist(conversation)\n await em.flush()\n } else {\n conversation.subject = conversation.subject ?? input.subject\n conversation.assignedUserId = conversation.assignedUserId ?? actor.userId\n conversation.lastMessageAt = new Date()\n // Flush the scalar updates BEFORE the ChannelThreadMapping lookup below: a\n // find/findOne on the same EntityManager between a scalar mutation and flush\n // can silently drop the pending UPDATE (core AGENTS.md \u2192 Entity Update Safety).\n await em.flush()\n }\n\n const existingMapping = await findOneWithDecryption(\n em,\n ChannelThreadMapping,\n {\n externalConversationId: conversation.id,\n tenantId,\n organizationId,\n },\n undefined,\n dscope,\n )\n if (!existingMapping) {\n const mapping = em.create(ChannelThreadMapping, {\n externalConversationId: conversation.id,\n messageThreadId,\n channelId: channel.id,\n providerKey: channel.providerKey,\n externalThreadRef,\n assignedUserId: actor.userId,\n tenantId,\n organizationId,\n })\n em.persist(mapping)\n }\n\n const channelLink = em.create(MessageChannelLink, {\n messageId,\n externalConversationId: conversation.id,\n providerKey: channel.providerKey,\n channelType: channel.channelType,\n direction: 'outbound',\n deliveryStatus: 'pending',\n channelPayload: {\n text: input.body.plain ?? messageBody,\n ...(input.body.html ? { html: input.body.html } : {}),\n },\n channelContentType: input.body.html ? 'text/html' : 'text/plain',\n channelMetadata: {\n // Caller-supplied pass-through metadata merged FIRST so the validated\n // routing fields below always win \u2014 a caller cannot override the\n // recipients/subject/threading headers via `channelMetadata`.\n ...(input.channelMetadata ?? {}),\n to: input.to,\n cc: input.cc ?? [],\n bcc: input.bcc ?? [],\n subject: input.subject,\n inReplyTo: input.inReplyTo ?? null,\n references: input.references ?? [],\n },\n tenantId,\n organizationId,\n })\n em.persist(channelLink)\n await em.flush()\n })\n\n const queue = getCommunicationChannelsQueue(COMMUNICATION_CHANNELS_QUEUES.outbound)\n const deliveryJob: OutboundDeliveryPayload = {\n messageId,\n scope: dscope,\n attempt: 1,\n }\n await queue.enqueue(deliveryJob as unknown as Record<string, unknown>)\n\n return {\n ok: true,\n messageId,\n threadId: messageThreadId,\n channelId: channel.id,\n providerKey: channel.providerKey,\n }\n}\n\n/** DI service type for cross-module callers (resolve `communicationChannelsSendAsUser`). */\nexport type SendAsUserService = typeof sendAsUser\n"],
|
|
5
|
-
"mappings": "AAGA,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,6BAA6B,2BAA2B;AACjE,SAAS,+BAA+B,qCAAqC;AAE7E,SAAS,kBAAkB;AAC3B,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,wBAAwB;
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n ChannelThreadMapping,\n CommunicationChannel,\n ExternalConversation,\n MessageChannelLink,\n} from '../data/entities'\nimport { ChannelMutationBlockedError, guardOutboundCreate } from './mutation-guards'\nimport { COMMUNICATION_CHANNELS_QUEUES, getCommunicationChannelsQueue } from './queue'\nimport type { OutboundDeliveryPayload } from '../workers/outbound-delivery'\nimport { htmlToText } from './email-mime'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('communication_channels')\n\nexport type SendAsUserActor = {\n userId: string\n tenantId: string\n organizationId: string | null\n /** Forwarded as the messages compose command `ctx.auth`. */\n auth?: unknown\n}\n\nexport type SendAsUserInput = {\n userChannelId: string\n to: string[]\n cc?: string[]\n bcc?: string[]\n subject: string\n body: { plain?: string; html?: string; bodyFormat?: 'text' | 'markdown' }\n inReplyTo?: string\n references?: string[]\n /**\n * Open Mercato `messages.message` id of the message being replied to. When\n * set, the composed message joins that message's thread (the messages module\n * derives `threadId` from the parent), so a CRM reply continues the existing\n * conversation instead of starting a new thread. Optional \u2014 omitted for new\n * threads.\n *\n * Not authorized here: the facade serves more than one surface, and each owns\n * what \"may reply to\" means. The caller MUST have established that the actor\n * can read this message under its own read rule before passing it.\n */\n parentMessageId?: string\n /**\n * Free-form metadata persisted on the resulting MessageChannelLink. Used by\n * downstream subscribers (e.g. the customers module's link-channel-message\n * subscriber) to anchor the sent message back to a CRM Person or honor a\n * caller-specified visibility flag. The hub does not interpret these keys.\n */\n channelMetadata?: Record<string, unknown>\n}\n\nexport type SendAsUserResult =\n | {\n ok: true\n messageId: string\n threadId: string\n channelId: string\n providerKey: string\n }\n | { ok: false; status: number; error: string; fieldErrors?: Record<string, string> }\n\n/**\n * In-process send-as-user facade.\n *\n * Validates the actor owns `userChannelId`, composes the Message via the\n * messages module command, persists the outbound MessageChannelLink + thread\n * mapping, and enqueues delivery. Returns a discriminated result instead of an\n * HTTP Response so it can be invoked both by the `/send-as-user` route and by\n * other modules via DI (`container.resolve('communicationChannelsSendAsUser')`)\n * \u2014 no HTTP self-call required.\n */\nexport async function sendAsUser(\n container: AppContainer,\n actor: SendAsUserActor,\n input: SendAsUserInput,\n): Promise<SendAsUserResult> {\n if (!input.body.plain && !input.body.html) {\n return { ok: false, status: 422, error: 'Either body.plain or body.html is required' }\n }\n // Re-validate here (not only in the HTTP route's zod schema) because this\n // facade is also reachable via DI; `input.to[0]` below would otherwise become\n // `undefined` for an empty recipient list.\n if (!Array.isArray(input.to) || input.to.length === 0) {\n return { ok: false, status: 422, error: 'At least one recipient is required' }\n }\n\n const em = (container.resolve('em') as EntityManager).fork()\n const { tenantId } = actor\n const organizationId = actor.organizationId\n const dscope = { tenantId, organizationId }\n\n const channel = await findOneWithDecryption(\n em,\n CommunicationChannel,\n { id: input.userChannelId, tenantId, organizationId, deletedAt: null },\n undefined,\n dscope,\n )\n if (!channel) return { ok: false, status: 404, error: 'Channel not found' }\n if (channel.userId !== actor.userId) {\n return { ok: false, status: 403, error: 'You can only send through channels you own' }\n }\n\n // Hub mutation guard: map known non-deliverable states (`requires_reauth`,\n // `disconnected`) to a 422 with field-level errors; other transitional states\n // fall through to the 409 below.\n try {\n await guardOutboundCreate(em, { channelId: channel.id, scope: dscope })\n } catch (err) {\n if (err instanceof ChannelMutationBlockedError) {\n return { ok: false, status: 422, error: err.message, fieldErrors: err.errors }\n }\n throw err\n }\n if (!channel.isActive || channel.status !== 'connected') {\n return {\n ok: false,\n status: 409,\n error: `Channel is in status '${channel.status}' (not connected)`,\n }\n }\n\n // Create the Message via the messages module compose command. The outbound\n // subscriber picks it up via `messages.message.sent` and routes through the\n // adapter chain.\n const commandBus = container.resolve('commandBus') as CommandBus\n const messageBody = input.body.plain ?? htmlToText(input.body.html ?? '')\n const composeInput = {\n type: `channel.${channel.providerKey}`,\n visibility: 'public' as const,\n sourceEntityType: 'communication_channels.send_as_user',\n sourceEntityId: channel.id,\n externalEmail: input.to[0],\n externalName: input.subject,\n recipients: [],\n subject: input.subject,\n body: messageBody,\n bodyFormat: input.body.bodyFormat === 'markdown' ? ('markdown' as const) : ('text' as const),\n priority: 'normal' as const,\n sendViaEmail: false,\n parentMessageId: input.parentMessageId,\n isDraft: false,\n tenantId,\n organizationId,\n userId: actor.userId,\n }\n let result\n try {\n result = await commandBus.execute<typeof composeInput, { id: string; threadId: string | null }>(\n 'messages.messages.compose',\n {\n input: composeInput,\n ctx: {\n container,\n auth: actor.auth as never,\n organizationScope: null,\n selectedOrganizationId: organizationId,\n organizationIds: organizationId ? [organizationId] : null,\n },\n },\n )\n } catch (err) {\n logger.error('communication_channels send-as-user compose failed', { err })\n return { ok: false, status: 500, error: '[internal] compose failed' }\n }\n\n const messageId = result.result.id\n const messageThreadId = result.result.threadId ?? messageId\n const externalThreadRef = `outbound:${messageThreadId}`\n\n // Persist the conversation, thread mapping, and channel link as one unit. The\n // conversation's id is DB-generated (`gen_random_uuid()`), so it must be\n // flushed before the mapping/link can reference it \u2014 hence the eager flushes\n // rather than `withAtomicFlush` (single trailing flush). `em.transactional`\n // wraps the whole sequence so a mid-way failure rolls back all three writes\n // instead of leaving an orphaned conversation row.\n await em.transactional(async () => {\n let conversation = await findOneWithDecryption(\n em,\n ExternalConversation,\n {\n channelId: channel.id,\n externalConversationId: externalThreadRef,\n tenantId,\n organizationId,\n },\n undefined,\n dscope,\n )\n if (!conversation) {\n conversation = em.create(ExternalConversation, {\n channelId: channel.id,\n externalConversationId: externalThreadRef,\n subject: input.subject,\n assignedUserId: actor.userId,\n tenantId,\n organizationId,\n lastMessageAt: new Date(),\n })\n em.persist(conversation)\n await em.flush()\n } else {\n conversation.subject = conversation.subject ?? input.subject\n conversation.assignedUserId = conversation.assignedUserId ?? actor.userId\n conversation.lastMessageAt = new Date()\n // Flush the scalar updates BEFORE the ChannelThreadMapping lookup below: a\n // find/findOne on the same EntityManager between a scalar mutation and flush\n // can silently drop the pending UPDATE (core AGENTS.md \u2192 Entity Update Safety).\n await em.flush()\n }\n\n const existingMapping = await findOneWithDecryption(\n em,\n ChannelThreadMapping,\n {\n externalConversationId: conversation.id,\n tenantId,\n organizationId,\n },\n undefined,\n dscope,\n )\n if (!existingMapping) {\n const mapping = em.create(ChannelThreadMapping, {\n externalConversationId: conversation.id,\n messageThreadId,\n channelId: channel.id,\n providerKey: channel.providerKey,\n externalThreadRef,\n assignedUserId: actor.userId,\n tenantId,\n organizationId,\n })\n em.persist(mapping)\n }\n\n const channelLink = em.create(MessageChannelLink, {\n messageId,\n externalConversationId: conversation.id,\n providerKey: channel.providerKey,\n channelType: channel.channelType,\n direction: 'outbound',\n deliveryStatus: 'pending',\n channelPayload: {\n text: input.body.plain ?? messageBody,\n ...(input.body.html ? { html: input.body.html } : {}),\n },\n channelContentType: input.body.html ? 'text/html' : 'text/plain',\n channelMetadata: {\n // Caller-supplied pass-through metadata merged FIRST so the validated\n // routing fields below always win \u2014 a caller cannot override the\n // recipients/subject/threading headers via `channelMetadata`.\n ...(input.channelMetadata ?? {}),\n to: input.to,\n cc: input.cc ?? [],\n bcc: input.bcc ?? [],\n subject: input.subject,\n inReplyTo: input.inReplyTo ?? null,\n references: input.references ?? [],\n },\n tenantId,\n organizationId,\n })\n em.persist(channelLink)\n await em.flush()\n })\n\n const queue = getCommunicationChannelsQueue(COMMUNICATION_CHANNELS_QUEUES.outbound)\n const deliveryJob: OutboundDeliveryPayload = {\n messageId,\n scope: dscope,\n attempt: 1,\n }\n await queue.enqueue(deliveryJob as unknown as Record<string, unknown>)\n\n return {\n ok: true,\n messageId,\n threadId: messageThreadId,\n channelId: channel.id,\n providerKey: channel.providerKey,\n }\n}\n\n/** DI service type for cross-module callers (resolve `communicationChannelsSendAsUser`). */\nexport type SendAsUserService = typeof sendAsUser\n"],
|
|
5
|
+
"mappings": "AAGA,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,6BAA6B,2BAA2B;AACjE,SAAS,+BAA+B,qCAAqC;AAE7E,SAAS,kBAAkB;AAC3B,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,wBAAwB;AA4DpD,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mB,CAAC;AAAA,QAC9B,IAAI,MAAM;AAAA,QACV,IAAI,MAAM,MAAM,CAAC;AAAA,QACjB,KAAK,MAAM,OAAO,CAAC;AAAA,QACnB,SAAS,MAAM;AAAA,QACf,WAAW,MAAM,aAAa;AAAA,QAC9B,YAAY,MAAM,cAAc,CAAC;AAAA,MACnC;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC;AACD,OAAG,QAAQ,WAAW;AACtB,UAAM,GAAG,MAAM;AAAA,EACjB,CAAC;AAED,QAAM,QAAQ,8BAA8B,8BAA8B,QAAQ;AAClF,QAAM,cAAuC;AAAA,IAC3C;AAAA,IACA,OAAO;AAAA,IACP,SAAS;AAAA,EACX;AACA,QAAM,MAAM,QAAQ,WAAiD;AAErE,SAAO;AAAA,IACL,IAAI;AAAA,IACJ;AAAA,IACA,UAAU;AAAA,IACV,WAAW,QAAQ;AAAA,IACnB,aAAa,QAAQ;AAAA,EACvB;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -11,8 +11,11 @@ import {
|
|
|
11
11
|
import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
|
|
12
12
|
import { resolveSingleOrganizationIdOrDeny } from "@open-mercato/core/modules/directory/utils/organizationScopeFilter";
|
|
13
13
|
import { isOrganizationReadAccessAllowed } from "@open-mercato/core/modules/directory/utils/organizationScopeGuard";
|
|
14
|
+
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
|
|
14
15
|
import { resolveAuthActorId } from "../../../../lib/interactionRequestContext.js";
|
|
15
16
|
import { CustomerEntity } from "../../../../data/entities.js";
|
|
17
|
+
import { listGrantsForViewerOnPerson, listSharedChannelIds } from "../../../../lib/conversationShares.js";
|
|
18
|
+
import { isMessageOnPersonEmailHistory } from "../../../../lib/personEmailThreads.js";
|
|
16
19
|
const metadata = {
|
|
17
20
|
path: "/customers/people/[id]/emails",
|
|
18
21
|
POST: {
|
|
@@ -33,6 +36,15 @@ const composeSchema = z.object({
|
|
|
33
36
|
references: z.array(z.string().max(500)).max(50).optional(),
|
|
34
37
|
parentMessageId: z.string().uuid().optional()
|
|
35
38
|
}).strict();
|
|
39
|
+
async function callerHasFeature(container, userId, feature, scope) {
|
|
40
|
+
try {
|
|
41
|
+
const rbac = container.resolve("rbacService");
|
|
42
|
+
if (typeof rbac?.userHasAllFeatures !== "function") return false;
|
|
43
|
+
return await rbac.userHasAllFeatures(userId, [feature], scope);
|
|
44
|
+
} catch {
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
36
48
|
async function POST(req, context) {
|
|
37
49
|
const { id: personId } = await context.params;
|
|
38
50
|
if (!z.string().uuid().safeParse(personId).success) {
|
|
@@ -74,6 +86,37 @@ async function POST(req, context) {
|
|
|
74
86
|
if (!isOrganizationReadAccessAllowed({ scope, auth, organizationId })) {
|
|
75
87
|
return NextResponse.json({ error: "Person not found" }, { status: 404 });
|
|
76
88
|
}
|
|
89
|
+
if (body.parentMessageId) {
|
|
90
|
+
const viewerUserId = auth.isApiKey ? null : auth.sub ?? null;
|
|
91
|
+
const shareScope = { tenantId: auth.tenantId, organizationId };
|
|
92
|
+
const canViewPeople = await callerHasFeature(container, userId, "customers.people.view", shareScope);
|
|
93
|
+
const [sharedConversations, sharedChannelIds] = canViewPeople ? await Promise.all([
|
|
94
|
+
listGrantsForViewerOnPerson(em, shareScope, viewerUserId, personId),
|
|
95
|
+
listSharedChannelIds(em, shareScope, viewerUserId)
|
|
96
|
+
]) : [[], []];
|
|
97
|
+
const parentVisible = canViewPeople && await isMessageOnPersonEmailHistory(em, {
|
|
98
|
+
personId,
|
|
99
|
+
tenantId: auth.tenantId,
|
|
100
|
+
organizationId,
|
|
101
|
+
viewerUserId,
|
|
102
|
+
userFeatures: void 0,
|
|
103
|
+
sharedConversations,
|
|
104
|
+
sharedChannelIds,
|
|
105
|
+
messageId: body.parentMessageId
|
|
106
|
+
});
|
|
107
|
+
if (!parentVisible) {
|
|
108
|
+
const { translate } = await resolveTranslations();
|
|
109
|
+
return NextResponse.json(
|
|
110
|
+
{
|
|
111
|
+
error: translate(
|
|
112
|
+
"customers.email.errors.parentMessageNotFound",
|
|
113
|
+
"The email you are replying to was not found"
|
|
114
|
+
)
|
|
115
|
+
},
|
|
116
|
+
{ status: 404 }
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
77
120
|
const guardResult = await validateCrudMutationGuard(container, {
|
|
78
121
|
tenantId: auth.tenantId,
|
|
79
122
|
organizationId,
|
|
@@ -142,7 +185,7 @@ const openApi = {
|
|
|
142
185
|
{ status: 400, description: "Invalid person id" },
|
|
143
186
|
{ status: 401, description: "Unauthorized" },
|
|
144
187
|
{ status: 403, description: "Missing customers.email.compose feature or mutation guard rejection" },
|
|
145
|
-
{ status: 404, description: "Person or channel not found" },
|
|
188
|
+
{ status: 404, description: "Person or channel not found, or the reply parent is not an email the caller can see on this Person" },
|
|
146
189
|
{ status: 409, description: "Channel not connected" },
|
|
147
190
|
{ status: 422, description: "Invalid request body" },
|
|
148
191
|
{ status: 500, description: "Send failed" }
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../src/modules/customers/api/people/%5Bid%5D/emails/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport {\n validateCrudMutationGuard,\n runCrudMutationGuardAfterSuccess,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { resolveSingleOrganizationIdOrDeny } from '@open-mercato/core/modules/directory/utils/organizationScopeFilter'\nimport { isOrganizationReadAccessAllowed } from '@open-mercato/core/modules/directory/utils/organizationScopeGuard'\nimport { resolveAuthActorId } from '../../../../lib/interactionRequestContext'\nimport { CustomerEntity } from '../../../../data/entities'\nimport type { SendAsUserService } from '@open-mercato/core/modules/communication_channels/lib/send-as-user'\n\nexport const metadata = {\n path: '/customers/people/[id]/emails',\n POST: {\n requireAuth: true,\n requireFeatures: ['customers.email.compose'],\n },\n}\n\nconst composeSchema = z\n .object({\n userChannelId: z.string().uuid(),\n to: z.array(z.string().email()).min(1).max(50),\n cc: z.array(z.string().email()).max(50).optional(),\n bcc: z.array(z.string().email()).max(50).optional(),\n subject: z.string().min(1).max(500),\n body: z.string().min(1).max(200_000),\n bodyFormat: z.enum(['text', 'html']).default('html'),\n visibility: z.enum(['private', 'shared']).default('private'),\n inReplyTo: z.string().max(500).optional(),\n references: z.array(z.string().max(500)).max(50).optional(),\n parentMessageId: z.string().uuid().optional(),\n })\n .strict()\n\ntype RouteContext = {\n params: Promise<{ id: string }> | { id: string }\n}\n\nexport async function POST(req: Request, context: RouteContext): Promise<Response> {\n const { id: personId } = await context.params\n if (!z.string().uuid().safeParse(personId).success) {\n return NextResponse.json({ error: 'Invalid person id' }, { status: 400 })\n }\n\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub || !auth?.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n let body: z.infer<typeof composeSchema>\n try {\n body = composeSchema.parse(await readJsonSafe(req, null))\n } catch (err) {\n return NextResponse.json(\n { error: err instanceof Error ? err.message : 'Invalid request body' },\n { status: 422 },\n )\n }\n\n const container = await createRequestContainer()\n const userId = resolveAuthActorId(auth)\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n\n const em = (container.resolve('em') as EntityManager).fork()\n\n // 1. Verify the Person exists in the caller's tenant, then fail-closed on the\n // record's own organization \u2014 same pattern as the [id]/route.ts GET handler.\n // Loading by tenant + id (not a hand-rolled selected org) keeps this working\n // under the \"All organizations\" scope; the record's own org then becomes the\n // concrete org the guard and the outbound message are attributed to.\n const person = await findOneWithDecryption(\n em,\n CustomerEntity,\n {\n id: personId,\n kind: 'person',\n tenantId: auth.tenantId,\n deletedAt: null,\n } as never,\n undefined,\n { tenantId: auth.tenantId as string, organizationId: resolveSingleOrganizationIdOrDeny(scope, auth) ?? null },\n )\n if (!person) {\n return NextResponse.json({ error: 'Person not found' }, { status: 404 })\n }\n const organizationId = (person as { organizationId?: string | null }).organizationId ?? null\n if (!isOrganizationReadAccessAllowed({ scope, auth, organizationId })) {\n return NextResponse.json({ error: 'Person not found' }, { status: 404 })\n }\n\n const guardResult = await validateCrudMutationGuard(container, {\n tenantId: auth.tenantId,\n organizationId,\n userId,\n resourceKind: 'customers.person',\n resourceId: personId,\n operation: 'custom',\n requestMethod: req.method,\n requestHeaders: req.headers,\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n\n // 2. Call the hub's send-as-user facade in-process (resolved via DI) so the\n // customers module makes no HTTP self-call. `crmVisibility` and `crmPersonId`\n // are injected as channelMetadata so the link-channel-message subscriber can\n // anchor the sent message back to this Person on the\n // `communication_channels.message.sent` event.\n const sendAsUserService = container.resolve(\n 'communicationChannelsSendAsUser',\n ) as SendAsUserService\n\n const sendResult = await sendAsUserService(\n container,\n { userId: auth.sub as string, tenantId: auth.tenantId as string, organizationId, auth },\n {\n userChannelId: body.userChannelId,\n to: body.to,\n cc: body.cc,\n bcc: body.bcc,\n subject: body.subject,\n body: body.bodyFormat === 'html' ? { html: body.body } : { plain: body.body },\n inReplyTo: body.inReplyTo,\n references: body.references,\n parentMessageId: body.parentMessageId,\n channelMetadata: {\n crmVisibility: body.visibility,\n crmPersonId: personId,\n },\n },\n )\n\n if (!sendResult.ok) {\n return NextResponse.json({ error: sendResult.error }, { status: sendResult.status })\n }\n\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(container, {\n tenantId: auth.tenantId,\n organizationId,\n userId,\n resourceKind: 'customers.person',\n resourceId: personId,\n operation: 'custom',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n // Delivery is async (handled by the outbound queue worker), so this is the\n // enqueue time \u2014 not the provider send time \u2014 and the provider's external\n // message id is not known yet (the worker assigns it on successful delivery).\n return NextResponse.json({\n messageId: sendResult.messageId,\n threadId: sendResult.threadId,\n queuedAt: new Date().toISOString(),\n })\n}\n\nexport const openApi = {\n tags: ['Customers', 'Email'],\n methods: {\n POST: {\n summary: 'Compose + send an email anchored to a Person',\n tags: ['Customers', 'Email'],\n responses: [\n { status: 200, description: 'Email queued for send' },\n { status: 400, description: 'Invalid person id' },\n { status: 401, description: 'Unauthorized' },\n { status: 403, description: 'Missing customers.email.compose feature or mutation guard rejection' },\n { status: 404, description: 'Person or channel not found' },\n { status: 409, description: 'Channel not connected' },\n { status: 422, description: 'Invalid request body' },\n { status: 500, description: 'Send failed' },\n ],\n },\n },\n}\nexport default POST\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,0CAA0C;AACnD,SAAS,yCAAyC;AAClD,SAAS,uCAAuC;AAChD,SAAS,0BAA0B;AACnC,SAAS,sBAAsB;
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport {\n validateCrudMutationGuard,\n runCrudMutationGuardAfterSuccess,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { resolveSingleOrganizationIdOrDeny } from '@open-mercato/core/modules/directory/utils/organizationScopeFilter'\nimport { isOrganizationReadAccessAllowed } from '@open-mercato/core/modules/directory/utils/organizationScopeGuard'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { resolveAuthActorId } from '../../../../lib/interactionRequestContext'\nimport { CustomerEntity } from '../../../../data/entities'\nimport { listGrantsForViewerOnPerson, listSharedChannelIds } from '../../../../lib/conversationShares'\nimport { isMessageOnPersonEmailHistory } from '../../../../lib/personEmailThreads'\nimport type { SendAsUserService } from '@open-mercato/core/modules/communication_channels/lib/send-as-user'\n\nexport const metadata = {\n path: '/customers/people/[id]/emails',\n POST: {\n requireAuth: true,\n requireFeatures: ['customers.email.compose'],\n },\n}\n\nconst composeSchema = z\n .object({\n userChannelId: z.string().uuid(),\n to: z.array(z.string().email()).min(1).max(50),\n cc: z.array(z.string().email()).max(50).optional(),\n bcc: z.array(z.string().email()).max(50).optional(),\n subject: z.string().min(1).max(500),\n body: z.string().min(1).max(200_000),\n bodyFormat: z.enum(['text', 'html']).default('html'),\n visibility: z.enum(['private', 'shared']).default('private'),\n inReplyTo: z.string().max(500).optional(),\n references: z.array(z.string().max(500)).max(50).optional(),\n parentMessageId: z.string().uuid().optional(),\n })\n .strict()\n\ntype RbacService = {\n userHasAllFeatures: (\n userId: string,\n required: string[],\n scope: { tenantId: string | null; organizationId: string | null },\n ) => Promise<boolean>\n}\n\nasync function callerHasFeature(\n container: { resolve: (name: string) => unknown },\n userId: string,\n feature: string,\n scope: { tenantId: string; organizationId: string | null },\n): Promise<boolean> {\n try {\n const rbac = container.resolve('rbacService') as RbacService | undefined\n if (typeof rbac?.userHasAllFeatures !== 'function') return false\n return await rbac.userHasAllFeatures(userId, [feature], scope)\n } catch {\n return false\n }\n}\n\ntype RouteContext = {\n params: Promise<{ id: string }> | { id: string }\n}\n\nexport async function POST(req: Request, context: RouteContext): Promise<Response> {\n const { id: personId } = await context.params\n if (!z.string().uuid().safeParse(personId).success) {\n return NextResponse.json({ error: 'Invalid person id' }, { status: 400 })\n }\n\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub || !auth?.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n let body: z.infer<typeof composeSchema>\n try {\n body = composeSchema.parse(await readJsonSafe(req, null))\n } catch (err) {\n return NextResponse.json(\n { error: err instanceof Error ? err.message : 'Invalid request body' },\n { status: 422 },\n )\n }\n\n const container = await createRequestContainer()\n const userId = resolveAuthActorId(auth)\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n\n const em = (container.resolve('em') as EntityManager).fork()\n\n // 1. Verify the Person exists in the caller's tenant, then fail-closed on the\n // record's own organization \u2014 same pattern as the [id]/route.ts GET handler.\n // Loading by tenant + id (not a hand-rolled selected org) keeps this working\n // under the \"All organizations\" scope; the record's own org then becomes the\n // concrete org the guard and the outbound message are attributed to.\n const person = await findOneWithDecryption(\n em,\n CustomerEntity,\n {\n id: personId,\n kind: 'person',\n tenantId: auth.tenantId,\n deletedAt: null,\n } as never,\n undefined,\n { tenantId: auth.tenantId as string, organizationId: resolveSingleOrganizationIdOrDeny(scope, auth) ?? null },\n )\n if (!person) {\n return NextResponse.json({ error: 'Person not found' }, { status: 404 })\n }\n const organizationId = (person as { organizationId?: string | null }).organizationId ?? null\n if (!isOrganizationReadAccessAllowed({ scope, auth, organizationId })) {\n return NextResponse.json({ error: 'Person not found' }, { status: 404 })\n }\n\n // A reply parent decides which thread the sent email joins, so it must be an\n // email this caller could see on this Person's Emails tab \u2014 the same feature,\n // anchor and visibility rule as `GET .../email-threads`, including conversation\n // shares and shared team mailboxes. Anything else answers like an unknown id.\n if (body.parentMessageId) {\n const viewerUserId = auth.isApiKey ? null : auth.sub ?? null\n const shareScope = { tenantId: auth.tenantId as string, organizationId }\n const canViewPeople = await callerHasFeature(container, userId, 'customers.people.view', shareScope)\n const [sharedConversations, sharedChannelIds] = canViewPeople\n ? await Promise.all([\n listGrantsForViewerOnPerson(em, shareScope, viewerUserId, personId),\n listSharedChannelIds(em, shareScope, viewerUserId),\n ])\n : [[], []]\n const parentVisible =\n canViewPeople &&\n (await isMessageOnPersonEmailHistory(em, {\n personId,\n tenantId: auth.tenantId as string,\n organizationId,\n viewerUserId,\n userFeatures: undefined,\n sharedConversations,\n sharedChannelIds,\n messageId: body.parentMessageId,\n }))\n if (!parentVisible) {\n const { translate } = await resolveTranslations()\n return NextResponse.json(\n {\n error: translate(\n 'customers.email.errors.parentMessageNotFound',\n 'The email you are replying to was not found',\n ),\n },\n { status: 404 },\n )\n }\n }\n\n const guardResult = await validateCrudMutationGuard(container, {\n tenantId: auth.tenantId,\n organizationId,\n userId,\n resourceKind: 'customers.person',\n resourceId: personId,\n operation: 'custom',\n requestMethod: req.method,\n requestHeaders: req.headers,\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n\n // 2. Call the hub's send-as-user facade in-process (resolved via DI) so the\n // customers module makes no HTTP self-call. `crmVisibility` and `crmPersonId`\n // are injected as channelMetadata so the link-channel-message subscriber can\n // anchor the sent message back to this Person on the\n // `communication_channels.message.sent` event.\n const sendAsUserService = container.resolve(\n 'communicationChannelsSendAsUser',\n ) as SendAsUserService\n\n const sendResult = await sendAsUserService(\n container,\n { userId: auth.sub as string, tenantId: auth.tenantId as string, organizationId, auth },\n {\n userChannelId: body.userChannelId,\n to: body.to,\n cc: body.cc,\n bcc: body.bcc,\n subject: body.subject,\n body: body.bodyFormat === 'html' ? { html: body.body } : { plain: body.body },\n inReplyTo: body.inReplyTo,\n references: body.references,\n parentMessageId: body.parentMessageId,\n channelMetadata: {\n crmVisibility: body.visibility,\n crmPersonId: personId,\n },\n },\n )\n\n if (!sendResult.ok) {\n return NextResponse.json({ error: sendResult.error }, { status: sendResult.status })\n }\n\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(container, {\n tenantId: auth.tenantId,\n organizationId,\n userId,\n resourceKind: 'customers.person',\n resourceId: personId,\n operation: 'custom',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n // Delivery is async (handled by the outbound queue worker), so this is the\n // enqueue time \u2014 not the provider send time \u2014 and the provider's external\n // message id is not known yet (the worker assigns it on successful delivery).\n return NextResponse.json({\n messageId: sendResult.messageId,\n threadId: sendResult.threadId,\n queuedAt: new Date().toISOString(),\n })\n}\n\nexport const openApi = {\n tags: ['Customers', 'Email'],\n methods: {\n POST: {\n summary: 'Compose + send an email anchored to a Person',\n tags: ['Customers', 'Email'],\n responses: [\n { status: 200, description: 'Email queued for send' },\n { status: 400, description: 'Invalid person id' },\n { status: 401, description: 'Unauthorized' },\n { status: 403, description: 'Missing customers.email.compose feature or mutation guard rejection' },\n { status: 404, description: 'Person or channel not found, or the reply parent is not an email the caller can see on this Person' },\n { status: 409, description: 'Channel not connected' },\n { status: 422, description: 'Invalid request body' },\n { status: 500, description: 'Send failed' },\n ],\n },\n },\n}\nexport default POST\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,0CAA0C;AACnD,SAAS,yCAAyC;AAClD,SAAS,uCAAuC;AAChD,SAAS,2BAA2B;AACpC,SAAS,0BAA0B;AACnC,SAAS,sBAAsB;AAC/B,SAAS,6BAA6B,4BAA4B;AAClE,SAAS,qCAAqC;AAGvC,MAAM,WAAW;AAAA,EACtB,MAAM;AAAA,EACN,MAAM;AAAA,IACJ,aAAa;AAAA,IACb,iB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wB;AAAA,QACpD,EAAE,QAAQ,KAAK,aAAa,oBAAoB;AAAA,QAChD,EAAE,QAAQ,KAAK,aAAa,eAAe;AAAA,QAC3C,EAAE,QAAQ,KAAK,aAAa,sEAAsE;AAAA,QAClG,EAAE,QAAQ,KAAK,aAAa,qGAAqG;AAAA,QACjI,EAAE,QAAQ,KAAK,aAAa,wBAAwB;AAAA,QACpD,EAAE,QAAQ,KAAK,aAAa,uBAAuB;AAAA,QACnD,EAAE,QAAQ,KAAK,aAAa,cAAc;AAAA,MAC5C;AAAA,IACF;AAAA,EACF;AACF;AACA,IAAO,gBAAQ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -220,7 +220,42 @@ async function buildPersonEmailThreads(em, opts) {
|
|
|
220
220
|
threads.sort((a, b) => b.lastMessageAt.localeCompare(a.lastMessageAt));
|
|
221
221
|
return threads.slice(0, maxThreads);
|
|
222
222
|
}
|
|
223
|
+
async function isMessageOnPersonEmailHistory(em, opts) {
|
|
224
|
+
const { personId, tenantId, organizationId, messageId } = opts;
|
|
225
|
+
const dscope = { tenantId, organizationId: organizationId ?? null };
|
|
226
|
+
const linkWhere = { messageId, tenantId };
|
|
227
|
+
if (organizationId) linkWhere.organizationId = organizationId;
|
|
228
|
+
const links = await findWithDecryption(
|
|
229
|
+
em,
|
|
230
|
+
"MessageChannelLink",
|
|
231
|
+
linkWhere,
|
|
232
|
+
void 0,
|
|
233
|
+
dscope
|
|
234
|
+
);
|
|
235
|
+
const linkIds = links.map((link) => typeof link.id === "string" ? link.id : null).filter((value) => !!value);
|
|
236
|
+
if (linkIds.length === 0) return false;
|
|
237
|
+
const interactionWhere = {
|
|
238
|
+
entity: personId,
|
|
239
|
+
interactionType: "email",
|
|
240
|
+
deletedAt: null,
|
|
241
|
+
tenantId,
|
|
242
|
+
externalMessageId: { $in: linkIds }
|
|
243
|
+
};
|
|
244
|
+
if (organizationId) interactionWhere.organizationId = organizationId;
|
|
245
|
+
Object.assign(
|
|
246
|
+
interactionWhere,
|
|
247
|
+
buildEmailVisibilityMikroFilter({
|
|
248
|
+
currentUserId: opts.viewerUserId,
|
|
249
|
+
userFeatures: opts.userFeatures,
|
|
250
|
+
sharedConversations: opts.sharedConversations,
|
|
251
|
+
sharedChannelIds: opts.sharedChannelIds
|
|
252
|
+
})
|
|
253
|
+
);
|
|
254
|
+
const visible = await em.count(CustomerInteraction, interactionWhere);
|
|
255
|
+
return visible > 0;
|
|
256
|
+
}
|
|
223
257
|
export {
|
|
224
|
-
buildPersonEmailThreads
|
|
258
|
+
buildPersonEmailThreads,
|
|
259
|
+
isMessageOnPersonEmailHistory
|
|
225
260
|
};
|
|
226
261
|
//# sourceMappingURL=personEmailThreads.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/customers/lib/personEmailThreads.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { CustomerInteraction } from '../data/entities'\nimport { resolveUserNames } from './userNames'\nimport { buildEmailVisibilityMikroFilter } from './visibilityFilter'\nimport type { ConversationShareGrant } from './conversationShares'\n\n/**\n * Read model that turns a Person's email `CustomerInteraction` rows into\n * Gmail-style threads for the CRM Person page.\n *\n * The Person\u2194email anchor lives only on `CustomerInteraction`\n * (`interactionType='email'`, `externalMessageId` \u2192 `MessageChannelLink.id`).\n * The thread grouping key and the rich per-message content (From/To/Cc, body,\n * direction) live in the communication_channels hub. We read the hub entities\n * by their string class names \u2014 the same cross-module pattern used by\n * `link-channel-message-handler.ts` \u2014 so the customers module never imports the\n * hub's entity classes (root AGENTS.md: no direct ORM relationships between\n * modules).\n */\n\nexport type EmailThreadDirection = 'inbound' | 'outbound'\n\nexport type PersonEmailMessage = {\n id: string\n /** Open Mercato `messages.message` id \u2014 used as `parentMessageId` when replying so the reply joins this thread. */\n messageId: string | null\n /** RFC2822 Message-ID of this email \u2014 used as `In-Reply-To` on a reply. */\n rfcMessageId: string | null\n /** RFC2822 References chain for this email. */\n references: string[]\n direction: EmailThreadDirection\n fromName: string | null\n fromEmail: string | null\n /**\n * True when the viewer is the author of this message. Outbound email carries\n * no `from` header in `channelMetadata`, so the sender label cannot be derived\n * from the addresses \u2014 and since conversation/channel sharing lets a teammate\n * read someone else's outbound mail, direction alone is not the author either.\n */\n authoredByViewer: boolean\n /** Display label of the sending colleague; null for the viewer's own mail and for inbound. */\n authorName: string | null\n to: string[]\n cc: string[]\n subject: string | null\n bodyText: string | null\n sentAt: string\n providerKey: string | null\n}\n\nexport type PersonEmailThread = {\n threadKey: string\n subject: string | null\n preview: string | null\n participants: string[]\n lastMessageAt: string\n messageCount: number\n providerKey: string | null\n lastDirection: EmailThreadDirection\n messages: PersonEmailMessage[]\n}\n\nexport type BuildPersonEmailThreadsOptions = {\n personId: string\n tenantId: string\n organizationId: string | null\n viewerUserId: string | null\n userFeatures: string[] | null | undefined\n /**\n * Conversation shares that widen this viewer's access. Optional and fail-closed:\n * omitting it yields the strict owner-only view.\n */\n sharedConversations?: ConversationShareGrant[]\n /** Channels marked as shared team mailboxes; optional and fail-closed. */\n sharedChannelIds?: string[]\n maxThreads?: number\n maxMessagesPerThread?: number\n}\n\nconst DEFAULT_MAX_THREADS = 50\nconst DEFAULT_MAX_MESSAGES_PER_THREAD = 200\nconst PREVIEW_LENGTH = 140\n\ntype JsonRecord = Record<string, unknown>\n\n/** Extracts `{ email, name }[]` from the many shapes a channel address field can take. */\nfunction extractAddresses(value: unknown): Array<{ email: string; name: string | null }> {\n const out: Array<{ email: string; name: string | null }> = []\n const pushOne = (item: unknown): void => {\n if (typeof item === 'string') {\n const trimmed = item.trim()\n if (trimmed) out.push({ email: trimmed, name: null })\n return\n }\n if (item && typeof item === 'object') {\n const rec = item as JsonRecord\n const address = typeof rec.address === 'string' ? rec.address.trim() : null\n const name = typeof rec.name === 'string' && rec.name.trim() ? rec.name.trim() : null\n if (address) out.push({ email: address, name })\n }\n }\n if (Array.isArray(value)) {\n for (const item of value) pushOne(item)\n } else {\n pushOne(value)\n }\n return out\n}\n\nfunction firstString(...values: unknown[]): string | null {\n for (const value of values) {\n if (typeof value === 'string' && value.trim().length > 0) return value\n }\n return null\n}\n\nfunction toStringArray(...values: unknown[]): string[] {\n for (const value of values) {\n if (Array.isArray(value)) {\n const strings = value.filter((item): item is string => typeof item === 'string' && item.trim().length > 0)\n if (strings.length > 0) return strings\n }\n }\n return []\n}\n\nfunction truncate(value: string | null): string | null {\n if (!value) return value\n const collapsed = value.replace(/\\s+/g, ' ').trim()\n if (collapsed.length <= PREVIEW_LENGTH) return collapsed\n return `${collapsed.slice(0, PREVIEW_LENGTH - 1)}\u2026`\n}\n\n/**\n * Builds the per-Person email-thread read model. Pure data assembly \u2014 callers\n * are responsible for auth and scoping (tenantId/organizationId required).\n */\nexport async function buildPersonEmailThreads(\n em: EntityManager,\n opts: BuildPersonEmailThreadsOptions,\n): Promise<PersonEmailThread[]> {\n const {\n personId,\n tenantId,\n organizationId,\n viewerUserId,\n userFeatures,\n sharedConversations,\n sharedChannelIds,\n maxThreads = DEFAULT_MAX_THREADS,\n maxMessagesPerThread = DEFAULT_MAX_MESSAGES_PER_THREAD,\n } = opts\n\n // \u2500\u2500 (1) Load the Person's email interactions (the Person\u2194email anchor) \u2500\u2500\n const interactionWhere: JsonRecord = {\n entity: personId,\n interactionType: 'email',\n deletedAt: null,\n tenantId,\n }\n if (organizationId) interactionWhere.organizationId = organizationId\n\n // Per-email visibility (v1: strict owner-only, no admin bypass) \u2014 the CRM\n // Person page applies the SAME rule as every other interactions read path via\n // `buildEmailVisibilityMikroFilter`, so the Emails tab and the `/interactions`\n // timeline can never disagree about who sees an email:\n // - `visibility = 'shared'` is visible to every user with CRM access to this\n // Person (lets a teammate pick up a handed-off thread),\n // - `visibility = 'private'` is visible ONLY to its author (the mailbox\n // owner) \u2014 never to teammates, not even an admin/superadmin (team\n // oversight is a deliberate v2 follow-up),\n // - legacy/unset rows (`visibility IS NULL`) stay visible so pre-existing\n // CRM history is never silently hidden.\n // Fail-closed: a null viewer (API-key caller) never matches the author arm, so\n // it only ever sees shared/legacy rows \u2014 never anyone's private email.\n // Merge the WHOLE fragment. Cherry-picking `.$or` here would silently discard\n // any other arm the predicate grows, which fails OPEN at a compile-clean call\n // site \u2014 the exact hazard the fragment contract now documents.\n Object.assign(\n interactionWhere,\n buildEmailVisibilityMikroFilter({\n currentUserId: viewerUserId,\n userFeatures,\n sharedConversations,\n sharedChannelIds,\n }),\n )\n\n // `customer_interaction.title`/`body` are encrypted at rest, so reads go\n // through `findWithDecryption` even though we only consume non-encrypted\n // columns here \u2014 this keeps the encrypted-entity contract intact.\n const dscope = { tenantId, organizationId: organizationId ?? null }\n const interactions = (await findWithDecryption(\n em,\n CustomerInteraction,\n interactionWhere as never,\n { orderBy: { occurredAt: 'desc', createdAt: 'desc' }, limit: maxThreads * 20 },\n dscope,\n )) as CustomerInteraction[]\n\n const linkIdByInteraction = new Map<string, { occurredAt: Date; authorUserId: string | null }>()\n const linkIds: string[] = []\n for (const interaction of interactions) {\n const linkId = interaction.externalMessageId\n if (!linkId || linkIdByInteraction.has(linkId)) continue\n linkIdByInteraction.set(linkId, {\n occurredAt: interaction.occurredAt ?? interaction.createdAt,\n authorUserId: interaction.authorUserId ?? null,\n })\n linkIds.push(linkId)\n }\n if (linkIds.length === 0) return []\n\n // \u2500\u2500 (2) Resolve MessageChannelLink rows (rich content + direction) \u2500\u2500\u2500\u2500\u2500\u2500\n const linkWhere: JsonRecord = { id: { $in: linkIds }, tenantId }\n if (organizationId) linkWhere.organizationId = organizationId\n const links = (await findWithDecryption(\n em,\n 'MessageChannelLink' as never,\n linkWhere as never,\n undefined,\n dscope,\n )) as JsonRecord[]\n\n // \u2500\u2500 (3) Resolve hub Message rows (the authoritative thread grouping) \u2500\u2500\u2500\u2500\n const messageIds = Array.from(\n new Set(\n links\n .map((link) => (typeof link.messageId === 'string' ? (link.messageId as string) : null))\n .filter((value): value is string => !!value),\n ),\n )\n const messageById = new Map<string, JsonRecord>()\n if (messageIds.length > 0) {\n const messageWhere: JsonRecord = { id: { $in: messageIds }, tenantId }\n if (organizationId) messageWhere.organizationId = organizationId\n const messages = (await findWithDecryption(\n em,\n 'Message' as never,\n messageWhere as never,\n undefined,\n dscope,\n )) as JsonRecord[]\n for (const message of messages) {\n if (typeof message.id === 'string') messageById.set(message.id, message)\n }\n }\n\n // \u2500\u2500 (3b) Resolve sender labels for colleagues' messages \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n //\n // Only for authors other than the viewer: their own mail renders as \"You\" and\n // needs no lookup. A shared conversation is exactly the case where a message\n // the viewer did not write shows up in their thread list, so without this the\n // UI would have to fall back on direction and misattribute it to the reader.\n const foreignAuthorIds = Array.from(\n new Set(\n Array.from(linkIdByInteraction.values())\n .map((entry) => entry.authorUserId)\n .filter((id): id is string => !!id && id !== viewerUserId),\n ),\n )\n const authorNames = foreignAuthorIds.length\n ? await resolveUserNames(em, tenantId, organizationId, foreignAuthorIds)\n : new Map<string, string>()\n\n // \u2500\u2500 (4) Build per-message DTOs grouped by thread \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 const threadsByKey = new Map<string, PersonEmailThread>()\n\n for (const link of links) {\n const linkId = typeof link.id === 'string' ? (link.id as string) : null\n if (!linkId) continue\n const direction: EmailThreadDirection = link.direction === 'outbound' ? 'outbound' : 'inbound'\n // `authorUserId` on the interaction is the MAILBOX OWNER, which on an\n // inbound message is the recipient, not the sender \u2014 so authorship is an\n // outbound-only notion. Inbound senders are named by the `from` header.\n const authorUserId = direction === 'outbound' ? linkIdByInteraction.get(linkId)?.authorUserId ?? null : null\n const authoredByViewer = !!viewerUserId && !!authorUserId && authorUserId === viewerUserId\n const providerKey = typeof link.providerKey === 'string' ? (link.providerKey as string) : null\n const payload = (link.channelPayload ?? null) as JsonRecord | null\n const meta = (link.channelMetadata ?? null) as JsonRecord | null\n const messageId = typeof link.messageId === 'string' ? (link.messageId as string) : null\n const message = messageId ? messageById.get(messageId) ?? null : null\n\n // Outbound addresses live in channelMetadata; inbound in channelPayload.\n // Prefer the direction-appropriate source, fall back to the other.\n const primary = direction === 'outbound' ? meta : payload\n const secondary = direction === 'outbound' ? payload : meta\n const fromList = extractAddresses(primary?.from ?? secondary?.from)\n const toList = extractAddresses(primary?.to ?? secondary?.to)\n const ccList = extractAddresses(primary?.cc ?? secondary?.cc)\n\n const subject = firstString(\n primary?.subject,\n secondary?.subject,\n typeof message?.subject === 'string' ? message.subject : null,\n )\n const bodyText = firstString(\n direction === 'outbound' ? meta?.bodyText : payload?.text,\n direction === 'outbound' ? payload?.text : meta?.bodyText,\n typeof message?.body === 'string' ? message.body : null,\n )\n\n const sentAtRaw =\n (typeof message?.sentAt === 'string' || message?.sentAt instanceof Date\n ? message.sentAt\n : null) ??\n (link.createdAt instanceof Date || typeof link.createdAt === 'string' ? link.createdAt : null) ??\n linkIdByInteraction.get(linkId)?.occurredAt ??\n new Date()\n const sentAt = (sentAtRaw instanceof Date ? sentAtRaw : new Date(sentAtRaw)).toISOString()\n\n const threadKey =\n (typeof message?.threadId === 'string' && message.threadId ? message.threadId : null) ??\n (messageId ? `message:${messageId}` : `link:${linkId}`)\n\n const dto: PersonEmailMessage = {\n id: linkId,\n messageId,\n rfcMessageId: firstString(primary?.messageId, secondary?.messageId),\n references: toStringArray(primary?.references, secondary?.references),\n direction,\n fromName: fromList[0]?.name ?? null,\n fromEmail: fromList[0]?.email ?? null,\n authoredByViewer,\n authorName: authoredByViewer ? null : authorUserId ? authorNames.get(authorUserId) ?? null : null,\n to: toList.map((a) => a.email),\n cc: ccList.map((a) => a.email),\n subject,\n bodyText,\n sentAt,\n providerKey,\n }\n\n const existing = threadsByKey.get(threadKey)\n if (existing) {\n existing.messages.push(dto)\n } else {\n threadsByKey.set(threadKey, {\n threadKey,\n subject,\n preview: null,\n participants: [],\n lastMessageAt: sentAt,\n messageCount: 0,\n providerKey,\n lastDirection: direction,\n messages: [dto],\n })\n }\n }\n\n // \u2500\u2500 (5) Finalize thread summaries \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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 const threads: PersonEmailThread[] = []\n for (const thread of threadsByKey.values()) {\n thread.messages.sort((a, b) => a.sentAt.localeCompare(b.sentAt))\n if (thread.messages.length > maxMessagesPerThread) {\n thread.messages = thread.messages.slice(thread.messages.length - maxMessagesPerThread)\n }\n const last = thread.messages[thread.messages.length - 1]\n const firstWithSubject = thread.messages.find((m) => m.subject)\n const participantSet = new Set<string>()\n for (const message of thread.messages) {\n // External counterpart = the \"from\" for inbound, the \"to\" for outbound.\n if (message.direction === 'inbound' && message.fromEmail) participantSet.add(message.fromEmail)\n if (message.direction === 'outbound') message.to.forEach((email) => participantSet.add(email))\n }\n thread.subject = firstWithSubject?.subject ?? thread.subject\n thread.preview = truncate(last?.bodyText ?? null)\n thread.participants = Array.from(participantSet)\n thread.lastMessageAt = last?.sentAt ?? thread.lastMessageAt\n thread.lastDirection = last?.direction ?? thread.lastDirection\n thread.providerKey = last?.providerKey ?? thread.providerKey\n thread.messageCount = thread.messages.length\n threads.push(thread)\n }\n\n threads.sort((a, b) => b.lastMessageAt.localeCompare(a.lastMessageAt))\n return threads.slice(0, maxThreads)\n}\n"],
|
|
5
|
-
"mappings": "AACA,SAAS,0BAA0B;AACnC,SAAS,2BAA2B;AACpC,SAAS,wBAAwB;AACjC,SAAS,uCAAuC;AA4EhD,MAAM,sBAAsB;AAC5B,MAAM,kCAAkC;AACxC,MAA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,eAAe,IAAI,KAAK,CAAC;AAAA,IAC/F;AACA,WAAO,UAAU,kBAAkB,WAAW,OAAO;AACrD,WAAO,UAAU,SAAS,MAAM,YAAY,IAAI;AAChD,WAAO,eAAe,MAAM,KAAK,cAAc;AAC/C,WAAO,gBAAgB,MAAM,UAAU,OAAO;AAC9C,WAAO,gBAAgB,MAAM,aAAa,OAAO;AACjD,WAAO,cAAc,MAAM,eAAe,OAAO;AACjD,WAAO,eAAe,OAAO,SAAS;AACtC,YAAQ,KAAK,MAAM;AAAA,EACrB;AAEA,UAAQ,KAAK,CAAC,GAAG,MAAM,EAAE,cAAc,cAAc,EAAE,aAAa,CAAC;AACrE,SAAO,QAAQ,MAAM,GAAG,UAAU;AACpC;",
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { CustomerInteraction } from '../data/entities'\nimport { resolveUserNames } from './userNames'\nimport { buildEmailVisibilityMikroFilter } from './visibilityFilter'\nimport type { ConversationShareGrant } from './conversationShares'\n\n/**\n * Read model that turns a Person's email `CustomerInteraction` rows into\n * Gmail-style threads for the CRM Person page.\n *\n * The Person\u2194email anchor lives only on `CustomerInteraction`\n * (`interactionType='email'`, `externalMessageId` \u2192 `MessageChannelLink.id`).\n * The thread grouping key and the rich per-message content (From/To/Cc, body,\n * direction) live in the communication_channels hub. We read the hub entities\n * by their string class names \u2014 the same cross-module pattern used by\n * `link-channel-message-handler.ts` \u2014 so the customers module never imports the\n * hub's entity classes (root AGENTS.md: no direct ORM relationships between\n * modules).\n */\n\nexport type EmailThreadDirection = 'inbound' | 'outbound'\n\nexport type PersonEmailMessage = {\n id: string\n /** Open Mercato `messages.message` id \u2014 used as `parentMessageId` when replying so the reply joins this thread. */\n messageId: string | null\n /** RFC2822 Message-ID of this email \u2014 used as `In-Reply-To` on a reply. */\n rfcMessageId: string | null\n /** RFC2822 References chain for this email. */\n references: string[]\n direction: EmailThreadDirection\n fromName: string | null\n fromEmail: string | null\n /**\n * True when the viewer is the author of this message. Outbound email carries\n * no `from` header in `channelMetadata`, so the sender label cannot be derived\n * from the addresses \u2014 and since conversation/channel sharing lets a teammate\n * read someone else's outbound mail, direction alone is not the author either.\n */\n authoredByViewer: boolean\n /** Display label of the sending colleague; null for the viewer's own mail and for inbound. */\n authorName: string | null\n to: string[]\n cc: string[]\n subject: string | null\n bodyText: string | null\n sentAt: string\n providerKey: string | null\n}\n\nexport type PersonEmailThread = {\n threadKey: string\n subject: string | null\n preview: string | null\n participants: string[]\n lastMessageAt: string\n messageCount: number\n providerKey: string | null\n lastDirection: EmailThreadDirection\n messages: PersonEmailMessage[]\n}\n\nexport type BuildPersonEmailThreadsOptions = {\n personId: string\n tenantId: string\n organizationId: string | null\n viewerUserId: string | null\n userFeatures: string[] | null | undefined\n /**\n * Conversation shares that widen this viewer's access. Optional and fail-closed:\n * omitting it yields the strict owner-only view.\n */\n sharedConversations?: ConversationShareGrant[]\n /** Channels marked as shared team mailboxes; optional and fail-closed. */\n sharedChannelIds?: string[]\n maxThreads?: number\n maxMessagesPerThread?: number\n}\n\nconst DEFAULT_MAX_THREADS = 50\nconst DEFAULT_MAX_MESSAGES_PER_THREAD = 200\nconst PREVIEW_LENGTH = 140\n\ntype JsonRecord = Record<string, unknown>\n\n/** Extracts `{ email, name }[]` from the many shapes a channel address field can take. */\nfunction extractAddresses(value: unknown): Array<{ email: string; name: string | null }> {\n const out: Array<{ email: string; name: string | null }> = []\n const pushOne = (item: unknown): void => {\n if (typeof item === 'string') {\n const trimmed = item.trim()\n if (trimmed) out.push({ email: trimmed, name: null })\n return\n }\n if (item && typeof item === 'object') {\n const rec = item as JsonRecord\n const address = typeof rec.address === 'string' ? rec.address.trim() : null\n const name = typeof rec.name === 'string' && rec.name.trim() ? rec.name.trim() : null\n if (address) out.push({ email: address, name })\n }\n }\n if (Array.isArray(value)) {\n for (const item of value) pushOne(item)\n } else {\n pushOne(value)\n }\n return out\n}\n\nfunction firstString(...values: unknown[]): string | null {\n for (const value of values) {\n if (typeof value === 'string' && value.trim().length > 0) return value\n }\n return null\n}\n\nfunction toStringArray(...values: unknown[]): string[] {\n for (const value of values) {\n if (Array.isArray(value)) {\n const strings = value.filter((item): item is string => typeof item === 'string' && item.trim().length > 0)\n if (strings.length > 0) return strings\n }\n }\n return []\n}\n\nfunction truncate(value: string | null): string | null {\n if (!value) return value\n const collapsed = value.replace(/\\s+/g, ' ').trim()\n if (collapsed.length <= PREVIEW_LENGTH) return collapsed\n return `${collapsed.slice(0, PREVIEW_LENGTH - 1)}\u2026`\n}\n\n/**\n * Builds the per-Person email-thread read model. Pure data assembly \u2014 callers\n * are responsible for auth and scoping (tenantId/organizationId required).\n */\nexport async function buildPersonEmailThreads(\n em: EntityManager,\n opts: BuildPersonEmailThreadsOptions,\n): Promise<PersonEmailThread[]> {\n const {\n personId,\n tenantId,\n organizationId,\n viewerUserId,\n userFeatures,\n sharedConversations,\n sharedChannelIds,\n maxThreads = DEFAULT_MAX_THREADS,\n maxMessagesPerThread = DEFAULT_MAX_MESSAGES_PER_THREAD,\n } = opts\n\n // \u2500\u2500 (1) Load the Person's email interactions (the Person\u2194email anchor) \u2500\u2500\n const interactionWhere: JsonRecord = {\n entity: personId,\n interactionType: 'email',\n deletedAt: null,\n tenantId,\n }\n if (organizationId) interactionWhere.organizationId = organizationId\n\n // Per-email visibility (v1: strict owner-only, no admin bypass) \u2014 the CRM\n // Person page applies the SAME rule as every other interactions read path via\n // `buildEmailVisibilityMikroFilter`, so the Emails tab and the `/interactions`\n // timeline can never disagree about who sees an email:\n // - `visibility = 'shared'` is visible to every user with CRM access to this\n // Person (lets a teammate pick up a handed-off thread),\n // - `visibility = 'private'` is visible ONLY to its author (the mailbox\n // owner) \u2014 never to teammates, not even an admin/superadmin (team\n // oversight is a deliberate v2 follow-up),\n // - legacy/unset rows (`visibility IS NULL`) stay visible so pre-existing\n // CRM history is never silently hidden.\n // Fail-closed: a null viewer (API-key caller) never matches the author arm, so\n // it only ever sees shared/legacy rows \u2014 never anyone's private email.\n // Merge the WHOLE fragment. Cherry-picking `.$or` here would silently discard\n // any other arm the predicate grows, which fails OPEN at a compile-clean call\n // site \u2014 the exact hazard the fragment contract now documents.\n Object.assign(\n interactionWhere,\n buildEmailVisibilityMikroFilter({\n currentUserId: viewerUserId,\n userFeatures,\n sharedConversations,\n sharedChannelIds,\n }),\n )\n\n // `customer_interaction.title`/`body` are encrypted at rest, so reads go\n // through `findWithDecryption` even though we only consume non-encrypted\n // columns here \u2014 this keeps the encrypted-entity contract intact.\n const dscope = { tenantId, organizationId: organizationId ?? null }\n const interactions = (await findWithDecryption(\n em,\n CustomerInteraction,\n interactionWhere as never,\n { orderBy: { occurredAt: 'desc', createdAt: 'desc' }, limit: maxThreads * 20 },\n dscope,\n )) as CustomerInteraction[]\n\n const linkIdByInteraction = new Map<string, { occurredAt: Date; authorUserId: string | null }>()\n const linkIds: string[] = []\n for (const interaction of interactions) {\n const linkId = interaction.externalMessageId\n if (!linkId || linkIdByInteraction.has(linkId)) continue\n linkIdByInteraction.set(linkId, {\n occurredAt: interaction.occurredAt ?? interaction.createdAt,\n authorUserId: interaction.authorUserId ?? null,\n })\n linkIds.push(linkId)\n }\n if (linkIds.length === 0) return []\n\n // \u2500\u2500 (2) Resolve MessageChannelLink rows (rich content + direction) \u2500\u2500\u2500\u2500\u2500\u2500\n const linkWhere: JsonRecord = { id: { $in: linkIds }, tenantId }\n if (organizationId) linkWhere.organizationId = organizationId\n const links = (await findWithDecryption(\n em,\n 'MessageChannelLink' as never,\n linkWhere as never,\n undefined,\n dscope,\n )) as JsonRecord[]\n\n // \u2500\u2500 (3) Resolve hub Message rows (the authoritative thread grouping) \u2500\u2500\u2500\u2500\n const messageIds = Array.from(\n new Set(\n links\n .map((link) => (typeof link.messageId === 'string' ? (link.messageId as string) : null))\n .filter((value): value is string => !!value),\n ),\n )\n const messageById = new Map<string, JsonRecord>()\n if (messageIds.length > 0) {\n const messageWhere: JsonRecord = { id: { $in: messageIds }, tenantId }\n if (organizationId) messageWhere.organizationId = organizationId\n const messages = (await findWithDecryption(\n em,\n 'Message' as never,\n messageWhere as never,\n undefined,\n dscope,\n )) as JsonRecord[]\n for (const message of messages) {\n if (typeof message.id === 'string') messageById.set(message.id, message)\n }\n }\n\n // \u2500\u2500 (3b) Resolve sender labels for colleagues' messages \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n //\n // Only for authors other than the viewer: their own mail renders as \"You\" and\n // needs no lookup. A shared conversation is exactly the case where a message\n // the viewer did not write shows up in their thread list, so without this the\n // UI would have to fall back on direction and misattribute it to the reader.\n const foreignAuthorIds = Array.from(\n new Set(\n Array.from(linkIdByInteraction.values())\n .map((entry) => entry.authorUserId)\n .filter((id): id is string => !!id && id !== viewerUserId),\n ),\n )\n const authorNames = foreignAuthorIds.length\n ? await resolveUserNames(em, tenantId, organizationId, foreignAuthorIds)\n : new Map<string, string>()\n\n // \u2500\u2500 (4) Build per-message DTOs grouped by thread \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 const threadsByKey = new Map<string, PersonEmailThread>()\n\n for (const link of links) {\n const linkId = typeof link.id === 'string' ? (link.id as string) : null\n if (!linkId) continue\n const direction: EmailThreadDirection = link.direction === 'outbound' ? 'outbound' : 'inbound'\n // `authorUserId` on the interaction is the MAILBOX OWNER, which on an\n // inbound message is the recipient, not the sender \u2014 so authorship is an\n // outbound-only notion. Inbound senders are named by the `from` header.\n const authorUserId = direction === 'outbound' ? linkIdByInteraction.get(linkId)?.authorUserId ?? null : null\n const authoredByViewer = !!viewerUserId && !!authorUserId && authorUserId === viewerUserId\n const providerKey = typeof link.providerKey === 'string' ? (link.providerKey as string) : null\n const payload = (link.channelPayload ?? null) as JsonRecord | null\n const meta = (link.channelMetadata ?? null) as JsonRecord | null\n const messageId = typeof link.messageId === 'string' ? (link.messageId as string) : null\n const message = messageId ? messageById.get(messageId) ?? null : null\n\n // Outbound addresses live in channelMetadata; inbound in channelPayload.\n // Prefer the direction-appropriate source, fall back to the other.\n const primary = direction === 'outbound' ? meta : payload\n const secondary = direction === 'outbound' ? payload : meta\n const fromList = extractAddresses(primary?.from ?? secondary?.from)\n const toList = extractAddresses(primary?.to ?? secondary?.to)\n const ccList = extractAddresses(primary?.cc ?? secondary?.cc)\n\n const subject = firstString(\n primary?.subject,\n secondary?.subject,\n typeof message?.subject === 'string' ? message.subject : null,\n )\n const bodyText = firstString(\n direction === 'outbound' ? meta?.bodyText : payload?.text,\n direction === 'outbound' ? payload?.text : meta?.bodyText,\n typeof message?.body === 'string' ? message.body : null,\n )\n\n const sentAtRaw =\n (typeof message?.sentAt === 'string' || message?.sentAt instanceof Date\n ? message.sentAt\n : null) ??\n (link.createdAt instanceof Date || typeof link.createdAt === 'string' ? link.createdAt : null) ??\n linkIdByInteraction.get(linkId)?.occurredAt ??\n new Date()\n const sentAt = (sentAtRaw instanceof Date ? sentAtRaw : new Date(sentAtRaw)).toISOString()\n\n const threadKey =\n (typeof message?.threadId === 'string' && message.threadId ? message.threadId : null) ??\n (messageId ? `message:${messageId}` : `link:${linkId}`)\n\n const dto: PersonEmailMessage = {\n id: linkId,\n messageId,\n rfcMessageId: firstString(primary?.messageId, secondary?.messageId),\n references: toStringArray(primary?.references, secondary?.references),\n direction,\n fromName: fromList[0]?.name ?? null,\n fromEmail: fromList[0]?.email ?? null,\n authoredByViewer,\n authorName: authoredByViewer ? null : authorUserId ? authorNames.get(authorUserId) ?? null : null,\n to: toList.map((a) => a.email),\n cc: ccList.map((a) => a.email),\n subject,\n bodyText,\n sentAt,\n providerKey,\n }\n\n const existing = threadsByKey.get(threadKey)\n if (existing) {\n existing.messages.push(dto)\n } else {\n threadsByKey.set(threadKey, {\n threadKey,\n subject,\n preview: null,\n participants: [],\n lastMessageAt: sentAt,\n messageCount: 0,\n providerKey,\n lastDirection: direction,\n messages: [dto],\n })\n }\n }\n\n // \u2500\u2500 (5) Finalize thread summaries \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\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 const threads: PersonEmailThread[] = []\n for (const thread of threadsByKey.values()) {\n thread.messages.sort((a, b) => a.sentAt.localeCompare(b.sentAt))\n if (thread.messages.length > maxMessagesPerThread) {\n thread.messages = thread.messages.slice(thread.messages.length - maxMessagesPerThread)\n }\n const last = thread.messages[thread.messages.length - 1]\n const firstWithSubject = thread.messages.find((m) => m.subject)\n const participantSet = new Set<string>()\n for (const message of thread.messages) {\n // External counterpart = the \"from\" for inbound, the \"to\" for outbound.\n if (message.direction === 'inbound' && message.fromEmail) participantSet.add(message.fromEmail)\n if (message.direction === 'outbound') message.to.forEach((email) => participantSet.add(email))\n }\n thread.subject = firstWithSubject?.subject ?? thread.subject\n thread.preview = truncate(last?.bodyText ?? null)\n thread.participants = Array.from(participantSet)\n thread.lastMessageAt = last?.sentAt ?? thread.lastMessageAt\n thread.lastDirection = last?.direction ?? thread.lastDirection\n thread.providerKey = last?.providerKey ?? thread.providerKey\n thread.messageCount = thread.messages.length\n threads.push(thread)\n }\n\n threads.sort((a, b) => b.lastMessageAt.localeCompare(a.lastMessageAt))\n return threads.slice(0, maxThreads)\n}\n\nexport type PersonEmailMessageAccessOptions = Pick<\n BuildPersonEmailThreadsOptions,\n 'personId' | 'tenantId' | 'organizationId' | 'viewerUserId' | 'userFeatures' | 'sharedConversations' | 'sharedChannelIds'\n> & {\n /** Open Mercato `messages.message` id the caller wants to reply to. */\n messageId: string\n}\n\n/**\n * Whether `messageId` is on this Person's email history as the viewer sees it \u2014\n * i.e. whether {@link buildPersonEmailThreads} would show it to them.\n *\n * Walks the same anchor (email `CustomerInteraction` \u2192 `MessageChannelLink` \u2192\n * message) with the same scope and the same visibility predicate, so a reply\n * from the Person page can only name a parent the Emails tab could have shown:\n * the viewer's own mail, shared or legacy mail, a conversation shared for THIS\n * Person, or a shared team mailbox. Callers remain responsible for resolving the\n * Person in scope first.\n */\nexport async function isMessageOnPersonEmailHistory(\n em: EntityManager,\n opts: PersonEmailMessageAccessOptions,\n): Promise<boolean> {\n const { personId, tenantId, organizationId, messageId } = opts\n const dscope = { tenantId, organizationId: organizationId ?? null }\n\n const linkWhere: JsonRecord = { messageId, tenantId }\n if (organizationId) linkWhere.organizationId = organizationId\n const links = (await findWithDecryption(\n em,\n 'MessageChannelLink' as never,\n linkWhere as never,\n undefined,\n dscope,\n )) as JsonRecord[]\n const linkIds = links\n .map((link) => (typeof link.id === 'string' ? (link.id as string) : null))\n .filter((value): value is string => !!value)\n if (linkIds.length === 0) return false\n\n const interactionWhere: JsonRecord = {\n entity: personId,\n interactionType: 'email',\n deletedAt: null,\n tenantId,\n externalMessageId: { $in: linkIds },\n }\n if (organizationId) interactionWhere.organizationId = organizationId\n Object.assign(\n interactionWhere,\n buildEmailVisibilityMikroFilter({\n currentUserId: opts.viewerUserId,\n userFeatures: opts.userFeatures,\n sharedConversations: opts.sharedConversations,\n sharedChannelIds: opts.sharedChannelIds,\n }),\n )\n const visible = await em.count(CustomerInteraction, interactionWhere as never)\n return visible > 0\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,0BAA0B;AACnC,SAAS,2BAA2B;AACpC,SAAS,wBAAwB;AACjC,SAAS,uCAAuC;AA4EhD,MAAM,sBAAsB;AAC5B,MAAM,kCAAkC;AACxC,MAAM,iBAAiB;AAKvB,SAAS,iBAAiB,OAA+D;AACvF,QAAM,MAAqD,CAAC;AAC5D,QAAM,UAAU,CAAC,SAAwB;AACvC,QAAI,OAAO,SAAS,UAAU;AAC5B,YAAM,UAAU,KAAK,KAAK;AAC1B,UAAI,QAAS,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TypeOrDefault } from "../../lib/message-types-registry.js";
|
|
|
13
13
|
import { attachOperationMetadataHeader } from "../../lib/operationMetadata.js";
|
|
14
14
|
import {
|
|
15
15
|
canPostToChannelThread,
|
|
16
|
-
hasChannelThreadReadAccess,
|
|
17
16
|
hasOrganizationAccess,
|
|
18
|
-
resolveMessageContext
|
|
17
|
+
resolveMessageContext,
|
|
18
|
+
resolveMessageReadAccess
|
|
19
19
|
} from "../../lib/routeHelpers.js";
|
|
20
20
|
import { resolveUserFeatures, runMessageMutationGuardAfterSuccess, runMessageMutationGuards } from "../guards.js";
|
|
21
21
|
import {
|
|
@@ -67,14 +67,8 @@ async function GET(req, { params }) {
|
|
|
67
67
|
if (!hasOrganizationAccess(scope.organizationId, message.organizationId)) {
|
|
68
68
|
return Response.json({ error: "Access denied" }, { status: 403 });
|
|
69
69
|
}
|
|
70
|
-
const recipient = await
|
|
71
|
-
messageId: params.id,
|
|
72
|
-
recipientUserId: scope.userId,
|
|
73
|
-
deletedAt: null
|
|
74
|
-
});
|
|
75
|
-
const isSender = message.senderUserId === scope.userId;
|
|
70
|
+
const { recipient, isSender, hasChannelThreadAccess } = await resolveMessageReadAccess(ctx, scope, message);
|
|
76
71
|
const isRecipient = Boolean(recipient);
|
|
77
|
-
const hasChannelThreadAccess = await hasChannelThreadReadAccess(ctx, scope, message);
|
|
78
72
|
if (!isSender && !isRecipient && !hasChannelThreadAccess) {
|
|
79
73
|
return Response.json({ error: "Access denied" }, { status: 403 });
|
|
80
74
|
}
|