@open-mercato/core 0.6.7-develop.6774.1.d836fe3135 → 0.6.7-develop.6775.1.c2313bb8a3
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,14 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
1
2
|
import { z } from "zod";
|
|
2
3
|
import { sql } from "kysely";
|
|
4
|
+
import { runWithCacheTenant } from "@open-mercato/cache";
|
|
5
|
+
import {
|
|
6
|
+
buildCollectionTags,
|
|
7
|
+
debugCrudCache,
|
|
8
|
+
isCrudCacheEnabled,
|
|
9
|
+
normalizeTagSegment,
|
|
10
|
+
resolveCrudCache
|
|
11
|
+
} from "@open-mercato/shared/lib/crud/cache";
|
|
3
12
|
import { findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
4
13
|
import { lookupHashCandidates } from "@open-mercato/shared/lib/encryption/aes";
|
|
5
14
|
import { User } from "../../auth/data/entities.js";
|
|
@@ -20,19 +29,62 @@ import {
|
|
|
20
29
|
messageListItemSchema
|
|
21
30
|
} from "./openapi.js";
|
|
22
31
|
const NO_MATCH_ID = "00000000-0000-0000-0000-000000000000";
|
|
32
|
+
const MESSAGE_LIST_CACHE_TTL_MS = 3e4;
|
|
33
|
+
const MESSAGE_LIST_RESOURCE = "messages.message";
|
|
23
34
|
function getDb(em) {
|
|
24
35
|
return em.getKysely();
|
|
25
36
|
}
|
|
37
|
+
function normalizeCacheFilterValue(value) {
|
|
38
|
+
if (value === void 0) return null;
|
|
39
|
+
if (value instanceof Date) return value.toISOString();
|
|
40
|
+
if (Array.isArray(value)) return value.map(normalizeCacheFilterValue);
|
|
41
|
+
if (value && typeof value === "object") {
|
|
42
|
+
return Object.entries(value).sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey)).map(([key, entryValue]) => [key, normalizeCacheFilterValue(entryValue)]);
|
|
43
|
+
}
|
|
44
|
+
return value;
|
|
45
|
+
}
|
|
46
|
+
function buildMessageListFilterSignature(input) {
|
|
47
|
+
const canonicalInput = Object.entries(input).sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey)).map(([key, value]) => [key, normalizeCacheFilterValue(value)]);
|
|
48
|
+
return createHash("sha256").update(JSON.stringify(canonicalInput)).digest("hex").slice(0, 32);
|
|
49
|
+
}
|
|
50
|
+
function buildMessageListCacheKey(scope, input) {
|
|
51
|
+
return [
|
|
52
|
+
"messages:list:v1",
|
|
53
|
+
`tenant:${normalizeTagSegment(scope.tenantId)}`,
|
|
54
|
+
`org:${normalizeTagSegment(scope.organizationId)}`,
|
|
55
|
+
`user:${normalizeTagSegment(scope.userId)}`,
|
|
56
|
+
`filters:${buildMessageListFilterSignature(input)}`
|
|
57
|
+
].join("|");
|
|
58
|
+
}
|
|
59
|
+
function isMessageListPayload(value) {
|
|
60
|
+
if (!value || typeof value !== "object") return false;
|
|
61
|
+
const payload = value;
|
|
62
|
+
return Array.isArray(payload.items) && typeof payload.page === "number" && typeof payload.pageSize === "number" && typeof payload.total === "number" && typeof payload.totalPages === "number";
|
|
63
|
+
}
|
|
26
64
|
const metadata = {
|
|
27
65
|
GET: { requireAuth: true },
|
|
28
66
|
POST: { requireAuth: true, requireFeatures: ["messages.compose"] }
|
|
29
67
|
};
|
|
30
68
|
async function GET(req) {
|
|
31
69
|
const { ctx, scope } = await resolveMessageContext(req);
|
|
32
|
-
const em = ctx.container.resolve("em");
|
|
33
70
|
const url = new URL(req.url);
|
|
34
71
|
const params = Object.fromEntries(url.searchParams);
|
|
35
72
|
const input = listMessagesSchema.parse(params);
|
|
73
|
+
const cache = isCrudCacheEnabled() ? resolveCrudCache(ctx.container) : null;
|
|
74
|
+
const cacheKey = cache ? buildMessageListCacheKey(scope, input) : null;
|
|
75
|
+
if (cache && cacheKey) {
|
|
76
|
+
try {
|
|
77
|
+
const cached = await runWithCacheTenant(scope.tenantId, () => cache.get(cacheKey));
|
|
78
|
+
if (isMessageListPayload(cached)) {
|
|
79
|
+
return Response.json(cached);
|
|
80
|
+
}
|
|
81
|
+
} catch (error) {
|
|
82
|
+
debugCrudCache("messages-list-cache-read-failed", {
|
|
83
|
+
error: error instanceof Error ? error.message : String(error)
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
const em = ctx.container.resolve("em");
|
|
36
88
|
const db = getDb(em);
|
|
37
89
|
const searchIds = input.search ? await findMessageIdsBySearchTokens({
|
|
38
90
|
em,
|
|
@@ -165,7 +217,7 @@ async function GET(req) {
|
|
|
165
217
|
const name = typeof user.name === "string" && user.name.trim().length ? user.name.trim() : null;
|
|
166
218
|
senderMetaById.set(user.id, { name, email: user.email ?? null });
|
|
167
219
|
});
|
|
168
|
-
|
|
220
|
+
const payload = {
|
|
169
221
|
items: typedRows.map((row) => {
|
|
170
222
|
const message = messagesById.get(row.id);
|
|
171
223
|
if (!message) return null;
|
|
@@ -205,7 +257,27 @@ async function GET(req) {
|
|
|
205
257
|
pageSize: input.pageSize,
|
|
206
258
|
total,
|
|
207
259
|
totalPages: Math.ceil(total / input.pageSize)
|
|
208
|
-
}
|
|
260
|
+
};
|
|
261
|
+
if (cache && cacheKey) {
|
|
262
|
+
try {
|
|
263
|
+
await runWithCacheTenant(
|
|
264
|
+
scope.tenantId,
|
|
265
|
+
() => cache.set(cacheKey, payload, {
|
|
266
|
+
ttl: MESSAGE_LIST_CACHE_TTL_MS,
|
|
267
|
+
tags: buildCollectionTags(
|
|
268
|
+
MESSAGE_LIST_RESOURCE,
|
|
269
|
+
scope.tenantId,
|
|
270
|
+
[scope.organizationId]
|
|
271
|
+
)
|
|
272
|
+
})
|
|
273
|
+
);
|
|
274
|
+
} catch (error) {
|
|
275
|
+
debugCrudCache("messages-list-cache-write-failed", {
|
|
276
|
+
error: error instanceof Error ? error.message : String(error)
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return Response.json(payload);
|
|
209
281
|
}
|
|
210
282
|
async function POST(req) {
|
|
211
283
|
const { ctx, scope } = await resolveMessageContext(req);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/messages/api/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { type Kysely, sql } from 'kysely'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands/command-bus'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi/types'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { lookupHashCandidates } from '@open-mercato/shared/lib/encryption/aes'\nimport { User } from '../../auth/data/entities'\nimport { Message, MessageObject } from '../data/entities'\nimport { composeMessageSchema, listMessagesSchema } from '../data/validators'\nimport { MESSAGE_ATTACHMENT_ENTITY_ID } from '../lib/constants'\nimport { getMessageType } from '../lib/message-types-registry'\nimport { validateMessageObjectsForType } from '../lib/object-validation'\nimport { attachOperationMetadataHeader } from '../lib/operationMetadata'\nimport { canUseMessageEmailFeature, resolveMessageContext } from '../lib/routeHelpers'\nimport { applyMessageParticipantScope } from '../lib/participantScope'\nimport { resolveUserFeatures, runMessageMutationGuardAfterSuccess, runMessageMutationGuards } from './guards'\nimport { findMessageIdsBySearchTokens } from '../lib/searchLookup'\nimport { MessageCommandExecuteResult } from '../commands/shared'\nimport {\n composeMessageSchema as composeSchema,\n composeResponseSchema,\n listMessagesSchema as listSchema,\n messageListItemSchema,\n} from './openapi'\n\ntype MessageCommandExecuteResultWithThreadId = MessageCommandExecuteResult & {\n threadId: string\n}\n\nconst NO_MATCH_ID = '00000000-0000-0000-0000-000000000000'\n\nfunction getDb(em: EntityManager): Kysely<any> {\n return em.getKysely<any>()\n}\n\ntype MessageListScopeRow = {\n id: string\n sender_user_id: string\n is_draft: boolean\n recipient_status: string | null\n read_at: string | null\n}\n\ntype AttachmentCountRow = {\n record_id: string\n count: string | number\n}\n\ntype RecipientCountRow = {\n message_id: string\n count: string | number\n}\n\nexport const metadata = {\n GET: { requireAuth: true },\n POST: { requireAuth: true, requireFeatures: ['messages.compose'] },\n}\n\nexport async function GET(req: Request) {\n const { ctx, scope } = await resolveMessageContext(req)\n const em = ctx.container.resolve('em') as EntityManager\n const url = new URL(req.url)\n const params = Object.fromEntries(url.searchParams)\n const input = listMessagesSchema.parse(params)\n const db = getDb(em) as any\n\n const searchIds = input.search\n ? await findMessageIdsBySearchTokens({\n em,\n query: input.search,\n tenantId: scope.tenantId ?? null,\n organizationId: scope.organizationId,\n })\n : undefined\n\n const buildBaseQuery = () => {\n let q: any = db\n .selectFrom('messages as m')\n .where('m.tenant_id', '=', scope.tenantId)\n .where('m.deleted_at', 'is', null)\n\n if (scope.organizationId) {\n q = q.where('m.organization_id', '=', scope.organizationId)\n } else {\n q = q.where('m.organization_id', 'is', null)\n }\n\n const joinRecipient = () => {\n q = q.leftJoin('message_recipients as r', (jb: any) => jb\n .onRef('m.id', '=', 'r.message_id')\n .on('r.recipient_user_id', '=', scope.userId))\n }\n\n switch (input.folder) {\n case 'inbox':\n joinRecipient()\n q = q\n .where('r.message_id', 'is not', null)\n .where('r.deleted_at', 'is', null)\n .where('r.archived_at', 'is', null)\n .where('m.is_draft', '=', false)\n break\n case 'archived':\n joinRecipient()\n q = q\n .where('r.message_id', 'is not', null)\n .where('r.deleted_at', 'is', null)\n .where('r.archived_at', 'is not', null)\n break\n case 'sent':\n q = q\n .where('m.sender_user_id', '=', scope.userId)\n .where('m.is_draft', '=', false)\n joinRecipient()\n break\n case 'drafts':\n q = q\n .where('m.sender_user_id', '=', scope.userId)\n .where('m.is_draft', '=', true)\n joinRecipient()\n break\n case 'all':\n // Sender-OR-recipient participant scope shared with the\n // communication_channels message enricher \u2014 see participantScope.ts (#4133).\n q = applyMessageParticipantScope(q, scope.userId)\n break\n default: {\n const unsupportedFolder: never = input.folder\n throw new Error(`Unsupported folder: ${String(unsupportedFolder)}`)\n }\n }\n\n if (input.status) q = q.where('r.status', '=', input.status)\n if (input.type) q = q.where('m.type', '=', input.type)\n if (input.visibility) q = q.where('m.visibility', '=', input.visibility)\n if (input.sourceEntityType) q = q.where('m.source_entity_type', '=', input.sourceEntityType)\n if (input.sourceEntityId) q = q.where('m.source_entity_id', '=', input.sourceEntityId)\n if (input.externalEmail) q = q.where('m.external_email_hash', 'in', lookupHashCandidates(input.externalEmail))\n if (input.senderId) q = q.where('m.sender_user_id', '=', input.senderId)\n\n if (input.search) {\n if (!searchIds || searchIds.length === 0) {\n q = q.where('m.id', '=', NO_MATCH_ID)\n } else {\n q = q.where('m.id', 'in', searchIds)\n }\n }\n\n if (input.since) q = q.where('m.sent_at', '>', new Date(input.since))\n\n if (input.hasObjects !== undefined) {\n const existsFn = (eb: any) => eb.exists(\n eb.selectFrom('message_objects')\n .select(sql<number>`1`.as('one'))\n .whereRef('message_objects.message_id', '=', 'm.id')\n )\n const notExistsFn = (eb: any) => eb.not(eb.exists(\n eb.selectFrom('message_objects')\n .select(sql<number>`1`.as('one'))\n .whereRef('message_objects.message_id', '=', 'm.id')\n ))\n q = input.hasObjects ? q.where(existsFn) : q.where(notExistsFn)\n }\n\n if (input.hasAttachments !== undefined) {\n const existsFn = (eb: any) => eb.exists(\n eb.selectFrom('attachments')\n .select(sql<number>`1`.as('one'))\n .where('attachments.entity_id', '=', MESSAGE_ATTACHMENT_ENTITY_ID)\n .where(sql<boolean>`attachments.record_id = m.id::text`)\n )\n const notExistsFn = (eb: any) => eb.not(eb.exists(\n eb.selectFrom('attachments')\n .select(sql<number>`1`.as('one'))\n .where('attachments.entity_id', '=', MESSAGE_ATTACHMENT_ENTITY_ID)\n .where(sql<boolean>`attachments.record_id = m.id::text`)\n ))\n q = input.hasAttachments ? q.where(existsFn) : q.where(notExistsFn)\n }\n\n if (input.hasActions !== undefined) {\n q = input.hasActions\n ? q.where('m.action_data', 'is not', null)\n : q.where('m.action_data', 'is', null)\n }\n\n return q\n }\n\n // Audited for #3386 rollout (P3): sort is on m.sent_at (a plain timestamp \u2014\n // not in the messages:message encryption map whose encrypted fields are:\n // subject, body, external_email, external_name, action_data, action_result).\n // The handler already uses the correct two-phase shape: Kysely SQL\n // ORDER BY + LIMIT/OFFSET produces a bounded page of IDs, then\n // findWithDecryption is called only for those IDs \u2014 never for the full\n // result set. The #3278 unbounded-decrypt hazard does not apply here.\n // Covered by __tests__/list.test.ts.\n const countResult = await buildBaseQuery()\n .select(sql<number>`count(*)`.as('count'))\n .executeTakeFirst() as { count: string | number } | undefined\n const total = Number(countResult?.count ?? 0)\n\n const offset = (input.page - 1) * input.pageSize\n const scopeRows = await buildBaseQuery()\n .select([\n 'm.id',\n 'm.sender_user_id',\n 'm.is_draft',\n 'r.status as recipient_status',\n 'r.read_at',\n ])\n .orderBy('m.sent_at', 'desc')\n .offset(offset)\n .limit(input.pageSize)\n .execute()\n\n const typedRows = scopeRows as MessageListScopeRow[]\n const messageIds = typedRows.map((row) => row.id)\n\n const messageEntities = messageIds.length > 0\n ? await findWithDecryption(\n em,\n Message,\n { id: { $in: messageIds } },\n undefined,\n { tenantId: scope.tenantId, organizationId: scope.organizationId }\n )\n : []\n\n const messagesById = new Map<string, Message>()\n for (const message of messageEntities) {\n messagesById.set(message.id, message)\n }\n\n const objects = messageIds.length > 0\n ? await em.find(MessageObject, { messageId: { $in: messageIds } })\n : []\n\n const objectsByMessage = objects.reduce((acc, obj) => {\n if (!acc[obj.messageId]) acc[obj.messageId] = []\n acc[obj.messageId].push(obj)\n return acc\n }, {} as Record<string, MessageObject[]>)\n\n const attachmentCounts: AttachmentCountRow[] = messageIds.length > 0\n ? await (getDb(em) as any)\n .selectFrom('attachments')\n .select(['record_id', sql<string>`count(*)`.as('count')])\n .where('entity_id', '=', MESSAGE_ATTACHMENT_ENTITY_ID)\n .where('record_id', 'in', messageIds)\n .groupBy('record_id')\n .execute()\n : []\n\n const attachmentCountByMessage = attachmentCounts.reduce((acc: Record<string, number>, row) => {\n acc[row.record_id] = Number(row.count)\n return acc\n }, {})\n\n const recipientCounts: RecipientCountRow[] = messageIds.length > 0\n ? await (getDb(em) as any)\n .selectFrom('message_recipients')\n .select(['message_id', sql<string>`count(*)`.as('count')])\n .where('message_id', 'in', messageIds)\n .where('deleted_at', 'is', null)\n .groupBy('message_id')\n .execute()\n : []\n\n const recipientCountByMessage = recipientCounts.reduce((acc: Record<string, number>, row) => {\n acc[row.message_id] = Number(row.count)\n return acc\n }, {})\n\n const senderUserIds = Array.from(new Set(typedRows.map((row) => row.sender_user_id).filter(Boolean)))\n const senderUsers = senderUserIds.length > 0\n ? await findWithDecryption(\n em,\n User,\n { id: { $in: senderUserIds } },\n undefined,\n { tenantId: scope.tenantId, organizationId: scope.organizationId }\n )\n : []\n\n const senderMetaById = new Map<string, { name: string | null; email: string | null }>()\n senderUsers.forEach((user) => {\n const name = typeof user.name === 'string' && user.name.trim().length ? user.name.trim() : null\n senderMetaById.set(user.id, { name, email: user.email ?? null })\n })\n\n return Response.json({\n items: typedRows\n .map((row) => {\n const message = messagesById.get(row.id)\n if (!message) return null\n const body = typeof message.body === 'string' ? message.body : ''\n const bodyPreview = body.substring(0, 150) + (body.length > 150 ? '...' : '')\n const actionData = message.actionData ?? null\n return {\n ...(senderMetaById.get(row.sender_user_id)\n ? {\n senderName: senderMetaById.get(row.sender_user_id)?.name ?? null,\n senderEmail: senderMetaById.get(row.sender_user_id)?.email ?? null,\n }\n : { senderName: null, senderEmail: null }),\n id: message.id,\n type: message.type,\n visibility: message.visibility ?? null,\n sourceEntityType: message.sourceEntityType ?? null,\n sourceEntityId: message.sourceEntityId ?? null,\n externalEmail: message.externalEmail ?? null,\n externalName: message.externalName ?? null,\n subject: message.subject,\n bodyPreview,\n senderUserId: message.senderUserId,\n priority: message.priority,\n status: row.recipient_status ?? (row.is_draft ? 'draft' : 'sent'),\n hasObjects: (objectsByMessage[message.id] || []).length > 0,\n objectCount: (objectsByMessage[message.id] || []).length,\n hasAttachments: (attachmentCountByMessage[message.id] || 0) > 0,\n attachmentCount: attachmentCountByMessage[message.id] || 0,\n recipientCount: recipientCountByMessage[message.id] || 0,\n hasActions:\n Boolean(actionData?.actions?.length)\n || Boolean(getMessageType(message.type)?.defaultActions?.length)\n || (objectsByMessage[message.id] || []).some((item) => item.actionRequired && Boolean(item.actionType)),\n actionTaken: message.actionTaken ?? null,\n sentAt: message.sentAt ? message.sentAt.toISOString() : null,\n readAt: row.read_at,\n threadId: message.threadId ?? null,\n }\n })\n .filter((item): item is NonNullable<typeof item> => item !== null),\n page: input.page,\n pageSize: input.pageSize,\n total,\n totalPages: Math.ceil(total / input.pageSize),\n })\n}\n\nexport async function POST(req: Request) {\n const { ctx, scope } = await resolveMessageContext(req)\n const commandBus = ctx.container.resolve('commandBus') as CommandBus\n const body = await req.json().catch(() => ({}))\n const input = composeMessageSchema.parse(body)\n\n const isPublicVisibility = input.visibility === 'public'\n const sendViaEmail = isPublicVisibility ? true : input.sendViaEmail\n if (sendViaEmail && !(await canUseMessageEmailFeature(ctx, scope))) {\n return Response.json({ error: 'Missing feature: messages.email' }, { status: 403 })\n }\n\n if (input.objects?.length) {\n const objectValidationError = validateMessageObjectsForType(input.type, input.objects)\n if (objectValidationError) {\n return Response.json({ error: objectValidationError }, { status: 400 })\n }\n }\n\n const guardResult = await runMessageMutationGuards(\n ctx.container,\n {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n resourceKind: 'messages.message',\n resourceId: null,\n operation: 'create',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: input as Record<string, unknown>,\n },\n resolveUserFeatures(ctx.auth),\n )\n if (!guardResult.ok) {\n return Response.json(\n guardResult.errorBody ?? { error: 'Operation blocked by guard' },\n { status: guardResult.errorStatus ?? 422 },\n )\n }\n\n const { result, logEntry } = await commandBus.execute('messages.messages.compose', {\n input: {\n ...input,\n sendViaEmail,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n },\n ctx: {\n container: ctx.container,\n auth: ctx.auth ?? null,\n organizationScope: null,\n selectedOrganizationId: scope.organizationId,\n organizationIds: scope.organizationId ? [scope.organizationId] : null,\n request: req,\n },\n })\n const { id: messageId, threadId: responseThreadId } = result as unknown as MessageCommandExecuteResultWithThreadId\n\n const response = Response.json({ id: messageId, threadId: responseThreadId }, { status: 201 })\n attachOperationMetadataHeader(response, logEntry, {\n resourceKind: 'messages.message',\n resourceId: messageId,\n })\n await runMessageMutationGuardAfterSuccess(guardResult.afterSuccessCallbacks, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n resourceKind: 'messages.message',\n resourceId: messageId,\n operation: 'create',\n requestMethod: req.method,\n requestHeaders: req.headers,\n })\n return response\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Messages',\n methods: {\n GET: {\n summary: 'List messages',\n query: listSchema,\n responses: [\n {\n status: 200,\n description: 'Message list',\n schema: z.object({\n items: z.array(messageListItemSchema),\n page: z.number(),\n pageSize: z.number(),\n total: z.number(),\n totalPages: z.number(),\n }),\n },\n ],\n },\n POST: {\n summary: 'Compose a message',\n requestBody: {\n schema: composeSchema,\n },\n responses: [\n {\n status: 201,\n description: 'Message created',\n schema: composeResponseSchema,\n },\n ],\n },\n },\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,SAAS;AAElB,SAAsB,WAAW;AAGjC,SAAS,0BAA0B;AACnC,SAAS,4BAA4B;AACrC,SAAS,YAAY;AACrB,SAAS,SAAS,qBAAqB;AACvC,SAAS,sBAAsB,0BAA0B;AACzD,SAAS,oCAAoC;AAC7C,SAAS,sBAAsB;AAC/B,SAAS,qCAAqC;AAC9C,SAAS,qCAAqC;AAC9C,SAAS,2BAA2B,6BAA6B;AACjE,SAAS,oCAAoC;AAC7C,SAAS,qBAAqB,qCAAqC,gCAAgC;AACnG,SAAS,oCAAoC;AAE7C;AAAA,EACE,wBAAwB;AAAA,EACxB;AAAA,EACA,sBAAsB;AAAA,EACtB;AAAA,OACK;AAMP,MAAM,cAAc;AAEpB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A,IACP,KAAK;AAAA,MACH,SAAS;AAAA,MACT,OAAO;AAAA,MACP,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ,EAAE,OAAO;AAAA,YACf,OAAO,EAAE,MAAM,qBAAqB;AAAA,YACpC,MAAM,EAAE,OAAO;AAAA,YACf,UAAU,EAAE,OAAO;AAAA,YACnB,OAAO,EAAE,OAAO;AAAA,YAChB,YAAY,EAAE,OAAO;AAAA,UACvB,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,IACA,MAAM;AAAA,MACJ,SAAS;AAAA,MACT,aAAa;AAAA,QACX,QAAQ;AAAA,MACV;AAAA,MACA,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ;AAAA,QACV;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
|
|
4
|
+
"sourcesContent": ["import { createHash } from 'node:crypto'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { type Kysely, sql } from 'kysely'\nimport { runWithCacheTenant } from '@open-mercato/cache'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands/command-bus'\nimport {\n buildCollectionTags,\n debugCrudCache,\n isCrudCacheEnabled,\n normalizeTagSegment,\n resolveCrudCache,\n} from '@open-mercato/shared/lib/crud/cache'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi/types'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { lookupHashCandidates } from '@open-mercato/shared/lib/encryption/aes'\nimport { User } from '../../auth/data/entities'\nimport { Message, MessageObject } from '../data/entities'\nimport { composeMessageSchema, listMessagesSchema, type ListMessagesInput } from '../data/validators'\nimport { MESSAGE_ATTACHMENT_ENTITY_ID } from '../lib/constants'\nimport { getMessageType } from '../lib/message-types-registry'\nimport { validateMessageObjectsForType } from '../lib/object-validation'\nimport { attachOperationMetadataHeader } from '../lib/operationMetadata'\nimport { canUseMessageEmailFeature, resolveMessageContext } from '../lib/routeHelpers'\nimport { applyMessageParticipantScope } from '../lib/participantScope'\nimport { resolveUserFeatures, runMessageMutationGuardAfterSuccess, runMessageMutationGuards } from './guards'\nimport { findMessageIdsBySearchTokens } from '../lib/searchLookup'\nimport { MessageCommandExecuteResult } from '../commands/shared'\nimport {\n composeMessageSchema as composeSchema,\n composeResponseSchema,\n listMessagesSchema as listSchema,\n messageListItemSchema,\n} from './openapi'\n\ntype MessageCommandExecuteResultWithThreadId = MessageCommandExecuteResult & {\n threadId: string\n}\n\nconst NO_MATCH_ID = '00000000-0000-0000-0000-000000000000'\nconst MESSAGE_LIST_CACHE_TTL_MS = 30_000\nconst MESSAGE_LIST_RESOURCE = 'messages.message'\n\nfunction getDb(em: EntityManager): Kysely<any> {\n return em.getKysely<any>()\n}\n\ntype MessageListScopeRow = {\n id: string\n sender_user_id: string\n is_draft: boolean\n recipient_status: string | null\n read_at: string | null\n}\n\ntype AttachmentCountRow = {\n record_id: string\n count: string | number\n}\n\ntype RecipientCountRow = {\n message_id: string\n count: string | number\n}\n\ntype MessageListPayload = {\n items: Array<Record<string, unknown>>\n page: number\n pageSize: number\n total: number\n totalPages: number\n}\n\ntype MessageListScope = Awaited<ReturnType<typeof resolveMessageContext>>['scope']\n\nfunction normalizeCacheFilterValue(value: unknown): unknown {\n if (value === undefined) return null\n if (value instanceof Date) return value.toISOString()\n if (Array.isArray(value)) return value.map(normalizeCacheFilterValue)\n if (value && typeof value === 'object') {\n return Object.entries(value as Record<string, unknown>)\n .sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey))\n .map(([key, entryValue]) => [key, normalizeCacheFilterValue(entryValue)])\n }\n return value\n}\n\nfunction buildMessageListFilterSignature(input: ListMessagesInput): string {\n const canonicalInput = Object.entries(input)\n .sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey))\n .map(([key, value]) => [key, normalizeCacheFilterValue(value)])\n\n return createHash('sha256')\n .update(JSON.stringify(canonicalInput))\n .digest('hex')\n .slice(0, 32)\n}\n\nfunction buildMessageListCacheKey(scope: MessageListScope, input: ListMessagesInput): string {\n return [\n 'messages:list:v1',\n `tenant:${normalizeTagSegment(scope.tenantId)}`,\n `org:${normalizeTagSegment(scope.organizationId)}`,\n `user:${normalizeTagSegment(scope.userId)}`,\n `filters:${buildMessageListFilterSignature(input)}`,\n ].join('|')\n}\n\nfunction isMessageListPayload(value: unknown): value is MessageListPayload {\n if (!value || typeof value !== 'object') return false\n const payload = value as Partial<MessageListPayload>\n return Array.isArray(payload.items)\n && typeof payload.page === 'number'\n && typeof payload.pageSize === 'number'\n && typeof payload.total === 'number'\n && typeof payload.totalPages === 'number'\n}\n\nexport const metadata = {\n GET: { requireAuth: true },\n POST: { requireAuth: true, requireFeatures: ['messages.compose'] },\n}\n\nexport async function GET(req: Request) {\n const { ctx, scope } = await resolveMessageContext(req)\n const url = new URL(req.url)\n const params = Object.fromEntries(url.searchParams)\n const input = listMessagesSchema.parse(params)\n\n const cache = isCrudCacheEnabled() ? resolveCrudCache(ctx.container) : null\n const cacheKey = cache ? buildMessageListCacheKey(scope, input) : null\n if (cache && cacheKey) {\n try {\n const cached = await runWithCacheTenant(scope.tenantId, () => cache.get(cacheKey))\n if (isMessageListPayload(cached)) {\n return Response.json(cached)\n }\n } catch (error) {\n debugCrudCache('messages-list-cache-read-failed', {\n error: error instanceof Error ? error.message : String(error),\n })\n }\n }\n\n const em = ctx.container.resolve('em') as EntityManager\n const db = getDb(em) as any\n\n const searchIds = input.search\n ? await findMessageIdsBySearchTokens({\n em,\n query: input.search,\n tenantId: scope.tenantId ?? null,\n organizationId: scope.organizationId,\n })\n : undefined\n\n const buildBaseQuery = () => {\n let q: any = db\n .selectFrom('messages as m')\n .where('m.tenant_id', '=', scope.tenantId)\n .where('m.deleted_at', 'is', null)\n\n if (scope.organizationId) {\n q = q.where('m.organization_id', '=', scope.organizationId)\n } else {\n q = q.where('m.organization_id', 'is', null)\n }\n\n const joinRecipient = () => {\n q = q.leftJoin('message_recipients as r', (jb: any) => jb\n .onRef('m.id', '=', 'r.message_id')\n .on('r.recipient_user_id', '=', scope.userId))\n }\n\n switch (input.folder) {\n case 'inbox':\n joinRecipient()\n q = q\n .where('r.message_id', 'is not', null)\n .where('r.deleted_at', 'is', null)\n .where('r.archived_at', 'is', null)\n .where('m.is_draft', '=', false)\n break\n case 'archived':\n joinRecipient()\n q = q\n .where('r.message_id', 'is not', null)\n .where('r.deleted_at', 'is', null)\n .where('r.archived_at', 'is not', null)\n break\n case 'sent':\n q = q\n .where('m.sender_user_id', '=', scope.userId)\n .where('m.is_draft', '=', false)\n joinRecipient()\n break\n case 'drafts':\n q = q\n .where('m.sender_user_id', '=', scope.userId)\n .where('m.is_draft', '=', true)\n joinRecipient()\n break\n case 'all':\n // Sender-OR-recipient participant scope shared with the\n // communication_channels message enricher \u2014 see participantScope.ts (#4133).\n q = applyMessageParticipantScope(q, scope.userId)\n break\n default: {\n const unsupportedFolder: never = input.folder\n throw new Error(`Unsupported folder: ${String(unsupportedFolder)}`)\n }\n }\n\n if (input.status) q = q.where('r.status', '=', input.status)\n if (input.type) q = q.where('m.type', '=', input.type)\n if (input.visibility) q = q.where('m.visibility', '=', input.visibility)\n if (input.sourceEntityType) q = q.where('m.source_entity_type', '=', input.sourceEntityType)\n if (input.sourceEntityId) q = q.where('m.source_entity_id', '=', input.sourceEntityId)\n if (input.externalEmail) q = q.where('m.external_email_hash', 'in', lookupHashCandidates(input.externalEmail))\n if (input.senderId) q = q.where('m.sender_user_id', '=', input.senderId)\n\n if (input.search) {\n if (!searchIds || searchIds.length === 0) {\n q = q.where('m.id', '=', NO_MATCH_ID)\n } else {\n q = q.where('m.id', 'in', searchIds)\n }\n }\n\n if (input.since) q = q.where('m.sent_at', '>', new Date(input.since))\n\n if (input.hasObjects !== undefined) {\n const existsFn = (eb: any) => eb.exists(\n eb.selectFrom('message_objects')\n .select(sql<number>`1`.as('one'))\n .whereRef('message_objects.message_id', '=', 'm.id')\n )\n const notExistsFn = (eb: any) => eb.not(eb.exists(\n eb.selectFrom('message_objects')\n .select(sql<number>`1`.as('one'))\n .whereRef('message_objects.message_id', '=', 'm.id')\n ))\n q = input.hasObjects ? q.where(existsFn) : q.where(notExistsFn)\n }\n\n if (input.hasAttachments !== undefined) {\n const existsFn = (eb: any) => eb.exists(\n eb.selectFrom('attachments')\n .select(sql<number>`1`.as('one'))\n .where('attachments.entity_id', '=', MESSAGE_ATTACHMENT_ENTITY_ID)\n .where(sql<boolean>`attachments.record_id = m.id::text`)\n )\n const notExistsFn = (eb: any) => eb.not(eb.exists(\n eb.selectFrom('attachments')\n .select(sql<number>`1`.as('one'))\n .where('attachments.entity_id', '=', MESSAGE_ATTACHMENT_ENTITY_ID)\n .where(sql<boolean>`attachments.record_id = m.id::text`)\n ))\n q = input.hasAttachments ? q.where(existsFn) : q.where(notExistsFn)\n }\n\n if (input.hasActions !== undefined) {\n q = input.hasActions\n ? q.where('m.action_data', 'is not', null)\n : q.where('m.action_data', 'is', null)\n }\n\n return q\n }\n\n // Audited for #3386 rollout (P3): sort is on m.sent_at (a plain timestamp \u2014\n // not in the messages:message encryption map whose encrypted fields are:\n // subject, body, external_email, external_name, action_data, action_result).\n // The handler already uses the correct two-phase shape: Kysely SQL\n // ORDER BY + LIMIT/OFFSET produces a bounded page of IDs, then\n // findWithDecryption is called only for those IDs \u2014 never for the full\n // result set. The #3278 unbounded-decrypt hazard does not apply here.\n // Covered by __tests__/list.test.ts.\n const countResult = await buildBaseQuery()\n .select(sql<number>`count(*)`.as('count'))\n .executeTakeFirst() as { count: string | number } | undefined\n const total = Number(countResult?.count ?? 0)\n\n const offset = (input.page - 1) * input.pageSize\n const scopeRows = await buildBaseQuery()\n .select([\n 'm.id',\n 'm.sender_user_id',\n 'm.is_draft',\n 'r.status as recipient_status',\n 'r.read_at',\n ])\n .orderBy('m.sent_at', 'desc')\n .offset(offset)\n .limit(input.pageSize)\n .execute()\n\n const typedRows = scopeRows as MessageListScopeRow[]\n const messageIds = typedRows.map((row) => row.id)\n\n const messageEntities = messageIds.length > 0\n ? await findWithDecryption(\n em,\n Message,\n { id: { $in: messageIds } },\n undefined,\n { tenantId: scope.tenantId, organizationId: scope.organizationId }\n )\n : []\n\n const messagesById = new Map<string, Message>()\n for (const message of messageEntities) {\n messagesById.set(message.id, message)\n }\n\n const objects = messageIds.length > 0\n ? await em.find(MessageObject, { messageId: { $in: messageIds } })\n : []\n\n const objectsByMessage = objects.reduce((acc, obj) => {\n if (!acc[obj.messageId]) acc[obj.messageId] = []\n acc[obj.messageId].push(obj)\n return acc\n }, {} as Record<string, MessageObject[]>)\n\n const attachmentCounts: AttachmentCountRow[] = messageIds.length > 0\n ? await (getDb(em) as any)\n .selectFrom('attachments')\n .select(['record_id', sql<string>`count(*)`.as('count')])\n .where('entity_id', '=', MESSAGE_ATTACHMENT_ENTITY_ID)\n .where('record_id', 'in', messageIds)\n .groupBy('record_id')\n .execute()\n : []\n\n const attachmentCountByMessage = attachmentCounts.reduce((acc: Record<string, number>, row) => {\n acc[row.record_id] = Number(row.count)\n return acc\n }, {})\n\n const recipientCounts: RecipientCountRow[] = messageIds.length > 0\n ? await (getDb(em) as any)\n .selectFrom('message_recipients')\n .select(['message_id', sql<string>`count(*)`.as('count')])\n .where('message_id', 'in', messageIds)\n .where('deleted_at', 'is', null)\n .groupBy('message_id')\n .execute()\n : []\n\n const recipientCountByMessage = recipientCounts.reduce((acc: Record<string, number>, row) => {\n acc[row.message_id] = Number(row.count)\n return acc\n }, {})\n\n const senderUserIds = Array.from(new Set(typedRows.map((row) => row.sender_user_id).filter(Boolean)))\n const senderUsers = senderUserIds.length > 0\n ? await findWithDecryption(\n em,\n User,\n { id: { $in: senderUserIds } },\n undefined,\n { tenantId: scope.tenantId, organizationId: scope.organizationId }\n )\n : []\n\n const senderMetaById = new Map<string, { name: string | null; email: string | null }>()\n senderUsers.forEach((user) => {\n const name = typeof user.name === 'string' && user.name.trim().length ? user.name.trim() : null\n senderMetaById.set(user.id, { name, email: user.email ?? null })\n })\n\n const payload: MessageListPayload = {\n items: typedRows\n .map((row) => {\n const message = messagesById.get(row.id)\n if (!message) return null\n const body = typeof message.body === 'string' ? message.body : ''\n const bodyPreview = body.substring(0, 150) + (body.length > 150 ? '...' : '')\n const actionData = message.actionData ?? null\n return {\n ...(senderMetaById.get(row.sender_user_id)\n ? {\n senderName: senderMetaById.get(row.sender_user_id)?.name ?? null,\n senderEmail: senderMetaById.get(row.sender_user_id)?.email ?? null,\n }\n : { senderName: null, senderEmail: null }),\n id: message.id,\n type: message.type,\n visibility: message.visibility ?? null,\n sourceEntityType: message.sourceEntityType ?? null,\n sourceEntityId: message.sourceEntityId ?? null,\n externalEmail: message.externalEmail ?? null,\n externalName: message.externalName ?? null,\n subject: message.subject,\n bodyPreview,\n senderUserId: message.senderUserId,\n priority: message.priority,\n status: row.recipient_status ?? (row.is_draft ? 'draft' : 'sent'),\n hasObjects: (objectsByMessage[message.id] || []).length > 0,\n objectCount: (objectsByMessage[message.id] || []).length,\n hasAttachments: (attachmentCountByMessage[message.id] || 0) > 0,\n attachmentCount: attachmentCountByMessage[message.id] || 0,\n recipientCount: recipientCountByMessage[message.id] || 0,\n hasActions:\n Boolean(actionData?.actions?.length)\n || Boolean(getMessageType(message.type)?.defaultActions?.length)\n || (objectsByMessage[message.id] || []).some((item) => item.actionRequired && Boolean(item.actionType)),\n actionTaken: message.actionTaken ?? null,\n sentAt: message.sentAt ? message.sentAt.toISOString() : null,\n readAt: row.read_at,\n threadId: message.threadId ?? null,\n }\n })\n .filter((item): item is NonNullable<typeof item> => item !== null),\n page: input.page,\n pageSize: input.pageSize,\n total,\n totalPages: Math.ceil(total / input.pageSize),\n }\n\n if (cache && cacheKey) {\n try {\n await runWithCacheTenant(scope.tenantId, () =>\n cache.set(cacheKey, payload, {\n ttl: MESSAGE_LIST_CACHE_TTL_MS,\n tags: buildCollectionTags(\n MESSAGE_LIST_RESOURCE,\n scope.tenantId,\n [scope.organizationId],\n ),\n }),\n )\n } catch (error) {\n debugCrudCache('messages-list-cache-write-failed', {\n error: error instanceof Error ? error.message : String(error),\n })\n }\n }\n\n return Response.json(payload)\n}\n\nexport async function POST(req: Request) {\n const { ctx, scope } = await resolveMessageContext(req)\n const commandBus = ctx.container.resolve('commandBus') as CommandBus\n const body = await req.json().catch(() => ({}))\n const input = composeMessageSchema.parse(body)\n\n const isPublicVisibility = input.visibility === 'public'\n const sendViaEmail = isPublicVisibility ? true : input.sendViaEmail\n if (sendViaEmail && !(await canUseMessageEmailFeature(ctx, scope))) {\n return Response.json({ error: 'Missing feature: messages.email' }, { status: 403 })\n }\n\n if (input.objects?.length) {\n const objectValidationError = validateMessageObjectsForType(input.type, input.objects)\n if (objectValidationError) {\n return Response.json({ error: objectValidationError }, { status: 400 })\n }\n }\n\n const guardResult = await runMessageMutationGuards(\n ctx.container,\n {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n resourceKind: 'messages.message',\n resourceId: null,\n operation: 'create',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: input as Record<string, unknown>,\n },\n resolveUserFeatures(ctx.auth),\n )\n if (!guardResult.ok) {\n return Response.json(\n guardResult.errorBody ?? { error: 'Operation blocked by guard' },\n { status: guardResult.errorStatus ?? 422 },\n )\n }\n\n const { result, logEntry } = await commandBus.execute('messages.messages.compose', {\n input: {\n ...input,\n sendViaEmail,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n },\n ctx: {\n container: ctx.container,\n auth: ctx.auth ?? null,\n organizationScope: null,\n selectedOrganizationId: scope.organizationId,\n organizationIds: scope.organizationId ? [scope.organizationId] : null,\n request: req,\n },\n })\n const { id: messageId, threadId: responseThreadId } = result as unknown as MessageCommandExecuteResultWithThreadId\n\n const response = Response.json({ id: messageId, threadId: responseThreadId }, { status: 201 })\n attachOperationMetadataHeader(response, logEntry, {\n resourceKind: 'messages.message',\n resourceId: messageId,\n })\n await runMessageMutationGuardAfterSuccess(guardResult.afterSuccessCallbacks, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: scope.userId,\n resourceKind: 'messages.message',\n resourceId: messageId,\n operation: 'create',\n requestMethod: req.method,\n requestHeaders: req.headers,\n })\n return response\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Messages',\n methods: {\n GET: {\n summary: 'List messages',\n query: listSchema,\n responses: [\n {\n status: 200,\n description: 'Message list',\n schema: z.object({\n items: z.array(messageListItemSchema),\n page: z.number(),\n pageSize: z.number(),\n total: z.number(),\n totalPages: z.number(),\n }),\n },\n ],\n },\n POST: {\n summary: 'Compose a message',\n requestBody: {\n schema: composeSchema,\n },\n responses: [\n {\n status: 201,\n description: 'Message created',\n schema: composeResponseSchema,\n },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,kBAAkB;AAC3B,SAAS,SAAS;AAElB,SAAsB,WAAW;AACjC,SAAS,0BAA0B;AAEnC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,0BAA0B;AACnC,SAAS,4BAA4B;AACrC,SAAS,YAAY;AACrB,SAAS,SAAS,qBAAqB;AACvC,SAAS,sBAAsB,0BAAkD;AACjF,SAAS,oCAAoC;AAC7C,SAAS,sBAAsB;AAC/B,SAAS,qCAAqC;AAC9C,SAAS,qCAAqC;AAC9C,SAAS,2BAA2B,6BAA6B;AACjE,SAAS,oCAAoC;AAC7C,SAAS,qBAAqB,qCAAqC,gCAAgC;AACnG,SAAS,oCAAoC;AAE7C;AAAA,EACE,wBAAwB;AAAA,EACxB;AAAA,EACA,sBAAsB;AAAA,EACtB;AAAA,OACK;AAMP,MAAM,cAAc;AACpB,MAAM,4BAA4B;AAClC,MAAM,wBAAwB;AAE9B,SAAS,MAAM,IAAgC;AAC7C,SAAO,GAAG,UAAe;AAC3B;AA8BA,SAAS,0BAA0B,OAAyB;AAC1D,MAAI,UAA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A,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ;AAAA,QACV;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/core",
|
|
3
|
-
"version": "0.6.7-develop.
|
|
3
|
+
"version": "0.6.7-develop.6775.1.c2313bb8a3",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -254,16 +254,16 @@
|
|
|
254
254
|
"zod": "^4.4.3"
|
|
255
255
|
},
|
|
256
256
|
"peerDependencies": {
|
|
257
|
-
"@open-mercato/ai-assistant": "0.6.7-develop.
|
|
258
|
-
"@open-mercato/shared": "0.6.7-develop.
|
|
259
|
-
"@open-mercato/ui": "0.6.7-develop.
|
|
257
|
+
"@open-mercato/ai-assistant": "0.6.7-develop.6775.1.c2313bb8a3",
|
|
258
|
+
"@open-mercato/shared": "0.6.7-develop.6775.1.c2313bb8a3",
|
|
259
|
+
"@open-mercato/ui": "0.6.7-develop.6775.1.c2313bb8a3",
|
|
260
260
|
"react": "^19.0.0",
|
|
261
261
|
"react-dom": "^19.0.0"
|
|
262
262
|
},
|
|
263
263
|
"devDependencies": {
|
|
264
|
-
"@open-mercato/ai-assistant": "0.6.7-develop.
|
|
265
|
-
"@open-mercato/shared": "0.6.7-develop.
|
|
266
|
-
"@open-mercato/ui": "0.6.7-develop.
|
|
264
|
+
"@open-mercato/ai-assistant": "0.6.7-develop.6775.1.c2313bb8a3",
|
|
265
|
+
"@open-mercato/shared": "0.6.7-develop.6775.1.c2313bb8a3",
|
|
266
|
+
"@open-mercato/ui": "0.6.7-develop.6775.1.c2313bb8a3",
|
|
267
267
|
"@testing-library/dom": "^10.4.1",
|
|
268
268
|
"@testing-library/jest-dom": "^6.9.1",
|
|
269
269
|
"@testing-library/react": "^16.3.1",
|
|
@@ -1,13 +1,22 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
1
2
|
import { z } from 'zod'
|
|
2
3
|
import type { EntityManager } from '@mikro-orm/postgresql'
|
|
3
4
|
import { type Kysely, sql } from 'kysely'
|
|
5
|
+
import { runWithCacheTenant } from '@open-mercato/cache'
|
|
4
6
|
import type { CommandBus } from '@open-mercato/shared/lib/commands/command-bus'
|
|
7
|
+
import {
|
|
8
|
+
buildCollectionTags,
|
|
9
|
+
debugCrudCache,
|
|
10
|
+
isCrudCacheEnabled,
|
|
11
|
+
normalizeTagSegment,
|
|
12
|
+
resolveCrudCache,
|
|
13
|
+
} from '@open-mercato/shared/lib/crud/cache'
|
|
5
14
|
import type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi/types'
|
|
6
15
|
import { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'
|
|
7
16
|
import { lookupHashCandidates } from '@open-mercato/shared/lib/encryption/aes'
|
|
8
17
|
import { User } from '../../auth/data/entities'
|
|
9
18
|
import { Message, MessageObject } from '../data/entities'
|
|
10
|
-
import { composeMessageSchema, listMessagesSchema } from '../data/validators'
|
|
19
|
+
import { composeMessageSchema, listMessagesSchema, type ListMessagesInput } from '../data/validators'
|
|
11
20
|
import { MESSAGE_ATTACHMENT_ENTITY_ID } from '../lib/constants'
|
|
12
21
|
import { getMessageType } from '../lib/message-types-registry'
|
|
13
22
|
import { validateMessageObjectsForType } from '../lib/object-validation'
|
|
@@ -29,6 +38,8 @@ type MessageCommandExecuteResultWithThreadId = MessageCommandExecuteResult & {
|
|
|
29
38
|
}
|
|
30
39
|
|
|
31
40
|
const NO_MATCH_ID = '00000000-0000-0000-0000-000000000000'
|
|
41
|
+
const MESSAGE_LIST_CACHE_TTL_MS = 30_000
|
|
42
|
+
const MESSAGE_LIST_RESOURCE = 'messages.message'
|
|
32
43
|
|
|
33
44
|
function getDb(em: EntityManager): Kysely<any> {
|
|
34
45
|
return em.getKysely<any>()
|
|
@@ -52,6 +63,59 @@ type RecipientCountRow = {
|
|
|
52
63
|
count: string | number
|
|
53
64
|
}
|
|
54
65
|
|
|
66
|
+
type MessageListPayload = {
|
|
67
|
+
items: Array<Record<string, unknown>>
|
|
68
|
+
page: number
|
|
69
|
+
pageSize: number
|
|
70
|
+
total: number
|
|
71
|
+
totalPages: number
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
type MessageListScope = Awaited<ReturnType<typeof resolveMessageContext>>['scope']
|
|
75
|
+
|
|
76
|
+
function normalizeCacheFilterValue(value: unknown): unknown {
|
|
77
|
+
if (value === undefined) return null
|
|
78
|
+
if (value instanceof Date) return value.toISOString()
|
|
79
|
+
if (Array.isArray(value)) return value.map(normalizeCacheFilterValue)
|
|
80
|
+
if (value && typeof value === 'object') {
|
|
81
|
+
return Object.entries(value as Record<string, unknown>)
|
|
82
|
+
.sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey))
|
|
83
|
+
.map(([key, entryValue]) => [key, normalizeCacheFilterValue(entryValue)])
|
|
84
|
+
}
|
|
85
|
+
return value
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function buildMessageListFilterSignature(input: ListMessagesInput): string {
|
|
89
|
+
const canonicalInput = Object.entries(input)
|
|
90
|
+
.sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey))
|
|
91
|
+
.map(([key, value]) => [key, normalizeCacheFilterValue(value)])
|
|
92
|
+
|
|
93
|
+
return createHash('sha256')
|
|
94
|
+
.update(JSON.stringify(canonicalInput))
|
|
95
|
+
.digest('hex')
|
|
96
|
+
.slice(0, 32)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function buildMessageListCacheKey(scope: MessageListScope, input: ListMessagesInput): string {
|
|
100
|
+
return [
|
|
101
|
+
'messages:list:v1',
|
|
102
|
+
`tenant:${normalizeTagSegment(scope.tenantId)}`,
|
|
103
|
+
`org:${normalizeTagSegment(scope.organizationId)}`,
|
|
104
|
+
`user:${normalizeTagSegment(scope.userId)}`,
|
|
105
|
+
`filters:${buildMessageListFilterSignature(input)}`,
|
|
106
|
+
].join('|')
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function isMessageListPayload(value: unknown): value is MessageListPayload {
|
|
110
|
+
if (!value || typeof value !== 'object') return false
|
|
111
|
+
const payload = value as Partial<MessageListPayload>
|
|
112
|
+
return Array.isArray(payload.items)
|
|
113
|
+
&& typeof payload.page === 'number'
|
|
114
|
+
&& typeof payload.pageSize === 'number'
|
|
115
|
+
&& typeof payload.total === 'number'
|
|
116
|
+
&& typeof payload.totalPages === 'number'
|
|
117
|
+
}
|
|
118
|
+
|
|
55
119
|
export const metadata = {
|
|
56
120
|
GET: { requireAuth: true },
|
|
57
121
|
POST: { requireAuth: true, requireFeatures: ['messages.compose'] },
|
|
@@ -59,10 +123,26 @@ export const metadata = {
|
|
|
59
123
|
|
|
60
124
|
export async function GET(req: Request) {
|
|
61
125
|
const { ctx, scope } = await resolveMessageContext(req)
|
|
62
|
-
const em = ctx.container.resolve('em') as EntityManager
|
|
63
126
|
const url = new URL(req.url)
|
|
64
127
|
const params = Object.fromEntries(url.searchParams)
|
|
65
128
|
const input = listMessagesSchema.parse(params)
|
|
129
|
+
|
|
130
|
+
const cache = isCrudCacheEnabled() ? resolveCrudCache(ctx.container) : null
|
|
131
|
+
const cacheKey = cache ? buildMessageListCacheKey(scope, input) : null
|
|
132
|
+
if (cache && cacheKey) {
|
|
133
|
+
try {
|
|
134
|
+
const cached = await runWithCacheTenant(scope.tenantId, () => cache.get(cacheKey))
|
|
135
|
+
if (isMessageListPayload(cached)) {
|
|
136
|
+
return Response.json(cached)
|
|
137
|
+
}
|
|
138
|
+
} catch (error) {
|
|
139
|
+
debugCrudCache('messages-list-cache-read-failed', {
|
|
140
|
+
error: error instanceof Error ? error.message : String(error),
|
|
141
|
+
})
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const em = ctx.container.resolve('em') as EntityManager
|
|
66
146
|
const db = getDb(em) as any
|
|
67
147
|
|
|
68
148
|
const searchIds = input.search
|
|
@@ -290,7 +370,7 @@ export async function GET(req: Request) {
|
|
|
290
370
|
senderMetaById.set(user.id, { name, email: user.email ?? null })
|
|
291
371
|
})
|
|
292
372
|
|
|
293
|
-
|
|
373
|
+
const payload: MessageListPayload = {
|
|
294
374
|
items: typedRows
|
|
295
375
|
.map((row) => {
|
|
296
376
|
const message = messagesById.get(row.id)
|
|
@@ -337,7 +417,28 @@ export async function GET(req: Request) {
|
|
|
337
417
|
pageSize: input.pageSize,
|
|
338
418
|
total,
|
|
339
419
|
totalPages: Math.ceil(total / input.pageSize),
|
|
340
|
-
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
if (cache && cacheKey) {
|
|
423
|
+
try {
|
|
424
|
+
await runWithCacheTenant(scope.tenantId, () =>
|
|
425
|
+
cache.set(cacheKey, payload, {
|
|
426
|
+
ttl: MESSAGE_LIST_CACHE_TTL_MS,
|
|
427
|
+
tags: buildCollectionTags(
|
|
428
|
+
MESSAGE_LIST_RESOURCE,
|
|
429
|
+
scope.tenantId,
|
|
430
|
+
[scope.organizationId],
|
|
431
|
+
),
|
|
432
|
+
}),
|
|
433
|
+
)
|
|
434
|
+
} catch (error) {
|
|
435
|
+
debugCrudCache('messages-list-cache-write-failed', {
|
|
436
|
+
error: error instanceof Error ? error.message : String(error),
|
|
437
|
+
})
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
return Response.json(payload)
|
|
341
442
|
}
|
|
342
443
|
|
|
343
444
|
export async function POST(req: Request) {
|