@open-mercato/core 0.6.7-develop.6553.1.2ec7246e04 → 0.6.7-develop.6566.1.15385fa179

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.
Files changed (143) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/attachments/api/partitions/route.js.map +1 -1
  3. package/dist/modules/attachments/lib/reconcileOrganization.js +9 -7
  4. package/dist/modules/attachments/lib/reconcileOrganization.js.map +2 -2
  5. package/dist/modules/catalog/api/products/route.js.map +1 -1
  6. package/dist/modules/customers/api/companies/[id]/people/route.js +2 -2
  7. package/dist/modules/customers/api/companies/[id]/people/route.js.map +2 -2
  8. package/dist/modules/customers/api/deals/[id]/companies/route.js +2 -2
  9. package/dist/modules/customers/api/deals/[id]/companies/route.js.map +2 -2
  10. package/dist/modules/customers/api/deals/[id]/people/route.js +2 -2
  11. package/dist/modules/customers/api/deals/[id]/people/route.js.map +2 -2
  12. package/dist/modules/customers/api/dictionaries/[kind]/[id]/route.js +4 -4
  13. package/dist/modules/customers/api/dictionaries/[kind]/[id]/route.js.map +2 -2
  14. package/dist/modules/customers/api/entity-roles-factory.js +3 -3
  15. package/dist/modules/customers/api/entity-roles-factory.js.map +2 -2
  16. package/dist/modules/customers/api/labels/assign/route.js +2 -2
  17. package/dist/modules/customers/api/labels/assign/route.js.map +2 -2
  18. package/dist/modules/customers/api/labels/unassign/route.js +2 -2
  19. package/dist/modules/customers/api/labels/unassign/route.js.map +2 -2
  20. package/dist/modules/customers/api/people/[id]/companies/[linkId]/route.js +3 -7
  21. package/dist/modules/customers/api/people/[id]/companies/[linkId]/route.js.map +2 -2
  22. package/dist/modules/customers/api/people/[id]/companies/context.js +3 -3
  23. package/dist/modules/customers/api/people/[id]/companies/context.js.map +2 -2
  24. package/dist/modules/customers/api/people/[id]/companies/enriched/route.js +2 -2
  25. package/dist/modules/customers/api/people/[id]/companies/enriched/route.js.map +2 -2
  26. package/dist/modules/customers/api/todos/route.js +2 -2
  27. package/dist/modules/customers/api/todos/route.js.map +2 -2
  28. package/dist/modules/customers/commands/addresses.js +3 -3
  29. package/dist/modules/customers/commands/addresses.js.map +2 -2
  30. package/dist/modules/customers/commands/comments.js +3 -3
  31. package/dist/modules/customers/commands/comments.js.map +2 -2
  32. package/dist/modules/customers/commands/companies.js +2 -2
  33. package/dist/modules/customers/commands/companies.js.map +2 -2
  34. package/dist/modules/customers/commands/deals.js +3 -3
  35. package/dist/modules/customers/commands/deals.js.map +2 -2
  36. package/dist/modules/customers/commands/dictionaries.js +3 -3
  37. package/dist/modules/customers/commands/dictionaries.js.map +2 -2
  38. package/dist/modules/customers/commands/entity-roles.js +3 -3
  39. package/dist/modules/customers/commands/entity-roles.js.map +2 -2
  40. package/dist/modules/customers/commands/interactions.js +6 -6
  41. package/dist/modules/customers/commands/interactions.js.map +2 -2
  42. package/dist/modules/customers/commands/labels.js +7 -7
  43. package/dist/modules/customers/commands/labels.js.map +2 -2
  44. package/dist/modules/customers/commands/people.js +3 -3
  45. package/dist/modules/customers/commands/people.js.map +2 -2
  46. package/dist/modules/customers/commands/personCompanyLinks.js +6 -6
  47. package/dist/modules/customers/commands/personCompanyLinks.js.map +2 -2
  48. package/dist/modules/customers/commands/pipeline-stages.js +3 -3
  49. package/dist/modules/customers/commands/pipeline-stages.js.map +2 -2
  50. package/dist/modules/customers/commands/pipelines.js +3 -3
  51. package/dist/modules/customers/commands/pipelines.js.map +2 -2
  52. package/dist/modules/customers/commands/shared.js +3 -3
  53. package/dist/modules/customers/commands/shared.js.map +2 -2
  54. package/dist/modules/customers/commands/tags.js +7 -7
  55. package/dist/modules/customers/commands/tags.js.map +2 -2
  56. package/dist/modules/customers/commands/todos.js +3 -3
  57. package/dist/modules/customers/commands/todos.js.map +2 -2
  58. package/dist/modules/customers/lib/personCompanies.js +4 -4
  59. package/dist/modules/customers/lib/personCompanies.js.map +2 -2
  60. package/dist/modules/perspectives/data/validators.js +4 -0
  61. package/dist/modules/perspectives/data/validators.js.map +2 -2
  62. package/dist/modules/sales/api/notes/route.js +2 -4
  63. package/dist/modules/sales/api/notes/route.js.map +2 -2
  64. package/dist/modules/sales/api/quotes/accept/route.js +2 -2
  65. package/dist/modules/sales/api/quotes/accept/route.js.map +2 -2
  66. package/dist/modules/sales/api/quotes/public/[token]/route.js +3 -7
  67. package/dist/modules/sales/api/quotes/public/[token]/route.js.map +2 -2
  68. package/dist/modules/sales/api/quotes/send/route.js +2 -2
  69. package/dist/modules/sales/api/quotes/send/route.js.map +2 -2
  70. package/dist/modules/sales/api/returns/[id]/route.js +2 -2
  71. package/dist/modules/sales/api/returns/[id]/route.js.map +2 -2
  72. package/dist/modules/sales/commands/configuration.js +11 -11
  73. package/dist/modules/sales/commands/configuration.js.map +2 -2
  74. package/dist/modules/sales/commands/documentAddresses.js +3 -3
  75. package/dist/modules/sales/commands/documentAddresses.js.map +2 -2
  76. package/dist/modules/sales/commands/documents.js +31 -39
  77. package/dist/modules/sales/commands/documents.js.map +2 -2
  78. package/dist/modules/sales/commands/notes.js +7 -7
  79. package/dist/modules/sales/commands/notes.js.map +2 -2
  80. package/dist/modules/sales/commands/payments.js +2 -2
  81. package/dist/modules/sales/commands/payments.js.map +2 -2
  82. package/dist/modules/sales/commands/returns.js +8 -8
  83. package/dist/modules/sales/commands/returns.js.map +2 -2
  84. package/dist/modules/sales/commands/shared.js +2 -2
  85. package/dist/modules/sales/commands/shared.js.map +2 -2
  86. package/dist/modules/sales/commands/shipments.js +5 -5
  87. package/dist/modules/sales/commands/shipments.js.map +2 -2
  88. package/dist/modules/sales/commands/statuses.js +2 -2
  89. package/dist/modules/sales/commands/statuses.js.map +2 -2
  90. package/dist/modules/sales/commands/tags.js +3 -3
  91. package/dist/modules/sales/commands/tags.js.map +2 -2
  92. package/package.json +8 -8
  93. package/src/modules/attachments/api/partitions/route.ts +1 -1
  94. package/src/modules/attachments/lib/reconcileOrganization.ts +16 -7
  95. package/src/modules/catalog/api/products/route.ts +1 -1
  96. package/src/modules/customer_accounts/i18n/de.json +12 -0
  97. package/src/modules/customer_accounts/i18n/en.json +12 -0
  98. package/src/modules/customer_accounts/i18n/es.json +34 -22
  99. package/src/modules/customer_accounts/i18n/pl.json +32 -20
  100. package/src/modules/customers/api/companies/[id]/people/route.ts +2 -2
  101. package/src/modules/customers/api/deals/[id]/companies/route.ts +2 -2
  102. package/src/modules/customers/api/deals/[id]/people/route.ts +2 -2
  103. package/src/modules/customers/api/dictionaries/[kind]/[id]/route.ts +4 -4
  104. package/src/modules/customers/api/entity-roles-factory.ts +3 -3
  105. package/src/modules/customers/api/labels/assign/route.ts +2 -2
  106. package/src/modules/customers/api/labels/unassign/route.ts +2 -2
  107. package/src/modules/customers/api/people/[id]/companies/[linkId]/route.ts +3 -7
  108. package/src/modules/customers/api/people/[id]/companies/context.ts +3 -3
  109. package/src/modules/customers/api/people/[id]/companies/enriched/route.ts +2 -2
  110. package/src/modules/customers/api/todos/route.ts +2 -2
  111. package/src/modules/customers/commands/addresses.ts +3 -3
  112. package/src/modules/customers/commands/comments.ts +3 -3
  113. package/src/modules/customers/commands/companies.ts +2 -2
  114. package/src/modules/customers/commands/deals.ts +3 -3
  115. package/src/modules/customers/commands/dictionaries.ts +3 -3
  116. package/src/modules/customers/commands/entity-roles.ts +3 -3
  117. package/src/modules/customers/commands/interactions.ts +6 -6
  118. package/src/modules/customers/commands/labels.ts +7 -7
  119. package/src/modules/customers/commands/people.ts +3 -3
  120. package/src/modules/customers/commands/personCompanyLinks.ts +6 -6
  121. package/src/modules/customers/commands/pipeline-stages.ts +3 -3
  122. package/src/modules/customers/commands/pipelines.ts +3 -3
  123. package/src/modules/customers/commands/shared.ts +3 -3
  124. package/src/modules/customers/commands/tags.ts +7 -7
  125. package/src/modules/customers/commands/todos.ts +3 -3
  126. package/src/modules/customers/lib/personCompanies.ts +4 -4
  127. package/src/modules/perspectives/data/validators.ts +4 -0
  128. package/src/modules/sales/api/notes/route.ts +2 -4
  129. package/src/modules/sales/api/quotes/accept/route.ts +2 -2
  130. package/src/modules/sales/api/quotes/public/[token]/route.ts +3 -7
  131. package/src/modules/sales/api/quotes/send/route.ts +2 -2
  132. package/src/modules/sales/api/returns/[id]/route.ts +2 -2
  133. package/src/modules/sales/commands/configuration.ts +11 -11
  134. package/src/modules/sales/commands/documentAddresses.ts +3 -3
  135. package/src/modules/sales/commands/documents.ts +23 -31
  136. package/src/modules/sales/commands/notes.ts +7 -7
  137. package/src/modules/sales/commands/payments.ts +2 -2
  138. package/src/modules/sales/commands/returns.ts +8 -8
  139. package/src/modules/sales/commands/shared.ts +2 -2
  140. package/src/modules/sales/commands/shipments.ts +5 -5
  141. package/src/modules/sales/commands/statuses.ts +2 -2
  142. package/src/modules/sales/commands/tags.ts +3 -3
  143. package/tsconfig.json +0 -2
@@ -1,4 +1,4 @@
1
- [build:core] found 3489 entry points
1
+ [build:core] found 3490 entry points
2
2
  [build:core] built successfully
3
3
  [build:core:generated] found 187 entry points
4
4
  [build:core:generated] built successfully
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/attachments/api/partitions/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { Attachment, AttachmentPartition } from '../../data/entities'\nimport { ensureDefaultPartitions, DEFAULT_ATTACHMENT_PARTITIONS, sanitizePartitionCode, isPartitionSettingsLocked } from '../../lib/partitions'\nimport { resolvePartitionEnvKey } from '../../lib/partitionEnv'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { resolveDefaultAttachmentOcrEnabled } from '../../lib/ocrConfig'\nimport {\n attachmentsTag,\n partitionCreateSchema,\n partitionUpdateSchema,\n partitionResponseSchema,\n partitionListResponseSchema,\n attachmentErrorSchema,\n} from '../openapi'\n\nconst deleteSchema = z.object({\n id: z.string().uuid(),\n})\n\nconst DEFAULT_CODES = new Set(DEFAULT_ATTACHMENT_PARTITIONS.map((entry) => entry.code))\n\ntype AuthLike = { sub?: string; tenantId?: string | null; orgId?: string | null; isSuperAdmin?: boolean } | null | undefined\n\nfunction isSuperAdmin(auth: AuthLike): boolean {\n return auth?.isSuperAdmin === true\n}\n\nfunction canManagePartition(auth: AuthLike, entry: AttachmentPartition): boolean {\n if (!auth?.tenantId) return false\n if (entry.tenantId && entry.tenantId === auth.tenantId) return true\n if (entry.tenantId == null && isSuperAdmin(auth)) return true\n return false\n}\n\nfunction partitionVisibilityFilter(auth: AuthLike) {\n if (isSuperAdmin(auth)) return {}\n return { $or: [{ tenantId: null }, { tenantId: auth?.tenantId ?? null }] }\n}\n\nfunction serializePartition(entry: AttachmentPartition) {\n return {\n id: entry.id,\n code: entry.code,\n title: entry.title,\n description: entry.description ?? null,\n isPublic: entry.isPublic ?? false,\n requiresOcr: entry.requiresOcr ?? resolveDefaultAttachmentOcrEnabled(),\n ocrModel: entry.ocrModel ?? null,\n storageDriver: entry.storageDriver ?? 'local',\n configJson: entry.configJson ?? null,\n createdAt: entry.createdAt instanceof Date ? entry.createdAt.toISOString() : null,\n updatedAt: entry.updatedAt instanceof Date ? entry.updatedAt.toISOString() : null,\n envKey: resolvePartitionEnvKey(entry.code),\n }\n}\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['attachments.manage'] },\n POST: { requireAuth: true, requireFeatures: ['attachments.manage'] },\n PUT: { requireAuth: true, requireFeatures: ['attachments.manage'] },\n DELETE: { requireAuth: true, requireFeatures: ['attachments.manage'] },\n} as const\n\nasync function resolveEm() {\n const { resolve } = await createRequestContainer()\n return resolve('em') as EntityManager\n}\n\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub || !auth.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n const em = await resolveEm()\n await ensureDefaultPartitions(em)\n const rows = await findWithDecryption(\n em,\n AttachmentPartition,\n partitionVisibilityFilter(auth),\n { orderBy: { createdAt: 'asc' } },\n { tenantId: auth.tenantId, organizationId: auth.orgId ?? null },\n )\n return NextResponse.json({ items: rows.map((entry) => serializePartition(entry)) })\n}\n\nexport async function POST(req: Request) {\n if (isPartitionSettingsLocked()) {\n return NextResponse.json(\n { error: 'Attachment partitions are managed by the environment in demo/onboarding mode.' },\n { status: 403 },\n )\n }\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub || !auth.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n let json: unknown = null\n try {\n json = await req.json()\n } catch {\n json = null\n }\n const parsed = partitionCreateSchema.safeParse(json)\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid payload' }, { status: 400 })\n }\n const code = sanitizePartitionCode(parsed.data.code)\n if (!code) {\n return NextResponse.json({ error: 'Partition code is required.' }, { status: 400 })\n }\n const em = await resolveEm()\n await ensureDefaultPartitions(em)\n const exists = await findOneWithDecryption(\n em,\n AttachmentPartition,\n { code },\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId ?? null },\n )\n if (exists) {\n return NextResponse.json({ error: 'Partition code already exists.' }, { status: 409 })\n }\n const entry = em.create(AttachmentPartition, {\n code,\n title: parsed.data.title.trim(),\n description: parsed.data.description?.trim() ?? null,\n storageDriver: parsed.data.storageDriver ?? 'local',\n configJson: parsed.data.configJson ?? null,\n isPublic: parsed.data.isPublic ?? false,\n requiresOcr:\n typeof parsed.data.requiresOcr === 'boolean'\n ? parsed.data.requiresOcr\n : resolveDefaultAttachmentOcrEnabled(),\n ocrModel: parsed.data.ocrModel?.trim() || null,\n tenantId: auth.tenantId,\n organizationId: auth.orgId ?? null,\n })\n await em.persist(entry).flush()\n return NextResponse.json({ item: serializePartition(entry) }, { status: 201 })\n}\n\nexport async function PUT(req: Request) {\n if (isPartitionSettingsLocked()) {\n return NextResponse.json(\n { error: 'Attachment partitions are managed by the environment in demo/onboarding mode.' },\n { status: 403 },\n )\n }\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub || !auth.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n let json: unknown = null\n try {\n json = await req.json()\n } catch {\n json = null\n }\n const parsed = partitionUpdateSchema.safeParse(json)\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid payload' }, { status: 400 })\n }\n const em = await resolveEm()\n const entry = await findOneWithDecryption(\n em,\n AttachmentPartition,\n { id: parsed.data.id },\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId ?? null },\n )\n if (!entry || !canManagePartition(auth, entry)) {\n return NextResponse.json({ error: 'Partition not found' }, { status: 404 })\n }\n if (sanitizePartitionCode(parsed.data.code) !== entry.code) {\n return NextResponse.json({ error: 'Partition code cannot be changed.' }, { status: 400 })\n }\n entry.title = parsed.data.title.trim()\n entry.description = parsed.data.description?.trim() ?? null\n entry.isPublic = parsed.data.isPublic ?? false\n if (typeof parsed.data.requiresOcr === 'boolean') {\n entry.requiresOcr = parsed.data.requiresOcr\n }\n if (parsed.data.ocrModel !== undefined) {\n entry.ocrModel = parsed.data.ocrModel?.trim() || null\n }\n if (parsed.data.storageDriver !== undefined) {\n entry.storageDriver = parsed.data.storageDriver\n }\n if (parsed.data.configJson !== undefined) {\n entry.configJson = parsed.data.configJson ?? null\n }\n await em.persist(entry).flush()\n return NextResponse.json({ item: serializePartition(entry) })\n}\n\nexport async function DELETE(req: Request) {\n if (isPartitionSettingsLocked()) {\n return NextResponse.json(\n { error: 'Attachment partitions are managed by the environment in demo/onboarding mode.' },\n { status: 403 },\n )\n }\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub || !auth.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n const url = new URL(req.url)\n const id = url.searchParams.get('id')\n const parsed = deleteSchema.safeParse({ id })\n if (!parsed.success) {\n return NextResponse.json({ error: 'Partition id is required' }, { status: 400 })\n }\n const em = await resolveEm()\n const entry = await findOneWithDecryption(\n em,\n AttachmentPartition,\n { id: parsed.data.id },\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId ?? null },\n )\n if (!entry || !canManagePartition(auth, entry)) {\n return NextResponse.json({ error: 'Partition not found' }, { status: 404 })\n }\n if (DEFAULT_CODES.has(entry.code)) {\n return NextResponse.json({ error: 'Default partitions cannot be removed.' }, { status: 400 })\n }\n const usageFilter: Record<string, unknown> = { partitionCode: entry.code }\n if (entry.tenantId) usageFilter.tenantId = entry.tenantId\n const usage = await em.count(Attachment, usageFilter)\n if (usage > 0) {\n return NextResponse.json({ error: 'Partition is in use and cannot be removed.' }, { status: 409 })\n }\n await em.remove(entry).flush()\n return NextResponse.json({ ok: true })\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: attachmentsTag,\n summary: 'Attachment partition management',\n methods: {\n GET: {\n summary: 'List all attachment partitions',\n description: 'Returns all configured attachment partitions with storage settings, OCR configuration, and access control settings.',\n responses: [\n { status: 200, description: 'List of partitions', schema: partitionListResponseSchema },\n ],\n errors: [\n { status: 401, description: 'Unauthorized', schema: attachmentErrorSchema },\n ],\n },\n POST: {\n summary: 'Create new partition',\n description: 'Creates a new attachment partition with specified storage and OCR settings. Requires unique partition code.',\n requestBody: {\n contentType: 'application/json',\n schema: partitionCreateSchema,\n },\n responses: [\n { status: 201, description: 'Partition created successfully', schema: partitionResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Invalid payload or partition code', schema: attachmentErrorSchema },\n { status: 401, description: 'Unauthorized', schema: attachmentErrorSchema },\n { status: 403, description: 'Partitions locked in demo mode', schema: attachmentErrorSchema },\n { status: 409, description: 'Partition code already exists', schema: attachmentErrorSchema },\n ],\n },\n PUT: {\n summary: 'Update partition',\n description: 'Updates an existing partition. Partition code cannot be changed. Title, description, OCR settings, and access control can be modified.',\n requestBody: {\n contentType: 'application/json',\n schema: partitionUpdateSchema,\n },\n responses: [\n { status: 200, description: 'Partition updated successfully', schema: partitionResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Invalid payload or code change attempt', schema: attachmentErrorSchema },\n { status: 401, description: 'Unauthorized', schema: attachmentErrorSchema },\n { status: 403, description: 'Partitions locked in demo mode', schema: attachmentErrorSchema },\n { status: 404, description: 'Partition not found', schema: attachmentErrorSchema },\n ],\n },\n DELETE: {\n summary: 'Delete partition',\n description: 'Deletes a partition. Default partitions cannot be deleted. Partitions with existing attachments cannot be deleted.',\n responses: [\n { status: 200, description: 'Partition deleted successfully', schema: z.object({ ok: z.literal(true) }) },\n ],\n errors: [\n { status: 400, description: 'Invalid ID or default partition deletion attempt', schema: attachmentErrorSchema },\n { status: 401, description: 'Unauthorized', schema: attachmentErrorSchema },\n { status: 403, description: 'Partitions locked in demo mode', schema: attachmentErrorSchema },\n { status: 404, description: 'Partition not found', schema: attachmentErrorSchema },\n { status: 409, description: 'Partition in use', schema: attachmentErrorSchema },\n ],\n },\n },\n}\n"],
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { Attachment, AttachmentPartition } from '../../data/entities'\nimport { ensureDefaultPartitions, DEFAULT_ATTACHMENT_PARTITIONS, sanitizePartitionCode, isPartitionSettingsLocked } from '../../lib/partitions'\nimport { resolvePartitionEnvKey } from '../../lib/partitionEnv'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { resolveDefaultAttachmentOcrEnabled } from '../../lib/ocrConfig'\nimport {\n attachmentsTag,\n partitionCreateSchema,\n partitionUpdateSchema,\n partitionResponseSchema,\n partitionListResponseSchema,\n attachmentErrorSchema,\n} from '../openapi'\n\nconst deleteSchema = z.object({\n id: z.string().uuid(),\n})\n\nconst DEFAULT_CODES = new Set(DEFAULT_ATTACHMENT_PARTITIONS.map((entry) => entry.code))\n\ntype AuthLike = { sub?: string; tenantId?: string | null; orgId?: string | null; isSuperAdmin?: boolean } | null | undefined\n\nfunction isSuperAdmin(auth: AuthLike): boolean {\n return auth?.isSuperAdmin === true\n}\n\nfunction canManagePartition(auth: AuthLike, entry: AttachmentPartition): boolean {\n if (!auth?.tenantId) return false\n if (entry.tenantId && entry.tenantId === auth.tenantId) return true\n if (entry.tenantId == null && isSuperAdmin(auth)) return true\n return false\n}\n\nfunction partitionVisibilityFilter(auth: AuthLike) {\n if (isSuperAdmin(auth)) return {}\n return { $or: [{ tenantId: null }, { tenantId: auth?.tenantId ?? null }] }\n}\n\nfunction serializePartition(entry: AttachmentPartition) {\n return {\n id: entry.id,\n code: entry.code,\n title: entry.title,\n description: entry.description ?? null,\n isPublic: entry.isPublic ?? false,\n requiresOcr: entry.requiresOcr ?? resolveDefaultAttachmentOcrEnabled(),\n ocrModel: entry.ocrModel ?? null,\n storageDriver: entry.storageDriver ?? 'local',\n configJson: entry.configJson ?? null,\n createdAt: entry.createdAt instanceof Date ? entry.createdAt.toISOString() : null,\n updatedAt: entry.updatedAt instanceof Date ? entry.updatedAt.toISOString() : null,\n envKey: resolvePartitionEnvKey(entry.code),\n }\n}\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['attachments.manage'] },\n POST: { requireAuth: true, requireFeatures: ['attachments.manage'] },\n PUT: { requireAuth: true, requireFeatures: ['attachments.manage'] },\n DELETE: { requireAuth: true, requireFeatures: ['attachments.manage'] },\n} as const\n\nasync function resolveEm() {\n const { resolve } = await createRequestContainer()\n return resolve('em') as EntityManager\n}\n\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub || !auth.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n const em = await resolveEm()\n await ensureDefaultPartitions(em)\n const rows = await findWithDecryption<AttachmentPartition>(\n em,\n AttachmentPartition,\n partitionVisibilityFilter(auth),\n { orderBy: { createdAt: 'asc' } },\n { tenantId: auth.tenantId, organizationId: auth.orgId ?? null },\n )\n return NextResponse.json({ items: rows.map((entry) => serializePartition(entry)) })\n}\n\nexport async function POST(req: Request) {\n if (isPartitionSettingsLocked()) {\n return NextResponse.json(\n { error: 'Attachment partitions are managed by the environment in demo/onboarding mode.' },\n { status: 403 },\n )\n }\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub || !auth.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n let json: unknown = null\n try {\n json = await req.json()\n } catch {\n json = null\n }\n const parsed = partitionCreateSchema.safeParse(json)\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid payload' }, { status: 400 })\n }\n const code = sanitizePartitionCode(parsed.data.code)\n if (!code) {\n return NextResponse.json({ error: 'Partition code is required.' }, { status: 400 })\n }\n const em = await resolveEm()\n await ensureDefaultPartitions(em)\n const exists = await findOneWithDecryption(\n em,\n AttachmentPartition,\n { code },\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId ?? null },\n )\n if (exists) {\n return NextResponse.json({ error: 'Partition code already exists.' }, { status: 409 })\n }\n const entry = em.create(AttachmentPartition, {\n code,\n title: parsed.data.title.trim(),\n description: parsed.data.description?.trim() ?? null,\n storageDriver: parsed.data.storageDriver ?? 'local',\n configJson: parsed.data.configJson ?? null,\n isPublic: parsed.data.isPublic ?? false,\n requiresOcr:\n typeof parsed.data.requiresOcr === 'boolean'\n ? parsed.data.requiresOcr\n : resolveDefaultAttachmentOcrEnabled(),\n ocrModel: parsed.data.ocrModel?.trim() || null,\n tenantId: auth.tenantId,\n organizationId: auth.orgId ?? null,\n })\n await em.persist(entry).flush()\n return NextResponse.json({ item: serializePartition(entry) }, { status: 201 })\n}\n\nexport async function PUT(req: Request) {\n if (isPartitionSettingsLocked()) {\n return NextResponse.json(\n { error: 'Attachment partitions are managed by the environment in demo/onboarding mode.' },\n { status: 403 },\n )\n }\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub || !auth.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n let json: unknown = null\n try {\n json = await req.json()\n } catch {\n json = null\n }\n const parsed = partitionUpdateSchema.safeParse(json)\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid payload' }, { status: 400 })\n }\n const em = await resolveEm()\n const entry = await findOneWithDecryption(\n em,\n AttachmentPartition,\n { id: parsed.data.id },\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId ?? null },\n )\n if (!entry || !canManagePartition(auth, entry)) {\n return NextResponse.json({ error: 'Partition not found' }, { status: 404 })\n }\n if (sanitizePartitionCode(parsed.data.code) !== entry.code) {\n return NextResponse.json({ error: 'Partition code cannot be changed.' }, { status: 400 })\n }\n entry.title = parsed.data.title.trim()\n entry.description = parsed.data.description?.trim() ?? null\n entry.isPublic = parsed.data.isPublic ?? false\n if (typeof parsed.data.requiresOcr === 'boolean') {\n entry.requiresOcr = parsed.data.requiresOcr\n }\n if (parsed.data.ocrModel !== undefined) {\n entry.ocrModel = parsed.data.ocrModel?.trim() || null\n }\n if (parsed.data.storageDriver !== undefined) {\n entry.storageDriver = parsed.data.storageDriver\n }\n if (parsed.data.configJson !== undefined) {\n entry.configJson = parsed.data.configJson ?? null\n }\n await em.persist(entry).flush()\n return NextResponse.json({ item: serializePartition(entry) })\n}\n\nexport async function DELETE(req: Request) {\n if (isPartitionSettingsLocked()) {\n return NextResponse.json(\n { error: 'Attachment partitions are managed by the environment in demo/onboarding mode.' },\n { status: 403 },\n )\n }\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub || !auth.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n const url = new URL(req.url)\n const id = url.searchParams.get('id')\n const parsed = deleteSchema.safeParse({ id })\n if (!parsed.success) {\n return NextResponse.json({ error: 'Partition id is required' }, { status: 400 })\n }\n const em = await resolveEm()\n const entry = await findOneWithDecryption(\n em,\n AttachmentPartition,\n { id: parsed.data.id },\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId ?? null },\n )\n if (!entry || !canManagePartition(auth, entry)) {\n return NextResponse.json({ error: 'Partition not found' }, { status: 404 })\n }\n if (DEFAULT_CODES.has(entry.code)) {\n return NextResponse.json({ error: 'Default partitions cannot be removed.' }, { status: 400 })\n }\n const usageFilter: Record<string, unknown> = { partitionCode: entry.code }\n if (entry.tenantId) usageFilter.tenantId = entry.tenantId\n const usage = await em.count(Attachment, usageFilter)\n if (usage > 0) {\n return NextResponse.json({ error: 'Partition is in use and cannot be removed.' }, { status: 409 })\n }\n await em.remove(entry).flush()\n return NextResponse.json({ ok: true })\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: attachmentsTag,\n summary: 'Attachment partition management',\n methods: {\n GET: {\n summary: 'List all attachment partitions',\n description: 'Returns all configured attachment partitions with storage settings, OCR configuration, and access control settings.',\n responses: [\n { status: 200, description: 'List of partitions', schema: partitionListResponseSchema },\n ],\n errors: [\n { status: 401, description: 'Unauthorized', schema: attachmentErrorSchema },\n ],\n },\n POST: {\n summary: 'Create new partition',\n description: 'Creates a new attachment partition with specified storage and OCR settings. Requires unique partition code.',\n requestBody: {\n contentType: 'application/json',\n schema: partitionCreateSchema,\n },\n responses: [\n { status: 201, description: 'Partition created successfully', schema: partitionResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Invalid payload or partition code', schema: attachmentErrorSchema },\n { status: 401, description: 'Unauthorized', schema: attachmentErrorSchema },\n { status: 403, description: 'Partitions locked in demo mode', schema: attachmentErrorSchema },\n { status: 409, description: 'Partition code already exists', schema: attachmentErrorSchema },\n ],\n },\n PUT: {\n summary: 'Update partition',\n description: 'Updates an existing partition. Partition code cannot be changed. Title, description, OCR settings, and access control can be modified.',\n requestBody: {\n contentType: 'application/json',\n schema: partitionUpdateSchema,\n },\n responses: [\n { status: 200, description: 'Partition updated successfully', schema: partitionResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Invalid payload or code change attempt', schema: attachmentErrorSchema },\n { status: 401, description: 'Unauthorized', schema: attachmentErrorSchema },\n { status: 403, description: 'Partitions locked in demo mode', schema: attachmentErrorSchema },\n { status: 404, description: 'Partition not found', schema: attachmentErrorSchema },\n ],\n },\n DELETE: {\n summary: 'Delete partition',\n description: 'Deletes a partition. Default partitions cannot be deleted. Partitions with existing attachments cannot be deleted.',\n responses: [\n { status: 200, description: 'Partition deleted successfully', schema: z.object({ ok: z.literal(true) }) },\n ],\n errors: [\n { status: 400, description: 'Invalid ID or default partition deletion attempt', schema: attachmentErrorSchema },\n { status: 401, description: 'Unauthorized', schema: attachmentErrorSchema },\n { status: 403, description: 'Partitions locked in demo mode', schema: attachmentErrorSchema },\n { status: 404, description: 'Partition not found', schema: attachmentErrorSchema },\n { status: 409, description: 'Partition in use', schema: attachmentErrorSchema },\n ],\n },\n },\n}\n"],
5
5
  "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,YAAY,2BAA2B;AAChD,SAAS,yBAAyB,+BAA+B,uBAAuB,iCAAiC;AACzH,SAAS,8BAA8B;AAEvC,SAAS,0CAA0C;AACnD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,eAAe,EAAE,OAAO;AAAA,EAC5B,IAAI,EAAE,OAAO,EAAE,KAAK;AACtB,CAAC;AAED,MAAM,gBAAgB,IAAI,IAAI,8BAA8B,IAAI,CAAC,UAAU,MAAM,IAAI,CAAC;AAItF,SAAS,aAAa,MAAyB;AAC7C,SAAO,MAAM,iBAAiB;AAChC;AAEA,SAAS,mBAAmB,MAAgB,OAAqC;AAC/E,MAAI,CAAC,MAAM,SAAU,QAAO;AAC5B,MAAI,MAAM,YAAY,MAAM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AwB;AAAA,MAChG;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,0CAA0C,QAAQ,sBAAsB;AAAA,QACpG,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,sBAAsB;AAAA,QAC1E,EAAE,QAAQ,KAAK,aAAa,kCAAkC,QAAQ,sBAAsB;AAAA,QAC5F,EAAE,QAAQ,KAAK,aAAa,uBAAuB,QAAQ,sBAAsB;AAAA,MACnF;AAAA,IACF;AAAA,IACA,QAAQ;AAAA,MACN,SAAS;AAAA,MACT,aAAa;AAAA,MACb,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,kCAAkC,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,IAAI,EAAE,CAAC,EAAE;AAAA,MAC1G;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,oDAAoD,QAAQ,sBAAsB;AAAA,QAC9G,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,sBAAsB;AAAA,QAC1E,EAAE,QAAQ,KAAK,aAAa,kCAAkC,QAAQ,sBAAsB;AAAA,QAC5F,EAAE,QAAQ,KAAK,aAAa,uBAAuB,QAAQ,sBAAsB;AAAA,QACjF,EAAE,QAAQ,KAAK,aAAa,oBAAoB,QAAQ,sBAAsB;AAAA,MAChF;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -54,13 +54,15 @@ async function reconcileAttachmentOrganizations(opts) {
54
54
  for (let index = 0; index < recordIds.length; index += batchSize) {
55
55
  const chunk = recordIds.slice(index, index + batchSize);
56
56
  try {
57
- const result = await queryEngine.query(entityId, {
58
- fields: ["id", "organization_id"],
59
- filters: { id: chunk.length === 1 ? { $eq: chunk[0] } : { $in: chunk } },
60
- tenantId,
61
- withDeleted: true,
62
- page: { pageSize: Math.max(chunk.length, 1) }
63
- });
57
+ const result = await em.transactional(
58
+ async () => queryEngine.query(entityId, {
59
+ fields: ["id", "organization_id"],
60
+ filters: { id: chunk.length === 1 ? { $eq: chunk[0] } : { $in: chunk } },
61
+ tenantId,
62
+ withDeleted: true,
63
+ page: { pageSize: Math.max(chunk.length, 1) }
64
+ })
65
+ );
64
66
  for (const item of result.items ?? []) {
65
67
  const record = item;
66
68
  const recordId = record.id != null ? String(record.id) : null;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/attachments/lib/reconcileOrganization.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport type { QueryEngine } from '@open-mercato/shared/lib/query/types'\nimport { Attachment } from '../data/entities'\n\nconst logger = createLogger('attachments').child({ component: 'reconcileOrganization' })\n\n/**\n * Virtual entity id for library attachments \u2014 these are not attached to a\n * parent record that owns an organization, so there is nothing to reconcile\n * against. They are counted as skipped rather than unresolved.\n */\nconst LIBRARY_ENTITY_ID = 'attachments:library'\n\nconst DEFAULT_BATCH_SIZE = 500\n\nexport type AttachmentOrgReconcileEntityStat = {\n scanned: number\n updated: number\n unresolved: number\n}\n\nexport type AttachmentOrgReconcileReport = {\n scanned: number\n updated: number\n unresolved: number\n skippedVirtual: number\n byEntity: Record<string, AttachmentOrgReconcileEntityStat>\n}\n\ntype AttachmentScanRow = {\n id: string\n entity_id: string | null\n record_id: string | null\n organization_id: string | null\n}\n\nfunction readParentOrganizationId(record: Record<string, unknown>): string | null {\n const raw = record['organization_id'] ?? record['organizationId']\n if (typeof raw === 'string' && raw.trim().length) return raw.trim()\n return null\n}\n\nfunction ensureBucket(\n report: AttachmentOrgReconcileReport,\n entityId: string,\n): AttachmentOrgReconcileEntityStat {\n const existing = report.byEntity[entityId]\n if (existing) return existing\n const bucket: AttachmentOrgReconcileEntityStat = { scanned: 0, updated: 0, unresolved: 0 }\n report.byEntity[entityId] = bucket\n return bucket\n}\n\n/**\n * Reconcile the `organization_id` of existing attachments to the organization\n * of the record they are attached to.\n *\n * Background (#3765): before the upload route became selected-organization\n * aware, a multi-org admin who switched the header organization uploaded files\n * that were silently stored under their *home* organization instead of the\n * selected one (the organization of the parent record). Those rows are now\n * invisible to org-scoped reads and stay orphaned. This heals them forward.\n *\n * The parent record's organization is the ground truth: an attachment is not\n * distinguishable from a legitimately home-org one by looking at the attachment\n * alone. Parent organizations are resolved generically through the Query Engine\n * by `entityId` (works for both base and custom entities, tenant-scoped and\n * organization-agnostic so the parent's real org is returned regardless of\n * which org the caller sits in) \u2014 the same mechanism the attachments module\n * already uses to enrich assignment details.\n *\n * The reconciliation is:\n * - idempotent \u2014 rows already matching their parent are left untouched;\n * - conservative \u2014 when the parent org cannot be resolved (unregistered\n * entity id, hard-deleted parent, parent without an org column) the row is\n * counted as `unresolved` and left as-is rather than guessed at;\n * - tenant-scoped \u2014 it reconciles every attachment in the tenant across all\n * organizations (the whole point is moving rows between orgs).\n *\n * Writes go through the passed `EntityManager` (which the caller runs inside a\n * transaction) so the whole reconciliation commits atomically.\n */\nexport async function reconcileAttachmentOrganizations(opts: {\n em: EntityManager\n queryEngine: QueryEngine\n tenantId: string\n batchSize?: number\n}): Promise<AttachmentOrgReconcileReport> {\n const { em, queryEngine, tenantId } = opts\n const batchSize = opts.batchSize && opts.batchSize > 0 ? opts.batchSize : DEFAULT_BATCH_SIZE\n const report: AttachmentOrgReconcileReport = {\n scanned: 0,\n updated: 0,\n unresolved: 0,\n skippedVirtual: 0,\n byEntity: {},\n }\n\n const rows = (await em.getConnection().execute(\n 'select id, entity_id, record_id, organization_id from attachments where tenant_id = ?',\n [tenantId],\n )) as AttachmentScanRow[]\n report.scanned = rows.length\n if (!rows.length) return report\n\n const groups = new Map<string, AttachmentScanRow[]>()\n for (const row of rows) {\n if (!row.id || !row.entity_id || !row.record_id) continue\n const list = groups.get(row.entity_id) ?? []\n list.push(row)\n groups.set(row.entity_id, list)\n }\n\n const pendingUpdates: Array<{ id: string; organizationId: string }> = []\n\n for (const [entityId, group] of groups) {\n const bucket = ensureBucket(report, entityId)\n bucket.scanned += group.length\n\n if (entityId === LIBRARY_ENTITY_ID) {\n report.skippedVirtual += group.length\n continue\n }\n\n const recordIds = Array.from(\n new Set(group.map((row) => row.record_id).filter((value): value is string => !!value)),\n )\n const parentOrgByRecordId = new Map<string, string | null>()\n let resolvable = true\n\n for (let index = 0; index < recordIds.length; index += batchSize) {\n const chunk = recordIds.slice(index, index + batchSize)\n try {\n const result = await queryEngine.query(entityId as any, {\n fields: ['id', 'organization_id'],\n filters: { id: chunk.length === 1 ? { $eq: chunk[0] } : { $in: chunk } },\n tenantId,\n withDeleted: true,\n page: { pageSize: Math.max(chunk.length, 1) },\n })\n for (const item of result.items ?? []) {\n const record = item as Record<string, unknown>\n const recordId = record.id != null ? String(record.id) : null\n if (!recordId) continue\n parentOrgByRecordId.set(recordId, readParentOrganizationId(record))\n }\n } catch (error) {\n resolvable = false\n logger.warn('org reconcile: cannot resolve parent organization for entity', {\n entityId,\n error,\n })\n break\n }\n }\n\n if (!resolvable) {\n bucket.unresolved += group.length\n report.unresolved += group.length\n continue\n }\n\n for (const row of group) {\n const target = row.record_id ? parentOrgByRecordId.get(row.record_id) : null\n if (!target) {\n bucket.unresolved += 1\n report.unresolved += 1\n continue\n }\n if ((row.organization_id ?? null) === target) continue\n pendingUpdates.push({ id: row.id, organizationId: target })\n bucket.updated += 1\n report.updated += 1\n }\n }\n\n for (let index = 0; index < pendingUpdates.length; index += batchSize) {\n const chunk = pendingUpdates.slice(index, index + batchSize)\n for (const update of chunk) {\n const reference = em.getReference(Attachment, update.id)\n reference.organizationId = update.organizationId\n }\n await em.flush()\n }\n\n return report\n}\n"],
5
- "mappings": "AACA,SAAS,oBAAoB;AAE7B,SAAS,kBAAkB;AAE3B,MAAM,SAAS,aAAa,aAAa,EAAE,MAAM,EAAE,WAAW,wBAAwB,CAAC;AAOvF,MAAM,oBAAoB;AAE1B,MAAM,qBAAqB;AAuB3B,SAAS,yBAAyB,QAAgD;AAChF,QAA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,KAAK,EAAE,IAAI,IAAI,IAAI,gBAAgB,OAAO,CAAC;AAC1D,aAAO,WAAW;AAClB,aAAO,WAAW;AAAA,IACpB;AAAA,EACF;AAEA,WAAS,QAAQ,GAAG,QAAQ,eAAe,QAAQ,SAAS,WAAW;AACrE,UAAM,QAAQ,eAAe,MAAM,OAAO,QAAQ,SAAS;AAC3D,eAAW,UAAU,OAAO;AAC1B,YAAM,YAAY,GAAG,aAAa,YAAY,OAAO,EAAE;AACvD,gBAAU,iBAAiB,OAAO;AAAA,IACpC;AACA,UAAM,GAAG,MAAM;AAAA,EACjB;AAEA,SAAO;AACT;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport type { QueryEngine } from '@open-mercato/shared/lib/query/types'\nimport { Attachment } from '../data/entities'\n\nconst logger = createLogger('attachments').child({ component: 'reconcileOrganization' })\n\n/**\n * Virtual entity id for library attachments \u2014 these are not attached to a\n * parent record that owns an organization, so there is nothing to reconcile\n * against. They are counted as skipped rather than unresolved.\n */\nconst LIBRARY_ENTITY_ID = 'attachments:library'\n\nconst DEFAULT_BATCH_SIZE = 500\n\nexport type AttachmentOrgReconcileEntityStat = {\n scanned: number\n updated: number\n unresolved: number\n}\n\nexport type AttachmentOrgReconcileReport = {\n scanned: number\n updated: number\n unresolved: number\n skippedVirtual: number\n byEntity: Record<string, AttachmentOrgReconcileEntityStat>\n}\n\ntype AttachmentScanRow = {\n id: string\n entity_id: string | null\n record_id: string | null\n organization_id: string | null\n}\n\nfunction readParentOrganizationId(record: Record<string, unknown>): string | null {\n const raw = record['organization_id'] ?? record['organizationId']\n if (typeof raw === 'string' && raw.trim().length) return raw.trim()\n return null\n}\n\nfunction ensureBucket(\n report: AttachmentOrgReconcileReport,\n entityId: string,\n): AttachmentOrgReconcileEntityStat {\n const existing = report.byEntity[entityId]\n if (existing) return existing\n const bucket: AttachmentOrgReconcileEntityStat = { scanned: 0, updated: 0, unresolved: 0 }\n report.byEntity[entityId] = bucket\n return bucket\n}\n\n/**\n * Reconcile the `organization_id` of existing attachments to the organization\n * of the record they are attached to.\n *\n * Background (#3765): before the upload route became selected-organization\n * aware, a multi-org admin who switched the header organization uploaded files\n * that were silently stored under their *home* organization instead of the\n * selected one (the organization of the parent record). Those rows are now\n * invisible to org-scoped reads and stay orphaned. This heals them forward.\n *\n * The parent record's organization is the ground truth: an attachment is not\n * distinguishable from a legitimately home-org one by looking at the attachment\n * alone. Parent organizations are resolved generically through the Query Engine\n * by `entityId` (works for both base and custom entities, tenant-scoped and\n * organization-agnostic so the parent's real org is returned regardless of\n * which org the caller sits in) \u2014 the same mechanism the attachments module\n * already uses to enrich assignment details.\n *\n * The reconciliation is:\n * - idempotent \u2014 rows already matching their parent are left untouched;\n * - conservative \u2014 when the parent org cannot be resolved (unregistered\n * entity id, hard-deleted parent, parent without an org column) the row is\n * counted as `unresolved` and left as-is rather than guessed at;\n * - tenant-scoped \u2014 it reconciles every attachment in the tenant across all\n * organizations (the whole point is moving rows between orgs).\n *\n * Writes go through the passed `EntityManager` (which the caller runs inside a\n * transaction) so the whole reconciliation commits atomically.\n */\nexport async function reconcileAttachmentOrganizations(opts: {\n em: EntityManager\n queryEngine: QueryEngine\n tenantId: string\n batchSize?: number\n}): Promise<AttachmentOrgReconcileReport> {\n const { em, queryEngine, tenantId } = opts\n const batchSize = opts.batchSize && opts.batchSize > 0 ? opts.batchSize : DEFAULT_BATCH_SIZE\n const report: AttachmentOrgReconcileReport = {\n scanned: 0,\n updated: 0,\n unresolved: 0,\n skippedVirtual: 0,\n byEntity: {},\n }\n\n const rows = (await em.getConnection().execute(\n 'select id, entity_id, record_id, organization_id from attachments where tenant_id = ?',\n [tenantId],\n )) as AttachmentScanRow[]\n report.scanned = rows.length\n if (!rows.length) return report\n\n const groups = new Map<string, AttachmentScanRow[]>()\n for (const row of rows) {\n if (!row.id || !row.entity_id || !row.record_id) continue\n const list = groups.get(row.entity_id) ?? []\n list.push(row)\n groups.set(row.entity_id, list)\n }\n\n const pendingUpdates: Array<{ id: string; organizationId: string }> = []\n\n for (const [entityId, group] of groups) {\n const bucket = ensureBucket(report, entityId)\n bucket.scanned += group.length\n\n if (entityId === LIBRARY_ENTITY_ID) {\n report.skippedVirtual += group.length\n continue\n }\n\n const recordIds = Array.from(\n new Set(group.map((row) => row.record_id).filter((value): value is string => !!value)),\n )\n const parentOrgByRecordId = new Map<string, string | null>()\n let resolvable = true\n\n for (let index = 0; index < recordIds.length; index += batchSize) {\n const chunk = recordIds.slice(index, index + batchSize)\n try {\n // An unregistrable entity id makes the Query Engine emit SQL against a\n // non-existent relation, and a failed statement aborts the surrounding\n // Postgres transaction the caller runs this reconcile in \u2014 poisoning\n // the whole backfill (#4145). Running each resolution query inside a\n // nested transaction scopes the failure to a savepoint, so the catch\n // below can mark just this group unresolved while every other group\n // and the final flush keep working.\n const result = await em.transactional(async () =>\n queryEngine.query(entityId as any, {\n fields: ['id', 'organization_id'],\n filters: { id: chunk.length === 1 ? { $eq: chunk[0] } : { $in: chunk } },\n tenantId,\n withDeleted: true,\n page: { pageSize: Math.max(chunk.length, 1) },\n }),\n )\n for (const item of result.items ?? []) {\n const record = item as Record<string, unknown>\n const recordId = record.id != null ? String(record.id) : null\n if (!recordId) continue\n parentOrgByRecordId.set(recordId, readParentOrganizationId(record))\n }\n } catch (error) {\n resolvable = false\n logger.warn('org reconcile: cannot resolve parent organization for entity', {\n entityId,\n error,\n })\n break\n }\n }\n\n if (!resolvable) {\n bucket.unresolved += group.length\n report.unresolved += group.length\n continue\n }\n\n for (const row of group) {\n const target = row.record_id ? parentOrgByRecordId.get(row.record_id) : null\n if (!target) {\n bucket.unresolved += 1\n report.unresolved += 1\n continue\n }\n if ((row.organization_id ?? null) === target) continue\n pendingUpdates.push({ id: row.id, organizationId: target })\n bucket.updated += 1\n report.updated += 1\n }\n }\n\n for (let index = 0; index < pendingUpdates.length; index += batchSize) {\n const chunk = pendingUpdates.slice(index, index + batchSize)\n for (const update of chunk) {\n const reference = em.getReference(Attachment, update.id)\n reference.organizationId = update.organizationId\n }\n await em.flush()\n }\n\n return report\n}\n"],
5
+ "mappings": "AACA,SAAS,oBAAoB;AAE7B,SAAS,kBAAkB;AAE3B,MAAM,SAAS,aAAa,aAAa,EAAE,MAAM,EAAE,WAAW,wBAAwB,CAAC;AAOvF,MAAM,oBAAoB;AAE1B,MAAM,qBAAqB;AAuB3B,SAAS,yBAAyB,QAAgD;AAChF,QAAM,MAAM,OAAO,iBAAiB,KAAK,OAAO,gBAAgB;AAChE,MAAI,OAAO,QAAQ,YAAY,IAAI,KAAK,EAAE,OAAQ,QAAO,IAAI,KAAK;AAClE,SAAO;AACT;AAEA,SAAS,aACP,QACA,UACkC;AAClC,QAAM,WAAW,OAAO,SAAS,QAAQ;AACzC,MAAI,SAAU,QAAO;AACrB,QAAM,SAA2C,EAAE,SAAS,GAAG,SAAS,GAAG,YAAY,EAAE;AACzF,SAAO,SAAS,QAAQ,IAAI;AAC5B,SAAO;AACT;AA+BA,eAAsB,iCAAiC,MAKb;AACxC,QAAM,EAAE,IAAI,aAAa,SAAS,IAAI;AACtC,QAAM,YAAY,KAAK,aAAa,KAAK,YAAY,IAAI,KAAK,YAAY;AAC1E,QAAM,SAAuC;AAAA,IAC3C,SAAS;AAAA,IACT,SAAS;AAAA,IACT,YAAY;AAAA,IACZ,gBAAgB;AAAA,IAChB,UAAU,CAAC;AAAA,EACb;AAEA,QAAM,OAAQ,MAAM,GAAG,cAAc,EAAE;AAAA,IACrC;AAAA,IACA,CAAC,QAAQ;AAAA,EACX;AACA,SAAO,UAAU,KAAK;AACtB,MAAI,CAAC,KAAK,OAAQ,QAAO;AAEzB,QAAM,SAAS,oBAAI,IAAiC;AACpD,aAAW,OAAO,MAAM;AACtB,QAAI,CAAC,IAAI,MAAM,CAAC,IAAI,aAAa,CAAC,IAAI,UAAW;AACjD,UAAM,OAAO,OAAO,IAAI,IAAI,SAAS,KAAK,CAAC;AAC3C,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CAAC;AACD;AAAA,MACF;AAAA,IACF;AAEA,QAAI,CAAC,YAAY;AACf,aAAO,cAAc,MAAM;AAC3B,aAAO,cAAc,MAAM;AAC3B;AAAA,IACF;AAEA,eAAW,OAAO,OAAO;AACvB,YAAM,SAAS,IAAI,YAAY,oBAAoB,IAAI,IAAI,SAAS,IAAI;AACxE,UAAI,CAAC,QAAQ;AACX,eAAO,cAAc;AACrB,eAAO,cAAc;AACrB;AAAA,MACF;AACA,WAAK,IAAI,mBAAmB,UAAU,OAAQ;AAC9C,qBAAe,KAAK,EAAE,IAAI,IAAI,IAAI,gBAAgB,OAAO,CAAC;AAC1D,aAAO,WAAW;AAClB,aAAO,WAAW;AAAA,IACpB;AAAA,EACF;AAEA,WAAS,QAAQ,GAAG,QAAQ,eAAe,QAAQ,SAAS,WAAW;AACrE,UAAM,QAAQ,eAAe,MAAM,OAAO,QAAQ,SAAS;AAC3D,eAAW,UAAU,OAAO;AAC1B,YAAM,YAAY,GAAG,aAAa,YAAY,OAAO,EAAE;AACvD,gBAAU,iBAAiB,OAAO;AAAA,IACpC;AACA,UAAM,GAAG,MAAM;AAAA,EACjB;AAEA,SAAO;AACT;",
6
6
  "names": []
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/catalog/api/products/route.ts"],
4
- "sourcesContent": ["import { z } from \"zod\";\nimport type { EntityManager } from \"@mikro-orm/postgresql\";\nimport { makeCrudRoute } from \"@open-mercato/shared/lib/crud/factory\";\nimport { CrudHttpError } from \"@open-mercato/shared/lib/crud/errors\";\nimport {\n buildCustomFieldFiltersFromQuery,\n extractAllCustomFieldEntries,\n} from \"@open-mercato/shared/lib/crud/custom-fields\";\nimport { resolveTranslations } from \"@open-mercato/shared/lib/i18n/server\";\nimport {\n CatalogOffer,\n CatalogProduct,\n CatalogProductCategory,\n CatalogProductCategoryAssignment,\n CatalogProductPrice,\n CatalogProductUnitConversion,\n CatalogProductVariant,\n CatalogProductTagAssignment,\n} from \"../../data/entities\";\nimport { CATALOG_PRODUCT_TYPES } from \"../../data/types\";\nimport type { CatalogProductType } from \"../../data/types\";\nimport {\n productCreateSchema,\n productUpdateSchema,\n} from \"../../data/validators\";\nimport { parseScopedCommandInput, resolveCrudRecordId } from \"../utils\";\nimport { splitCustomFieldPayload } from \"@open-mercato/shared/lib/crud/custom-fields\";\nimport { E } from \"#generated/entities.ids.generated\";\nimport * as F from \"#generated/entities/catalog_product\";\nimport { parseBooleanFlag, sanitizeSearchTerm } from \"../helpers\";\nimport { escapeLikePattern } from \"@open-mercato/shared/lib/db/escapeLikePattern\";\nimport type { CrudCtx } from \"@open-mercato/shared/lib/crud/factory\";\nimport { buildScopedWhere } from \"@open-mercato/shared/lib/api/crud\";\nimport {\n resolvePriceChannelId,\n resolvePriceOfferId,\n resolvePriceVariantId,\n resolvePriceKindCode,\n type PricingContext,\n type PriceRow,\n} from \"../../lib/pricing\";\nimport type { CatalogPricingService } from \"../../services/catalogPricingService\";\nimport { fieldsetCodeRegex } from \"@open-mercato/core/modules/entities/data/validators\";\nimport { SalesChannel } from \"@open-mercato/core/modules/sales/data/entities\";\nimport {\n createCatalogCrudOpenApi,\n createPagedListResponseSchema,\n defaultOkResponseSchema,\n} from \"../openapi\";\nimport { findWithDecryption } from \"@open-mercato/shared/lib/encryption/find\";\nimport { canonicalizeUnitCode, toUnitLookupKey } from \"../../lib/unitCodes\";\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('catalog')\nconst rawBodySchema = z.object({}).passthrough();\n\nconst UUID_REGEX =\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/;\n\nconst listSchema = z\n .object({\n page: z.coerce.number().min(1).default(1),\n pageSize: z.coerce.number().min(1).max(100).default(50),\n id: z.string().uuid().optional(),\n search: z.string().optional(),\n status: z.string().optional(),\n isActive: z.string().optional(),\n configurable: z.string().optional(),\n productType: z.enum(CATALOG_PRODUCT_TYPES).optional(),\n channelIds: z.string().optional(),\n channelId: z.string().uuid().optional(),\n categoryIds: z.string().optional(),\n tagIds: z.string().optional(),\n offerId: z.string().uuid().optional(),\n userId: z.string().uuid().optional(),\n userGroupId: z.string().uuid().optional(),\n customerId: z.string().uuid().optional(),\n customerGroupId: z.string().uuid().optional(),\n quantity: z.coerce.number().min(1).max(100000).optional(),\n quantityUnit: z.string().trim().max(50).optional(),\n priceDate: z.string().optional(),\n sortField: z.string().optional(),\n sortDir: z.enum([\"asc\", \"desc\"]).optional(),\n withDeleted: z.coerce.boolean().optional(),\n customFieldset: z.string().regex(fieldsetCodeRegex).optional(),\n })\n .passthrough();\n\ntype ProductsQuery = z.infer<typeof listSchema>;\n\nconst routeMetadata = {\n GET: { requireAuth: true, requireFeatures: [\"catalog.products.view\"] },\n POST: { requireAuth: true, requireFeatures: [\"catalog.products.manage\"] },\n PUT: { requireAuth: true, requireFeatures: [\"catalog.products.manage\"] },\n DELETE: { requireAuth: true, requireFeatures: [\"catalog.products.manage\"] },\n};\n\nexport const metadata = routeMetadata;\n\nexport function parseIdList(raw?: string): string[] {\n if (!raw) return [];\n return raw\n .split(\",\")\n .map((value) => value.trim())\n .filter((value) => UUID_REGEX.test(value));\n}\n\nexport async function buildProductFilters(\n query: ProductsQuery,\n ctx: CrudCtx,\n): Promise<Record<string, unknown>> {\n const filters: Record<string, unknown> = {};\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const restrictedProductIds: { value: Set<string> | null } = { value: null };\n\n const intersectProductIds = (ids: string[]) => {\n const normalized = ids.filter(\n (id): id is string => typeof id === \"string\" && id.trim().length > 0,\n );\n const current = new Set(normalized);\n if (!current.size) {\n restrictedProductIds.value = new Set();\n return;\n }\n if (!restrictedProductIds.value) {\n restrictedProductIds.value = current;\n return;\n }\n restrictedProductIds.value = new Set(\n Array.from(restrictedProductIds.value).filter((id) => current.has(id)),\n );\n };\n\n const applyRestrictedProducts = () => {\n if (!restrictedProductIds.value) return;\n if (restrictedProductIds.value.size === 0) {\n filters.id = { $eq: \"00000000-0000-0000-0000-000000000000\" };\n return;\n }\n const ids = Array.from(restrictedProductIds.value);\n const existing = filters.id as Record<string, unknown> | undefined;\n if (existing && typeof existing === \"object\") {\n if (\n \"$eq\" in existing &&\n typeof (existing as { $eq?: unknown }).$eq === \"string\"\n ) {\n const target = (existing as { $eq: string }).$eq;\n if (!restrictedProductIds.value.has(target)) {\n filters.id = { $eq: \"00000000-0000-0000-0000-000000000000\" };\n }\n return;\n }\n if (\n \"$in\" in existing &&\n Array.isArray((existing as { $in?: unknown }).$in)\n ) {\n const subset = (existing as { $in: string[] }).$in.filter((id) =>\n restrictedProductIds.value!.has(id),\n );\n filters.id = subset.length\n ? { $in: subset }\n : { $eq: \"00000000-0000-0000-0000-000000000000\" };\n return;\n }\n }\n filters.id = ids.length === 1 ? { $eq: ids[0] } : { $in: ids };\n };\n if (query.id) {\n filters.id = { $eq: query.id };\n }\n if (query.status && query.status.trim()) {\n filters.status_entry_id = { $eq: query.status.trim() };\n }\n const active = parseBooleanFlag(query.isActive);\n if (active !== undefined) {\n filters.is_active = active;\n }\n const configurable = parseBooleanFlag(query.configurable);\n if (configurable !== undefined) {\n filters.is_configurable = configurable;\n }\n if (query.productType) {\n filters.product_type = { $eq: query.productType };\n }\n const scope = {\n organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n tenantId: ctx.auth?.tenantId ?? null,\n };\n const term = sanitizeSearchTerm(query.search);\n const channelFilterIds = parseIdList(query.channelIds);\n const categoryFilterIds = parseIdList(query.categoryIds);\n const tagFilterIds = parseIdList(query.tagIds);\n const customFieldset =\n typeof query.customFieldset === \"string\" &&\n query.customFieldset.trim().length\n ? query.customFieldset.trim()\n : null;\n const tenantId = ctx.auth?.tenantId ?? null;\n\n // These prequeries are independent \u2014 each only feeds the final product-id\n // intersection, none depends on another's result \u2014 so dispatch them together\n // instead of awaiting one after another (#3179). A task returns null when its\n // filter is inactive (intersection skipped) or the matched product-id list\n // (possibly empty) when active, preserving the \"active filter with no matches\n // => empty result\" behavior.\n const searchTask = async (): Promise<string[] | null> => {\n if (!term) return null;\n const like = `%${escapeLikePattern(term)}%`;\n const searchMatches = await findWithDecryption(\n em,\n CatalogProduct,\n {\n ...scope,\n ...(query.withDeleted ? {} : { deletedAt: null }),\n $or: [\n { title: { $ilike: like } },\n { subtitle: { $ilike: like } },\n { description: { $ilike: like } },\n { sku: { $ilike: like } },\n { handle: { $ilike: like } },\n ],\n },\n { fields: [\"id\"] },\n scope,\n );\n return searchMatches\n .map((product) => product.id)\n .filter((id): id is string => typeof id === \"string\" && id.length > 0);\n };\n\n const channelTask = async (): Promise<string[] | null> => {\n if (!channelFilterIds.length) return null;\n const offerRows = await findWithDecryption(\n em,\n CatalogOffer,\n {\n channelId: { $in: channelFilterIds },\n deletedAt: null,\n ...scope,\n },\n { fields: [\"id\", \"product\"] },\n scope,\n );\n return offerRows\n .map((offer) =>\n typeof offer.product === \"string\"\n ? offer.product\n : (offer.product?.id ?? null),\n )\n .filter((id): id is string => !!id);\n };\n\n const categoryTask = async (): Promise<string[] | null> => {\n if (!categoryFilterIds.length) return null;\n const assignments = await findWithDecryption(\n em,\n CatalogProductCategoryAssignment,\n { category: { $in: categoryFilterIds }, ...scope },\n { fields: [\"id\", \"product\"] },\n scope,\n );\n return assignments\n .map((assignment) =>\n typeof assignment.product === \"string\"\n ? assignment.product\n : (assignment.product?.id ?? null),\n )\n .filter((id): id is string => !!id);\n };\n\n const tagTask = async (): Promise<string[] | null> => {\n if (!tagFilterIds.length) return null;\n const assignments = await findWithDecryption(\n em,\n CatalogProductTagAssignment,\n { tag: { $in: tagFilterIds }, ...scope },\n { fields: [\"id\", \"product\"] },\n scope,\n );\n return assignments\n .map((assignment) =>\n typeof assignment.product === \"string\"\n ? assignment.product\n : (assignment.product?.id ?? null),\n )\n .filter((id): id is string => !!id);\n };\n\n const customFieldTask = async (): Promise<Record<string, unknown>> => {\n try {\n const scopedEm = ctx.container.resolve(\"em\") as EntityManager;\n return await buildCustomFieldFiltersFromQuery({\n entityIds: [E.catalog.catalog_product],\n query,\n em: scopedEm,\n tenantId,\n fieldset: customFieldset ?? undefined,\n });\n } catch (err) {\n // Custom field filter parsing may fail for non-existent or misconfigured fields.\n // Fall back to base filters to avoid blocking the product listing.\n logger.debug('catalog.products custom field filter error', { err });\n return {};\n }\n };\n\n const [searchIds, channelIds, categoryIds, tagIds, cfFilters] =\n await Promise.all([\n searchTask(),\n channelTask(),\n categoryTask(),\n tagTask(),\n customFieldTask(),\n ]);\n\n // Apply intersections in the original order; intersection is commutative, so\n // the result is identical to the previous sequential pass. An empty array is\n // still intersected (active filter that matched nothing); null is skipped.\n for (const productIds of [searchIds, channelIds, categoryIds, tagIds]) {\n if (productIds) intersectProductIds(productIds);\n }\n Object.assign(filters, cfFilters);\n applyRestrictedProducts();\n return filters;\n}\n\nexport function buildPricingContext(\n query: ProductsQuery,\n channelFallback: string | null,\n): PricingContext {\n const quantity = Number.isFinite(Number(query.quantity))\n ? Number(query.quantity)\n : 1;\n const parsedDate = query.priceDate ? new Date(query.priceDate) : new Date();\n const channelId = query.channelId ?? channelFallback ?? null;\n return {\n channelId,\n offerId: query.offerId ?? null,\n userId: query.userId ?? null,\n userGroupId: query.userGroupId ?? null,\n customerId: query.customerId ?? null,\n customerGroupId: query.customerGroupId ?? null,\n quantity: Number.isFinite(quantity) && quantity > 0 ? quantity : 1,\n date: Number.isNaN(parsedDate.getTime()) ? new Date() : parsedDate,\n };\n}\n\ntype ProductListItem = Record<string, unknown> & {\n id?: string;\n title?: string | null;\n subtitle?: string | null;\n description?: string | null;\n sku?: string | null;\n handle?: string | null;\n product_type?: CatalogProductType | null;\n primary_currency_code?: string | null;\n default_unit?: string | null;\n default_sales_unit?: string | null;\n default_sales_unit_quantity?: number | null;\n uom_rounding_scale?: number | null;\n uom_rounding_mode?: \"half_up\" | \"down\" | \"up\" | null;\n unit_price_enabled?: boolean | null;\n unit_price_reference_unit?: \"kg\" | \"l\" | \"m2\" | \"m3\" | \"pc\" | null;\n unit_price_base_quantity?: number | null;\n default_media_id?: string | null;\n default_media_url?: string | null;\n weight_value?: string | null;\n weightValue?: string | null;\n weight_unit?: string | null;\n weightUnit?: string | null;\n dimensions?: Record<string, unknown> | null;\n custom_fieldset_code?: string | null;\n option_schema_id?: string | null;\n offers?: Array<Record<string, unknown>>;\n channelIds?: string[];\n categories?: Array<Record<string, unknown>>;\n categoryIds?: string[];\n tags?: string[];\n};\n\nasync function decorateProductsAfterList(\n payload: { items?: ProductListItem[] },\n ctx: CrudCtx & { query: ProductsQuery },\n): Promise<void> {\n const items = Array.isArray(payload?.items) ? payload.items : [];\n if (!items.length) return;\n const productIds = items\n .map((item) => (typeof item.id === \"string\" ? item.id : null))\n .filter((id): id is string => !!id);\n if (!productIds.length) return;\n try {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const scope = {\n organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n tenantId: ctx.auth?.tenantId ?? null,\n };\n const offers = await findWithDecryption(\n em,\n CatalogOffer,\n { product: { $in: productIds }, deletedAt: null, ...scope },\n { orderBy: { createdAt: \"asc\" } },\n scope,\n );\n const channelIds = Array.from(\n new Set(\n offers\n .map((offer) => offer.channelId)\n .filter(\n (id): id is string => typeof id === \"string\" && id.length > 0,\n ),\n ),\n );\n const channelLookup = new Map<\n string,\n { name?: string | null; code?: string | null }\n >();\n if (channelIds.length) {\n const scopedChannelsWhere = buildScopedWhere(\n { id: { $in: channelIds } },\n {\n organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n organizationIds: Array.isArray(ctx.organizationIds)\n ? ctx.organizationIds\n : undefined,\n tenantId: ctx.auth?.tenantId ?? null,\n },\n );\n const channels = await findWithDecryption(em, SalesChannel, scopedChannelsWhere, {\n fields: [\"id\", \"name\", \"code\"],\n });\n for (const channel of channels) {\n channelLookup.set(channel.id, {\n name: channel.name,\n code: channel.code ?? null,\n });\n }\n }\n const offersByProduct = new Map<string, Array<Record<string, unknown>>>();\n for (const offer of offers) {\n const productId =\n typeof offer.product === \"string\"\n ? offer.product\n : (offer.product?.id ?? null);\n if (!productId) continue;\n const channelInfo = channelLookup.get(offer.channelId);\n const entry = offersByProduct.get(productId) ?? [];\n entry.push({\n id: offer.id,\n channelId: offer.channelId,\n channelName: channelInfo?.name ?? null,\n channelCode: channelInfo?.code ?? null,\n title: offer.title,\n description: offer.description ?? null,\n isActive: offer.isActive,\n defaultMediaId: offer.defaultMediaId ?? null,\n defaultMediaUrl: offer.defaultMediaUrl ?? null,\n metadata: offer.metadata ?? null,\n updatedAt:\n offer.updatedAt instanceof Date\n ? offer.updatedAt.toISOString()\n : (typeof offer.updatedAt === \"string\" ? offer.updatedAt : null),\n });\n offersByProduct.set(productId, entry);\n }\n\n const categoryAssignments = await findWithDecryption(\n em,\n CatalogProductCategoryAssignment,\n { product: { $in: productIds }, ...scope },\n { populate: [\"category\"], orderBy: { position: \"asc\" } },\n scope,\n );\n const parentIds = new Set<string>();\n for (const assignment of categoryAssignments) {\n const category =\n typeof assignment.category === \"string\"\n ? null\n : (assignment.category ?? null);\n if (!category) continue;\n const parentId = category.parentId ?? null;\n if (parentId) parentIds.add(parentId);\n }\n const parentCategories = parentIds.size\n ? await findWithDecryption(\n em,\n CatalogProductCategory,\n { id: { $in: Array.from(parentIds) }, ...scope },\n { fields: [\"id\", \"name\"] },\n scope,\n )\n : [];\n const parentNameById = new Map<string, string | null>();\n for (const parent of parentCategories) {\n parentNameById.set(parent.id, parent.name ?? null);\n }\n const categoriesByProduct = new Map<\n string,\n Array<{\n id: string;\n name: string | null;\n treePath: string | null;\n parentId: string | null;\n parentName: string | null;\n }>\n >();\n for (const assignment of categoryAssignments) {\n const productId =\n typeof assignment.product === \"string\"\n ? assignment.product\n : (assignment.product?.id ?? null);\n if (!productId) continue;\n const category =\n typeof assignment.category === \"string\"\n ? null\n : (assignment.category ?? null);\n if (!category) continue;\n const parentId = category.parentId ?? null;\n const parentName = parentId\n ? (parentNameById.get(parentId) ?? null)\n : null;\n const bucket = categoriesByProduct.get(productId) ?? [];\n bucket.push({\n id: category.id,\n name: category.name ?? null,\n treePath: category.treePath ?? null,\n parentId,\n parentName,\n });\n categoriesByProduct.set(productId, bucket);\n }\n\n const tagAssignments = await findWithDecryption(\n em,\n CatalogProductTagAssignment,\n { product: { $in: productIds } },\n { populate: [\"tag\"] },\n {\n tenantId: ctx.auth?.tenantId ?? null,\n organizationId: ctx.auth?.orgId ?? null,\n },\n );\n const tagsByProduct = new Map<string, string[]>();\n for (const assignment of tagAssignments) {\n const productId =\n typeof assignment.product === \"string\"\n ? assignment.product\n : (assignment.product?.id ?? null);\n if (!productId) continue;\n const tag =\n typeof assignment.tag === \"string\" ? null : (assignment.tag ?? null);\n if (!tag) continue;\n const label =\n typeof tag.label === \"string\" && tag.label.trim().length\n ? tag.label\n : null;\n if (!label) continue;\n const bucket = tagsByProduct.get(productId) ?? [];\n bucket.push(label);\n tagsByProduct.set(productId, bucket);\n }\n\n const variants = await findWithDecryption(\n em,\n CatalogProductVariant,\n { product: { $in: productIds }, deletedAt: null, ...scope },\n { fields: [\"id\", \"product\"] },\n scope,\n );\n const variantToProduct = new Map<string, string>();\n for (const variant of variants) {\n const productId =\n typeof variant.product === \"string\"\n ? variant.product\n : (variant.product?.id ?? null);\n if (!productId) continue;\n variantToProduct.set(variant.id, productId);\n }\n const variantIds = Array.from(variantToProduct.keys());\n const priceWhere =\n variantIds.length > 0\n ? {\n $or: [\n { product: { $in: productIds } },\n { variant: { $in: variantIds } },\n ],\n }\n : { product: { $in: productIds } };\n const priceRows = await findWithDecryption(\n em,\n CatalogProductPrice,\n { ...priceWhere, ...scope },\n { populate: [\"offer\", \"variant\", \"product\", \"priceKind\"] },\n scope,\n );\n const pricesByProduct = new Map<string, PriceRow[]>();\n for (const price of priceRows) {\n let productId: string | null = null;\n if (price.product) {\n productId =\n typeof price.product === \"string\"\n ? price.product\n : (price.product?.id ?? null);\n } else if (price.variant) {\n const variantId =\n typeof price.variant === \"string\" ? price.variant : price.variant.id;\n productId = variantToProduct.get(variantId) ?? null;\n }\n if (!productId) continue;\n const entry = pricesByProduct.get(productId) ?? [];\n entry.push(price);\n pricesByProduct.set(productId, entry);\n }\n\n const requestQuantityUnitKey = toUnitLookupKey(\n ctx.query.quantityUnit,\n );\n const conversionsByProduct = new Map<string, Map<string, number>>();\n const conversionOrganizationId =\n ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null;\n const conversionTenantId = ctx.auth?.tenantId ?? null;\n if (\n requestQuantityUnitKey &&\n productIds.length &&\n conversionOrganizationId &&\n conversionTenantId\n ) {\n const conversionRows = await findWithDecryption(\n em,\n CatalogProductUnitConversion,\n {\n product: { $in: productIds },\n organizationId: conversionOrganizationId,\n tenantId: conversionTenantId,\n deletedAt: null,\n isActive: true,\n },\n { fields: [\"id\", \"product\", \"unitCode\", \"toBaseFactor\"] },\n { organizationId: conversionOrganizationId, tenantId: conversionTenantId },\n );\n for (const row of conversionRows) {\n const productId =\n typeof row.product === \"string\"\n ? row.product\n : (row.product?.id ?? null);\n const unitKey = toUnitLookupKey(row.unitCode);\n const factor = Number(row.toBaseFactor);\n if (!productId || !unitKey || !Number.isFinite(factor) || factor <= 0)\n continue;\n const bucket =\n conversionsByProduct.get(productId) ?? new Map<string, number>();\n bucket.set(unitKey, factor);\n conversionsByProduct.set(productId, bucket);\n }\n }\n\n const channelFilterIds = parseIdList(ctx.query.channelIds);\n const channelContext =\n ctx.query.channelId ??\n (channelFilterIds.length === 1 ? channelFilterIds[0] : null);\n const pricingContext = buildPricingContext(ctx.query, channelContext);\n const pricingService = ctx.container.resolve<CatalogPricingService>(\n \"catalogPricingService\",\n );\n\n const pricingEntries: Array<{ rows: PriceRow[]; context: PricingContext } | null> = [];\n for (const item of items) {\n const id = typeof item.id === \"string\" ? item.id : null;\n if (!id) {\n pricingEntries.push(null);\n continue;\n }\n const offerEntries = offersByProduct.get(id) ?? [];\n item.offers = offerEntries;\n const channelIds = Array.from(\n new Set(\n offerEntries\n .map((offer) =>\n typeof offer.channelId === \"string\" ? offer.channelId : null,\n )\n .filter((channelId): channelId is string => !!channelId),\n ),\n );\n item.channelIds = channelIds;\n const categories = categoriesByProduct.get(id) ?? [];\n item.categories = categories;\n item.categoryIds = categories.map((category) => category.id);\n item.tags = tagsByProduct.get(id) ?? [];\n if (item.is_quote_only === true) {\n item.pricing = null;\n pricingEntries.push(null);\n continue;\n }\n const priceCandidates = pricesByProduct.get(id) ?? [];\n const normalizedQuantityForPricing = (() => {\n if (!requestQuantityUnitKey) return pricingContext.quantity;\n const baseUnit = toUnitLookupKey(item.default_unit);\n if (!baseUnit || requestQuantityUnitKey === baseUnit)\n return pricingContext.quantity;\n const productConversions = conversionsByProduct.get(id);\n const factor = productConversions?.get(requestQuantityUnitKey) ?? null;\n if (!factor || !Number.isFinite(factor) || factor <= 0) {\n logger.debug('catalog.products invalid conversion factor', { productId: id, unit: requestQuantityUnitKey, factor });\n return pricingContext.quantity;\n }\n const normalized = pricingContext.quantity * factor;\n return Number.isFinite(normalized) && normalized > 0\n ? normalized\n : pricingContext.quantity;\n })();\n const channelScopedContext =\n pricingContext.channelId || channelIds.length !== 1\n ? pricingContext\n : { ...pricingContext, channelId: channelIds[0] };\n pricingEntries.push({\n rows: priceCandidates,\n context: { ...channelScopedContext, quantity: normalizedQuantityForPricing },\n });\n }\n\n const resolveInputs: Array<{ rows: PriceRow[]; context: PricingContext }> = [];\n const resolveIndices: number[] = [];\n for (let i = 0; i < pricingEntries.length; i++) {\n if (pricingEntries[i] !== null) {\n resolveInputs.push(pricingEntries[i]!);\n resolveIndices.push(i);\n }\n }\n const priceResults = await pricingService.resolvePriceMany(resolveInputs);\n\n for (let i = 0; i < resolveIndices.length; i++) {\n const item = items[resolveIndices[i]];\n const best = priceResults[i];\n if (best) {\n item.pricing = {\n kind: resolvePriceKindCode(best),\n price_kind_id:\n typeof best.priceKind === \"string\"\n ? best.priceKind\n : (best.priceKind?.id ?? null),\n price_kind_code: resolvePriceKindCode(best),\n currency_code: best.currencyCode,\n unit_price_net: best.unitPriceNet,\n unit_price_gross: best.unitPriceGross,\n min_quantity: best.minQuantity,\n max_quantity: best.maxQuantity ?? null,\n tax_rate: best.taxRate ?? null,\n tax_amount: best.taxAmount ?? null,\n scope: {\n variant_id: resolvePriceVariantId(best),\n offer_id: resolvePriceOfferId(best),\n channel_id: resolvePriceChannelId(best),\n user_id: best.userId ?? null,\n user_group_id: best.userGroupId ?? null,\n customer_id: best.customerId ?? null,\n customer_group_id: best.customerGroupId ?? null,\n },\n };\n } else {\n item.pricing = null;\n }\n }\n } catch (error) {\n logger.error('decorateProductsAfterList Failed to load unit conversions', { err: error });\n }\n\n const searchTerm = ctx.query.search ? sanitizeSearchTerm(ctx.query.search) : null;\n if (searchTerm && !ctx.query.sortField && Array.isArray(payload.items)) {\n const needle = searchTerm.toLowerCase();\n payload.items.sort((a, b) => {\n const scoreA = scoreProductSearchRelevance(needle, a.title, a.sku);\n const scoreB = scoreProductSearchRelevance(needle, b.title, b.sku);\n if (scoreA !== scoreB) return scoreA - scoreB;\n return (a.title ?? \"\").localeCompare(b.title ?? \"\");\n });\n }\n}\n\nexport function scoreProductSearchRelevance(\n needle: string,\n title: string | null | undefined,\n sku: string | null | undefined,\n): number {\n const t = (title ?? \"\").toLowerCase();\n const s = (sku ?? \"\").toLowerCase();\n if (t === needle) return 0;\n if (s === needle) return 1;\n if (t.startsWith(needle)) return 2;\n if (s.startsWith(needle)) return 3;\n if (t.includes(needle)) return 4;\n if (s.includes(needle)) return 5;\n return 6;\n}\n\nconst crud = makeCrudRoute({\n metadata: routeMetadata,\n orm: {\n entity: CatalogProduct,\n idField: \"id\",\n orgField: \"organizationId\",\n tenantField: \"tenantId\",\n softDeleteField: \"deletedAt\",\n },\n indexer: {\n entityType: E.catalog.catalog_product,\n },\n list: {\n schema: listSchema,\n entityId: E.catalog.catalog_product,\n fields: [\n F.id,\n F.title,\n F.subtitle,\n F.description,\n F.sku,\n F.handle,\n \"tax_rate_id\",\n \"tax_rate\",\n F.product_type,\n F.status_entry_id,\n F.primary_currency_code,\n F.default_unit,\n \"default_sales_unit\",\n \"default_sales_unit_quantity\",\n \"uom_rounding_scale\",\n \"uom_rounding_mode\",\n \"unit_price_enabled\",\n \"unit_price_reference_unit\",\n \"unit_price_base_quantity\",\n F.default_media_id,\n F.default_media_url,\n F.weight_value,\n F.weight_unit,\n F.dimensions,\n F.is_configurable,\n F.is_active,\n \"country_of_origin_code\",\n \"pkwiu_code\",\n \"cn_code\",\n \"hs_code\",\n \"tax_classification_code\",\n \"gtu_codes\",\n \"age_min\",\n \"is_excise_good\",\n \"excise_category\",\n \"requires_prescription\",\n \"hazmat_class\",\n \"un_number\",\n \"hazmat_packing_group\",\n \"contains_lithium_battery\",\n \"launch_at\",\n \"end_of_life_at\",\n \"available_from\",\n \"available_until\",\n \"min_order_qty\",\n \"max_order_qty\",\n \"order_qty_increment\",\n \"requires_shipping\",\n \"is_quote_only\",\n \"seo_title\",\n \"seo_description\",\n \"canonical_url\",\n F.metadata,\n \"custom_fieldset_code\",\n \"option_schema_id\",\n F.created_at,\n F.updated_at,\n ],\n decorateCustomFields: { entityIds: [E.catalog.catalog_product] },\n sortFieldMap: {\n title: F.title,\n sku: F.sku,\n createdAt: F.created_at,\n updatedAt: F.updated_at,\n },\n buildFilters: buildProductFilters,\n transformItem: (item: ProductListItem | null | undefined) => {\n if (!item) return item;\n const normalized = { ...item };\n const cfEntries = extractAllCustomFieldEntries(item);\n for (const key of Object.keys(normalized)) {\n if (key.startsWith(\"cf:\")) {\n delete normalized[key];\n }\n }\n const defaultUnit = canonicalizeUnitCode(normalized.default_unit) ?? null;\n const defaultSalesUnit =\n canonicalizeUnitCode(normalized.default_sales_unit) ?? null;\n const unitPriceReferenceUnit =\n canonicalizeUnitCode(normalized.unit_price_reference_unit) ?? null;\n return {\n ...normalized,\n default_unit: defaultUnit,\n default_sales_unit: defaultSalesUnit,\n unit_price_reference_unit: unitPriceReferenceUnit,\n ...cfEntries,\n unit_price: {\n enabled: Boolean(normalized.unit_price_enabled),\n reference_unit: unitPriceReferenceUnit,\n base_quantity: normalized.unit_price_base_quantity ?? null,\n },\n };\n },\n },\n hooks: {\n afterList: decorateProductsAfterList,\n },\n actions: {\n create: {\n commandId: \"catalog.products.create\",\n schema: rawBodySchema,\n mapInput: async ({ raw, ctx }) => {\n const { translate } = await resolveTranslations();\n const parsed = parseScopedCommandInput(\n productCreateSchema,\n raw ?? {},\n ctx,\n translate,\n );\n const { base, custom } = splitCustomFieldPayload(parsed);\n return Object.keys(custom).length\n ? { ...base, customFields: custom }\n : base;\n },\n response: ({ result }) => ({\n id: result?.productId ?? result?.id ?? null,\n }),\n status: 201,\n },\n update: {\n commandId: \"catalog.products.update\",\n schema: rawBodySchema,\n mapInput: async ({ raw, ctx }) => {\n const { translate } = await resolveTranslations();\n const parsed = parseScopedCommandInput(\n productUpdateSchema,\n raw ?? {},\n ctx,\n translate,\n );\n const { base, custom } = splitCustomFieldPayload(parsed);\n return Object.keys(custom).length\n ? { ...base, customFields: custom }\n : base;\n },\n response: () => ({ ok: true }),\n },\n delete: {\n commandId: \"catalog.products.delete\",\n schema: rawBodySchema,\n mapInput: async ({ parsed, ctx }) => {\n const { translate } = await resolveTranslations();\n const id = resolveCrudRecordId(parsed, ctx, translate);\n if (!id)\n throw new CrudHttpError(400, {\n error: translate(\n \"catalog.errors.id_required\",\n \"Product id is required.\",\n ),\n });\n return { id };\n },\n response: () => ({ ok: true }),\n },\n },\n});\n\nexport const GET = crud.GET;\nexport const POST = crud.POST;\nexport const PUT = crud.PUT;\nexport const DELETE = crud.DELETE;\n\nconst productListItemSchema = z.object({\n id: z.string().uuid(),\n title: z.string().nullable().optional(),\n subtitle: z.string().nullable().optional(),\n description: z.string().nullable().optional(),\n sku: z.string().nullable().optional(),\n handle: z.string().nullable().optional(),\n product_type: z.string().nullable().optional(),\n status_entry_id: z.string().uuid().nullable().optional(),\n primary_currency_code: z.string().nullable().optional(),\n default_unit: z.string().nullable().optional(),\n default_sales_unit: z.string().nullable().optional(),\n default_sales_unit_quantity: z.number().nullable().optional(),\n uom_rounding_scale: z.number().nullable().optional(),\n uom_rounding_mode: z.enum([\"half_up\", \"down\", \"up\"]).nullable().optional(),\n unit_price_enabled: z.boolean().nullable().optional(),\n unit_price_reference_unit: z\n .enum([\"kg\", \"l\", \"m2\", \"m3\", \"pc\"])\n .nullable()\n .optional(),\n unit_price_base_quantity: z.number().nullable().optional(),\n unit_price: z\n .object({\n enabled: z.boolean(),\n reference_unit: z.enum([\"kg\", \"l\", \"m2\", \"m3\", \"pc\"]).nullable(),\n base_quantity: z.number().nullable(),\n })\n .optional(),\n default_media_id: z.string().uuid().nullable().optional(),\n default_media_url: z.string().nullable().optional(),\n weight_value: z.number().nullable().optional(),\n weight_unit: z.string().nullable().optional(),\n dimensions: z.record(z.string(), z.unknown()).nullable().optional(),\n is_configurable: z.boolean().nullable().optional(),\n is_active: z.boolean().nullable().optional(),\n country_of_origin_code: z.string().nullable().optional(),\n pkwiu_code: z.string().nullable().optional(),\n cn_code: z.string().nullable().optional(),\n hs_code: z.string().nullable().optional(),\n tax_classification_code: z.string().nullable().optional(),\n gtu_codes: z.array(z.string()).nullable().optional(),\n age_min: z.number().nullable().optional(),\n is_excise_good: z.boolean().nullable().optional(),\n excise_category: z.string().nullable().optional(),\n requires_prescription: z.boolean().nullable().optional(),\n hazmat_class: z.string().nullable().optional(),\n un_number: z.string().nullable().optional(),\n hazmat_packing_group: z.string().nullable().optional(),\n contains_lithium_battery: z.boolean().nullable().optional(),\n launch_at: z.string().nullable().optional(),\n end_of_life_at: z.string().nullable().optional(),\n available_from: z.string().nullable().optional(),\n available_until: z.string().nullable().optional(),\n min_order_qty: z.number().nullable().optional(),\n max_order_qty: z.number().nullable().optional(),\n order_qty_increment: z.number().nullable().optional(),\n requires_shipping: z.boolean().nullable().optional(),\n is_quote_only: z.boolean().nullable().optional(),\n seo_title: z.string().nullable().optional(),\n seo_description: z.string().nullable().optional(),\n canonical_url: z.string().nullable().optional(),\n metadata: z.record(z.string(), z.unknown()).nullable().optional(),\n custom_fieldset_code: z.string().nullable().optional(),\n option_schema_id: z.string().uuid().nullable().optional(),\n created_at: z.string().nullable().optional(),\n updated_at: z.string().nullable().optional(),\n offers: z.array(z.record(z.string(), z.unknown())).optional(),\n channelIds: z.array(z.string()).optional(),\n categories: z.array(z.record(z.string(), z.unknown())).optional(),\n categoryIds: z.array(z.string()).optional(),\n tags: z.array(z.string()).optional(),\n pricing: z.record(z.string(), z.unknown()).nullable().optional(),\n});\n\nexport const openApi = createCatalogCrudOpenApi({\n resourceName: \"Product\",\n pluralName: \"Products\",\n querySchema: listSchema,\n listResponseSchema: createPagedListResponseSchema(productListItemSchema),\n create: {\n schema: productCreateSchema,\n description: \"Creates a new product in the catalog.\",\n },\n update: {\n schema: productUpdateSchema,\n responseSchema: defaultOkResponseSchema,\n description: \"Updates an existing product by id.\",\n },\n del: {\n schema: z.object({ id: z.string().uuid() }),\n responseSchema: defaultOkResponseSchema,\n description: \"Deletes a product by id.\",\n },\n});\n"],
4
+ "sourcesContent": ["import { z } from \"zod\";\nimport type { EntityManager } from \"@mikro-orm/postgresql\";\nimport { makeCrudRoute } from \"@open-mercato/shared/lib/crud/factory\";\nimport { CrudHttpError } from \"@open-mercato/shared/lib/crud/errors\";\nimport {\n buildCustomFieldFiltersFromQuery,\n extractAllCustomFieldEntries,\n} from \"@open-mercato/shared/lib/crud/custom-fields\";\nimport { resolveTranslations } from \"@open-mercato/shared/lib/i18n/server\";\nimport {\n CatalogOffer,\n CatalogProduct,\n CatalogProductCategory,\n CatalogProductCategoryAssignment,\n CatalogProductPrice,\n CatalogProductUnitConversion,\n CatalogProductVariant,\n CatalogProductTagAssignment,\n} from \"../../data/entities\";\nimport { CATALOG_PRODUCT_TYPES } from \"../../data/types\";\nimport type { CatalogProductType } from \"../../data/types\";\nimport {\n productCreateSchema,\n productUpdateSchema,\n} from \"../../data/validators\";\nimport { parseScopedCommandInput, resolveCrudRecordId } from \"../utils\";\nimport { splitCustomFieldPayload } from \"@open-mercato/shared/lib/crud/custom-fields\";\nimport { E } from \"#generated/entities.ids.generated\";\nimport * as F from \"#generated/entities/catalog_product\";\nimport { parseBooleanFlag, sanitizeSearchTerm } from \"../helpers\";\nimport { escapeLikePattern } from \"@open-mercato/shared/lib/db/escapeLikePattern\";\nimport type { CrudCtx } from \"@open-mercato/shared/lib/crud/factory\";\nimport { buildScopedWhere } from \"@open-mercato/shared/lib/api/crud\";\nimport {\n resolvePriceChannelId,\n resolvePriceOfferId,\n resolvePriceVariantId,\n resolvePriceKindCode,\n type PricingContext,\n type PriceRow,\n} from \"../../lib/pricing\";\nimport type { CatalogPricingService } from \"../../services/catalogPricingService\";\nimport { fieldsetCodeRegex } from \"@open-mercato/core/modules/entities/data/validators\";\nimport { SalesChannel } from \"@open-mercato/core/modules/sales/data/entities\";\nimport {\n createCatalogCrudOpenApi,\n createPagedListResponseSchema,\n defaultOkResponseSchema,\n} from \"../openapi\";\nimport { findWithDecryption } from \"@open-mercato/shared/lib/encryption/find\";\nimport { canonicalizeUnitCode, toUnitLookupKey } from \"../../lib/unitCodes\";\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('catalog')\nconst rawBodySchema = z.object({}).passthrough();\n\nconst UUID_REGEX =\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/;\n\nconst listSchema = z\n .object({\n page: z.coerce.number().min(1).default(1),\n pageSize: z.coerce.number().min(1).max(100).default(50),\n id: z.string().uuid().optional(),\n search: z.string().optional(),\n status: z.string().optional(),\n isActive: z.string().optional(),\n configurable: z.string().optional(),\n productType: z.enum(CATALOG_PRODUCT_TYPES).optional(),\n channelIds: z.string().optional(),\n channelId: z.string().uuid().optional(),\n categoryIds: z.string().optional(),\n tagIds: z.string().optional(),\n offerId: z.string().uuid().optional(),\n userId: z.string().uuid().optional(),\n userGroupId: z.string().uuid().optional(),\n customerId: z.string().uuid().optional(),\n customerGroupId: z.string().uuid().optional(),\n quantity: z.coerce.number().min(1).max(100000).optional(),\n quantityUnit: z.string().trim().max(50).optional(),\n priceDate: z.string().optional(),\n sortField: z.string().optional(),\n sortDir: z.enum([\"asc\", \"desc\"]).optional(),\n withDeleted: z.coerce.boolean().optional(),\n customFieldset: z.string().regex(fieldsetCodeRegex).optional(),\n })\n .passthrough();\n\ntype ProductsQuery = z.infer<typeof listSchema>;\n\nconst routeMetadata = {\n GET: { requireAuth: true, requireFeatures: [\"catalog.products.view\"] },\n POST: { requireAuth: true, requireFeatures: [\"catalog.products.manage\"] },\n PUT: { requireAuth: true, requireFeatures: [\"catalog.products.manage\"] },\n DELETE: { requireAuth: true, requireFeatures: [\"catalog.products.manage\"] },\n};\n\nexport const metadata = routeMetadata;\n\nexport function parseIdList(raw?: string): string[] {\n if (!raw) return [];\n return raw\n .split(\",\")\n .map((value) => value.trim())\n .filter((value) => UUID_REGEX.test(value));\n}\n\nexport async function buildProductFilters(\n query: ProductsQuery,\n ctx: CrudCtx,\n): Promise<Record<string, unknown>> {\n const filters: Record<string, unknown> = {};\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const restrictedProductIds: { value: Set<string> | null } = { value: null };\n\n const intersectProductIds = (ids: string[]) => {\n const normalized = ids.filter(\n (id): id is string => typeof id === \"string\" && id.trim().length > 0,\n );\n const current = new Set(normalized);\n if (!current.size) {\n restrictedProductIds.value = new Set();\n return;\n }\n if (!restrictedProductIds.value) {\n restrictedProductIds.value = current;\n return;\n }\n restrictedProductIds.value = new Set(\n Array.from(restrictedProductIds.value).filter((id) => current.has(id)),\n );\n };\n\n const applyRestrictedProducts = () => {\n if (!restrictedProductIds.value) return;\n if (restrictedProductIds.value.size === 0) {\n filters.id = { $eq: \"00000000-0000-0000-0000-000000000000\" };\n return;\n }\n const ids = Array.from(restrictedProductIds.value);\n const existing = filters.id as Record<string, unknown> | undefined;\n if (existing && typeof existing === \"object\") {\n if (\n \"$eq\" in existing &&\n typeof (existing as { $eq?: unknown }).$eq === \"string\"\n ) {\n const target = (existing as { $eq: string }).$eq;\n if (!restrictedProductIds.value.has(target)) {\n filters.id = { $eq: \"00000000-0000-0000-0000-000000000000\" };\n }\n return;\n }\n if (\n \"$in\" in existing &&\n Array.isArray((existing as { $in?: unknown }).$in)\n ) {\n const subset = (existing as { $in: string[] }).$in.filter((id) =>\n restrictedProductIds.value!.has(id),\n );\n filters.id = subset.length\n ? { $in: subset }\n : { $eq: \"00000000-0000-0000-0000-000000000000\" };\n return;\n }\n }\n filters.id = ids.length === 1 ? { $eq: ids[0] } : { $in: ids };\n };\n if (query.id) {\n filters.id = { $eq: query.id };\n }\n if (query.status && query.status.trim()) {\n filters.status_entry_id = { $eq: query.status.trim() };\n }\n const active = parseBooleanFlag(query.isActive);\n if (active !== undefined) {\n filters.is_active = active;\n }\n const configurable = parseBooleanFlag(query.configurable);\n if (configurable !== undefined) {\n filters.is_configurable = configurable;\n }\n if (query.productType) {\n filters.product_type = { $eq: query.productType };\n }\n const scope = {\n organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n tenantId: ctx.auth?.tenantId ?? null,\n };\n const term = sanitizeSearchTerm(query.search);\n const channelFilterIds = parseIdList(query.channelIds);\n const categoryFilterIds = parseIdList(query.categoryIds);\n const tagFilterIds = parseIdList(query.tagIds);\n const customFieldset =\n typeof query.customFieldset === \"string\" &&\n query.customFieldset.trim().length\n ? query.customFieldset.trim()\n : null;\n const tenantId = ctx.auth?.tenantId ?? null;\n\n // These prequeries are independent \u2014 each only feeds the final product-id\n // intersection, none depends on another's result \u2014 so dispatch them together\n // instead of awaiting one after another (#3179). A task returns null when its\n // filter is inactive (intersection skipped) or the matched product-id list\n // (possibly empty) when active, preserving the \"active filter with no matches\n // => empty result\" behavior.\n const searchTask = async (): Promise<string[] | null> => {\n if (!term) return null;\n const like = `%${escapeLikePattern(term)}%`;\n const searchMatches = await findWithDecryption(\n em,\n CatalogProduct,\n {\n ...scope,\n ...(query.withDeleted ? {} : { deletedAt: null }),\n $or: [\n { title: { $ilike: like } },\n { subtitle: { $ilike: like } },\n { description: { $ilike: like } },\n { sku: { $ilike: like } },\n { handle: { $ilike: like } },\n ],\n },\n { fields: [\"id\"] },\n scope,\n );\n return searchMatches\n .map((product) => product.id)\n .filter((id): id is string => typeof id === \"string\" && id.length > 0);\n };\n\n const channelTask = async (): Promise<string[] | null> => {\n if (!channelFilterIds.length) return null;\n const offerRows = await findWithDecryption(\n em,\n CatalogOffer,\n {\n channelId: { $in: channelFilterIds },\n deletedAt: null,\n ...scope,\n },\n { fields: [\"id\", \"product\"] },\n scope,\n );\n return offerRows\n .map((offer) =>\n typeof offer.product === \"string\"\n ? offer.product\n : (offer.product?.id ?? null),\n )\n .filter((id): id is string => !!id);\n };\n\n const categoryTask = async (): Promise<string[] | null> => {\n if (!categoryFilterIds.length) return null;\n const assignments = await findWithDecryption(\n em,\n CatalogProductCategoryAssignment,\n { category: { $in: categoryFilterIds }, ...scope },\n { fields: [\"id\", \"product\"] },\n scope,\n );\n return assignments\n .map((assignment) =>\n typeof assignment.product === \"string\"\n ? assignment.product\n : (assignment.product?.id ?? null),\n )\n .filter((id): id is string => !!id);\n };\n\n const tagTask = async (): Promise<string[] | null> => {\n if (!tagFilterIds.length) return null;\n const assignments = await findWithDecryption(\n em,\n CatalogProductTagAssignment,\n { tag: { $in: tagFilterIds }, ...scope },\n { fields: [\"id\", \"product\"] },\n scope,\n );\n return assignments\n .map((assignment) =>\n typeof assignment.product === \"string\"\n ? assignment.product\n : (assignment.product?.id ?? null),\n )\n .filter((id): id is string => !!id);\n };\n\n const customFieldTask = async (): Promise<Record<string, unknown>> => {\n try {\n const scopedEm = ctx.container.resolve(\"em\") as EntityManager;\n return await buildCustomFieldFiltersFromQuery({\n entityIds: [E.catalog.catalog_product],\n query,\n em: scopedEm,\n tenantId,\n fieldset: customFieldset ?? undefined,\n });\n } catch (err) {\n // Custom field filter parsing may fail for non-existent or misconfigured fields.\n // Fall back to base filters to avoid blocking the product listing.\n logger.debug('catalog.products custom field filter error', { err });\n return {};\n }\n };\n\n const [searchIds, channelIds, categoryIds, tagIds, cfFilters] =\n await Promise.all([\n searchTask(),\n channelTask(),\n categoryTask(),\n tagTask(),\n customFieldTask(),\n ]);\n\n // Apply intersections in the original order; intersection is commutative, so\n // the result is identical to the previous sequential pass. An empty array is\n // still intersected (active filter that matched nothing); null is skipped.\n for (const productIds of [searchIds, channelIds, categoryIds, tagIds]) {\n if (productIds) intersectProductIds(productIds);\n }\n Object.assign(filters, cfFilters);\n applyRestrictedProducts();\n return filters;\n}\n\nexport function buildPricingContext(\n query: ProductsQuery,\n channelFallback: string | null,\n): PricingContext {\n const quantity = Number.isFinite(Number(query.quantity))\n ? Number(query.quantity)\n : 1;\n const parsedDate = query.priceDate ? new Date(query.priceDate) : new Date();\n const channelId = query.channelId ?? channelFallback ?? null;\n return {\n channelId,\n offerId: query.offerId ?? null,\n userId: query.userId ?? null,\n userGroupId: query.userGroupId ?? null,\n customerId: query.customerId ?? null,\n customerGroupId: query.customerGroupId ?? null,\n quantity: Number.isFinite(quantity) && quantity > 0 ? quantity : 1,\n date: Number.isNaN(parsedDate.getTime()) ? new Date() : parsedDate,\n };\n}\n\ntype ProductListItem = Record<string, unknown> & {\n id?: string;\n title?: string | null;\n subtitle?: string | null;\n description?: string | null;\n sku?: string | null;\n handle?: string | null;\n product_type?: CatalogProductType | null;\n primary_currency_code?: string | null;\n default_unit?: string | null;\n default_sales_unit?: string | null;\n default_sales_unit_quantity?: number | null;\n uom_rounding_scale?: number | null;\n uom_rounding_mode?: \"half_up\" | \"down\" | \"up\" | null;\n unit_price_enabled?: boolean | null;\n unit_price_reference_unit?: \"kg\" | \"l\" | \"m2\" | \"m3\" | \"pc\" | null;\n unit_price_base_quantity?: number | null;\n default_media_id?: string | null;\n default_media_url?: string | null;\n weight_value?: string | null;\n weightValue?: string | null;\n weight_unit?: string | null;\n weightUnit?: string | null;\n dimensions?: Record<string, unknown> | null;\n custom_fieldset_code?: string | null;\n option_schema_id?: string | null;\n offers?: Array<Record<string, unknown>>;\n channelIds?: string[];\n categories?: Array<Record<string, unknown>>;\n categoryIds?: string[];\n tags?: string[];\n};\n\nasync function decorateProductsAfterList(\n payload: { items?: ProductListItem[] },\n ctx: CrudCtx & { query: ProductsQuery },\n): Promise<void> {\n const items = Array.isArray(payload?.items) ? payload.items : [];\n if (!items.length) return;\n const productIds = items\n .map((item) => (typeof item.id === \"string\" ? item.id : null))\n .filter((id): id is string => !!id);\n if (!productIds.length) return;\n try {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const scope = {\n organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n tenantId: ctx.auth?.tenantId ?? null,\n };\n const offers = await findWithDecryption(\n em,\n CatalogOffer,\n { product: { $in: productIds }, deletedAt: null, ...scope },\n { orderBy: { createdAt: \"asc\" } },\n scope,\n );\n const channelIds = Array.from(\n new Set(\n offers\n .map((offer) => offer.channelId)\n .filter(\n (id): id is string => typeof id === \"string\" && id.length > 0,\n ),\n ),\n );\n const channelLookup = new Map<\n string,\n { name?: string | null; code?: string | null }\n >();\n if (channelIds.length) {\n const scopedChannelsWhere = buildScopedWhere(\n { id: { $in: channelIds } },\n {\n organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n organizationIds: Array.isArray(ctx.organizationIds)\n ? ctx.organizationIds\n : undefined,\n tenantId: ctx.auth?.tenantId ?? null,\n },\n );\n const channels = await findWithDecryption(em, SalesChannel, scopedChannelsWhere, {\n fields: [\"id\", \"name\", \"code\"],\n });\n for (const channel of channels) {\n channelLookup.set(channel.id, {\n name: channel.name,\n code: channel.code ?? null,\n });\n }\n }\n const offersByProduct = new Map<string, Array<Record<string, unknown>>>();\n for (const offer of offers) {\n const productId =\n typeof offer.product === \"string\"\n ? offer.product\n : (offer.product?.id ?? null);\n if (!productId) continue;\n const channelInfo = channelLookup.get(offer.channelId);\n const entry = offersByProduct.get(productId) ?? [];\n entry.push({\n id: offer.id,\n channelId: offer.channelId,\n channelName: channelInfo?.name ?? null,\n channelCode: channelInfo?.code ?? null,\n title: offer.title,\n description: offer.description ?? null,\n isActive: offer.isActive,\n defaultMediaId: offer.defaultMediaId ?? null,\n defaultMediaUrl: offer.defaultMediaUrl ?? null,\n metadata: offer.metadata ?? null,\n updatedAt:\n offer.updatedAt instanceof Date\n ? offer.updatedAt.toISOString()\n : (typeof offer.updatedAt === \"string\" ? offer.updatedAt : null),\n });\n offersByProduct.set(productId, entry);\n }\n\n const categoryAssignments = await findWithDecryption(\n em,\n CatalogProductCategoryAssignment,\n { product: { $in: productIds }, ...scope },\n { populate: [\"category\"], orderBy: { position: \"asc\" } },\n scope,\n );\n const parentIds = new Set<string>();\n for (const assignment of categoryAssignments) {\n const category =\n typeof assignment.category === \"string\"\n ? null\n : (assignment.category ?? null);\n if (!category) continue;\n const parentId = category.parentId ?? null;\n if (parentId) parentIds.add(parentId);\n }\n const parentCategories = parentIds.size\n ? await findWithDecryption(\n em,\n CatalogProductCategory,\n { id: { $in: Array.from(parentIds) }, ...scope },\n { fields: [\"id\", \"name\"] },\n scope,\n )\n : [];\n const parentNameById = new Map<string, string | null>();\n for (const parent of parentCategories) {\n parentNameById.set(parent.id, parent.name ?? null);\n }\n const categoriesByProduct = new Map<\n string,\n Array<{\n id: string;\n name: string | null;\n treePath: string | null;\n parentId: string | null;\n parentName: string | null;\n }>\n >();\n for (const assignment of categoryAssignments) {\n const productId =\n typeof assignment.product === \"string\"\n ? assignment.product\n : (assignment.product?.id ?? null);\n if (!productId) continue;\n const category =\n typeof assignment.category === \"string\"\n ? null\n : (assignment.category ?? null);\n if (!category) continue;\n const parentId = category.parentId ?? null;\n const parentName = parentId\n ? (parentNameById.get(parentId) ?? null)\n : null;\n const bucket = categoriesByProduct.get(productId) ?? [];\n bucket.push({\n id: category.id,\n name: category.name ?? null,\n treePath: category.treePath ?? null,\n parentId,\n parentName,\n });\n categoriesByProduct.set(productId, bucket);\n }\n\n const tagAssignments = await findWithDecryption(\n em,\n CatalogProductTagAssignment,\n { product: { $in: productIds } },\n { populate: [\"tag\"] },\n {\n tenantId: ctx.auth?.tenantId ?? null,\n organizationId: ctx.auth?.orgId ?? null,\n },\n );\n const tagsByProduct = new Map<string, string[]>();\n for (const assignment of tagAssignments) {\n const productId =\n typeof assignment.product === \"string\"\n ? assignment.product\n : (assignment.product?.id ?? null);\n if (!productId) continue;\n const tag =\n typeof assignment.tag === \"string\" ? null : (assignment.tag ?? null);\n if (!tag) continue;\n const label =\n typeof tag.label === \"string\" && tag.label.trim().length\n ? tag.label\n : null;\n if (!label) continue;\n const bucket = tagsByProduct.get(productId) ?? [];\n bucket.push(label);\n tagsByProduct.set(productId, bucket);\n }\n\n const variants = await findWithDecryption(\n em,\n CatalogProductVariant,\n { product: { $in: productIds }, deletedAt: null, ...scope },\n { fields: [\"id\", \"product\"] },\n scope,\n );\n const variantToProduct = new Map<string, string>();\n for (const variant of variants) {\n const productId =\n typeof variant.product === \"string\"\n ? variant.product\n : (variant.product?.id ?? null);\n if (!productId) continue;\n variantToProduct.set(variant.id, productId);\n }\n const variantIds = Array.from(variantToProduct.keys());\n const priceWhere =\n variantIds.length > 0\n ? {\n $or: [\n { product: { $in: productIds } },\n { variant: { $in: variantIds } },\n ],\n }\n : { product: { $in: productIds } };\n const priceRows = await findWithDecryption<CatalogProductPrice>(\n em,\n CatalogProductPrice,\n { ...priceWhere, ...scope },\n { populate: [\"offer\", \"variant\", \"product\", \"priceKind\"] },\n scope,\n );\n const pricesByProduct = new Map<string, PriceRow[]>();\n for (const price of priceRows) {\n let productId: string | null = null;\n if (price.product) {\n productId =\n typeof price.product === \"string\"\n ? price.product\n : (price.product?.id ?? null);\n } else if (price.variant) {\n const variantId =\n typeof price.variant === \"string\" ? price.variant : price.variant.id;\n productId = variantToProduct.get(variantId) ?? null;\n }\n if (!productId) continue;\n const entry = pricesByProduct.get(productId) ?? [];\n entry.push(price);\n pricesByProduct.set(productId, entry);\n }\n\n const requestQuantityUnitKey = toUnitLookupKey(\n ctx.query.quantityUnit,\n );\n const conversionsByProduct = new Map<string, Map<string, number>>();\n const conversionOrganizationId =\n ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null;\n const conversionTenantId = ctx.auth?.tenantId ?? null;\n if (\n requestQuantityUnitKey &&\n productIds.length &&\n conversionOrganizationId &&\n conversionTenantId\n ) {\n const conversionRows = await findWithDecryption(\n em,\n CatalogProductUnitConversion,\n {\n product: { $in: productIds },\n organizationId: conversionOrganizationId,\n tenantId: conversionTenantId,\n deletedAt: null,\n isActive: true,\n },\n { fields: [\"id\", \"product\", \"unitCode\", \"toBaseFactor\"] },\n { organizationId: conversionOrganizationId, tenantId: conversionTenantId },\n );\n for (const row of conversionRows) {\n const productId =\n typeof row.product === \"string\"\n ? row.product\n : (row.product?.id ?? null);\n const unitKey = toUnitLookupKey(row.unitCode);\n const factor = Number(row.toBaseFactor);\n if (!productId || !unitKey || !Number.isFinite(factor) || factor <= 0)\n continue;\n const bucket =\n conversionsByProduct.get(productId) ?? new Map<string, number>();\n bucket.set(unitKey, factor);\n conversionsByProduct.set(productId, bucket);\n }\n }\n\n const channelFilterIds = parseIdList(ctx.query.channelIds);\n const channelContext =\n ctx.query.channelId ??\n (channelFilterIds.length === 1 ? channelFilterIds[0] : null);\n const pricingContext = buildPricingContext(ctx.query, channelContext);\n const pricingService = ctx.container.resolve<CatalogPricingService>(\n \"catalogPricingService\",\n );\n\n const pricingEntries: Array<{ rows: PriceRow[]; context: PricingContext } | null> = [];\n for (const item of items) {\n const id = typeof item.id === \"string\" ? item.id : null;\n if (!id) {\n pricingEntries.push(null);\n continue;\n }\n const offerEntries = offersByProduct.get(id) ?? [];\n item.offers = offerEntries;\n const channelIds = Array.from(\n new Set(\n offerEntries\n .map((offer) =>\n typeof offer.channelId === \"string\" ? offer.channelId : null,\n )\n .filter((channelId): channelId is string => !!channelId),\n ),\n );\n item.channelIds = channelIds;\n const categories = categoriesByProduct.get(id) ?? [];\n item.categories = categories;\n item.categoryIds = categories.map((category) => category.id);\n item.tags = tagsByProduct.get(id) ?? [];\n if (item.is_quote_only === true) {\n item.pricing = null;\n pricingEntries.push(null);\n continue;\n }\n const priceCandidates = pricesByProduct.get(id) ?? [];\n const normalizedQuantityForPricing = (() => {\n if (!requestQuantityUnitKey) return pricingContext.quantity;\n const baseUnit = toUnitLookupKey(item.default_unit);\n if (!baseUnit || requestQuantityUnitKey === baseUnit)\n return pricingContext.quantity;\n const productConversions = conversionsByProduct.get(id);\n const factor = productConversions?.get(requestQuantityUnitKey) ?? null;\n if (!factor || !Number.isFinite(factor) || factor <= 0) {\n logger.debug('catalog.products invalid conversion factor', { productId: id, unit: requestQuantityUnitKey, factor });\n return pricingContext.quantity;\n }\n const normalized = pricingContext.quantity * factor;\n return Number.isFinite(normalized) && normalized > 0\n ? normalized\n : pricingContext.quantity;\n })();\n const channelScopedContext =\n pricingContext.channelId || channelIds.length !== 1\n ? pricingContext\n : { ...pricingContext, channelId: channelIds[0] };\n pricingEntries.push({\n rows: priceCandidates,\n context: { ...channelScopedContext, quantity: normalizedQuantityForPricing },\n });\n }\n\n const resolveInputs: Array<{ rows: PriceRow[]; context: PricingContext }> = [];\n const resolveIndices: number[] = [];\n for (let i = 0; i < pricingEntries.length; i++) {\n if (pricingEntries[i] !== null) {\n resolveInputs.push(pricingEntries[i]!);\n resolveIndices.push(i);\n }\n }\n const priceResults = await pricingService.resolvePriceMany(resolveInputs);\n\n for (let i = 0; i < resolveIndices.length; i++) {\n const item = items[resolveIndices[i]];\n const best = priceResults[i];\n if (best) {\n item.pricing = {\n kind: resolvePriceKindCode(best),\n price_kind_id:\n typeof best.priceKind === \"string\"\n ? best.priceKind\n : (best.priceKind?.id ?? null),\n price_kind_code: resolvePriceKindCode(best),\n currency_code: best.currencyCode,\n unit_price_net: best.unitPriceNet,\n unit_price_gross: best.unitPriceGross,\n min_quantity: best.minQuantity,\n max_quantity: best.maxQuantity ?? null,\n tax_rate: best.taxRate ?? null,\n tax_amount: best.taxAmount ?? null,\n scope: {\n variant_id: resolvePriceVariantId(best),\n offer_id: resolvePriceOfferId(best),\n channel_id: resolvePriceChannelId(best),\n user_id: best.userId ?? null,\n user_group_id: best.userGroupId ?? null,\n customer_id: best.customerId ?? null,\n customer_group_id: best.customerGroupId ?? null,\n },\n };\n } else {\n item.pricing = null;\n }\n }\n } catch (error) {\n logger.error('decorateProductsAfterList Failed to load unit conversions', { err: error });\n }\n\n const searchTerm = ctx.query.search ? sanitizeSearchTerm(ctx.query.search) : null;\n if (searchTerm && !ctx.query.sortField && Array.isArray(payload.items)) {\n const needle = searchTerm.toLowerCase();\n payload.items.sort((a, b) => {\n const scoreA = scoreProductSearchRelevance(needle, a.title, a.sku);\n const scoreB = scoreProductSearchRelevance(needle, b.title, b.sku);\n if (scoreA !== scoreB) return scoreA - scoreB;\n return (a.title ?? \"\").localeCompare(b.title ?? \"\");\n });\n }\n}\n\nexport function scoreProductSearchRelevance(\n needle: string,\n title: string | null | undefined,\n sku: string | null | undefined,\n): number {\n const t = (title ?? \"\").toLowerCase();\n const s = (sku ?? \"\").toLowerCase();\n if (t === needle) return 0;\n if (s === needle) return 1;\n if (t.startsWith(needle)) return 2;\n if (s.startsWith(needle)) return 3;\n if (t.includes(needle)) return 4;\n if (s.includes(needle)) return 5;\n return 6;\n}\n\nconst crud = makeCrudRoute({\n metadata: routeMetadata,\n orm: {\n entity: CatalogProduct,\n idField: \"id\",\n orgField: \"organizationId\",\n tenantField: \"tenantId\",\n softDeleteField: \"deletedAt\",\n },\n indexer: {\n entityType: E.catalog.catalog_product,\n },\n list: {\n schema: listSchema,\n entityId: E.catalog.catalog_product,\n fields: [\n F.id,\n F.title,\n F.subtitle,\n F.description,\n F.sku,\n F.handle,\n \"tax_rate_id\",\n \"tax_rate\",\n F.product_type,\n F.status_entry_id,\n F.primary_currency_code,\n F.default_unit,\n \"default_sales_unit\",\n \"default_sales_unit_quantity\",\n \"uom_rounding_scale\",\n \"uom_rounding_mode\",\n \"unit_price_enabled\",\n \"unit_price_reference_unit\",\n \"unit_price_base_quantity\",\n F.default_media_id,\n F.default_media_url,\n F.weight_value,\n F.weight_unit,\n F.dimensions,\n F.is_configurable,\n F.is_active,\n \"country_of_origin_code\",\n \"pkwiu_code\",\n \"cn_code\",\n \"hs_code\",\n \"tax_classification_code\",\n \"gtu_codes\",\n \"age_min\",\n \"is_excise_good\",\n \"excise_category\",\n \"requires_prescription\",\n \"hazmat_class\",\n \"un_number\",\n \"hazmat_packing_group\",\n \"contains_lithium_battery\",\n \"launch_at\",\n \"end_of_life_at\",\n \"available_from\",\n \"available_until\",\n \"min_order_qty\",\n \"max_order_qty\",\n \"order_qty_increment\",\n \"requires_shipping\",\n \"is_quote_only\",\n \"seo_title\",\n \"seo_description\",\n \"canonical_url\",\n F.metadata,\n \"custom_fieldset_code\",\n \"option_schema_id\",\n F.created_at,\n F.updated_at,\n ],\n decorateCustomFields: { entityIds: [E.catalog.catalog_product] },\n sortFieldMap: {\n title: F.title,\n sku: F.sku,\n createdAt: F.created_at,\n updatedAt: F.updated_at,\n },\n buildFilters: buildProductFilters,\n transformItem: (item: ProductListItem | null | undefined) => {\n if (!item) return item;\n const normalized = { ...item };\n const cfEntries = extractAllCustomFieldEntries(item);\n for (const key of Object.keys(normalized)) {\n if (key.startsWith(\"cf:\")) {\n delete normalized[key];\n }\n }\n const defaultUnit = canonicalizeUnitCode(normalized.default_unit) ?? null;\n const defaultSalesUnit =\n canonicalizeUnitCode(normalized.default_sales_unit) ?? null;\n const unitPriceReferenceUnit =\n canonicalizeUnitCode(normalized.unit_price_reference_unit) ?? null;\n return {\n ...normalized,\n default_unit: defaultUnit,\n default_sales_unit: defaultSalesUnit,\n unit_price_reference_unit: unitPriceReferenceUnit,\n ...cfEntries,\n unit_price: {\n enabled: Boolean(normalized.unit_price_enabled),\n reference_unit: unitPriceReferenceUnit,\n base_quantity: normalized.unit_price_base_quantity ?? null,\n },\n };\n },\n },\n hooks: {\n afterList: decorateProductsAfterList,\n },\n actions: {\n create: {\n commandId: \"catalog.products.create\",\n schema: rawBodySchema,\n mapInput: async ({ raw, ctx }) => {\n const { translate } = await resolveTranslations();\n const parsed = parseScopedCommandInput(\n productCreateSchema,\n raw ?? {},\n ctx,\n translate,\n );\n const { base, custom } = splitCustomFieldPayload(parsed);\n return Object.keys(custom).length\n ? { ...base, customFields: custom }\n : base;\n },\n response: ({ result }) => ({\n id: result?.productId ?? result?.id ?? null,\n }),\n status: 201,\n },\n update: {\n commandId: \"catalog.products.update\",\n schema: rawBodySchema,\n mapInput: async ({ raw, ctx }) => {\n const { translate } = await resolveTranslations();\n const parsed = parseScopedCommandInput(\n productUpdateSchema,\n raw ?? {},\n ctx,\n translate,\n );\n const { base, custom } = splitCustomFieldPayload(parsed);\n return Object.keys(custom).length\n ? { ...base, customFields: custom }\n : base;\n },\n response: () => ({ ok: true }),\n },\n delete: {\n commandId: \"catalog.products.delete\",\n schema: rawBodySchema,\n mapInput: async ({ parsed, ctx }) => {\n const { translate } = await resolveTranslations();\n const id = resolveCrudRecordId(parsed, ctx, translate);\n if (!id)\n throw new CrudHttpError(400, {\n error: translate(\n \"catalog.errors.id_required\",\n \"Product id is required.\",\n ),\n });\n return { id };\n },\n response: () => ({ ok: true }),\n },\n },\n});\n\nexport const GET = crud.GET;\nexport const POST = crud.POST;\nexport const PUT = crud.PUT;\nexport const DELETE = crud.DELETE;\n\nconst productListItemSchema = z.object({\n id: z.string().uuid(),\n title: z.string().nullable().optional(),\n subtitle: z.string().nullable().optional(),\n description: z.string().nullable().optional(),\n sku: z.string().nullable().optional(),\n handle: z.string().nullable().optional(),\n product_type: z.string().nullable().optional(),\n status_entry_id: z.string().uuid().nullable().optional(),\n primary_currency_code: z.string().nullable().optional(),\n default_unit: z.string().nullable().optional(),\n default_sales_unit: z.string().nullable().optional(),\n default_sales_unit_quantity: z.number().nullable().optional(),\n uom_rounding_scale: z.number().nullable().optional(),\n uom_rounding_mode: z.enum([\"half_up\", \"down\", \"up\"]).nullable().optional(),\n unit_price_enabled: z.boolean().nullable().optional(),\n unit_price_reference_unit: z\n .enum([\"kg\", \"l\", \"m2\", \"m3\", \"pc\"])\n .nullable()\n .optional(),\n unit_price_base_quantity: z.number().nullable().optional(),\n unit_price: z\n .object({\n enabled: z.boolean(),\n reference_unit: z.enum([\"kg\", \"l\", \"m2\", \"m3\", \"pc\"]).nullable(),\n base_quantity: z.number().nullable(),\n })\n .optional(),\n default_media_id: z.string().uuid().nullable().optional(),\n default_media_url: z.string().nullable().optional(),\n weight_value: z.number().nullable().optional(),\n weight_unit: z.string().nullable().optional(),\n dimensions: z.record(z.string(), z.unknown()).nullable().optional(),\n is_configurable: z.boolean().nullable().optional(),\n is_active: z.boolean().nullable().optional(),\n country_of_origin_code: z.string().nullable().optional(),\n pkwiu_code: z.string().nullable().optional(),\n cn_code: z.string().nullable().optional(),\n hs_code: z.string().nullable().optional(),\n tax_classification_code: z.string().nullable().optional(),\n gtu_codes: z.array(z.string()).nullable().optional(),\n age_min: z.number().nullable().optional(),\n is_excise_good: z.boolean().nullable().optional(),\n excise_category: z.string().nullable().optional(),\n requires_prescription: z.boolean().nullable().optional(),\n hazmat_class: z.string().nullable().optional(),\n un_number: z.string().nullable().optional(),\n hazmat_packing_group: z.string().nullable().optional(),\n contains_lithium_battery: z.boolean().nullable().optional(),\n launch_at: z.string().nullable().optional(),\n end_of_life_at: z.string().nullable().optional(),\n available_from: z.string().nullable().optional(),\n available_until: z.string().nullable().optional(),\n min_order_qty: z.number().nullable().optional(),\n max_order_qty: z.number().nullable().optional(),\n order_qty_increment: z.number().nullable().optional(),\n requires_shipping: z.boolean().nullable().optional(),\n is_quote_only: z.boolean().nullable().optional(),\n seo_title: z.string().nullable().optional(),\n seo_description: z.string().nullable().optional(),\n canonical_url: z.string().nullable().optional(),\n metadata: z.record(z.string(), z.unknown()).nullable().optional(),\n custom_fieldset_code: z.string().nullable().optional(),\n option_schema_id: z.string().uuid().nullable().optional(),\n created_at: z.string().nullable().optional(),\n updated_at: z.string().nullable().optional(),\n offers: z.array(z.record(z.string(), z.unknown())).optional(),\n channelIds: z.array(z.string()).optional(),\n categories: z.array(z.record(z.string(), z.unknown())).optional(),\n categoryIds: z.array(z.string()).optional(),\n tags: z.array(z.string()).optional(),\n pricing: z.record(z.string(), z.unknown()).nullable().optional(),\n});\n\nexport const openApi = createCatalogCrudOpenApi({\n resourceName: \"Product\",\n pluralName: \"Products\",\n querySchema: listSchema,\n listResponseSchema: createPagedListResponseSchema(productListItemSchema),\n create: {\n schema: productCreateSchema,\n description: \"Creates a new product in the catalog.\",\n },\n update: {\n schema: productUpdateSchema,\n responseSchema: defaultOkResponseSchema,\n description: \"Updates an existing product by id.\",\n },\n del: {\n schema: z.object({ id: z.string().uuid() }),\n responseSchema: defaultOkResponseSchema,\n description: \"Deletes a product by id.\",\n },\n});\n"],
5
5
  "mappings": "AAAA,SAAS,SAAS;AAElB,SAAS,qBAAqB;AAC9B,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,6BAA6B;AAEtC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,yBAAyB,2BAA2B;AAC7D,SAAS,+BAA+B;AACxC,SAAS,SAAS;AAClB,YAAY,OAAO;AACnB,SAAS,kBAAkB,0BAA0B;AACrD,SAAS,yBAAyB;AAElC,SAAS,wBAAwB;AACjC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAEP,SAAS,yBA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,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS;AAAA,EAC3C,YAAY,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS;AAAA,EAC3C,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,CAAC,EAAE,SAAS;AAAA,EAC5D,YAAY,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS;AAAA,EACzC,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,CAAC,EAAE,SAAS;AAAA,EAChE,aAAa,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS;AAAA,EAC1C,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS;AAAA,EACnC,SAAS,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,EAAE,SAAS,EAAE,SAAS;AACjE,CAAC;AAEM,MAAM,UAAU,yBAAyB;AAAA,EAC9C,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,oBAAoB,8BAA8B,qBAAqB;AAAA,EACvE,QAAQ;AAAA,IACN,QAAQ;AAAA,IACR,aAAa;AAAA,EACf;AAAA,EACA,QAAQ;AAAA,IACN,QAAQ;AAAA,IACR,gBAAgB;AAAA,IAChB,aAAa;AAAA,EACf;AAAA,EACA,KAAK;AAAA,IACH,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAAA,IAC1C,gBAAgB;AAAA,IAChB,aAAa;AAAA,EACf;AACF,CAAC;",
6
6
  "names": ["channelIds"]
7
7
  }
@@ -1,6 +1,6 @@
1
1
  import { NextResponse } from "next/server";
2
2
  import { z } from "zod";
3
- import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
3
+ import { CrudHttpError, isCrudHttpError, notFound } from "@open-mercato/shared/lib/crud/errors";
4
4
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
5
5
  import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
6
6
  import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
@@ -85,7 +85,7 @@ async function GET(req, ctx) {
85
85
  decryptionScope
86
86
  );
87
87
  if (!company) {
88
- throw new CrudHttpError(404, { error: translate("customers.errors.company_not_found", "Company not found") });
88
+ throw notFound(translate("customers.errors.company_not_found", "Company not found"));
89
89
  }
90
90
  if (!isOrganizationReadAccessAllowed({ scope, auth, organizationId: company.organizationId })) {
91
91
  throw new CrudHttpError(403, { error: translate("customers.errors.access_denied", "Access denied") });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../../src/modules/customers/api/companies/%5Bid%5D/people/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { isOrganizationReadAccessAllowed } from '@open-mercato/core/modules/directory/utils/organizationScopeGuard'\nimport {\n CustomerEntity,\n CustomerPersonCompanyLink,\n CustomerPersonProfile,\n} from '../../../../data/entities'\nimport {\n filterActivePersonCompanyLinks,\n withActiveCustomerPersonCompanyLinkFilter,\n} from '../../../../lib/personCompanyLinkTable'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customers')\n\nconst paramsSchema = z.object({\n id: z.string().uuid(),\n})\n\nconst querySchema = z.object({\n page: z.coerce.number().min(1).default(1),\n pageSize: z.coerce.number().min(1).max(100).default(20),\n search: z.string().optional(),\n sort: z.enum(['name-asc', 'name-desc', 'recent']).default('name-asc'),\n})\n\ntype CompanyPersonItem = {\n id: string\n displayName: string\n primaryEmail: string | null\n primaryPhone: string | null\n status: string | null\n lifecycleStage: string | null\n jobTitle: string | null\n department: string | null\n createdAt: string\n organizationId: string\n temperature: string | null\n source: string | null\n linkedAt: string | null\n}\n\nfunction matchesSearch(item: CompanyPersonItem, query: string): boolean {\n const normalized = query.trim().toLowerCase()\n if (!normalized.length) return true\n return [\n item.displayName,\n item.primaryEmail,\n item.primaryPhone,\n item.jobTitle,\n item.department,\n item.status,\n item.lifecycleStage,\n item.source,\n ]\n .filter((value): value is string => typeof value === 'string' && value.length > 0)\n .some((value) => value.toLowerCase().includes(normalized))\n}\n\nfunction sortItems(items: CompanyPersonItem[], sort: 'name-asc' | 'name-desc' | 'recent'): CompanyPersonItem[] {\n if (sort === 'recent') {\n return [...items].sort((left, right) => {\n const leftTimestamp = left.linkedAt ? new Date(left.linkedAt).getTime() : new Date(left.createdAt).getTime()\n const rightTimestamp = right.linkedAt ? new Date(right.linkedAt).getTime() : new Date(right.createdAt).getTime()\n if (leftTimestamp === rightTimestamp) return left.displayName.localeCompare(right.displayName)\n return rightTimestamp - leftTimestamp\n })\n }\n\n return [...items].sort((left, right) => {\n const compare = left.displayName.localeCompare(right.displayName, undefined, { sensitivity: 'base' })\n return sort === 'name-asc' ? compare : -compare\n })\n}\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['customers.companies.view'] },\n}\n\nexport async function GET(req: Request, ctx: { params?: { id?: string } }) {\n const { translate } = await resolveTranslations()\n try {\n const { id } = paramsSchema.parse({ id: ctx.params?.id })\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId) throw new CrudHttpError(401, { error: 'Unauthorized' })\n\n const query = querySchema.parse({\n page: new URL(req.url).searchParams.get('page') ?? undefined,\n pageSize: new URL(req.url).searchParams.get('pageSize') ?? undefined,\n search: new URL(req.url).searchParams.get('search') ?? undefined,\n sort: new URL(req.url).searchParams.get('sort') ?? undefined,\n })\n\n const container = await createRequestContainer()\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const em = (container.resolve('em') as EntityManager).fork()\n const decryptionScope = {\n tenantId: auth.tenantId,\n organizationId: scope?.selectedId ?? auth.orgId ?? null,\n }\n\n const company = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id, kind: 'company', tenantId: auth.tenantId, deletedAt: null },\n {},\n decryptionScope,\n )\n if (!company) {\n throw new CrudHttpError(404, { error: translate('customers.errors.company_not_found', 'Company not found') })\n }\n\n if (!isOrganizationReadAccessAllowed({ scope, auth, organizationId: company.organizationId })) {\n throw new CrudHttpError(403, { error: translate('customers.errors.access_denied', 'Access denied') })\n }\n\n const entityScope = { tenantId: auth.tenantId, organizationId: company.organizationId }\n const linkWhere = await withActiveCustomerPersonCompanyLinkFilter(\n em,\n {\n company: company.id,\n tenantId: company.tenantId,\n organizationId: company.organizationId,\n },\n 'customers.companies.people.GET',\n )\n const links = filterActivePersonCompanyLinks(\n await findWithDecryption(\n em,\n CustomerPersonCompanyLink,\n linkWhere,\n { populate: ['person'] },\n entityScope,\n ),\n )\n\n const personIds = links\n .map((link) => link.person?.id)\n .filter((personId): personId is string => typeof personId === 'string' && personId.length > 0)\n\n const profiles = personIds.length > 0\n ? await findWithDecryption(\n em,\n CustomerPersonProfile,\n {\n entity: { $in: personIds },\n tenantId: company.tenantId,\n organizationId: company.organizationId,\n },\n {},\n entityScope,\n )\n : []\n const profileByPersonId = new Map(\n profiles.map((profile) => [(profile.entity as { id: string }).id, profile]),\n )\n\n const items = links\n .map((link) => {\n const person = link.person\n if (!person?.id) return null\n const profile = profileByPersonId.get(person.id) ?? null\n return {\n id: person.id,\n displayName: person.displayName ?? person.primaryEmail ?? person.id,\n primaryEmail: person.primaryEmail ?? null,\n primaryPhone: person.primaryPhone ?? null,\n status: person.status ?? null,\n lifecycleStage: person.lifecycleStage ?? null,\n jobTitle: profile?.jobTitle ?? null,\n department: profile?.department ?? null,\n createdAt: person.createdAt.toISOString(),\n organizationId: person.organizationId,\n temperature: person.temperature ?? null,\n source: person.source ?? null,\n linkedAt: link.createdAt ? link.createdAt.toISOString() : null,\n } satisfies CompanyPersonItem\n })\n .filter((item): item is CompanyPersonItem => item !== null)\n\n const filtered = query.search?.trim().length ? items.filter((item) => matchesSearch(item, query.search ?? '')) : items\n const sorted = sortItems(filtered, query.sort)\n const total = sorted.length\n const totalPages = Math.max(1, Math.ceil(total / query.pageSize))\n const page = Math.min(query.page, totalPages)\n const start = (page - 1) * query.pageSize\n\n return NextResponse.json({\n items: sorted.slice(start, start + query.pageSize),\n total,\n page,\n pageSize: query.pageSize,\n totalPages,\n })\n } catch (error) {\n if (isCrudHttpError(error)) {\n return NextResponse.json(error.body, { status: error.status })\n }\n logger.error('customers.companies.people.GET', { err: error })\n return NextResponse.json({ error: translate('customers.errors.company_people_load_failed', 'Failed to load linked people') }, { status: 500 })\n }\n}\n\nconst companyPeopleItemSchema = z.object({\n id: z.string().uuid(),\n displayName: z.string(),\n primaryEmail: z.string().nullable(),\n primaryPhone: z.string().nullable(),\n status: z.string().nullable(),\n lifecycleStage: z.string().nullable(),\n jobTitle: z.string().nullable(),\n department: z.string().nullable(),\n createdAt: z.string(),\n organizationId: z.string().uuid().nullable(),\n temperature: z.string().nullable(),\n source: z.string().nullable(),\n linkedAt: z.string().nullable(),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Customers',\n methods: {\n GET: {\n summary: 'List linked people for a company',\n query: querySchema,\n responses: [\n {\n status: 200,\n description: 'Paginated linked people',\n schema: z.object({\n items: z.array(companyPeopleItemSchema),\n total: z.number().int().nonnegative(),\n page: z.number().int().min(1),\n pageSize: z.number().int().min(1),\n totalPages: z.number().int().min(1),\n }),\n },\n ],\n },\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B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ACP,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,uBAAuB;AAAA,YACtC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY;AAAA,YACpC,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAAA,YAC5B,UAAU,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAAA,YAChC,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAAA,UACpC,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { CrudHttpError, isCrudHttpError, notFound } from '@open-mercato/shared/lib/crud/errors'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { isOrganizationReadAccessAllowed } from '@open-mercato/core/modules/directory/utils/organizationScopeGuard'\nimport {\n CustomerEntity,\n CustomerPersonCompanyLink,\n CustomerPersonProfile,\n} from '../../../../data/entities'\nimport {\n filterActivePersonCompanyLinks,\n withActiveCustomerPersonCompanyLinkFilter,\n} from '../../../../lib/personCompanyLinkTable'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customers')\n\nconst paramsSchema = z.object({\n id: z.string().uuid(),\n})\n\nconst querySchema = z.object({\n page: z.coerce.number().min(1).default(1),\n pageSize: z.coerce.number().min(1).max(100).default(20),\n search: z.string().optional(),\n sort: z.enum(['name-asc', 'name-desc', 'recent']).default('name-asc'),\n})\n\ntype CompanyPersonItem = {\n id: string\n displayName: string\n primaryEmail: string | null\n primaryPhone: string | null\n status: string | null\n lifecycleStage: string | null\n jobTitle: string | null\n department: string | null\n createdAt: string\n organizationId: string\n temperature: string | null\n source: string | null\n linkedAt: string | null\n}\n\nfunction matchesSearch(item: CompanyPersonItem, query: string): boolean {\n const normalized = query.trim().toLowerCase()\n if (!normalized.length) return true\n return [\n item.displayName,\n item.primaryEmail,\n item.primaryPhone,\n item.jobTitle,\n item.department,\n item.status,\n item.lifecycleStage,\n item.source,\n ]\n .filter((value): value is string => typeof value === 'string' && value.length > 0)\n .some((value) => value.toLowerCase().includes(normalized))\n}\n\nfunction sortItems(items: CompanyPersonItem[], sort: 'name-asc' | 'name-desc' | 'recent'): CompanyPersonItem[] {\n if (sort === 'recent') {\n return [...items].sort((left, right) => {\n const leftTimestamp = left.linkedAt ? new Date(left.linkedAt).getTime() : new Date(left.createdAt).getTime()\n const rightTimestamp = right.linkedAt ? new Date(right.linkedAt).getTime() : new Date(right.createdAt).getTime()\n if (leftTimestamp === rightTimestamp) return left.displayName.localeCompare(right.displayName)\n return rightTimestamp - leftTimestamp\n })\n }\n\n return [...items].sort((left, right) => {\n const compare = left.displayName.localeCompare(right.displayName, undefined, { sensitivity: 'base' })\n return sort === 'name-asc' ? compare : -compare\n })\n}\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['customers.companies.view'] },\n}\n\nexport async function GET(req: Request, ctx: { params?: { id?: string } }) {\n const { translate } = await resolveTranslations()\n try {\n const { id } = paramsSchema.parse({ id: ctx.params?.id })\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId) throw new CrudHttpError(401, { error: 'Unauthorized' })\n\n const query = querySchema.parse({\n page: new URL(req.url).searchParams.get('page') ?? undefined,\n pageSize: new URL(req.url).searchParams.get('pageSize') ?? undefined,\n search: new URL(req.url).searchParams.get('search') ?? undefined,\n sort: new URL(req.url).searchParams.get('sort') ?? undefined,\n })\n\n const container = await createRequestContainer()\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const em = (container.resolve('em') as EntityManager).fork()\n const decryptionScope = {\n tenantId: auth.tenantId,\n organizationId: scope?.selectedId ?? auth.orgId ?? null,\n }\n\n const company = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id, kind: 'company', tenantId: auth.tenantId, deletedAt: null },\n {},\n decryptionScope,\n )\n if (!company) {\n throw notFound(translate('customers.errors.company_not_found', 'Company not found'))\n }\n\n if (!isOrganizationReadAccessAllowed({ scope, auth, organizationId: company.organizationId })) {\n throw new CrudHttpError(403, { error: translate('customers.errors.access_denied', 'Access denied') })\n }\n\n const entityScope = { tenantId: auth.tenantId, organizationId: company.organizationId }\n const linkWhere = await withActiveCustomerPersonCompanyLinkFilter(\n em,\n {\n company: company.id,\n tenantId: company.tenantId,\n organizationId: company.organizationId,\n },\n 'customers.companies.people.GET',\n )\n const links = filterActivePersonCompanyLinks(\n await findWithDecryption(\n em,\n CustomerPersonCompanyLink,\n linkWhere,\n { populate: ['person'] },\n entityScope,\n ),\n )\n\n const personIds = links\n .map((link) => link.person?.id)\n .filter((personId): personId is string => typeof personId === 'string' && personId.length > 0)\n\n const profiles = personIds.length > 0\n ? await findWithDecryption(\n em,\n CustomerPersonProfile,\n {\n entity: { $in: personIds },\n tenantId: company.tenantId,\n organizationId: company.organizationId,\n },\n {},\n entityScope,\n )\n : []\n const profileByPersonId = new Map(\n profiles.map((profile) => [(profile.entity as { id: string }).id, profile]),\n )\n\n const items = links\n .map((link) => {\n const person = link.person\n if (!person?.id) return null\n const profile = profileByPersonId.get(person.id) ?? null\n return {\n id: person.id,\n displayName: person.displayName ?? person.primaryEmail ?? person.id,\n primaryEmail: person.primaryEmail ?? null,\n primaryPhone: person.primaryPhone ?? null,\n status: person.status ?? null,\n lifecycleStage: person.lifecycleStage ?? null,\n jobTitle: profile?.jobTitle ?? null,\n department: profile?.department ?? null,\n createdAt: person.createdAt.toISOString(),\n organizationId: person.organizationId,\n temperature: person.temperature ?? null,\n source: person.source ?? null,\n linkedAt: link.createdAt ? link.createdAt.toISOString() : null,\n } satisfies CompanyPersonItem\n })\n .filter((item): item is CompanyPersonItem => item !== null)\n\n const filtered = query.search?.trim().length ? items.filter((item) => matchesSearch(item, query.search ?? '')) : items\n const sorted = sortItems(filtered, query.sort)\n const total = sorted.length\n const totalPages = Math.max(1, Math.ceil(total / query.pageSize))\n const page = Math.min(query.page, totalPages)\n const start = (page - 1) * query.pageSize\n\n return NextResponse.json({\n items: sorted.slice(start, start + query.pageSize),\n total,\n page,\n pageSize: query.pageSize,\n totalPages,\n })\n } catch (error) {\n if (isCrudHttpError(error)) {\n return NextResponse.json(error.body, { status: error.status })\n }\n logger.error('customers.companies.people.GET', { err: error })\n return NextResponse.json({ error: translate('customers.errors.company_people_load_failed', 'Failed to load linked people') }, { status: 500 })\n }\n}\n\nconst companyPeopleItemSchema = z.object({\n id: z.string().uuid(),\n displayName: z.string(),\n primaryEmail: z.string().nullable(),\n primaryPhone: z.string().nullable(),\n status: z.string().nullable(),\n lifecycleStage: z.string().nullable(),\n jobTitle: z.string().nullable(),\n department: z.string().nullable(),\n createdAt: z.string(),\n organizationId: z.string().uuid().nullable(),\n temperature: z.string().nullable(),\n source: z.string().nullable(),\n linkedAt: z.string().nullable(),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Customers',\n methods: {\n GET: {\n summary: 'List linked people for a company',\n query: querySchema,\n responses: [\n {\n status: 200,\n description: 'Paginated linked people',\n schema: z.object({\n items: z.array(companyPeopleItemSchema),\n total: z.number().int().nonnegative(),\n page: z.number().int().min(1),\n pageSize: z.number().int().min(1),\n totalPages: z.number().int().min(1),\n }),\n },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,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MACP,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ,EAAE,OAAO;AAAA,YACf,OAAO,EAAE,MAAM,uBAAuB;AAAA,YACtC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY;AAAA,YACpC,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAAA,YAC5B,UAAU,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAAA,YAChC,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAAA,UACpC,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -1,6 +1,6 @@
1
1
  import { NextResponse } from "next/server";
2
2
  import { z } from "zod";
3
- import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
3
+ import { CrudHttpError, isCrudHttpError, notFound } from "@open-mercato/shared/lib/crud/errors";
4
4
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
5
5
  import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
6
6
  import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
@@ -73,7 +73,7 @@ async function GET(req, ctx) {
73
73
  decryptionScope
74
74
  );
75
75
  if (!deal) {
76
- throw new CrudHttpError(404, { error: translate("customers.errors.deal_not_found", "Deal not found") });
76
+ throw notFound(translate("customers.errors.deal_not_found", "Deal not found"));
77
77
  }
78
78
  if (!isOrganizationReadAccessAllowed({ scope, auth, organizationId: deal.organizationId })) {
79
79
  throw new CrudHttpError(403, { error: translate("customers.errors.access_denied", "Access denied") });