@open-mercato/core 0.10.1-develop.7841.1.af87ac614d → 0.10.1-develop.7857.1.259928eb85

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 (98) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/api_keys/api/keys/route.js +15 -1
  3. package/dist/modules/api_keys/api/keys/route.js.map +2 -2
  4. package/dist/modules/attachments/api/file/[id]/route.js +6 -1
  5. package/dist/modules/attachments/api/file/[id]/route.js.map +2 -2
  6. package/dist/modules/attachments/api/image/[id]/[[...slug]]/route.js +6 -1
  7. package/dist/modules/attachments/api/image/[id]/[[...slug]]/route.js.map +2 -2
  8. package/dist/modules/attachments/api/library/[id]/route.js +16 -1
  9. package/dist/modules/attachments/api/library/[id]/route.js.map +2 -2
  10. package/dist/modules/attachments/api/route.js +11 -3
  11. package/dist/modules/attachments/api/route.js.map +2 -2
  12. package/dist/modules/attachments/cli.js +2 -0
  13. package/dist/modules/attachments/cli.js.map +2 -2
  14. package/dist/modules/attachments/data/validators.js +11 -0
  15. package/dist/modules/attachments/data/validators.js.map +2 -2
  16. package/dist/modules/attachments/index.js +10 -0
  17. package/dist/modules/attachments/index.js.map +2 -2
  18. package/dist/modules/attachments/lib/access-query.js +5 -1
  19. package/dist/modules/attachments/lib/access-query.js.map +2 -2
  20. package/dist/modules/attachments/lib/createFromBuffer.js +2 -0
  21. package/dist/modules/attachments/lib/createFromBuffer.js.map +2 -2
  22. package/dist/modules/attachments/lib/drivers/driverFactory.js +54 -33
  23. package/dist/modules/attachments/lib/drivers/driverFactory.js.map +2 -2
  24. package/dist/modules/attachments/lib/drivers/index.js +11 -1
  25. package/dist/modules/attachments/lib/drivers/index.js.map +2 -2
  26. package/dist/modules/attachments/lib/drivers/storageValidation.js +85 -0
  27. package/dist/modules/attachments/lib/drivers/storageValidation.js.map +7 -0
  28. package/dist/modules/attachments/lib/scoped-upload-service.js +3 -1
  29. package/dist/modules/attachments/lib/scoped-upload-service.js.map +2 -2
  30. package/dist/modules/attachments/lib/storageErrors.js +22 -0
  31. package/dist/modules/attachments/lib/storageErrors.js.map +7 -0
  32. package/dist/modules/auth/api/users/route.js +16 -1
  33. package/dist/modules/auth/api/users/route.js.map +2 -2
  34. package/dist/modules/auth/backend/users/page.js +13 -2
  35. package/dist/modules/auth/backend/users/page.js.map +2 -2
  36. package/dist/modules/catalog/commands/products.js +4 -2
  37. package/dist/modules/catalog/commands/products.js.map +2 -2
  38. package/dist/modules/customers/api/companies/[id]/route.js +4 -9
  39. package/dist/modules/customers/api/companies/[id]/route.js.map +2 -2
  40. package/dist/modules/customers/api/people/[id]/route.js +4 -9
  41. package/dist/modules/customers/api/people/[id]/route.js.map +2 -2
  42. package/dist/modules/customers/components/detail/TaskDialog.js +2 -0
  43. package/dist/modules/customers/components/detail/TaskDialog.js.map +2 -2
  44. package/dist/modules/customers/lib/todoCompatibility.js +23 -0
  45. package/dist/modules/customers/lib/todoCompatibility.js.map +2 -2
  46. package/dist/modules/directory/api/organization-branding/route.js +6 -9
  47. package/dist/modules/directory/api/organization-branding/route.js.map +2 -2
  48. package/dist/modules/directory/backend/directory/branding/page.js +15 -3
  49. package/dist/modules/directory/backend/directory/branding/page.js.map +2 -2
  50. package/dist/modules/wms/api/listEnrichers.js +3 -1
  51. package/dist/modules/wms/api/listEnrichers.js.map +2 -2
  52. package/dist/modules/wms/index.js +1 -1
  53. package/dist/modules/wms/index.js.map +2 -2
  54. package/jest.config.cjs +1 -1
  55. package/package.json +8 -8
  56. package/src/modules/api_keys/api/keys/route.ts +15 -1
  57. package/src/modules/api_keys/i18n/de.json +1 -0
  58. package/src/modules/api_keys/i18n/en.json +1 -0
  59. package/src/modules/api_keys/i18n/es.json +1 -0
  60. package/src/modules/api_keys/i18n/ko.json +1 -0
  61. package/src/modules/api_keys/i18n/pl.json +1 -0
  62. package/src/modules/attachments/api/file/[id]/route.ts +7 -1
  63. package/src/modules/attachments/api/image/[id]/[[...slug]]/route.ts +7 -1
  64. package/src/modules/attachments/api/library/[id]/route.ts +14 -1
  65. package/src/modules/attachments/api/route.ts +11 -3
  66. package/src/modules/attachments/cli.ts +2 -0
  67. package/src/modules/attachments/data/validators.ts +11 -0
  68. package/src/modules/attachments/i18n/de.json +1 -0
  69. package/src/modules/attachments/i18n/en.json +1 -0
  70. package/src/modules/attachments/i18n/es.json +1 -0
  71. package/src/modules/attachments/i18n/ko.json +1 -0
  72. package/src/modules/attachments/i18n/pl.json +1 -0
  73. package/src/modules/attachments/index.ts +12 -0
  74. package/src/modules/attachments/lib/access-query.ts +5 -1
  75. package/src/modules/attachments/lib/createFromBuffer.ts +2 -0
  76. package/src/modules/attachments/lib/drivers/driverFactory.ts +79 -55
  77. package/src/modules/attachments/lib/drivers/index.ts +13 -0
  78. package/src/modules/attachments/lib/drivers/storageValidation.ts +114 -0
  79. package/src/modules/attachments/lib/scoped-upload-service.ts +3 -1
  80. package/src/modules/attachments/lib/storageErrors.ts +21 -0
  81. package/src/modules/auth/api/users/route.ts +18 -1
  82. package/src/modules/auth/backend/users/page.tsx +14 -2
  83. package/src/modules/auth/i18n/de.json +1 -0
  84. package/src/modules/auth/i18n/en.json +1 -0
  85. package/src/modules/auth/i18n/es.json +1 -0
  86. package/src/modules/auth/i18n/ko.json +1 -0
  87. package/src/modules/auth/i18n/pl.json +1 -0
  88. package/src/modules/catalog/commands/products.ts +4 -1
  89. package/src/modules/customer_accounts/AGENTS.md +1 -1
  90. package/src/modules/customers/api/companies/[id]/route.ts +6 -13
  91. package/src/modules/customers/api/people/[id]/route.ts +6 -13
  92. package/src/modules/customers/components/detail/TaskDialog.tsx +2 -0
  93. package/src/modules/customers/lib/todoCompatibility.ts +28 -0
  94. package/src/modules/directory/api/organization-branding/route.ts +5 -8
  95. package/src/modules/directory/backend/directory/branding/page.tsx +15 -3
  96. package/src/modules/sales/AGENTS.md +3 -3
  97. package/src/modules/wms/api/listEnrichers.ts +5 -2
  98. package/src/modules/wms/index.ts +1 -1
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/customers/lib/todoCompatibility.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { QueryEngine } from '@open-mercato/shared/lib/query/types'\nimport type { EntityId } from '@open-mercato/shared/modules/entities'\nimport { isValidEntityIdShape } from '@open-mercato/shared/lib/query/engine'\nimport { parseBooleanFromUnknown } from '@open-mercato/shared/lib/boolean'\nimport {\n CustomerInteraction,\n CustomerTodoLink,\n} from '../data/entities'\nimport type { InteractionRecord } from './interactionCompatibility'\nimport {\n CUSTOMER_INTERACTION_TASK_SOURCE,\n EXAMPLE_TODO_SOURCE,\n resolveExampleIntegrationHref,\n} from './interactionCompatibility'\nimport { hydrateCanonicalInteractions, loadCustomerSummaries } from './interactionReadModel'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customers')\n\nexport type CustomerTodoRow = {\n id: string\n todoId: string\n todoSource: string\n todoTitle: string | null\n todoIsDone: boolean | null\n todoPriority?: number | null\n todoSeverity?: string | null\n todoDescription?: string | null\n todoDueAt?: string | null\n todoTimezone?: string | null\n todoCustomValues?: Record<string, unknown> | null\n todoOrganizationId: string | null\n todoUpdatedAt?: string | null\n organizationId: string\n tenantId: string\n createdAt: string\n externalHref?: string | null\n _integrations?: Record<string, unknown>\n customer: {\n id: string | null\n displayName: string | null\n kind: string | null\n }\n}\n\nexport type LegacyTodoDetail = {\n title: string | null\n isDone: boolean | null\n priority: number | null\n severity: string | null\n description: string | null\n dueAt: string | null\n organizationId: string | null\n updatedAt: string | null\n customValues: Record<string, unknown> | null\n}\n\ntype CustomerSummary = {\n id: string | null\n displayName: string | null\n kind: string | null\n}\n\ntype CustomersAuthLike = {\n tenantId: string | null\n orgId?: string | null\n sub?: string | null\n userId?: string | null\n keyId?: string | null\n}\n\ntype CustomersContainerLike = {\n resolve: (name: string) => unknown\n}\n\nexport type CanonicalTodoListResult = {\n items: CustomerTodoRow[]\n bridgeIds: Set<string>\n total: number\n}\n\nfunction emptyCanonicalTodoList(): CanonicalTodoListResult {\n return { items: [], bridgeIds: new Set(), total: 0 }\n}\n\nfunction isCollapsedRestrictedOrganizationScope(\n organizationIds: string[] | null | undefined,\n isUnrestricted: boolean | undefined,\n): boolean {\n return isUnrestricted !== true && (!organizationIds || organizationIds.length === 0)\n}\n\nexport type ListTodosPagination = { page: number; pageSize: number }\n\nfunction resolveLegacyTodoSource(source: string | null | undefined): string {\n return typeof source === 'string' && source.trim().length > 0\n ? source\n : EXAMPLE_TODO_SOURCE\n}\n\nfunction extractTodoTitle(record: Record<string, unknown>): string | null {\n // `task_name` / `taskName` carry a workflow user task's name; the query engine\n // returns the raw column on the ORM path and the camelCase property on the\n // indexed one, so both spellings are read.\n const candidates = ['title', 'subject', 'name', 'task_name', 'taskName', 'summary', 'text', 'description']\n for (const key of candidates) {\n const value = record[key]\n if (typeof value === 'string' && value.trim().length > 0) {\n return value.trim()\n }\n }\n return null\n}\n\nfunction parseNumber(value: unknown): number | null {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (!trimmed.length) return null\n const parsed = Number(trimmed)\n if (!Number.isNaN(parsed)) return parsed\n }\n return null\n}\n\nfunction parseDateValue(value: unknown): string | null {\n if (value instanceof Date) {\n return Number.isNaN(value.getTime()) ? null : value.toISOString()\n }\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (!trimmed.length) return null\n const parsed = new Date(trimmed)\n return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString()\n }\n return null\n}\n\nfunction readCustomField(record: Record<string, unknown>, key: string): unknown {\n const custom = record.custom ?? record.customFields ?? record.cf\n if (custom && typeof custom === 'object') {\n const bucket = custom as Record<string, unknown>\n if (key in bucket) return bucket[key]\n }\n return undefined\n}\n\nexport function normalizeTodoSearch(value: string | undefined): string | null {\n if (typeof value !== 'string') return null\n const trimmed = value.trim().toLowerCase()\n return trimmed.length > 0 ? trimmed : null\n}\n\nexport function sortTodoRows(rows: CustomerTodoRow[]): CustomerTodoRow[] {\n return [...rows].sort((left, right) => {\n const leftTime = new Date(left.createdAt).getTime()\n const rightTime = new Date(right.createdAt).getTime()\n if (leftTime === rightTime) {\n return right.id.localeCompare(left.id)\n }\n return rightTime - leftTime\n })\n}\n\nexport function filterTodoRows(rows: CustomerTodoRow[], search: string | null): CustomerTodoRow[] {\n if (!search) return rows\n return rows.filter((row) => {\n const haystack = [\n row.customer.displayName,\n row.todoTitle,\n row.todoDescription,\n ]\n .filter((value): value is string => typeof value === 'string' && value.trim().length > 0)\n .join(' ')\n .toLowerCase()\n return haystack.includes(search)\n })\n}\n\nexport function paginateTodoRows(\n rows: CustomerTodoRow[],\n page: number,\n pageSize: number,\n exportAll: boolean,\n): { items: CustomerTodoRow[]; total: number; page: number; pageSize: number; totalPages: number } {\n const total = rows.length\n if (exportAll) {\n return {\n items: rows,\n total,\n page: 1,\n pageSize: total,\n totalPages: 1,\n }\n }\n const start = (page - 1) * pageSize\n return {\n items: rows.slice(start, start + pageSize),\n total,\n page,\n pageSize,\n totalPages: Math.max(1, Math.ceil(total / pageSize)),\n }\n}\n\nexport async function resolveLegacyTodoDetails(\n queryEngine: QueryEngine,\n links: CustomerTodoLink[],\n tenantId: string | null,\n organizationIds: Array<string | null>,\n): Promise<Map<string, LegacyTodoDetail>> {\n const details = new Map<string, LegacyTodoDetail>()\n if (!links.length || !tenantId) return details\n\n const scopedOrganizationIds = organizationIds.filter(\n (value): value is string => typeof value === 'string' && value.trim().length > 0,\n )\n\n const idsBySource = new Map<string, Set<string>>()\n for (const link of links) {\n const source = resolveLegacyTodoSource(link.todoSource)\n const id =\n typeof link.todoId === 'string' && link.todoId.trim().length > 0\n ? link.todoId\n : String(link.todoId ?? '')\n if (!id) continue\n if (!idsBySource.has(source)) idsBySource.set(source, new Set<string>())\n idsBySource.get(source)!.add(id)\n }\n\n for (const [source, idSet] of idsBySource.entries()) {\n const ids = Array.from(idSet)\n if (!ids.length) continue\n if (!isValidEntityIdShape(source)) {\n // A legacy/malformed `todoSource` (e.g. a bare module name written before\n // the value was required to be a `module:entity` id) does not resolve to\n // any real table. Querying it anyway surfaces a raw DB error (\"relation\n // ... does not exist\") as a dashboard-wide schema-mismatch banner instead\n // of just leaving that row's details unresolved.\n logger.warn('Skipping malformed legacy todo source', { component: 'todoCompatibility', source })\n continue\n }\n try {\n const result = await queryEngine.query<Record<string, unknown>>(source as EntityId, {\n tenantId,\n organizationIds: scopedOrganizationIds.length > 0 ? scopedOrganizationIds : undefined,\n filters: { id: { $in: ids } },\n includeCustomFields: ['priority', 'due_at', 'severity', 'description'],\n page: { page: 1, pageSize: Math.max(ids.length, 1) },\n })\n\n for (const item of result.items ?? []) {\n if (!item || typeof item !== 'object') continue\n const record = item as Record<string, unknown>\n const rawId =\n typeof record.id === 'string' && record.id.trim().length > 0\n ? record.id\n : String(record.id ?? '')\n if (!rawId) continue\n\n const isDone = (() => {\n const direct = parseBooleanFromUnknown(record.is_done)\n if (direct !== null) return direct\n const custom = parseBooleanFromUnknown(readCustomField(record, 'is_done'))\n if (custom !== null) return custom\n const generic = parseBooleanFromUnknown(record.isDone)\n if (generic !== null) return generic\n return parseBooleanFromUnknown(readCustomField(record, 'isDone'))\n })()\n\n const priority = (() => {\n const candidates = [\n record['cf:priority'],\n record['cf_priority'],\n record.priority,\n readCustomField(record, 'priority'),\n ]\n for (const candidate of candidates) {\n const parsed = parseNumber(candidate)\n if (parsed !== null) return parsed\n }\n return null\n })()\n\n const severity = (() => {\n const candidates = [\n record['cf:severity'],\n record['cf_severity'],\n record.severity,\n readCustomField(record, 'severity'),\n ]\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.trim().length > 0) {\n return candidate.trim()\n }\n }\n return null\n })()\n\n const description = (() => {\n const candidates = [\n record.description,\n record['cf:description'],\n record['cf_description'],\n readCustomField(record, 'description'),\n ]\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.trim().length > 0) {\n return candidate.trim()\n }\n }\n return null\n })()\n\n const dueAt = (() => {\n const candidates = [\n record.due_at,\n record.dueAt,\n record['cf:due_at'],\n record['cf_due_at'],\n readCustomField(record, 'due_at'),\n readCustomField(record, 'dueAt'),\n ]\n for (const candidate of candidates) {\n const parsed = parseDateValue(candidate)\n if (parsed) return parsed\n }\n return null\n })()\n\n const organizationId = (() => {\n const candidates = [\n record.organization_id,\n record.organizationId,\n record['cf:organization_id'],\n record['cf_organization_id'],\n readCustomField(record, 'organization_id'),\n readCustomField(record, 'organizationId'),\n ]\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.trim().length > 0) {\n return candidate.trim()\n }\n }\n return null\n })()\n\n const customValues: Record<string, unknown> = {}\n const assignCustomValue = (key: string, value: unknown) => {\n const trimmedKey = key.trim()\n if (!trimmedKey.length) return\n customValues[trimmedKey] = value === undefined ? null : value\n }\n for (const [rawKey, rawValue] of Object.entries(record)) {\n if (rawKey.startsWith('cf:')) {\n assignCustomValue(rawKey.slice(3), rawValue)\n } else if (rawKey.startsWith('cf_')) {\n assignCustomValue(rawKey.slice(3), rawValue)\n }\n }\n const nestedCustom = record.custom ?? record.customFields ?? record.cf\n if (nestedCustom && typeof nestedCustom === 'object') {\n for (const [key, value] of Object.entries(nestedCustom as Record<string, unknown>)) {\n assignCustomValue(key, value)\n }\n }\n\n const updatedAt = (() => {\n const candidates = [record.updated_at, record.updatedAt]\n for (const candidate of candidates) {\n const parsed = parseDateValue(candidate)\n if (parsed) return parsed\n }\n return null\n })()\n\n details.set(`${source}:${rawId}`, {\n title: extractTodoTitle(record),\n isDone,\n priority,\n severity,\n description,\n dueAt,\n organizationId,\n updatedAt,\n customValues: Object.keys(customValues).length > 0 ? customValues : null,\n })\n }\n } catch (err) {\n logger.warn('Failed to resolve todo details', { component: 'todoCompatibility', source, err })\n continue\n }\n }\n\n return details\n}\n\nexport async function listLegacyTodoRows(\n em: EntityManager,\n queryEngine: QueryEngine,\n tenantId: string,\n organizationIds: string[] | null,\n entityId: string | undefined,\n options?: { limit?: number | null; isUnrestricted?: boolean },\n): Promise<CustomerTodoRow[]> {\n if (isCollapsedRestrictedOrganizationScope(organizationIds, options?.isUnrestricted)) {\n return []\n }\n const where: Record<string, unknown> = { tenantId }\n if (organizationIds && organizationIds.length > 0) {\n where.organizationId = { $in: organizationIds }\n }\n if (entityId) {\n where.entity = entityId\n }\n\n const findOptions: Record<string, unknown> = {\n populate: ['entity'],\n orderBy: { createdAt: 'desc' },\n }\n if (typeof options?.limit === 'number' && Number.isFinite(options.limit) && options.limit > 0) {\n findOptions.limit = options.limit\n }\n\n const links = await em.find(CustomerTodoLink, where, findOptions as any)\n const details = await resolveLegacyTodoDetails(\n queryEngine,\n links,\n tenantId,\n organizationIds ?? [],\n )\n\n return links.map((link) => {\n const source = resolveLegacyTodoSource(link.todoSource)\n return mapLegacyTodoLinkToRow(\n link,\n details.get(`${source}:${link.todoId}`) ?? null,\n )\n })\n}\n\nexport async function listCanonicalTodoRows(\n em: EntityManager,\n container: CustomersContainerLike,\n auth: CustomersAuthLike,\n selectedOrganizationId: string | null,\n organizationIds: string[] | null,\n options?: {\n entityId?: string\n includeDeleted?: boolean\n source?: string | string[] | null\n pagination?: ListTodosPagination | null\n searchText?: string | null\n limit?: number | null\n isUnrestricted?: boolean\n },\n): Promise<CanonicalTodoListResult> {\n if (isCollapsedRestrictedOrganizationScope(organizationIds, options?.isUnrestricted)) {\n return emptyCanonicalTodoList()\n }\n const where: Record<string, unknown> = {\n tenantId: auth.tenantId,\n interactionType: 'task',\n }\n if (!options?.includeDeleted) {\n where.deletedAt = null\n }\n if (organizationIds && organizationIds.length > 0) {\n where.organizationId = { $in: organizationIds }\n }\n if (options?.entityId) {\n where.entity = options.entityId\n }\n if (options?.source) {\n where.source = Array.isArray(options.source) ? { $in: options.source } : options.source\n }\n const trimmedSearch =\n typeof options?.searchText === 'string' ? options.searchText.trim() : ''\n if (trimmedSearch.length > 0) {\n const pattern = `%${trimmedSearch}%`\n where.$or = [\n { title: { $ilike: pattern } },\n { body: { $ilike: pattern } },\n ]\n }\n\n const findOptions: Record<string, unknown> = {\n orderBy: { createdAt: 'desc' },\n }\n const pagination = options?.pagination ?? null\n if (pagination) {\n findOptions.offset = Math.max(0, (pagination.page - 1) * pagination.pageSize)\n findOptions.limit = pagination.pageSize\n } else if (\n typeof options?.limit === 'number' &&\n Number.isFinite(options.limit) &&\n options.limit > 0\n ) {\n findOptions.limit = options.limit\n }\n\n let interactions: CustomerInteraction[]\n let total: number\n if (pagination) {\n const [rows, count] = await em.findAndCount(CustomerInteraction, where, findOptions as any)\n interactions = rows\n total = count\n } else {\n interactions = await em.find(CustomerInteraction, where, findOptions as any)\n total = interactions.filter((interaction) => !interaction.deletedAt).length\n }\n const activeInteractions = interactions.filter((interaction) => !interaction.deletedAt)\n const groups = new Map<string, CustomerInteraction[]>()\n\n for (const interaction of activeInteractions) {\n const organizationId =\n typeof interaction.organizationId === 'string' && interaction.organizationId.trim().length > 0\n ? interaction.organizationId\n : selectedOrganizationId ?? ''\n const bucket = groups.get(organizationId)\n if (bucket) {\n bucket.push(interaction)\n } else {\n groups.set(organizationId, [interaction])\n }\n }\n\n const rowByInteractionId = new Map<string, CustomerTodoRow>()\n\n for (const [groupOrganizationId, groupedInteractions] of groups.entries()) {\n const scopedOrganizationId = groupOrganizationId.length > 0 ? groupOrganizationId : null\n const hydrated = await hydrateCanonicalInteractions({\n em,\n container,\n auth: {\n ...auth,\n orgId: auth.orgId ?? null,\n },\n selectedOrganizationId: scopedOrganizationId,\n interactions: groupedInteractions,\n })\n const customerIds = Array.from(\n new Set(\n hydrated\n .map((interaction) => interaction.entityId ?? null)\n .filter((value): value is string => !!value),\n ),\n )\n const customerSummaries = await loadCustomerSummaries(\n em,\n customerIds,\n auth.tenantId,\n scopedOrganizationId,\n )\n\n for (const interaction of hydrated) {\n rowByInteractionId.set(\n interaction.id,\n mapInteractionRecordToTodoRow(\n interaction,\n interaction.entityId ? customerSummaries.get(interaction.entityId) ?? null : null,\n ),\n )\n }\n }\n\n return {\n items: activeInteractions\n .map((interaction) => rowByInteractionId.get(interaction.id) ?? null)\n .filter((row): row is CustomerTodoRow => !!row),\n bridgeIds: new Set(interactions.map((interaction) => interaction.id)),\n total,\n }\n}\n\nexport function mapLegacyTodoLinkToRow(\n link: CustomerTodoLink,\n detail: LegacyTodoDetail | null,\n customerOverride?: CustomerSummary | null,\n): CustomerTodoRow {\n const entity = customerOverride ?? {\n id: typeof link.entity === 'string' ? null : link.entity.id,\n displayName: typeof link.entity === 'string' ? null : link.entity.displayName ?? null,\n kind: typeof link.entity === 'string' ? null : link.entity.kind ?? null,\n }\n\n return {\n id: link.id,\n todoId: link.todoId,\n todoSource: resolveLegacyTodoSource(link.todoSource),\n todoTitle: detail?.title ?? null,\n todoIsDone: detail?.isDone ?? null,\n todoPriority: detail?.priority ?? null,\n todoSeverity: detail?.severity ?? null,\n todoDescription: detail?.description ?? null,\n todoDueAt: detail?.dueAt ?? null,\n todoCustomValues: detail?.customValues ?? null,\n todoOrganizationId: detail?.organizationId ?? link.organizationId ?? null,\n todoUpdatedAt: detail?.updatedAt ?? null,\n organizationId: link.organizationId,\n tenantId: link.tenantId,\n createdAt: link.createdAt.toISOString(),\n _integrations: undefined,\n customer: entity,\n }\n}\n\nexport function mapInteractionRecordToTodoRow(\n interaction: InteractionRecord,\n customer: CustomerSummary | null,\n options?: { rowId?: string | null; todoSource?: string | null },\n): CustomerTodoRow {\n const customValues: Record<string, unknown> = { ...(interaction.customValues ?? {}) }\n if (interaction.priority !== undefined && customValues.priority === undefined) {\n customValues.priority = interaction.priority ?? null\n }\n if (interaction.body !== undefined && customValues.description === undefined) {\n customValues.description = interaction.body ?? null\n }\n if (interaction.scheduledAt !== undefined && customValues.due_at === undefined) {\n customValues.due_at = interaction.scheduledAt ?? null\n }\n\n return {\n id:\n typeof options?.rowId === 'string' && options.rowId.trim().length > 0\n ? options.rowId\n : interaction.id,\n todoId: interaction.id,\n todoSource:\n typeof options?.todoSource === 'string' && options.todoSource.trim().length > 0\n ? options.todoSource\n : CUSTOMER_INTERACTION_TASK_SOURCE,\n todoTitle: interaction.title ?? null,\n todoIsDone: interaction.status === 'done',\n todoPriority: interaction.priority ?? null,\n todoSeverity:\n typeof customValues.severity === 'string' && customValues.severity.trim().length > 0\n ? customValues.severity.trim()\n : null,\n todoDescription: interaction.body ?? null,\n todoDueAt: interaction.scheduledAt ?? null,\n todoTimezone: interaction.timezone ?? null,\n todoCustomValues: Object.keys(customValues).length > 0 ? customValues : null,\n todoOrganizationId: interaction.organizationId ?? null,\n todoUpdatedAt: interaction.updatedAt ?? null,\n organizationId: interaction.organizationId ?? '',\n tenantId: interaction.tenantId ?? '',\n createdAt: interaction.createdAt,\n externalHref: resolveExampleIntegrationHref(interaction),\n _integrations: interaction._integrations ?? undefined,\n customer: customer ?? {\n id: interaction.entityId ?? null,\n displayName: null,\n kind: null,\n },\n }\n}\n"],
5
- "mappings": "AAGA,SAAS,4BAA4B;AACrC,SAAS,+BAA+B;AACxC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,8BAA8B,6BAA6B;AACpE,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AAgEvC,SAAS,yBAAkD;AACzD,SAAO,EAAE,OAAO,CAAC,GAAG,WAAW,oBAAI,IAAI,GAAG,OAAO,EAAE;AACrD;AAEA,SAAS,uCACP,iBACA,gBACS;AACT,SAAO,mBAAmB,SAAS,CAAC,mBAAmB,gBAAgB,WAAW;AACpF;AAIA,SAAS,wBAAwB,QAA2C;AAC1E,SAAO,OAAO,WAAW,YAAY,OAAO,KAAK,EAAE,SAAS,IACxD,SACA;AACN;AAEA,SAAS,iBAAiB,QAAgD;AAIxE,QAAM,aAAa,CAAC,SAAS,WAAW,QAAQ,aAAa,YAAY,WAAW,QAAQ,aAAa;AACzG,aAAW,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,SAAS,IAAI,eAAe;AAAA,IACxE,oBAAoB,YAAY,kBAAkB;AAAA,IAClD,eAAe,YAAY,aAAa;AAAA,IACxC,gBAAgB,YAAY,kBAAkB;AAAA,IAC9C,UAAU,YAAY,YAAY;AAAA,IAClC,WAAW,YAAY;AAAA,IACvB,cAAc,8BAA8B,WAAW;AAAA,IACvD,eAAe,YAAY,iBAAiB;AAAA,IAC5C,UAAU,YAAY;AAAA,MACpB,IAAI,YAAY,YAAY;AAAA,MAC5B,aAAa;AAAA,MACb,MAAM;AAAA,IACR;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { QueryEngine } from '@open-mercato/shared/lib/query/types'\nimport type { EntityId } from '@open-mercato/shared/modules/entities'\nimport { isValidEntityIdShape } from '@open-mercato/shared/lib/query/engine'\nimport { parseBooleanFromUnknown } from '@open-mercato/shared/lib/boolean'\nimport {\n CustomerInteraction,\n CustomerTodoLink,\n} from '../data/entities'\nimport type { InteractionRecord } from './interactionCompatibility'\nimport {\n CUSTOMER_INTERACTION_TASK_SOURCE,\n CUSTOMER_INTERACTION_TODO_ADAPTER_SOURCE,\n EXAMPLE_TODO_SOURCE,\n resolveExampleIntegrationHref,\n} from './interactionCompatibility'\nimport { hydrateCanonicalInteractions, loadCustomerSummaries } from './interactionReadModel'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customers')\n\nexport async function countCustomerTodos(\n em: EntityManager,\n scope: { entityId: string; tenantId: string; organizationId: string },\n unified: boolean,\n): Promise<number> {\n const entityScope = {\n entity: scope.entityId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n }\n if (unified) {\n return em.count(CustomerInteraction, { ...entityScope, interactionType: 'task', deletedAt: null })\n }\n\n const adapterScope = {\n ...entityScope,\n interactionType: 'task',\n source: CUSTOMER_INTERACTION_TODO_ADAPTER_SOURCE,\n }\n const adapterIds = em.createQueryBuilder(CustomerInteraction).select('id').where(adapterScope)\n const [legacyCount, adapterCount] = await Promise.all([\n em.count(CustomerTodoLink, { ...entityScope, todoId: { $nin: adapterIds } }),\n em.count(CustomerInteraction, { ...adapterScope, deletedAt: null }),\n ])\n return legacyCount + adapterCount\n}\n\nexport type CustomerTodoRow = {\n id: string\n todoId: string\n todoSource: string\n todoTitle: string | null\n todoIsDone: boolean | null\n todoPriority?: number | null\n todoSeverity?: string | null\n todoDescription?: string | null\n todoDueAt?: string | null\n todoTimezone?: string | null\n todoCustomValues?: Record<string, unknown> | null\n todoOrganizationId: string | null\n todoUpdatedAt?: string | null\n organizationId: string\n tenantId: string\n createdAt: string\n externalHref?: string | null\n _integrations?: Record<string, unknown>\n customer: {\n id: string | null\n displayName: string | null\n kind: string | null\n }\n}\n\nexport type LegacyTodoDetail = {\n title: string | null\n isDone: boolean | null\n priority: number | null\n severity: string | null\n description: string | null\n dueAt: string | null\n organizationId: string | null\n updatedAt: string | null\n customValues: Record<string, unknown> | null\n}\n\ntype CustomerSummary = {\n id: string | null\n displayName: string | null\n kind: string | null\n}\n\ntype CustomersAuthLike = {\n tenantId: string | null\n orgId?: string | null\n sub?: string | null\n userId?: string | null\n keyId?: string | null\n}\n\ntype CustomersContainerLike = {\n resolve: (name: string) => unknown\n}\n\nexport type CanonicalTodoListResult = {\n items: CustomerTodoRow[]\n bridgeIds: Set<string>\n total: number\n}\n\nfunction emptyCanonicalTodoList(): CanonicalTodoListResult {\n return { items: [], bridgeIds: new Set(), total: 0 }\n}\n\nfunction isCollapsedRestrictedOrganizationScope(\n organizationIds: string[] | null | undefined,\n isUnrestricted: boolean | undefined,\n): boolean {\n return isUnrestricted !== true && (!organizationIds || organizationIds.length === 0)\n}\n\nexport type ListTodosPagination = { page: number; pageSize: number }\n\nfunction resolveLegacyTodoSource(source: string | null | undefined): string {\n return typeof source === 'string' && source.trim().length > 0\n ? source\n : EXAMPLE_TODO_SOURCE\n}\n\nfunction extractTodoTitle(record: Record<string, unknown>): string | null {\n // `task_name` / `taskName` carry a workflow user task's name; the query engine\n // returns the raw column on the ORM path and the camelCase property on the\n // indexed one, so both spellings are read.\n const candidates = ['title', 'subject', 'name', 'task_name', 'taskName', 'summary', 'text', 'description']\n for (const key of candidates) {\n const value = record[key]\n if (typeof value === 'string' && value.trim().length > 0) {\n return value.trim()\n }\n }\n return null\n}\n\nfunction parseNumber(value: unknown): number | null {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (!trimmed.length) return null\n const parsed = Number(trimmed)\n if (!Number.isNaN(parsed)) return parsed\n }\n return null\n}\n\nfunction parseDateValue(value: unknown): string | null {\n if (value instanceof Date) {\n return Number.isNaN(value.getTime()) ? null : value.toISOString()\n }\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (!trimmed.length) return null\n const parsed = new Date(trimmed)\n return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString()\n }\n return null\n}\n\nfunction readCustomField(record: Record<string, unknown>, key: string): unknown {\n const custom = record.custom ?? record.customFields ?? record.cf\n if (custom && typeof custom === 'object') {\n const bucket = custom as Record<string, unknown>\n if (key in bucket) return bucket[key]\n }\n return undefined\n}\n\nexport function normalizeTodoSearch(value: string | undefined): string | null {\n if (typeof value !== 'string') return null\n const trimmed = value.trim().toLowerCase()\n return trimmed.length > 0 ? trimmed : null\n}\n\nexport function sortTodoRows(rows: CustomerTodoRow[]): CustomerTodoRow[] {\n return [...rows].sort((left, right) => {\n const leftTime = new Date(left.createdAt).getTime()\n const rightTime = new Date(right.createdAt).getTime()\n if (leftTime === rightTime) {\n return right.id.localeCompare(left.id)\n }\n return rightTime - leftTime\n })\n}\n\nexport function filterTodoRows(rows: CustomerTodoRow[], search: string | null): CustomerTodoRow[] {\n if (!search) return rows\n return rows.filter((row) => {\n const haystack = [\n row.customer.displayName,\n row.todoTitle,\n row.todoDescription,\n ]\n .filter((value): value is string => typeof value === 'string' && value.trim().length > 0)\n .join(' ')\n .toLowerCase()\n return haystack.includes(search)\n })\n}\n\nexport function paginateTodoRows(\n rows: CustomerTodoRow[],\n page: number,\n pageSize: number,\n exportAll: boolean,\n): { items: CustomerTodoRow[]; total: number; page: number; pageSize: number; totalPages: number } {\n const total = rows.length\n if (exportAll) {\n return {\n items: rows,\n total,\n page: 1,\n pageSize: total,\n totalPages: 1,\n }\n }\n const start = (page - 1) * pageSize\n return {\n items: rows.slice(start, start + pageSize),\n total,\n page,\n pageSize,\n totalPages: Math.max(1, Math.ceil(total / pageSize)),\n }\n}\n\nexport async function resolveLegacyTodoDetails(\n queryEngine: QueryEngine,\n links: CustomerTodoLink[],\n tenantId: string | null,\n organizationIds: Array<string | null>,\n): Promise<Map<string, LegacyTodoDetail>> {\n const details = new Map<string, LegacyTodoDetail>()\n if (!links.length || !tenantId) return details\n\n const scopedOrganizationIds = organizationIds.filter(\n (value): value is string => typeof value === 'string' && value.trim().length > 0,\n )\n\n const idsBySource = new Map<string, Set<string>>()\n for (const link of links) {\n const source = resolveLegacyTodoSource(link.todoSource)\n const id =\n typeof link.todoId === 'string' && link.todoId.trim().length > 0\n ? link.todoId\n : String(link.todoId ?? '')\n if (!id) continue\n if (!idsBySource.has(source)) idsBySource.set(source, new Set<string>())\n idsBySource.get(source)!.add(id)\n }\n\n for (const [source, idSet] of idsBySource.entries()) {\n const ids = Array.from(idSet)\n if (!ids.length) continue\n if (!isValidEntityIdShape(source)) {\n // A legacy/malformed `todoSource` (e.g. a bare module name written before\n // the value was required to be a `module:entity` id) does not resolve to\n // any real table. Querying it anyway surfaces a raw DB error (\"relation\n // ... does not exist\") as a dashboard-wide schema-mismatch banner instead\n // of just leaving that row's details unresolved.\n logger.warn('Skipping malformed legacy todo source', { component: 'todoCompatibility', source })\n continue\n }\n try {\n const result = await queryEngine.query<Record<string, unknown>>(source as EntityId, {\n tenantId,\n organizationIds: scopedOrganizationIds.length > 0 ? scopedOrganizationIds : undefined,\n filters: { id: { $in: ids } },\n includeCustomFields: ['priority', 'due_at', 'severity', 'description'],\n page: { page: 1, pageSize: Math.max(ids.length, 1) },\n })\n\n for (const item of result.items ?? []) {\n if (!item || typeof item !== 'object') continue\n const record = item as Record<string, unknown>\n const rawId =\n typeof record.id === 'string' && record.id.trim().length > 0\n ? record.id\n : String(record.id ?? '')\n if (!rawId) continue\n\n const isDone = (() => {\n const direct = parseBooleanFromUnknown(record.is_done)\n if (direct !== null) return direct\n const custom = parseBooleanFromUnknown(readCustomField(record, 'is_done'))\n if (custom !== null) return custom\n const generic = parseBooleanFromUnknown(record.isDone)\n if (generic !== null) return generic\n return parseBooleanFromUnknown(readCustomField(record, 'isDone'))\n })()\n\n const priority = (() => {\n const candidates = [\n record['cf:priority'],\n record['cf_priority'],\n record.priority,\n readCustomField(record, 'priority'),\n ]\n for (const candidate of candidates) {\n const parsed = parseNumber(candidate)\n if (parsed !== null) return parsed\n }\n return null\n })()\n\n const severity = (() => {\n const candidates = [\n record['cf:severity'],\n record['cf_severity'],\n record.severity,\n readCustomField(record, 'severity'),\n ]\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.trim().length > 0) {\n return candidate.trim()\n }\n }\n return null\n })()\n\n const description = (() => {\n const candidates = [\n record.description,\n record['cf:description'],\n record['cf_description'],\n readCustomField(record, 'description'),\n ]\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.trim().length > 0) {\n return candidate.trim()\n }\n }\n return null\n })()\n\n const dueAt = (() => {\n const candidates = [\n record.due_at,\n record.dueAt,\n record['cf:due_at'],\n record['cf_due_at'],\n readCustomField(record, 'due_at'),\n readCustomField(record, 'dueAt'),\n ]\n for (const candidate of candidates) {\n const parsed = parseDateValue(candidate)\n if (parsed) return parsed\n }\n return null\n })()\n\n const organizationId = (() => {\n const candidates = [\n record.organization_id,\n record.organizationId,\n record['cf:organization_id'],\n record['cf_organization_id'],\n readCustomField(record, 'organization_id'),\n readCustomField(record, 'organizationId'),\n ]\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.trim().length > 0) {\n return candidate.trim()\n }\n }\n return null\n })()\n\n const customValues: Record<string, unknown> = {}\n const assignCustomValue = (key: string, value: unknown) => {\n const trimmedKey = key.trim()\n if (!trimmedKey.length) return\n customValues[trimmedKey] = value === undefined ? null : value\n }\n for (const [rawKey, rawValue] of Object.entries(record)) {\n if (rawKey.startsWith('cf:')) {\n assignCustomValue(rawKey.slice(3), rawValue)\n } else if (rawKey.startsWith('cf_')) {\n assignCustomValue(rawKey.slice(3), rawValue)\n }\n }\n const nestedCustom = record.custom ?? record.customFields ?? record.cf\n if (nestedCustom && typeof nestedCustom === 'object') {\n for (const [key, value] of Object.entries(nestedCustom as Record<string, unknown>)) {\n assignCustomValue(key, value)\n }\n }\n\n const updatedAt = (() => {\n const candidates = [record.updated_at, record.updatedAt]\n for (const candidate of candidates) {\n const parsed = parseDateValue(candidate)\n if (parsed) return parsed\n }\n return null\n })()\n\n details.set(`${source}:${rawId}`, {\n title: extractTodoTitle(record),\n isDone,\n priority,\n severity,\n description,\n dueAt,\n organizationId,\n updatedAt,\n customValues: Object.keys(customValues).length > 0 ? customValues : null,\n })\n }\n } catch (err) {\n logger.warn('Failed to resolve todo details', { component: 'todoCompatibility', source, err })\n continue\n }\n }\n\n return details\n}\n\nexport async function listLegacyTodoRows(\n em: EntityManager,\n queryEngine: QueryEngine,\n tenantId: string,\n organizationIds: string[] | null,\n entityId: string | undefined,\n options?: { limit?: number | null; isUnrestricted?: boolean },\n): Promise<CustomerTodoRow[]> {\n if (isCollapsedRestrictedOrganizationScope(organizationIds, options?.isUnrestricted)) {\n return []\n }\n const where: Record<string, unknown> = { tenantId }\n if (organizationIds && organizationIds.length > 0) {\n where.organizationId = { $in: organizationIds }\n }\n if (entityId) {\n where.entity = entityId\n }\n\n const findOptions: Record<string, unknown> = {\n populate: ['entity'],\n orderBy: { createdAt: 'desc' },\n }\n if (typeof options?.limit === 'number' && Number.isFinite(options.limit) && options.limit > 0) {\n findOptions.limit = options.limit\n }\n\n const links = await em.find(CustomerTodoLink, where, findOptions as any)\n const details = await resolveLegacyTodoDetails(\n queryEngine,\n links,\n tenantId,\n organizationIds ?? [],\n )\n\n return links.map((link) => {\n const source = resolveLegacyTodoSource(link.todoSource)\n return mapLegacyTodoLinkToRow(\n link,\n details.get(`${source}:${link.todoId}`) ?? null,\n )\n })\n}\n\nexport async function listCanonicalTodoRows(\n em: EntityManager,\n container: CustomersContainerLike,\n auth: CustomersAuthLike,\n selectedOrganizationId: string | null,\n organizationIds: string[] | null,\n options?: {\n entityId?: string\n includeDeleted?: boolean\n source?: string | string[] | null\n pagination?: ListTodosPagination | null\n searchText?: string | null\n limit?: number | null\n isUnrestricted?: boolean\n },\n): Promise<CanonicalTodoListResult> {\n if (isCollapsedRestrictedOrganizationScope(organizationIds, options?.isUnrestricted)) {\n return emptyCanonicalTodoList()\n }\n const where: Record<string, unknown> = {\n tenantId: auth.tenantId,\n interactionType: 'task',\n }\n if (!options?.includeDeleted) {\n where.deletedAt = null\n }\n if (organizationIds && organizationIds.length > 0) {\n where.organizationId = { $in: organizationIds }\n }\n if (options?.entityId) {\n where.entity = options.entityId\n }\n if (options?.source) {\n where.source = Array.isArray(options.source) ? { $in: options.source } : options.source\n }\n const trimmedSearch =\n typeof options?.searchText === 'string' ? options.searchText.trim() : ''\n if (trimmedSearch.length > 0) {\n const pattern = `%${trimmedSearch}%`\n where.$or = [\n { title: { $ilike: pattern } },\n { body: { $ilike: pattern } },\n ]\n }\n\n const findOptions: Record<string, unknown> = {\n orderBy: { createdAt: 'desc' },\n }\n const pagination = options?.pagination ?? null\n if (pagination) {\n findOptions.offset = Math.max(0, (pagination.page - 1) * pagination.pageSize)\n findOptions.limit = pagination.pageSize\n } else if (\n typeof options?.limit === 'number' &&\n Number.isFinite(options.limit) &&\n options.limit > 0\n ) {\n findOptions.limit = options.limit\n }\n\n let interactions: CustomerInteraction[]\n let total: number\n if (pagination) {\n const [rows, count] = await em.findAndCount(CustomerInteraction, where, findOptions as any)\n interactions = rows\n total = count\n } else {\n interactions = await em.find(CustomerInteraction, where, findOptions as any)\n total = interactions.filter((interaction) => !interaction.deletedAt).length\n }\n const activeInteractions = interactions.filter((interaction) => !interaction.deletedAt)\n const groups = new Map<string, CustomerInteraction[]>()\n\n for (const interaction of activeInteractions) {\n const organizationId =\n typeof interaction.organizationId === 'string' && interaction.organizationId.trim().length > 0\n ? interaction.organizationId\n : selectedOrganizationId ?? ''\n const bucket = groups.get(organizationId)\n if (bucket) {\n bucket.push(interaction)\n } else {\n groups.set(organizationId, [interaction])\n }\n }\n\n const rowByInteractionId = new Map<string, CustomerTodoRow>()\n\n for (const [groupOrganizationId, groupedInteractions] of groups.entries()) {\n const scopedOrganizationId = groupOrganizationId.length > 0 ? groupOrganizationId : null\n const hydrated = await hydrateCanonicalInteractions({\n em,\n container,\n auth: {\n ...auth,\n orgId: auth.orgId ?? null,\n },\n selectedOrganizationId: scopedOrganizationId,\n interactions: groupedInteractions,\n })\n const customerIds = Array.from(\n new Set(\n hydrated\n .map((interaction) => interaction.entityId ?? null)\n .filter((value): value is string => !!value),\n ),\n )\n const customerSummaries = await loadCustomerSummaries(\n em,\n customerIds,\n auth.tenantId,\n scopedOrganizationId,\n )\n\n for (const interaction of hydrated) {\n rowByInteractionId.set(\n interaction.id,\n mapInteractionRecordToTodoRow(\n interaction,\n interaction.entityId ? customerSummaries.get(interaction.entityId) ?? null : null,\n ),\n )\n }\n }\n\n return {\n items: activeInteractions\n .map((interaction) => rowByInteractionId.get(interaction.id) ?? null)\n .filter((row): row is CustomerTodoRow => !!row),\n bridgeIds: new Set(interactions.map((interaction) => interaction.id)),\n total,\n }\n}\n\nexport function mapLegacyTodoLinkToRow(\n link: CustomerTodoLink,\n detail: LegacyTodoDetail | null,\n customerOverride?: CustomerSummary | null,\n): CustomerTodoRow {\n const entity = customerOverride ?? {\n id: typeof link.entity === 'string' ? null : link.entity.id,\n displayName: typeof link.entity === 'string' ? null : link.entity.displayName ?? null,\n kind: typeof link.entity === 'string' ? null : link.entity.kind ?? null,\n }\n\n return {\n id: link.id,\n todoId: link.todoId,\n todoSource: resolveLegacyTodoSource(link.todoSource),\n todoTitle: detail?.title ?? null,\n todoIsDone: detail?.isDone ?? null,\n todoPriority: detail?.priority ?? null,\n todoSeverity: detail?.severity ?? null,\n todoDescription: detail?.description ?? null,\n todoDueAt: detail?.dueAt ?? null,\n todoCustomValues: detail?.customValues ?? null,\n todoOrganizationId: detail?.organizationId ?? link.organizationId ?? null,\n todoUpdatedAt: detail?.updatedAt ?? null,\n organizationId: link.organizationId,\n tenantId: link.tenantId,\n createdAt: link.createdAt.toISOString(),\n _integrations: undefined,\n customer: entity,\n }\n}\n\nexport function mapInteractionRecordToTodoRow(\n interaction: InteractionRecord,\n customer: CustomerSummary | null,\n options?: { rowId?: string | null; todoSource?: string | null },\n): CustomerTodoRow {\n const customValues: Record<string, unknown> = { ...(interaction.customValues ?? {}) }\n if (interaction.priority !== undefined && customValues.priority === undefined) {\n customValues.priority = interaction.priority ?? null\n }\n if (interaction.body !== undefined && customValues.description === undefined) {\n customValues.description = interaction.body ?? null\n }\n if (interaction.scheduledAt !== undefined && customValues.due_at === undefined) {\n customValues.due_at = interaction.scheduledAt ?? null\n }\n\n return {\n id:\n typeof options?.rowId === 'string' && options.rowId.trim().length > 0\n ? options.rowId\n : interaction.id,\n todoId: interaction.id,\n todoSource:\n typeof options?.todoSource === 'string' && options.todoSource.trim().length > 0\n ? options.todoSource\n : CUSTOMER_INTERACTION_TASK_SOURCE,\n todoTitle: interaction.title ?? null,\n todoIsDone: interaction.status === 'done',\n todoPriority: interaction.priority ?? null,\n todoSeverity:\n typeof customValues.severity === 'string' && customValues.severity.trim().length > 0\n ? customValues.severity.trim()\n : null,\n todoDescription: interaction.body ?? null,\n todoDueAt: interaction.scheduledAt ?? null,\n todoTimezone: interaction.timezone ?? null,\n todoCustomValues: Object.keys(customValues).length > 0 ? customValues : null,\n todoOrganizationId: interaction.organizationId ?? null,\n todoUpdatedAt: interaction.updatedAt ?? null,\n organizationId: interaction.organizationId ?? '',\n tenantId: interaction.tenantId ?? '',\n createdAt: interaction.createdAt,\n externalHref: resolveExampleIntegrationHref(interaction),\n _integrations: interaction._integrations ?? undefined,\n customer: customer ?? {\n id: interaction.entityId ?? null,\n displayName: null,\n kind: null,\n },\n }\n}\n"],
5
+ "mappings": "AAGA,SAAS,4BAA4B;AACrC,SAAS,+BAA+B;AACxC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,8BAA8B,6BAA6B;AACpE,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AAEvC,eAAsB,mBACpB,IACA,OACA,SACiB;AACjB,QAAM,cAAc;AAAA,IAClB,QAAQ,MAAM;AAAA,IACd,UAAU,MAAM;AAAA,IAChB,gBAAgB,MAAM;AAAA,EACxB;AACA,MAAI,SAAS;AACX,WAAO,GAAG,MAAM,qBAAqB,EAAE,GAAG,aAAa,iBAAiB,QAAQ,WAAW,KAAK,CAAC;AAAA,EACnG;AAEA,QAAM,eAAe;AAAA,IACnB,GAAG;AAAA,IACH,iBAAiB;AAAA,IACjB,QAAQ;AAAA,EACV;AACA,QAAM,aAAa,GAAG,mBAAmB,mBAAmB,EAAE,OAAO,IAAI,EAAE,MAAM,YAAY;AAC7F,QAAM,CAAC,aAAa,YAAY,IAAI,MAAM,QAAQ,IAAI;AAAA,IACpD,GAAG,MAAM,kBAAkB,EAAE,GAAG,aAAa,QAAQ,EAAE,MAAM,WAAW,EAAE,CAAC;AAAA,IAC3E,GAAG,MAAM,qBAAqB,EAAE,GAAG,cAAc,WAAW,KAAK,CAAC;AAAA,EACpE,CAAC;AACD,SAAO,cAAc;AACvB;AAgEA,SAAS,yBAAkD;AACzD,SAAO,EAAE,OAAO,CAAC,GAAG,WAAW,oBAAI,IAAI,GAAG,OAAO,EAAE;AACrD;AAEA,SAAS,uCACP,iBACA,gBACS;AACT,SAAO,mBAAmB,SAAS,CAA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YAAY;AAAA,IACtC,cACE,OAAO,aAAa,aAAa,YAAY,aAAa,SAAS,KAAK,EAAE,SAAS,IAC/E,aAAa,SAAS,KAAK,IAC3B;AAAA,IACN,iBAAiB,YAAY,QAAQ;AAAA,IACrC,WAAW,YAAY,eAAe;AAAA,IACtC,cAAc,YAAY,YAAY;AAAA,IACtC,kBAAkB,OAAO,KAAK,YAAY,EAAE,SAAS,IAAI,eAAe;AAAA,IACxE,oBAAoB,YAAY,kBAAkB;AAAA,IAClD,eAAe,YAAY,aAAa;AAAA,IACxC,gBAAgB,YAAY,kBAAkB;AAAA,IAC9C,UAAU,YAAY,YAAY;AAAA,IAClC,WAAW,YAAY;AAAA,IACvB,cAAc,8BAA8B,WAAW;AAAA,IACvD,eAAe,YAAY,iBAAiB;AAAA,IAC5C,UAAU,YAAY;AAAA,MACpB,IAAI,YAAY,YAAY;AAAA,MAC5B,aAAa;AAAA,MACb,MAAM;AAAA,IACR;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -14,7 +14,7 @@ import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
14
14
  import { Organization } from "@open-mercato/core/modules/directory/data/entities";
15
15
  import { organizationUpdateSchema } from "@open-mercato/core/modules/directory/data/validators";
16
16
  import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
17
- import { resolveSingleOrganizationIdOrDeny } from "@open-mercato/core/modules/directory/utils/organizationScopeFilter";
17
+ import { isExplicitlyEmptyOrganizationScope } from "@open-mercato/shared/lib/auth/organizationScope";
18
18
  import "@open-mercato/core/modules/directory/commands/organizations";
19
19
  import { createLogger } from "@open-mercato/shared/lib/logger";
20
20
  import { getCommandInterceptorHttpRejection } from "@open-mercato/shared/lib/commands/errors";
@@ -63,15 +63,12 @@ async function resolveCurrentOrganization(req) {
63
63
  }
64
64
  const container = await createRequestContainer();
65
65
  const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req });
66
- let organizationId;
67
- try {
68
- organizationId = resolveSingleOrganizationIdOrDeny(scope, auth);
69
- } catch (error) {
70
- if (isCrudHttpError(error)) {
71
- return { response: NextResponse.json(error.body, { status: error.status }) };
72
- }
73
- throw error;
66
+ if (isExplicitlyEmptyOrganizationScope(scope)) {
67
+ return {
68
+ response: NextResponse.json({ error: translate("api.errors.forbidden", "Forbidden") }, { status: 403 })
69
+ };
74
70
  }
71
+ const organizationId = scope.selectedId;
75
72
  const tenantId = scope.tenantId ?? auth.tenantId ?? null;
76
73
  if (!organizationId || !tenantId) {
77
74
  return {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/directory/api/organization-branding/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { runWithCacheTenant } from '@open-mercato/cache'\nimport type { CommandBus, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\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 { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport { enforceCommandOptimisticLock } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { Organization } from '@open-mercato/core/modules/directory/data/entities'\nimport { organizationUpdateSchema } from '@open-mercato/core/modules/directory/data/validators'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { resolveSingleOrganizationIdOrDeny } from '@open-mercato/core/modules/directory/utils/organizationScopeFilter'\nimport '@open-mercato/core/modules/directory/commands/organizations'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getCommandInterceptorHttpRejection } from '@open-mercato/shared/lib/commands/errors'\n\nconst logger = createLogger('directory').child({ component: 'organization-branding' })\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['directory.organizations.view'] },\n PUT: { requireAuth: true, requireFeatures: ['directory.organizations.manage'] },\n}\n\nconst brandingResponseSchema = z.object({\n organizationId: z.string().uuid(),\n organizationName: z.string(),\n tenantId: z.string().uuid(),\n logoUrl: z.string().nullable(),\n logoPreserveAspectRatio: z.boolean(),\n updatedAt: z.string().nullable(),\n})\n\nconst brandingUpdateSchema = z.object({\n logoUrl: organizationUpdateSchema.shape.logoUrl,\n logoPreserveAspectRatio: organizationUpdateSchema.shape.logoPreserveAspectRatio,\n})\n\nconst errorSchema = z.object({\n error: z.string(),\n})\n\ntype RequestContainer = Awaited<ReturnType<typeof createRequestContainer>>\n\nfunction buildCommandContext(\n container: RequestContainer,\n auth: NonNullable<Awaited<ReturnType<typeof getAuthFromRequest>>>,\n req: Request,\n organizationId: string,\n tenantId: string,\n): CommandRuntimeContext {\n return {\n container,\n auth,\n organizationScope: {\n selectedId: organizationId,\n filterIds: [organizationId],\n allowedIds: null,\n tenantId,\n },\n selectedOrganizationId: organizationId,\n organizationIds: [organizationId],\n request: req,\n }\n}\n\nasync function resolveCurrentOrganization(req: Request) {\n const { translate } = await resolveTranslations()\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub) {\n return {\n response: NextResponse.json({ error: translate('api.errors.unauthorized', 'Unauthorized') }, { status: 401 }),\n }\n }\n\n const container = await createRequestContainer()\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n let organizationId: string | null\n try {\n organizationId = resolveSingleOrganizationIdOrDeny(scope, auth)\n } catch (error) {\n if (isCrudHttpError(error)) {\n return { response: NextResponse.json(error.body, { status: error.status }) }\n }\n throw error\n }\n const tenantId = scope.tenantId ?? auth.tenantId ?? null\n if (!organizationId || !tenantId) {\n return {\n response: NextResponse.json(\n {\n error: translate(\n 'directory.branding.errors.organizationRequired',\n 'Select a single organization before changing sidebar branding.',\n ),\n },\n { status: 400 },\n ),\n }\n }\n\n const em = container.resolve('em') as EntityManager\n const organization = await findOneWithDecryption(\n em,\n Organization,\n { id: organizationId, tenant: tenantId, deletedAt: null },\n { populate: ['tenant'] },\n { tenantId, organizationId },\n )\n if (!organization) {\n return {\n response: NextResponse.json(\n { error: translate('directory.branding.errors.notFound', 'Organization not found') },\n { status: 404 },\n ),\n }\n }\n\n return { auth, container, organization, organizationId, tenantId, translate }\n}\n\nfunction toIsoOrNull(value: Date | string | null | undefined): string | null {\n if (value == null) return null\n if (value instanceof Date) {\n const ms = value.getTime()\n return Number.isFinite(ms) ? new Date(ms).toISOString() : null\n }\n const trimmed = String(value).trim()\n if (!trimmed) return null\n const parsed = new Date(trimmed)\n return Number.isFinite(parsed.getTime()) ? parsed.toISOString() : null\n}\n\nfunction toResponsePayload(organization: Organization, tenantId: string) {\n return {\n organizationId: String(organization.id),\n organizationName: organization.name,\n tenantId,\n logoUrl: organization.logoUrl ?? null,\n logoPreserveAspectRatio: !!organization.logoPreserveAspectRatio,\n updatedAt: toIsoOrNull(organization.updatedAt),\n }\n}\n\nasync function invalidateSidebarBrandingCache(container: RequestContainer, organizationId: string, tenantId: string) {\n try {\n const cache = container.resolve('cache') as {\n deleteByTags?: (tags: string[]) => Promise<unknown>\n } | null\n await runWithCacheTenant(tenantId, () =>\n cache?.deleteByTags?.([\n `nav:sidebar:organization:${organizationId}`,\n `nav:sidebar:tenant:${tenantId}`,\n ]),\n )\n } catch {\n // Cache invalidation is best-effort; the persisted branding is the source of truth.\n }\n}\n\nexport async function GET(req: Request) {\n const resolved = await resolveCurrentOrganization(req)\n if ('response' in resolved) return resolved.response\n\n return NextResponse.json(toResponsePayload(resolved.organization, resolved.tenantId))\n}\n\nexport async function PUT(req: Request) {\n const resolved = await resolveCurrentOrganization(req)\n if ('response' in resolved) return resolved.response\n\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json(\n { error: resolved.translate('directory.branding.errors.invalidLogoUrl', 'Enter a valid image URL.') },\n { status: 422 },\n )\n }\n if (!body || typeof body !== 'object' || !Object.prototype.hasOwnProperty.call(body, 'logoUrl')) {\n return NextResponse.json(\n { error: resolved.translate('directory.branding.errors.invalidLogoUrl', 'Enter a valid image URL.') },\n { status: 422 },\n )\n }\n\n const parsed = brandingUpdateSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json(\n {\n error: resolved.translate('directory.branding.errors.invalidLogoUrl', 'Enter a valid image URL.'),\n issues: parsed.error.issues,\n },\n { status: 422 },\n )\n }\n\n try {\n // Refuse a stale overwrite when two tabs edit the same organization branding.\n // Strictly additive \u2014 a no-op when the client omits the expected-version header.\n enforceCommandOptimisticLock({\n resourceKind: 'directory.organization',\n resourceId: resolved.organizationId,\n current: resolved.organization.updatedAt ?? null,\n request: req,\n })\n\n // Mutation-guard contract for custom write routes: validate before the write,\n // then run the after-success hook once the command persists.\n const guardResult = await validateCrudMutationGuard(resolved.container, {\n tenantId: resolved.tenantId,\n organizationId: resolved.organizationId,\n userId: resolved.auth.sub,\n resourceKind: 'directory.organization',\n resourceId: resolved.organizationId,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: {\n logoUrl: parsed.data.logoUrl ?? null,\n ...(parsed.data.logoPreserveAspectRatio !== undefined\n ? { logoPreserveAspectRatio: parsed.data.logoPreserveAspectRatio }\n : {}),\n },\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n\n const commandBus = resolved.container.resolve('commandBus') as CommandBus\n const ctx = buildCommandContext(\n resolved.container,\n resolved.auth,\n req,\n resolved.organizationId,\n resolved.tenantId,\n )\n const { result } = await commandBus.execute<Record<string, unknown>, Organization>(\n 'directory.organizations.update',\n {\n input: {\n id: resolved.organizationId,\n tenantId: resolved.tenantId,\n logoUrl: parsed.data.logoUrl ?? null,\n ...(parsed.data.logoPreserveAspectRatio !== undefined\n ? { logoPreserveAspectRatio: parsed.data.logoPreserveAspectRatio }\n : {}),\n },\n ctx,\n },\n )\n\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(resolved.container, {\n tenantId: resolved.tenantId,\n organizationId: resolved.organizationId,\n userId: resolved.auth.sub,\n resourceKind: 'directory.organization',\n resourceId: resolved.organizationId,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n await invalidateSidebarBrandingCache(resolved.container, resolved.organizationId, resolved.tenantId)\n return NextResponse.json(toResponsePayload(result, resolved.tenantId))\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n const interceptorRejection = getCommandInterceptorHttpRejection(err)\n if (interceptorRejection) {\n return NextResponse.json(interceptorRejection.body, { status: interceptorRejection.status })\n }\n logger.error('Organization branding update failed', { err })\n return NextResponse.json(\n { error: resolved.translate('directory.branding.errors.save', 'Failed to update organization branding.') },\n { status: 400 },\n )\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Directory',\n summary: 'Current organization branding',\n methods: {\n GET: {\n summary: 'Read sidebar branding for the selected organization',\n description: 'Returns the logo URL used by the backend sidebar for the currently selected organization.',\n responses: [\n { status: 200, description: 'Organization branding', schema: brandingResponseSchema },\n ],\n errors: [\n { status: 400, description: 'A concrete organization scope is required', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n { status: 404, description: 'Organization not found', schema: errorSchema },\n ],\n },\n PUT: {\n summary: 'Update sidebar branding for the selected organization',\n description: 'Stores an external image URL or an internal attachment image URL as the selected organization logo.',\n requestBody: {\n contentType: 'application/json',\n schema: brandingUpdateSchema,\n },\n responses: [\n { status: 200, description: 'Updated organization branding', schema: brandingResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Save failed', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n { status: 409, description: 'Organization branding changed since it was loaded', schema: errorSchema },\n { status: 422, description: 'Invalid logo URL', schema: errorSchema },\n ],\n },\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AAGnC,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,oCAAoC;AAC7C,SAAS,6BAA6B;AACtC,SAAS,2BAA2B;AACpC,SAAS,oBAAoB;AAC7B,SAAS,gCAAgC;AACzC,SAAS,0CAA0C;AACnD,SAAS,yCAAyC;AAClD,OAAO;AACP,SAAS,oBAAoB;AAC7B,SAAS,0CAA0C;AAEnD,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,wBAAwB,CAAC;AAE9E,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,8BAA8B,EAAE;AAAA,EAC5E,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,gCAAgC,EAAE;AAChF;AAEA,MAAM,yBAAyB,EAAE,OAAO;AAAA,EACtC,gBAAgB,EAAE,OAAO,EAAE,KAAK;AAAA,EAChC,kBAAkB,EAAE,OAAO;AAAA,EAC3B,UAAU,EAAE,OAAO,EAAE,KAAK;AAAA,EAC1B,SAAS,EAAE,OAAO,EAAE,SAAS;AAAA,EAC7B,yBAAyB,EAAE,QAAQ;AAAA,EACnC,WAAW,EAAE,OAAO,EAAE,SAAS;AACjC,CAAC;AAED,MAAM,uBAAuB,EAAE,OAAO;AAAA,EACpC,SAAS,yBAAyB,MAAM;AAAA,EACxC,yBAAyB,yBAAyB,MAAM;AAC1D,CAAC;AAED,MAAM,cAAc,EAAE,OAAO;AAAA,EAC3B,OAAO,EAAE,OAAO;AAClB,CAAC;AAID,SAAS,oBACP,WACA,MACA,KACA,gBACA,UACuB;AACvB,SAAO;AAAA,IACL;AAA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AAQ,KAAK,aAAa,qDAAqD,QAAQ,YAAY;AAAA,QACrG,EAAE,QAAQ,KAAK,aAAa,oBAAoB,QAAQ,YAAY;AAAA,MACtE;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { runWithCacheTenant } from '@open-mercato/cache'\nimport type { CommandBus, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\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 { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport { enforceCommandOptimisticLock } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { Organization } from '@open-mercato/core/modules/directory/data/entities'\nimport { organizationUpdateSchema } from '@open-mercato/core/modules/directory/data/validators'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { isExplicitlyEmptyOrganizationScope } from '@open-mercato/shared/lib/auth/organizationScope'\nimport '@open-mercato/core/modules/directory/commands/organizations'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getCommandInterceptorHttpRejection } from '@open-mercato/shared/lib/commands/errors'\n\nconst logger = createLogger('directory').child({ component: 'organization-branding' })\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['directory.organizations.view'] },\n PUT: { requireAuth: true, requireFeatures: ['directory.organizations.manage'] },\n}\n\nconst brandingResponseSchema = z.object({\n organizationId: z.string().uuid(),\n organizationName: z.string(),\n tenantId: z.string().uuid(),\n logoUrl: z.string().nullable(),\n logoPreserveAspectRatio: z.boolean(),\n updatedAt: z.string().nullable(),\n})\n\nconst brandingUpdateSchema = z.object({\n logoUrl: organizationUpdateSchema.shape.logoUrl,\n logoPreserveAspectRatio: organizationUpdateSchema.shape.logoPreserveAspectRatio,\n})\n\nconst errorSchema = z.object({\n error: z.string(),\n})\n\ntype RequestContainer = Awaited<ReturnType<typeof createRequestContainer>>\n\nfunction buildCommandContext(\n container: RequestContainer,\n auth: NonNullable<Awaited<ReturnType<typeof getAuthFromRequest>>>,\n req: Request,\n organizationId: string,\n tenantId: string,\n): CommandRuntimeContext {\n return {\n container,\n auth,\n organizationScope: {\n selectedId: organizationId,\n filterIds: [organizationId],\n allowedIds: null,\n tenantId,\n },\n selectedOrganizationId: organizationId,\n organizationIds: [organizationId],\n request: req,\n }\n}\n\nasync function resolveCurrentOrganization(req: Request) {\n const { translate } = await resolveTranslations()\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub) {\n return {\n response: NextResponse.json({ error: translate('api.errors.unauthorized', 'Unauthorized') }, { status: 401 }),\n }\n }\n\n const container = await createRequestContainer()\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n if (isExplicitlyEmptyOrganizationScope(scope)) {\n return {\n response: NextResponse.json({ error: translate('api.errors.forbidden', 'Forbidden') }, { status: 403 }),\n }\n }\n const organizationId = scope.selectedId\n const tenantId = scope.tenantId ?? auth.tenantId ?? null\n if (!organizationId || !tenantId) {\n return {\n response: NextResponse.json(\n {\n error: translate(\n 'directory.branding.errors.organizationRequired',\n 'Select a single organization before changing sidebar branding.',\n ),\n },\n { status: 400 },\n ),\n }\n }\n\n const em = container.resolve('em') as EntityManager\n const organization = await findOneWithDecryption(\n em,\n Organization,\n { id: organizationId, tenant: tenantId, deletedAt: null },\n { populate: ['tenant'] },\n { tenantId, organizationId },\n )\n if (!organization) {\n return {\n response: NextResponse.json(\n { error: translate('directory.branding.errors.notFound', 'Organization not found') },\n { status: 404 },\n ),\n }\n }\n\n return { auth, container, organization, organizationId, tenantId, translate }\n}\n\nfunction toIsoOrNull(value: Date | string | null | undefined): string | null {\n if (value == null) return null\n if (value instanceof Date) {\n const ms = value.getTime()\n return Number.isFinite(ms) ? new Date(ms).toISOString() : null\n }\n const trimmed = String(value).trim()\n if (!trimmed) return null\n const parsed = new Date(trimmed)\n return Number.isFinite(parsed.getTime()) ? parsed.toISOString() : null\n}\n\nfunction toResponsePayload(organization: Organization, tenantId: string) {\n return {\n organizationId: String(organization.id),\n organizationName: organization.name,\n tenantId,\n logoUrl: organization.logoUrl ?? null,\n logoPreserveAspectRatio: !!organization.logoPreserveAspectRatio,\n updatedAt: toIsoOrNull(organization.updatedAt),\n }\n}\n\nasync function invalidateSidebarBrandingCache(container: RequestContainer, organizationId: string, tenantId: string) {\n try {\n const cache = container.resolve('cache') as {\n deleteByTags?: (tags: string[]) => Promise<unknown>\n } | null\n await runWithCacheTenant(tenantId, () =>\n cache?.deleteByTags?.([\n `nav:sidebar:organization:${organizationId}`,\n `nav:sidebar:tenant:${tenantId}`,\n ]),\n )\n } catch {\n // Cache invalidation is best-effort; the persisted branding is the source of truth.\n }\n}\n\nexport async function GET(req: Request) {\n const resolved = await resolveCurrentOrganization(req)\n if ('response' in resolved) return resolved.response\n\n return NextResponse.json(toResponsePayload(resolved.organization, resolved.tenantId))\n}\n\nexport async function PUT(req: Request) {\n const resolved = await resolveCurrentOrganization(req)\n if ('response' in resolved) return resolved.response\n\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json(\n { error: resolved.translate('directory.branding.errors.invalidLogoUrl', 'Enter a valid image URL.') },\n { status: 422 },\n )\n }\n if (!body || typeof body !== 'object' || !Object.prototype.hasOwnProperty.call(body, 'logoUrl')) {\n return NextResponse.json(\n { error: resolved.translate('directory.branding.errors.invalidLogoUrl', 'Enter a valid image URL.') },\n { status: 422 },\n )\n }\n\n const parsed = brandingUpdateSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json(\n {\n error: resolved.translate('directory.branding.errors.invalidLogoUrl', 'Enter a valid image URL.'),\n issues: parsed.error.issues,\n },\n { status: 422 },\n )\n }\n\n try {\n // Refuse a stale overwrite when two tabs edit the same organization branding.\n // Strictly additive \u2014 a no-op when the client omits the expected-version header.\n enforceCommandOptimisticLock({\n resourceKind: 'directory.organization',\n resourceId: resolved.organizationId,\n current: resolved.organization.updatedAt ?? null,\n request: req,\n })\n\n // Mutation-guard contract for custom write routes: validate before the write,\n // then run the after-success hook once the command persists.\n const guardResult = await validateCrudMutationGuard(resolved.container, {\n tenantId: resolved.tenantId,\n organizationId: resolved.organizationId,\n userId: resolved.auth.sub,\n resourceKind: 'directory.organization',\n resourceId: resolved.organizationId,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: {\n logoUrl: parsed.data.logoUrl ?? null,\n ...(parsed.data.logoPreserveAspectRatio !== undefined\n ? { logoPreserveAspectRatio: parsed.data.logoPreserveAspectRatio }\n : {}),\n },\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n\n const commandBus = resolved.container.resolve('commandBus') as CommandBus\n const ctx = buildCommandContext(\n resolved.container,\n resolved.auth,\n req,\n resolved.organizationId,\n resolved.tenantId,\n )\n const { result } = await commandBus.execute<Record<string, unknown>, Organization>(\n 'directory.organizations.update',\n {\n input: {\n id: resolved.organizationId,\n tenantId: resolved.tenantId,\n logoUrl: parsed.data.logoUrl ?? null,\n ...(parsed.data.logoPreserveAspectRatio !== undefined\n ? { logoPreserveAspectRatio: parsed.data.logoPreserveAspectRatio }\n : {}),\n },\n ctx,\n },\n )\n\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(resolved.container, {\n tenantId: resolved.tenantId,\n organizationId: resolved.organizationId,\n userId: resolved.auth.sub,\n resourceKind: 'directory.organization',\n resourceId: resolved.organizationId,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n await invalidateSidebarBrandingCache(resolved.container, resolved.organizationId, resolved.tenantId)\n return NextResponse.json(toResponsePayload(result, resolved.tenantId))\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n const interceptorRejection = getCommandInterceptorHttpRejection(err)\n if (interceptorRejection) {\n return NextResponse.json(interceptorRejection.body, { status: interceptorRejection.status })\n }\n logger.error('Organization branding update failed', { err })\n return NextResponse.json(\n { error: resolved.translate('directory.branding.errors.save', 'Failed to update organization branding.') },\n { status: 400 },\n )\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Directory',\n summary: 'Current organization branding',\n methods: {\n GET: {\n summary: 'Read sidebar branding for the selected organization',\n description: 'Returns the logo URL used by the backend sidebar for the currently selected organization.',\n responses: [\n { status: 200, description: 'Organization branding', schema: brandingResponseSchema },\n ],\n errors: [\n { status: 400, description: 'A concrete organization scope is required', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n { status: 404, description: 'Organization not found', schema: errorSchema },\n ],\n },\n PUT: {\n summary: 'Update sidebar branding for the selected organization',\n description: 'Stores an external image URL or an internal attachment image URL as the selected organization logo.',\n requestBody: {\n contentType: 'application/json',\n schema: brandingUpdateSchema,\n },\n responses: [\n { status: 200, description: 'Updated organization branding', schema: brandingResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Save failed', schema: errorSchema },\n { status: 401, description: 'Unauthorized', schema: errorSchema },\n { status: 409, description: 'Organization branding changed since it was loaded', schema: errorSchema },\n { status: 422, description: 'Invalid logo URL', schema: errorSchema },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AAGnC,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,oCAAoC;AAC7C,SAAS,6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AE,OAAO,SAAS,UAAU,kCAAkC,yCAAyC,EAAE;AAAA,MACzG,EAAE,QAAQ,IAAI;AAAA,IAChB;AAAA,EACF;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,KAAK;AAAA,MACH,SAAS;AAAA,MACT,aAAa;AAAA,MACb,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,yBAAyB,QAAQ,uBAAuB;AAAA,MACtF;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,6CAA6C,QAAQ,YAAY;AAAA,QAC7F,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,YAAY;AAAA,QAChE,EAAE,QAAQ,KAAK,aAAa,0BAA0B,QAAQ,YAAY;AAAA,MAC5E;AAAA,IACF;AAAA,IACA,KAAK;AAAA,MACH,SAAS;AAAA,MACT,aAAa;AAAA,MACb,aAAa;AAAA,QACX,aAAa;AAAA,QACb,QAAQ;AAAA,MACV;AAAA,MACA,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,iCAAiC,QAAQ,uBAAuB;AAAA,MAC9F;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,eAAe,QAAQ,YAAY;AAAA,QAC/D,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,YAAY;AAAA,QAChE,EAAE,QAAQ,KAAK,aAAa,qDAAqD,QAAQ,YAAY;AAAA,QACrG,EAAE,QAAQ,KAAK,aAAa,oBAAoB,QAAQ,YAAY;AAAA,MACtE;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -15,13 +15,15 @@ import { Button } from "@open-mercato/ui/primitives/button";
15
15
  import { Input } from "@open-mercato/ui/primitives/input";
16
16
  import { SwitchField } from "@open-mercato/ui/primitives/switch-field";
17
17
  import { useT } from "@open-mercato/shared/lib/i18n/context";
18
- import { useOrganizationScopeDetail } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
18
+ import { useOrganizationScopeDetail, useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
19
+ import { getCurrentOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/organizationEvents";
19
20
  const BRANDING_API = "/api/directory/organization-branding";
20
21
  const BRANDING_ENTITY_ID = "directory.organization";
21
22
  function OrganizationBrandingPage() {
22
23
  const t = useT();
23
24
  const queryClient = useQueryClient();
24
25
  const { organizationId, tenantId } = useOrganizationScopeDetail();
26
+ const scopeVersion = useOrganizationScopeVersion();
25
27
  const [logoUrl, setLogoUrl] = React.useState("");
26
28
  const [logoPreserveAspectRatio, setLogoPreserveAspectRatio] = React.useState(false);
27
29
  const [selectedFile, setSelectedFile] = React.useState(null);
@@ -45,7 +47,8 @@ function OrganizationBrandingPage() {
45
47
  setLogoUrl(data?.logoUrl ?? "");
46
48
  setLogoPreserveAspectRatio(data?.logoPreserveAspectRatio ?? false);
47
49
  setSelectedFile(null);
48
- }, [data?.logoPreserveAspectRatio, data?.logoUrl, organizationId, tenantId]);
50
+ if (fileInputRef.current) fileInputRef.current.value = "";
51
+ }, [scopeVersion, organizationId, tenantId, data?.organizationId, data?.logoPreserveAspectRatio, data?.logoUrl]);
49
52
  React.useEffect(() => {
50
53
  if (!selectedFile || typeof URL === "undefined") {
51
54
  setFilePreviewUrl(null);
@@ -81,7 +84,13 @@ function OrganizationBrandingPage() {
81
84
  try {
82
85
  await runMutation({
83
86
  operation: async () => {
87
+ if (getCurrentOrganizationScopeVersion() !== scopeVersion) {
88
+ throw new Error("[internal] Organization scope changed during branding save");
89
+ }
84
90
  const uploadedLogoUrl = shouldUpload ? await uploadLogo(data.organizationId) : null;
91
+ if (getCurrentOrganizationScopeVersion() !== scopeVersion) {
92
+ throw new Error("[internal] Organization scope changed during branding save");
93
+ }
85
94
  const resolvedLogoUrl = uploadedLogoUrl ?? nextLogoUrl ?? logoUrl.trim();
86
95
  const response = await withScopedApiRequestHeaders(
87
96
  buildOptimisticLockHeader(data.updatedAt),
@@ -112,12 +121,15 @@ function OrganizationBrandingPage() {
112
121
  hasUpload: shouldUpload
113
122
  }
114
123
  });
124
+ if (getCurrentOrganizationScopeVersion() !== scopeVersion) return;
115
125
  await queryClient.invalidateQueries({ queryKey: ["directory-organization-branding"] });
126
+ if (getCurrentOrganizationScopeVersion() !== scopeVersion) return;
116
127
  window.dispatchEvent(new Event("om:refresh-sidebar"));
117
128
  setSelectedFile(null);
118
129
  if (fileInputRef.current) fileInputRef.current.value = "";
119
130
  flash(t("directory.branding.flash.saved", "Organization branding updated"), "success");
120
131
  } catch (err) {
132
+ if (getCurrentOrganizationScopeVersion() !== scopeVersion) return;
121
133
  if (surfaceRecordConflict(err, t)) return;
122
134
  const fallback = t("directory.branding.errors.save", "Failed to update organization branding");
123
135
  const message = err instanceof Error ? err.message : fallback;
@@ -125,7 +137,7 @@ function OrganizationBrandingPage() {
125
137
  } finally {
126
138
  setSaving(false);
127
139
  }
128
- }, [data, logoPreserveAspectRatio, logoUrl, queryClient, runMutation, selectedFile, t, uploadLogo]);
140
+ }, [data, logoPreserveAspectRatio, logoUrl, queryClient, runMutation, scopeVersion, selectedFile, t, uploadLogo]);
129
141
  const handleSubmit = React.useCallback((event) => {
130
142
  event.preventDefault();
131
143
  void saveBranding();
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/modules/directory/backend/directory/branding/page.tsx"],
4
- "sourcesContent": ["'use client'\n\nimport * as React from 'react'\nimport { useQuery, useQueryClient } from '@tanstack/react-query'\nimport { ImagePlus, Loader2, RotateCcw, Save } from 'lucide-react'\nimport { Page, PageBody, PageHeader } from '@open-mercato/ui/backend/Page'\nimport { LoadingMessage, ErrorMessage } from '@open-mercato/ui/backend/detail'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { apiCallOrThrow, readApiResultOrThrow, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { surfaceRecordConflict } from '@open-mercato/ui/backend/conflicts'\nimport { Alert, AlertDescription } from '@open-mercato/ui/primitives/alert'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport { SwitchField } from '@open-mercato/ui/primitives/switch-field'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { useOrganizationScopeDetail } from '@open-mercato/shared/lib/frontend/useOrganizationScope'\n\ntype BrandingPayload = {\n organizationId: string\n organizationName: string\n tenantId: string\n logoUrl: string | null\n logoPreserveAspectRatio: boolean\n updatedAt: string | null\n}\n\ntype UploadPayload = {\n ok: true\n item: {\n id: string\n url: string\n thumbnailUrl?: string\n }\n}\n\nconst BRANDING_API = '/api/directory/organization-branding'\nconst BRANDING_ENTITY_ID = 'directory.organization'\n\nexport default function OrganizationBrandingPage() {\n const t = useT()\n const queryClient = useQueryClient()\n const { organizationId, tenantId } = useOrganizationScopeDetail()\n const [logoUrl, setLogoUrl] = React.useState('')\n const [logoPreserveAspectRatio, setLogoPreserveAspectRatio] = React.useState(false)\n const [selectedFile, setSelectedFile] = React.useState<File | null>(null)\n const [filePreviewUrl, setFilePreviewUrl] = React.useState<string | null>(null)\n const [saving, setSaving] = React.useState(false)\n const fileInputRef = React.useRef<HTMLInputElement | null>(null)\n const { runMutation } = useGuardedMutation({\n contextId: 'directory.organization-branding',\n blockedMessage: t('directory.branding.errors.blocked', 'Branding save was blocked.'),\n })\n\n const { data, isLoading, error } = useQuery<BrandingPayload>({\n queryKey: ['directory-organization-branding', organizationId, tenantId],\n enabled: Boolean(organizationId),\n queryFn: () => readApiResultOrThrow<BrandingPayload>(\n BRANDING_API,\n undefined,\n { errorMessage: t('directory.branding.errors.load', 'Failed to load organization branding') },\n ),\n })\n\n React.useEffect(() => {\n setLogoUrl(data?.logoUrl ?? '')\n setLogoPreserveAspectRatio(data?.logoPreserveAspectRatio ?? false)\n setSelectedFile(null)\n }, [data?.logoPreserveAspectRatio, data?.logoUrl, organizationId, tenantId])\n\n React.useEffect(() => {\n if (!selectedFile || typeof URL === 'undefined') {\n setFilePreviewUrl(null)\n return\n }\n const nextPreviewUrl = URL.createObjectURL(selectedFile)\n setFilePreviewUrl(nextPreviewUrl)\n return () => URL.revokeObjectURL(nextPreviewUrl)\n }, [selectedFile])\n\n const currentPreviewUrl = filePreviewUrl ?? logoUrl\n\n const uploadLogo = React.useCallback(async (organizationId: string): Promise<string | null> => {\n if (!selectedFile) return null\n const form = new FormData()\n form.set('entityId', BRANDING_ENTITY_ID)\n form.set('recordId', organizationId)\n form.set('file', selectedFile)\n form.set('tags', JSON.stringify(['organization-logo']))\n\n const upload = await readApiResultOrThrow<UploadPayload>(\n '/api/attachments',\n {\n method: 'POST',\n body: form,\n },\n { errorMessage: t('directory.branding.errors.upload', 'Failed to upload logo') },\n )\n return upload?.item.url ?? upload?.item.thumbnailUrl ?? null\n }, [selectedFile, t])\n\n const saveBranding = React.useCallback(async (\n nextLogoUrl?: string,\n options?: { skipUpload?: boolean; logoPreserveAspectRatio?: boolean },\n ) => {\n if (!data) return\n const shouldUpload = Boolean(selectedFile && !options?.skipUpload)\n const resolvedLogoPreserveAspectRatio = options?.logoPreserveAspectRatio ?? logoPreserveAspectRatio\n setSaving(true)\n try {\n await runMutation({\n operation: async () => {\n const uploadedLogoUrl = shouldUpload ? await uploadLogo(data.organizationId) : null\n const resolvedLogoUrl = uploadedLogoUrl ?? nextLogoUrl ?? logoUrl.trim()\n const response = await withScopedApiRequestHeaders(\n buildOptimisticLockHeader(data.updatedAt),\n () => apiCallOrThrow<BrandingPayload>(\n BRANDING_API,\n {\n method: 'PUT',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n logoUrl: resolvedLogoUrl || null,\n logoPreserveAspectRatio: resolvedLogoPreserveAspectRatio,\n }),\n },\n { errorMessage: t('directory.branding.errors.save', 'Failed to update organization branding') },\n ),\n )\n return response.result\n },\n context: {\n entityId: BRANDING_ENTITY_ID,\n recordId: data.organizationId,\n operation: 'update-branding',\n },\n mutationPayload: {\n organizationId: data.organizationId,\n logoUrl: (nextLogoUrl ?? logoUrl.trim()) || null,\n logoPreserveAspectRatio: resolvedLogoPreserveAspectRatio,\n hasUpload: shouldUpload,\n },\n })\n await queryClient.invalidateQueries({ queryKey: ['directory-organization-branding'] })\n window.dispatchEvent(new Event('om:refresh-sidebar'))\n setSelectedFile(null)\n if (fileInputRef.current) fileInputRef.current.value = ''\n flash(t('directory.branding.flash.saved', 'Organization branding updated'), 'success')\n } catch (err: unknown) {\n if (surfaceRecordConflict(err, t)) return\n const fallback = t('directory.branding.errors.save', 'Failed to update organization branding')\n const message = err instanceof Error ? err.message : fallback\n flash(message, 'error')\n } finally {\n setSaving(false)\n }\n }, [data, logoPreserveAspectRatio, logoUrl, queryClient, runMutation, selectedFile, t, uploadLogo])\n\n const handleSubmit = React.useCallback((event: React.FormEvent<HTMLFormElement>) => {\n event.preventDefault()\n void saveBranding()\n }, [saveBranding])\n\n if (!organizationId) {\n return (\n <Page>\n <PageHeader title={t('directory.branding.title', 'Organization branding')} />\n <PageBody>\n <Alert status=\"information\">\n <AlertDescription>\n {t(\n 'directory.branding.organizationRequired',\n 'Branding is managed for one organization at a time. Select a single organization to continue.',\n )}\n </AlertDescription>\n </Alert>\n </PageBody>\n </Page>\n )\n }\n\n if (isLoading) {\n return <LoadingMessage label={t('directory.branding.loading', 'Loading organization branding...')} />\n }\n\n if (error || !data) {\n return (\n <ErrorMessage\n label={t('directory.branding.errors.load', 'Failed to load organization branding')}\n description={error instanceof Error ? error.message : undefined}\n />\n )\n }\n\n return (\n <Page>\n <PageHeader\n title={t('directory.branding.title', 'Organization branding')}\n description={t(\n 'directory.branding.description',\n 'Set the logo used in the backend sidebar for the currently selected organization.',\n )}\n />\n <PageBody>\n <form className=\"space-y-5\" onSubmit={handleSubmit}>\n <div className=\"grid gap-5 lg:grid-cols-[260px_1fr]\">\n <div className=\"space-y-3\">\n <div className=\"flex aspect-square w-full max-w-[220px] items-center justify-center overflow-hidden rounded-lg border bg-muted/30\">\n {currentPreviewUrl ? (\n <img\n src={currentPreviewUrl}\n alt={t('directory.branding.previewAlt', '{{name}} logo preview', { name: data.organizationName })}\n className={`h-full w-full ${logoPreserveAspectRatio ? 'object-contain' : 'rounded-full object-cover'}`}\n />\n ) : (\n <ImagePlus className=\"size-10 text-muted-foreground\" aria-hidden />\n )}\n </div>\n <p className=\"text-sm font-medium text-foreground\">{data.organizationName}</p>\n <p className=\"text-xs text-muted-foreground\">\n {t('directory.branding.currentScope', 'Current organization')}\n </p>\n </div>\n\n <div className=\"space-y-4\">\n <div className=\"space-y-2\">\n <label htmlFor=\"organization-logo-file\" className=\"text-sm font-medium\">\n {t('directory.branding.file.label', 'Upload logo')}\n </label>\n <Input\n ref={fileInputRef}\n id=\"organization-logo-file\"\n type=\"file\"\n accept=\"image/png,image/jpeg,image/webp\"\n onChange={(event) => {\n const file = event.currentTarget.files?.[0]\n if (!file) return\n setSelectedFile(file)\n }}\n />\n <p className=\"text-xs text-muted-foreground\">\n {t('directory.branding.file.hint', 'PNG, JPG, or WebP works best. Uploaded files are stored as organization attachments.')}\n </p>\n </div>\n\n <div className=\"space-y-2\">\n <label htmlFor=\"organization-logo-url\" className=\"text-sm font-medium\">\n {t('directory.branding.url.label', 'Logo URL')}\n </label>\n <Input\n id=\"organization-logo-url\"\n value={logoUrl}\n onChange={(event) => setLogoUrl(event.currentTarget.value)}\n placeholder={t('directory.branding.url.placeholder', 'https://example.com/logo.svg')}\n />\n <p className=\"text-xs text-muted-foreground\">\n {t('directory.branding.url.hint', 'Use an external image URL or leave empty to fall back to the default Open Mercato logo.')}\n </p>\n </div>\n\n <SwitchField\n id=\"organization-logo-preserve-aspect-ratio\"\n label={t('directory.branding.aspectRatio.label', 'Keep the aspect ratio')}\n description={t(\n 'directory.branding.aspectRatio.description',\n 'When disabled, the sidebar crops the logo into the standard icon shape.',\n )}\n checked={logoPreserveAspectRatio}\n disabled={saving}\n onCheckedChange={setLogoPreserveAspectRatio}\n />\n\n <div className=\"flex flex-wrap items-center gap-2\">\n <Button type=\"submit\" disabled={saving}>\n {saving ? <Loader2 className=\"mr-2 size-4 animate-spin\" aria-hidden /> : <Save className=\"mr-2 size-4\" aria-hidden />}\n {t('directory.branding.actions.save', 'Save branding')}\n </Button>\n <Button\n type=\"button\"\n variant=\"outline\"\n disabled={saving}\n onClick={() => {\n setSelectedFile(null)\n if (fileInputRef.current) fileInputRef.current.value = ''\n setLogoUrl('')\n setLogoPreserveAspectRatio(false)\n void saveBranding('', { skipUpload: true, logoPreserveAspectRatio: false })\n }}\n >\n <RotateCcw className=\"mr-2 size-4\" aria-hidden />\n {t('directory.branding.actions.reset', 'Use default logo')}\n </Button>\n </div>\n </div>\n </div>\n </form>\n </PageBody>\n </Page>\n )\n}\n"],
5
- "mappings": ";AAsKM,SACE,KADF;AApKN,YAAY,WAAW;AACvB,SAAS,UAAU,sBAAsB;AACzC,SAAS,WAAW,SAAS,WAAW,YAAY;AACpD,SAAS,MAAM,UAAU,kBAAkB;AAC3C,SAAS,gBAAgB,oBAAoB;AAC7C,SAAS,aAAa;AACtB,SAAS,0BAA0B;AACnC,SAAS,gBAAgB,sBAAsB,mCAAmC;AAClF,SAAS,iCAAiC;AAC1C,SAAS,6BAA6B;AACtC,SAAS,OAAO,wBAAwB;AACxC,SAAS,cAAc;AACvB,SAAS,aAAa;AACtB,SAAS,mBAAmB;AAC5B,SAAS,YAAY;AACrB,SAAS,kCAAkC;AAoB3C,MAAM,eAAe;AACrB,MAAM,qBAAqB;AAEZ,SAAR,2BAA4C;AACjD,QAAM,IAAI,KAAK;AACf,QAAM,cAAc,eAAe;AACnC,QAAM,EAAE,gBAAgB,SAAS,IAAI,2BAA2B;AAChE,QAAM,CAAC,SAAS,UAAU,IAAI,MAAM,SAAS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port { useQuery, useQueryClient } from '@tanstack/react-query'\nimport { ImagePlus, Loader2, RotateCcw, Save } from 'lucide-react'\nimport { Page, PageBody, PageHeader } from '@open-mercato/ui/backend/Page'\nimport { LoadingMessage, ErrorMessage } from '@open-mercato/ui/backend/detail'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { apiCallOrThrow, readApiResultOrThrow, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { surfaceRecordConflict } from '@open-mercato/ui/backend/conflicts'\nimport { Alert, AlertDescription } from '@open-mercato/ui/primitives/alert'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport { SwitchField } from '@open-mercato/ui/primitives/switch-field'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { useOrganizationScopeDetail, useOrganizationScopeVersion } from '@open-mercato/shared/lib/frontend/useOrganizationScope'\nimport { getCurrentOrganizationScopeVersion } from '@open-mercato/shared/lib/frontend/organizationEvents'\n\ntype BrandingPayload = {\n organizationId: string\n organizationName: string\n tenantId: string\n logoUrl: string | null\n logoPreserveAspectRatio: boolean\n updatedAt: string | null\n}\n\ntype UploadPayload = {\n ok: true\n item: {\n id: string\n url: string\n thumbnailUrl?: string\n }\n}\n\nconst BRANDING_API = '/api/directory/organization-branding'\nconst BRANDING_ENTITY_ID = 'directory.organization'\n\nexport default function OrganizationBrandingPage() {\n const t = useT()\n const queryClient = useQueryClient()\n const { organizationId, tenantId } = useOrganizationScopeDetail()\n const scopeVersion = useOrganizationScopeVersion()\n const [logoUrl, setLogoUrl] = React.useState('')\n const [logoPreserveAspectRatio, setLogoPreserveAspectRatio] = React.useState(false)\n const [selectedFile, setSelectedFile] = React.useState<File | null>(null)\n const [filePreviewUrl, setFilePreviewUrl] = React.useState<string | null>(null)\n const [saving, setSaving] = React.useState(false)\n const fileInputRef = React.useRef<HTMLInputElement | null>(null)\n const { runMutation } = useGuardedMutation({\n contextId: 'directory.organization-branding',\n blockedMessage: t('directory.branding.errors.blocked', 'Branding save was blocked.'),\n })\n\n const { data, isLoading, error } = useQuery<BrandingPayload>({\n queryKey: ['directory-organization-branding', organizationId, tenantId],\n enabled: Boolean(organizationId),\n queryFn: () => readApiResultOrThrow<BrandingPayload>(\n BRANDING_API,\n undefined,\n { errorMessage: t('directory.branding.errors.load', 'Failed to load organization branding') },\n ),\n })\n\n React.useEffect(() => {\n setLogoUrl(data?.logoUrl ?? '')\n setLogoPreserveAspectRatio(data?.logoPreserveAspectRatio ?? false)\n setSelectedFile(null)\n if (fileInputRef.current) fileInputRef.current.value = ''\n }, [scopeVersion, organizationId, tenantId, data?.organizationId, data?.logoPreserveAspectRatio, data?.logoUrl])\n\n React.useEffect(() => {\n if (!selectedFile || typeof URL === 'undefined') {\n setFilePreviewUrl(null)\n return\n }\n const nextPreviewUrl = URL.createObjectURL(selectedFile)\n setFilePreviewUrl(nextPreviewUrl)\n return () => URL.revokeObjectURL(nextPreviewUrl)\n }, [selectedFile])\n\n const currentPreviewUrl = filePreviewUrl ?? logoUrl\n\n const uploadLogo = React.useCallback(async (organizationId: string): Promise<string | null> => {\n if (!selectedFile) return null\n const form = new FormData()\n form.set('entityId', BRANDING_ENTITY_ID)\n form.set('recordId', organizationId)\n form.set('file', selectedFile)\n form.set('tags', JSON.stringify(['organization-logo']))\n\n const upload = await readApiResultOrThrow<UploadPayload>(\n '/api/attachments',\n {\n method: 'POST',\n body: form,\n },\n { errorMessage: t('directory.branding.errors.upload', 'Failed to upload logo') },\n )\n return upload?.item.url ?? upload?.item.thumbnailUrl ?? null\n }, [selectedFile, t])\n\n const saveBranding = React.useCallback(async (\n nextLogoUrl?: string,\n options?: { skipUpload?: boolean; logoPreserveAspectRatio?: boolean },\n ) => {\n if (!data) return\n const shouldUpload = Boolean(selectedFile && !options?.skipUpload)\n const resolvedLogoPreserveAspectRatio = options?.logoPreserveAspectRatio ?? logoPreserveAspectRatio\n setSaving(true)\n try {\n await runMutation({\n operation: async () => {\n if (getCurrentOrganizationScopeVersion() !== scopeVersion) {\n throw new Error('[internal] Organization scope changed during branding save')\n }\n const uploadedLogoUrl = shouldUpload ? await uploadLogo(data.organizationId) : null\n if (getCurrentOrganizationScopeVersion() !== scopeVersion) {\n throw new Error('[internal] Organization scope changed during branding save')\n }\n const resolvedLogoUrl = uploadedLogoUrl ?? nextLogoUrl ?? logoUrl.trim()\n const response = await withScopedApiRequestHeaders(\n buildOptimisticLockHeader(data.updatedAt),\n () => apiCallOrThrow<BrandingPayload>(\n BRANDING_API,\n {\n method: 'PUT',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n logoUrl: resolvedLogoUrl || null,\n logoPreserveAspectRatio: resolvedLogoPreserveAspectRatio,\n }),\n },\n { errorMessage: t('directory.branding.errors.save', 'Failed to update organization branding') },\n ),\n )\n return response.result\n },\n context: {\n entityId: BRANDING_ENTITY_ID,\n recordId: data.organizationId,\n operation: 'update-branding',\n },\n mutationPayload: {\n organizationId: data.organizationId,\n logoUrl: (nextLogoUrl ?? logoUrl.trim()) || null,\n logoPreserveAspectRatio: resolvedLogoPreserveAspectRatio,\n hasUpload: shouldUpload,\n },\n })\n if (getCurrentOrganizationScopeVersion() !== scopeVersion) return\n await queryClient.invalidateQueries({ queryKey: ['directory-organization-branding'] })\n if (getCurrentOrganizationScopeVersion() !== scopeVersion) return\n window.dispatchEvent(new Event('om:refresh-sidebar'))\n setSelectedFile(null)\n if (fileInputRef.current) fileInputRef.current.value = ''\n flash(t('directory.branding.flash.saved', 'Organization branding updated'), 'success')\n } catch (err: unknown) {\n if (getCurrentOrganizationScopeVersion() !== scopeVersion) return\n if (surfaceRecordConflict(err, t)) return\n const fallback = t('directory.branding.errors.save', 'Failed to update organization branding')\n const message = err instanceof Error ? err.message : fallback\n flash(message, 'error')\n } finally {\n setSaving(false)\n }\n }, [data, logoPreserveAspectRatio, logoUrl, queryClient, runMutation, scopeVersion, selectedFile, t, uploadLogo])\n\n const handleSubmit = React.useCallback((event: React.FormEvent<HTMLFormElement>) => {\n event.preventDefault()\n void saveBranding()\n }, [saveBranding])\n\n if (!organizationId) {\n return (\n <Page>\n <PageHeader title={t('directory.branding.title', 'Organization branding')} />\n <PageBody>\n <Alert status=\"information\">\n <AlertDescription>\n {t(\n 'directory.branding.organizationRequired',\n 'Branding is managed for one organization at a time. Select a single organization to continue.',\n )}\n </AlertDescription>\n </Alert>\n </PageBody>\n </Page>\n )\n }\n\n if (isLoading) {\n return <LoadingMessage label={t('directory.branding.loading', 'Loading organization branding...')} />\n }\n\n if (error || !data) {\n return (\n <ErrorMessage\n label={t('directory.branding.errors.load', 'Failed to load organization branding')}\n description={error instanceof Error ? error.message : undefined}\n />\n )\n }\n\n return (\n <Page>\n <PageHeader\n title={t('directory.branding.title', 'Organization branding')}\n description={t(\n 'directory.branding.description',\n 'Set the logo used in the backend sidebar for the currently selected organization.',\n )}\n />\n <PageBody>\n <form className=\"space-y-5\" onSubmit={handleSubmit}>\n <div className=\"grid gap-5 lg:grid-cols-[260px_1fr]\">\n <div className=\"space-y-3\">\n <div className=\"flex aspect-square w-full max-w-[220px] items-center justify-center overflow-hidden rounded-lg border bg-muted/30\">\n {currentPreviewUrl ? (\n <img\n src={currentPreviewUrl}\n alt={t('directory.branding.previewAlt', '{{name}} logo preview', { name: data.organizationName })}\n className={`h-full w-full ${logoPreserveAspectRatio ? 'object-contain' : 'rounded-full object-cover'}`}\n />\n ) : (\n <ImagePlus className=\"size-10 text-muted-foreground\" aria-hidden />\n )}\n </div>\n <p className=\"text-sm font-medium text-foreground\">{data.organizationName}</p>\n <p className=\"text-xs text-muted-foreground\">\n {t('directory.branding.currentScope', 'Current organization')}\n </p>\n </div>\n\n <div className=\"space-y-4\">\n <div className=\"space-y-2\">\n <label htmlFor=\"organization-logo-file\" className=\"text-sm font-medium\">\n {t('directory.branding.file.label', 'Upload logo')}\n </label>\n <Input\n ref={fileInputRef}\n id=\"organization-logo-file\"\n type=\"file\"\n accept=\"image/png,image/jpeg,image/webp\"\n onChange={(event) => {\n const file = event.currentTarget.files?.[0]\n if (!file) return\n setSelectedFile(file)\n }}\n />\n <p className=\"text-xs text-muted-foreground\">\n {t('directory.branding.file.hint', 'PNG, JPG, or WebP works best. Uploaded files are stored as organization attachments.')}\n </p>\n </div>\n\n <div className=\"space-y-2\">\n <label htmlFor=\"organization-logo-url\" className=\"text-sm font-medium\">\n {t('directory.branding.url.label', 'Logo URL')}\n </label>\n <Input\n id=\"organization-logo-url\"\n value={logoUrl}\n onChange={(event) => setLogoUrl(event.currentTarget.value)}\n placeholder={t('directory.branding.url.placeholder', 'https://example.com/logo.svg')}\n />\n <p className=\"text-xs text-muted-foreground\">\n {t('directory.branding.url.hint', 'Use an external image URL or leave empty to fall back to the default Open Mercato logo.')}\n </p>\n </div>\n\n <SwitchField\n id=\"organization-logo-preserve-aspect-ratio\"\n label={t('directory.branding.aspectRatio.label', 'Keep the aspect ratio')}\n description={t(\n 'directory.branding.aspectRatio.description',\n 'When disabled, the sidebar crops the logo into the standard icon shape.',\n )}\n checked={logoPreserveAspectRatio}\n disabled={saving}\n onCheckedChange={setLogoPreserveAspectRatio}\n />\n\n <div className=\"flex flex-wrap items-center gap-2\">\n <Button type=\"submit\" disabled={saving}>\n {saving ? <Loader2 className=\"mr-2 size-4 animate-spin\" aria-hidden /> : <Save className=\"mr-2 size-4\" aria-hidden />}\n {t('directory.branding.actions.save', 'Save branding')}\n </Button>\n <Button\n type=\"button\"\n variant=\"outline\"\n disabled={saving}\n onClick={() => {\n setSelectedFile(null)\n if (fileInputRef.current) fileInputRef.current.value = ''\n setLogoUrl('')\n setLogoPreserveAspectRatio(false)\n void saveBranding('', { skipUpload: true, logoPreserveAspectRatio: false })\n }}\n >\n <RotateCcw className=\"mr-2 size-4\" aria-hidden />\n {t('directory.branding.actions.reset', 'Use default logo')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zD,aAAa,EAAE,sCAAsC,8BAA8B;AAAA;AAAA,UACrF;AAAA,UACA,oBAAC,OAAE,WAAU,iCACV,YAAE,+BAA+B,yFAAyF,GAC7H;AAAA,WACF;AAAA,QAEA;AAAA,UAAC;AAAA;AAAA,YACC,IAAG;AAAA,YACH,OAAO,EAAE,wCAAwC,uBAAuB;AAAA,YACxE,aAAa;AAAA,cACX;AAAA,cACA;AAAA,YACF;AAAA,YACA,SAAS;AAAA,YACT,UAAU;AAAA,YACV,iBAAiB;AAAA;AAAA,QACnB;AAAA,QAEA,qBAAC,SAAI,WAAU,qCACb;AAAA,+BAAC,UAAO,MAAK,UAAS,UAAU,QAC7B;AAAA,qBAAS,oBAAC,WAAQ,WAAU,4BAA2B,eAAW,MAAC,IAAK,oBAAC,QAAK,WAAU,eAAc,eAAW,MAAC;AAAA,YAClH,EAAE,mCAAmC,eAAe;AAAA,aACvD;AAAA,UACA;AAAA,YAAC;AAAA;AAAA,cACC,MAAK;AAAA,cACL,SAAQ;AAAA,cACR,UAAU;AAAA,cACV,SAAS,MAAM;AACb,gCAAgB,IAAI;AACpB,oBAAI,aAAa,QAAS,cAAa,QAAQ,QAAQ;AACvD,2BAAW,EAAE;AACb,2CAA2B,KAAK;AAChC,qBAAK,aAAa,IAAI,EAAE,YAAY,MAAM,yBAAyB,MAAM,CAAC;AAAA,cAC5E;AAAA,cAEA;AAAA,oCAAC,aAAU,WAAU,eAAc,eAAW,MAAC;AAAA,gBAC9C,EAAE,oCAAoC,kBAAkB;AAAA;AAAA;AAAA,UAC3D;AAAA,WACF;AAAA,SACF;AAAA,OACF,GACF,GACF;AAAA,KACF;AAEJ;",
6
6
  "names": ["organizationId"]
7
7
  }
@@ -148,11 +148,13 @@ const CUSTOMER_FIELDS = ["id", "display_name"];
148
148
  async function attachVendorLabelsToListItems(payload, ctx) {
149
149
  const items = Array.isArray(payload?.items) ? payload.items : [];
150
150
  if (items.length === 0) return;
151
+ const customerEntityId = E.customers?.customer_entity;
152
+ if (!customerEntityId) return;
151
153
  const ids = uniqueIdsFromKeys(items, ["vendor_id"]);
152
154
  if (ids.length === 0) return;
153
155
  const map = await batchLoadById(
154
156
  ctx,
155
- E.customers.customer_entity,
157
+ customerEntityId,
156
158
  ids,
157
159
  CUSTOMER_FIELDS,
158
160
  "vendor"
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/wms/api/listEnrichers.ts"],
4
- "sourcesContent": ["// Lightweight afterList enrichers shared across WMS list routes.\n//\n// These run inside `makeCrudRoute({ hooks: { afterList } })` and batch-resolve\n// foreign-key labels (e.g. warehouse_id -> warehouse_name) so backend tables\n// can render the human-readable label without N+1 lookups on the client.\n//\n// We deliberately use the `queryEngine` (entity-id-based) rather than ORM\n// entity classes so this file stays decoupled from `wms/data/entities`\n// internals and from the catalog ORM \u2014 same pattern used by High #5 in WMS\n// data enrichers.\n\nimport type { CrudCtx } from '@open-mercato/shared/lib/crud/factory'\nimport type { QueryEngine } from '@open-mercato/shared/lib/query/types'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { E } from '#generated/entities.ids.generated'\n\nconst logger = createLogger('wms')\n\ntype AnyListPayload = {\n items?: Array<Record<string, unknown>>\n}\n\ntype LookupRow = Record<string, unknown> & { id?: string | null }\n\nconst LOOKUP_BATCH_SIZE = 500\n\nfunction uniqueIdsFromKeys(\n items: Array<Record<string, unknown>>,\n keys: string[],\n): string[] {\n const set = new Set<string>()\n for (const item of items) {\n for (const key of keys) {\n const value = item?.[key]\n if (typeof value === 'string' && value.length > 0) set.add(value)\n }\n }\n return Array.from(set)\n}\n\n/**\n * Internal: batch-load `entityId` rows by primary id through the QueryEngine\n * and return them keyed by id. Splits requests into chunks of 500. Errors are\n * logged (with a `source` tag for grep-ability) and degrade to an empty map so\n * the surrounding list response still goes through.\n */\nasync function batchLoadById(\n ctx: CrudCtx,\n entityId: string,\n ids: string[],\n fields: string[],\n source: string,\n): Promise<Map<string, LookupRow>> {\n if (ids.length === 0) return new Map()\n const tenantId = ctx.auth?.tenantId\n if (!tenantId) return new Map()\n const queryEngine = ctx.container.resolve('queryEngine') as QueryEngine\n const map = new Map<string, LookupRow>()\n for (let offset = 0; offset < ids.length; offset += LOOKUP_BATCH_SIZE) {\n const slice = ids.slice(offset, offset + LOOKUP_BATCH_SIZE)\n try {\n const result = await queryEngine.query<LookupRow>(entityId, {\n tenantId,\n organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? undefined,\n organizationIds: ctx.organizationIds ?? undefined,\n filters: { id: { $in: slice } },\n fields,\n page: { page: 1, pageSize: slice.length },\n })\n for (const row of result.items ?? []) {\n if (row?.id && typeof row.id === 'string') map.set(row.id, row)\n }\n } catch (err) {\n logger.warn('batch lookup failed', { source, entityId, err })\n }\n }\n return map\n}\n\nfunction decorateOnce(item: Record<string, unknown>, key: string, value: unknown): void {\n if (item[key] === undefined) item[key] = value\n}\n\n// ---------------------------------------------------------------------------\n// Warehouses\n// ---------------------------------------------------------------------------\n\ntype WarehouseRow = LookupRow & { name?: string | null; code?: string | null }\n\nconst WAREHOUSE_FIELDS = ['id', 'name', 'code']\n\n/**\n * Decorate list items with `warehouse_name` and `warehouse_code` when they\n * carry a `warehouse_id` column. Mutates `payload.items` in place.\n */\nexport async function attachWarehouseLabelsToListItems(\n payload: AnyListPayload,\n ctx: CrudCtx,\n): Promise<void> {\n const items = Array.isArray(payload?.items) ? payload.items : []\n if (items.length === 0) return\n const ids = uniqueIdsFromKeys(items, ['warehouse_id'])\n if (ids.length === 0) return\n const map = (await batchLoadById(\n ctx,\n E.wms.warehouse,\n ids,\n WAREHOUSE_FIELDS,\n 'warehouse',\n )) as Map<string, WarehouseRow>\n if (map.size === 0) return\n for (const item of items) {\n const id = item?.warehouse_id\n if (typeof id !== 'string' || !id) continue\n const row = map.get(id)\n if (!row) continue\n decorateOnce(item, 'warehouse_name', row.name ?? null)\n decorateOnce(item, 'warehouse_code', row.code ?? null)\n }\n}\n\n// ---------------------------------------------------------------------------\n// Locations\n// ---------------------------------------------------------------------------\n\ntype LocationLookupRow = LookupRow & { code?: string | null; type?: string | null }\n\nconst LOCATION_FIELDS = ['id', 'code', 'type']\n\n/**\n * Decorate list items with location label/type for any of these foreign-key\n * columns: `location_id`, `location_from_id`, `location_to_id`. The decorated\n * fields follow the same prefix:\n *\n * location_id -> location_code, location_type\n * location_from_id -> location_from_code, location_from_type\n * location_to_id -> location_to_code, location_to_type\n *\n * Mutates `payload.items` in place.\n */\nexport async function attachLocationLabelsToListItems(\n payload: AnyListPayload,\n ctx: CrudCtx,\n): Promise<void> {\n const items = Array.isArray(payload?.items) ? payload.items : []\n if (items.length === 0) return\n const fkColumns = ['location_id', 'location_from_id', 'location_to_id']\n const ids = uniqueIdsFromKeys(items, fkColumns)\n if (ids.length === 0) return\n const map = (await batchLoadById(\n ctx,\n E.wms.warehouse_location,\n ids,\n LOCATION_FIELDS,\n 'location',\n )) as Map<string, LocationLookupRow>\n if (map.size === 0) return\n for (const item of items) {\n for (const fk of fkColumns) {\n const id = item?.[fk]\n if (typeof id !== 'string' || !id) continue\n const row = map.get(id)\n if (!row) continue\n const prefix = fk.replace(/_id$/, '')\n decorateOnce(item, `${prefix}_code`, row.code ?? null)\n decorateOnce(item, `${prefix}_type`, row.type ?? null)\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Catalog variants\n// ---------------------------------------------------------------------------\n\ntype VariantLookupRow = LookupRow & {\n name?: string | null\n sku?: string | null\n product_id?: string | null\n}\n\nconst VARIANT_FIELDS = ['id', 'name', 'sku', 'product_id']\n\n/**\n * Decorate list items with `variant_name`, `variant_sku`, and `product_id`\n * when they carry a `catalog_variant_id` column. Mutates `payload.items` in\n * place. Uses `queryEngine.query(E.catalog.catalog_product_variant, ...)`\n * rather than importing the catalog ORM entity directly, to keep the WMS\n * module decoupled from the catalog package internals.\n */\nexport async function attachVariantLabelsToListItems(\n payload: AnyListPayload,\n ctx: CrudCtx,\n): Promise<void> {\n const items = Array.isArray(payload?.items) ? payload.items : []\n if (items.length === 0) return\n const ids = uniqueIdsFromKeys(items, ['catalog_variant_id'])\n if (ids.length === 0) return\n const map = (await batchLoadById(\n ctx,\n E.catalog.catalog_product_variant,\n ids,\n VARIANT_FIELDS,\n 'variant',\n )) as Map<string, VariantLookupRow>\n if (map.size === 0) return\n for (const item of items) {\n const id = item?.catalog_variant_id\n if (typeof id !== 'string' || !id) continue\n const row = map.get(id)\n if (!row) continue\n decorateOnce(item, 'variant_name', row.name ?? null)\n decorateOnce(item, 'variant_sku', row.sku ?? null)\n decorateOnce(item, 'catalog_product_id', row.product_id ?? null)\n }\n}\n\n// ---------------------------------------------------------------------------\n// Catalog products\n// ---------------------------------------------------------------------------\n\ntype ProductLookupRow = LookupRow & { title?: string | null; sku?: string | null }\n\nconst PRODUCT_FIELDS = ['id', 'title', 'sku']\n\n/**\n * Decorate list items with `product_title` and `product_sku` when they carry a\n * `catalog_product_id` column. Mutates `payload.items` in place.\n */\nexport async function attachProductLabelsToListItems(\n payload: AnyListPayload,\n ctx: CrudCtx,\n): Promise<void> {\n const items = Array.isArray(payload?.items) ? payload.items : []\n if (items.length === 0) return\n const ids = uniqueIdsFromKeys(items, ['catalog_product_id'])\n if (ids.length === 0) return\n const map = (await batchLoadById(\n ctx,\n E.catalog.catalog_product,\n ids,\n PRODUCT_FIELDS,\n 'product',\n )) as Map<string, ProductLookupRow>\n if (map.size === 0) return\n for (const item of items) {\n const id = item?.catalog_product_id\n if (typeof id !== 'string' || !id) continue\n const row = map.get(id)\n if (!row) continue\n decorateOnce(item, 'product_title', row.title ?? null)\n decorateOnce(item, 'product_sku', row.sku ?? null)\n }\n}\n\n/**\n * Decorate inventory profile rows with catalog product and variant labels.\n * Mutates `payload.items` in place.\n */\nexport async function attachInventoryProfileCatalogLabelsToListItems(\n payload: AnyListPayload,\n ctx: CrudCtx,\n): Promise<void> {\n await Promise.all([\n attachProductLabelsToListItems(payload, ctx),\n attachVariantLabelsToListItems(payload, ctx),\n ])\n}\n\n// ---------------------------------------------------------------------------\n// Customers (ASN vendors)\n// ---------------------------------------------------------------------------\n\ntype CustomerLookupRow = LookupRow & { display_name?: string | null }\n\nconst CUSTOMER_FIELDS = ['id', 'display_name']\n\n/**\n * Decorate list items with `vendor_name` when they carry a `vendor_id` column\n * referencing `customers.customer_entity` by UUID only (no ORM cross-module\n * relations). Mutates `payload.items` in place.\n */\nexport async function attachVendorLabelsToListItems(\n payload: AnyListPayload,\n ctx: CrudCtx,\n): Promise<void> {\n const items = Array.isArray(payload?.items) ? payload.items : []\n if (items.length === 0) return\n const ids = uniqueIdsFromKeys(items, ['vendor_id'])\n if (ids.length === 0) return\n const map = (await batchLoadById(\n ctx,\n E.customers.customer_entity,\n ids,\n CUSTOMER_FIELDS,\n 'vendor',\n )) as Map<string, CustomerLookupRow>\n if (map.size === 0) return\n for (const item of items) {\n const id = item?.vendor_id\n if (typeof id !== 'string' || !id) continue\n const row = map.get(id)\n if (!row) continue\n decorateOnce(item, 'vendor_name', row.display_name ?? null)\n }\n}\n\n// ---------------------------------------------------------------------------\n// Reservation sources\n// ---------------------------------------------------------------------------\n\ntype SalesOrderLookupRow = LookupRow & { order_number?: string | null }\n\nconst SALES_ORDER_FIELDS = ['id', 'order_number']\n\n/**\n * Decorate reservation rows with `source_label` when the source can be resolved\n * to a human-readable reference (currently sales orders). Mutates\n * `payload.items` in place.\n */\nexport async function attachReservationSourceLabelsToListItems(\n payload: AnyListPayload,\n ctx: CrudCtx,\n): Promise<void> {\n const items = Array.isArray(payload?.items) ? payload.items : []\n if (items.length === 0) return\n\n const orderIds = uniqueIdsFromKeys(\n items.filter((item) => item?.source_type === 'order'),\n ['source_id'],\n )\n if (orderIds.length === 0) return\n\n const map = (await batchLoadById(\n ctx,\n E.sales.sales_order,\n orderIds,\n SALES_ORDER_FIELDS,\n 'reservation-source',\n )) as Map<string, SalesOrderLookupRow>\n if (map.size === 0) return\n\n for (const item of items) {\n if (item?.source_type !== 'order') continue\n const id = item?.source_id\n if (typeof id !== 'string' || !id) continue\n const row = map.get(id)\n const orderNumber = row?.order_number?.trim()\n if (orderNumber) decorateOnce(item, 'source_label', orderNumber)\n }\n}\n"],
5
- "mappings": "AAaA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,MAAM,SAAS,aAAa,KAAK;AAQjC,MAAM,oBAAoB;AAE1B,SAAS,kBACP,OACA,MACU;AACV,QAAM,MAAM,oBAAI,IAAY;AAC5B,aAAW,QAAQ,OAAO;AACxB,eAAW,OAAO,MAAM;AACtB,YAAM,QAAQ,OAAO,GAAG;AACxB,UAAI,OAAO,UAAU,YAAY,MAAM,SAAS,EAAG,KAAI,IAAI,KAAK;AAAA,IAClE;AAAA,EACF;AACA,SAAO,MAAM,KAAK,GAAG;AACvB;AAQA,eAAe,cACb,KACA,UACA,KACA,QACA,QACiC;AACjC,MAAI,IAAI,WAAW,EAAG,QAAO,oBAAI,IAAI;AACrC,QAAM,WAAW,IAAI,MAAM;AAC3B,MAAI,CAAC,SAAU,QAAO,oBAAI,IAAI;AAC9B,QAAM,cAAc,IAAI,UAAU,QAAQ,aAAa;AACvD,QAAM,MAAM,oBAAI,IAAuB;AACvC,WAAS,SAAS,GAAG,SAAS,IAAI,QAAQ,UAAU,mBAAmB;AACrE,UAAM,QAAQ,IAAI,MAAM,QAAQ,SAAS,iBAAiB;AAC1D,QAAI;AACF,YAAM,SAAS,MAAM,YAAY,MAAiB,UAAU;AAAA,QAC1D;AAAA,QACA,gBAAgB,IAAI,0BAA0B,IAAI,MAAM,SAAS;AAAA,QACjE,iBAAiB,IAAI,mBAAmB;AAAA,QACxC,SAAS,EAAE,IAAI,EAAE,KAAK,MAAM,EAAE;AAAA,QAC9B;AAAA,QACA,MAAM,EAAE,MAAM,GAAG,UAAU,MAAM,OAAO;AAAA,MAC1C,CAAC;AACD,iBAAW,OAAO,OAAO,SAAS,CAAC,GAAG;AACpC,YAAI,KAAK,MAAM,OAAO,IAAI,OAAO,SAAU,KAAI,IA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AI,EAAE;AACtB,QAAI,CAAC,IAAK;AACV,iBAAa,MAAM,eAAe,IAAI,gBAAgB,IAAI;AAAA,EAC5D;AACF;AAQA,MAAM,qBAAqB,CAAC,MAAM,cAAc;AAOhD,eAAsB,yCACpB,SACA,KACe;AACf,QAAM,QAAQ,MAAM,QAAQ,SAAS,KAAK,IAAI,QAAQ,QAAQ,CAAC;AAC/D,MAAI,MAAM,WAAW,EAAG;AAExB,QAAM,WAAW;AAAA,IACf,MAAM,OAAO,CAAC,SAAS,MAAM,gBAAgB,OAAO;AAAA,IACpD,CAAC,WAAW;AAAA,EACd;AACA,MAAI,SAAS,WAAW,EAAG;AAE3B,QAAM,MAAO,MAAM;AAAA,IACjB;AAAA,IACA,EAAE,MAAM;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACA,MAAI,IAAI,SAAS,EAAG;AAEpB,aAAW,QAAQ,OAAO;AACxB,QAAI,MAAM,gBAAgB,QAAS;AACnC,UAAM,KAAK,MAAM;AACjB,QAAI,OAAO,OAAO,YAAY,CAAC,GAAI;AACnC,UAAM,MAAM,IAAI,IAAI,EAAE;AACtB,UAAM,cAAc,KAAK,cAAc,KAAK;AAC5C,QAAI,YAAa,cAAa,MAAM,gBAAgB,WAAW;AAAA,EACjE;AACF;",
4
+ "sourcesContent": ["// Lightweight afterList enrichers shared across WMS list routes.\n//\n// These run inside `makeCrudRoute({ hooks: { afterList } })` and batch-resolve\n// foreign-key labels (e.g. warehouse_id -> warehouse_name) so backend tables\n// can render the human-readable label without N+1 lookups on the client.\n//\n// We deliberately use the `queryEngine` (entity-id-based) rather than ORM\n// entity classes so this file stays decoupled from `wms/data/entities`\n// internals and from the catalog ORM \u2014 same pattern used by High #5 in WMS\n// data enrichers.\n\nimport type { CrudCtx } from '@open-mercato/shared/lib/crud/factory'\nimport type { QueryEngine } from '@open-mercato/shared/lib/query/types'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { E } from '#generated/entities.ids.generated'\n\nconst logger = createLogger('wms')\n\ntype AnyListPayload = {\n items?: Array<Record<string, unknown>>\n}\n\ntype LookupRow = Record<string, unknown> & { id?: string | null }\n\nconst LOOKUP_BATCH_SIZE = 500\n\nfunction uniqueIdsFromKeys(\n items: Array<Record<string, unknown>>,\n keys: string[],\n): string[] {\n const set = new Set<string>()\n for (const item of items) {\n for (const key of keys) {\n const value = item?.[key]\n if (typeof value === 'string' && value.length > 0) set.add(value)\n }\n }\n return Array.from(set)\n}\n\n/**\n * Internal: batch-load `entityId` rows by primary id through the QueryEngine\n * and return them keyed by id. Splits requests into chunks of 500. Errors are\n * logged (with a `source` tag for grep-ability) and degrade to an empty map so\n * the surrounding list response still goes through.\n */\nasync function batchLoadById(\n ctx: CrudCtx,\n entityId: string,\n ids: string[],\n fields: string[],\n source: string,\n): Promise<Map<string, LookupRow>> {\n if (ids.length === 0) return new Map()\n const tenantId = ctx.auth?.tenantId\n if (!tenantId) return new Map()\n const queryEngine = ctx.container.resolve('queryEngine') as QueryEngine\n const map = new Map<string, LookupRow>()\n for (let offset = 0; offset < ids.length; offset += LOOKUP_BATCH_SIZE) {\n const slice = ids.slice(offset, offset + LOOKUP_BATCH_SIZE)\n try {\n const result = await queryEngine.query<LookupRow>(entityId, {\n tenantId,\n organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? undefined,\n organizationIds: ctx.organizationIds ?? undefined,\n filters: { id: { $in: slice } },\n fields,\n page: { page: 1, pageSize: slice.length },\n })\n for (const row of result.items ?? []) {\n if (row?.id && typeof row.id === 'string') map.set(row.id, row)\n }\n } catch (err) {\n logger.warn('batch lookup failed', { source, entityId, err })\n }\n }\n return map\n}\n\nfunction decorateOnce(item: Record<string, unknown>, key: string, value: unknown): void {\n if (item[key] === undefined) item[key] = value\n}\n\n// ---------------------------------------------------------------------------\n// Warehouses\n// ---------------------------------------------------------------------------\n\ntype WarehouseRow = LookupRow & { name?: string | null; code?: string | null }\n\nconst WAREHOUSE_FIELDS = ['id', 'name', 'code']\n\n/**\n * Decorate list items with `warehouse_name` and `warehouse_code` when they\n * carry a `warehouse_id` column. Mutates `payload.items` in place.\n */\nexport async function attachWarehouseLabelsToListItems(\n payload: AnyListPayload,\n ctx: CrudCtx,\n): Promise<void> {\n const items = Array.isArray(payload?.items) ? payload.items : []\n if (items.length === 0) return\n const ids = uniqueIdsFromKeys(items, ['warehouse_id'])\n if (ids.length === 0) return\n const map = (await batchLoadById(\n ctx,\n E.wms.warehouse,\n ids,\n WAREHOUSE_FIELDS,\n 'warehouse',\n )) as Map<string, WarehouseRow>\n if (map.size === 0) return\n for (const item of items) {\n const id = item?.warehouse_id\n if (typeof id !== 'string' || !id) continue\n const row = map.get(id)\n if (!row) continue\n decorateOnce(item, 'warehouse_name', row.name ?? null)\n decorateOnce(item, 'warehouse_code', row.code ?? null)\n }\n}\n\n// ---------------------------------------------------------------------------\n// Locations\n// ---------------------------------------------------------------------------\n\ntype LocationLookupRow = LookupRow & { code?: string | null; type?: string | null }\n\nconst LOCATION_FIELDS = ['id', 'code', 'type']\n\n/**\n * Decorate list items with location label/type for any of these foreign-key\n * columns: `location_id`, `location_from_id`, `location_to_id`. The decorated\n * fields follow the same prefix:\n *\n * location_id -> location_code, location_type\n * location_from_id -> location_from_code, location_from_type\n * location_to_id -> location_to_code, location_to_type\n *\n * Mutates `payload.items` in place.\n */\nexport async function attachLocationLabelsToListItems(\n payload: AnyListPayload,\n ctx: CrudCtx,\n): Promise<void> {\n const items = Array.isArray(payload?.items) ? payload.items : []\n if (items.length === 0) return\n const fkColumns = ['location_id', 'location_from_id', 'location_to_id']\n const ids = uniqueIdsFromKeys(items, fkColumns)\n if (ids.length === 0) return\n const map = (await batchLoadById(\n ctx,\n E.wms.warehouse_location,\n ids,\n LOCATION_FIELDS,\n 'location',\n )) as Map<string, LocationLookupRow>\n if (map.size === 0) return\n for (const item of items) {\n for (const fk of fkColumns) {\n const id = item?.[fk]\n if (typeof id !== 'string' || !id) continue\n const row = map.get(id)\n if (!row) continue\n const prefix = fk.replace(/_id$/, '')\n decorateOnce(item, `${prefix}_code`, row.code ?? null)\n decorateOnce(item, `${prefix}_type`, row.type ?? null)\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Catalog variants\n// ---------------------------------------------------------------------------\n\ntype VariantLookupRow = LookupRow & {\n name?: string | null\n sku?: string | null\n product_id?: string | null\n}\n\nconst VARIANT_FIELDS = ['id', 'name', 'sku', 'product_id']\n\n/**\n * Decorate list items with `variant_name`, `variant_sku`, and `product_id`\n * when they carry a `catalog_variant_id` column. Mutates `payload.items` in\n * place. Uses `queryEngine.query(E.catalog.catalog_product_variant, ...)`\n * rather than importing the catalog ORM entity directly, to keep the WMS\n * module decoupled from the catalog package internals.\n */\nexport async function attachVariantLabelsToListItems(\n payload: AnyListPayload,\n ctx: CrudCtx,\n): Promise<void> {\n const items = Array.isArray(payload?.items) ? payload.items : []\n if (items.length === 0) return\n const ids = uniqueIdsFromKeys(items, ['catalog_variant_id'])\n if (ids.length === 0) return\n const map = (await batchLoadById(\n ctx,\n E.catalog.catalog_product_variant,\n ids,\n VARIANT_FIELDS,\n 'variant',\n )) as Map<string, VariantLookupRow>\n if (map.size === 0) return\n for (const item of items) {\n const id = item?.catalog_variant_id\n if (typeof id !== 'string' || !id) continue\n const row = map.get(id)\n if (!row) continue\n decorateOnce(item, 'variant_name', row.name ?? null)\n decorateOnce(item, 'variant_sku', row.sku ?? null)\n decorateOnce(item, 'catalog_product_id', row.product_id ?? null)\n }\n}\n\n// ---------------------------------------------------------------------------\n// Catalog products\n// ---------------------------------------------------------------------------\n\ntype ProductLookupRow = LookupRow & { title?: string | null; sku?: string | null }\n\nconst PRODUCT_FIELDS = ['id', 'title', 'sku']\n\n/**\n * Decorate list items with `product_title` and `product_sku` when they carry a\n * `catalog_product_id` column. Mutates `payload.items` in place.\n */\nexport async function attachProductLabelsToListItems(\n payload: AnyListPayload,\n ctx: CrudCtx,\n): Promise<void> {\n const items = Array.isArray(payload?.items) ? payload.items : []\n if (items.length === 0) return\n const ids = uniqueIdsFromKeys(items, ['catalog_product_id'])\n if (ids.length === 0) return\n const map = (await batchLoadById(\n ctx,\n E.catalog.catalog_product,\n ids,\n PRODUCT_FIELDS,\n 'product',\n )) as Map<string, ProductLookupRow>\n if (map.size === 0) return\n for (const item of items) {\n const id = item?.catalog_product_id\n if (typeof id !== 'string' || !id) continue\n const row = map.get(id)\n if (!row) continue\n decorateOnce(item, 'product_title', row.title ?? null)\n decorateOnce(item, 'product_sku', row.sku ?? null)\n }\n}\n\n/**\n * Decorate inventory profile rows with catalog product and variant labels.\n * Mutates `payload.items` in place.\n */\nexport async function attachInventoryProfileCatalogLabelsToListItems(\n payload: AnyListPayload,\n ctx: CrudCtx,\n): Promise<void> {\n await Promise.all([\n attachProductLabelsToListItems(payload, ctx),\n attachVariantLabelsToListItems(payload, ctx),\n ])\n}\n\n// ---------------------------------------------------------------------------\n// Customers (ASN vendors)\n// ---------------------------------------------------------------------------\n\ntype CustomerLookupRow = LookupRow & { display_name?: string | null }\n\nconst CUSTOMER_FIELDS = ['id', 'display_name']\n\n/**\n * Decorate list items with `vendor_name` when they carry a `vendor_id` column\n * referencing `customers.customer_entity` by UUID only (no ORM cross-module\n * relations). No-op when the optional `customers` module is not enabled.\n * Mutates `payload.items` in place.\n */\nexport async function attachVendorLabelsToListItems(\n payload: AnyListPayload,\n ctx: CrudCtx,\n): Promise<void> {\n const items = Array.isArray(payload?.items) ? payload.items : []\n if (items.length === 0) return\n const customerEntityId = E.customers?.customer_entity\n if (!customerEntityId) return\n const ids = uniqueIdsFromKeys(items, ['vendor_id'])\n if (ids.length === 0) return\n const map = (await batchLoadById(\n ctx,\n customerEntityId,\n ids,\n CUSTOMER_FIELDS,\n 'vendor',\n )) as Map<string, CustomerLookupRow>\n if (map.size === 0) return\n for (const item of items) {\n const id = item?.vendor_id\n if (typeof id !== 'string' || !id) continue\n const row = map.get(id)\n if (!row) continue\n decorateOnce(item, 'vendor_name', row.display_name ?? null)\n }\n}\n\n// ---------------------------------------------------------------------------\n// Reservation sources\n// ---------------------------------------------------------------------------\n\ntype SalesOrderLookupRow = LookupRow & { order_number?: string | null }\n\nconst SALES_ORDER_FIELDS = ['id', 'order_number']\n\n/**\n * Decorate reservation rows with `source_label` when the source can be resolved\n * to a human-readable reference (currently sales orders). Mutates\n * `payload.items` in place.\n */\nexport async function attachReservationSourceLabelsToListItems(\n payload: AnyListPayload,\n ctx: CrudCtx,\n): Promise<void> {\n const items = Array.isArray(payload?.items) ? payload.items : []\n if (items.length === 0) return\n\n const orderIds = uniqueIdsFromKeys(\n items.filter((item) => item?.source_type === 'order'),\n ['source_id'],\n )\n if (orderIds.length === 0) return\n\n const map = (await batchLoadById(\n ctx,\n E.sales.sales_order,\n orderIds,\n SALES_ORDER_FIELDS,\n 'reservation-source',\n )) as Map<string, SalesOrderLookupRow>\n if (map.size === 0) return\n\n for (const item of items) {\n if (item?.source_type !== 'order') continue\n const id = item?.source_id\n if (typeof id !== 'string' || !id) continue\n const row = map.get(id)\n const orderNumber = row?.order_number?.trim()\n if (orderNumber) decorateOnce(item, 'source_label', orderNumber)\n }\n}\n"],
5
+ "mappings": "AAaA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,MAAM,SAAS,aAAa,KAAK;AAQjC,MAAM,oBAAoB;AAE1B,SAAS,kBACP,OACA,MACU;AACV,QAAM,MAAM,oBAAI,IAAY;AAC5B,aAAW,QAAQ,OAAO;AACxB,eAAW,OAAO,MAAM;AACtB,YAAM,QAAQ,OAAO,GAAG;AACxB,UAAI,OAAO,UAAU,YAAY,MAAM,SAAS,EAAG,KAAI,IAAI,KAAK;AAAA,IAClE;AAAA,EACF;AACA,SAAO,MAAM,KAAK,GAAG;AACvB;AAQA,eAAe,cACb,KACA,UACA,KACA,QACA,QACiC;AACjC,MAAI,IAAI,WAAW,EAAG,QAAO,oBAAI,IAAI;AACrC,QAAM,WAAW,IAAI,MAAM;AAC3B,MAAI,CAAC,SAAU,QAAO,oBAAI,IAA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UAAM,KAAK,MAAM;AACjB,QAAI,OAAO,OAAO,YAAY,CAAC,GAAI;AACnC,UAAM,MAAM,IAAI,IAAI,EAAE;AACtB,UAAM,cAAc,KAAK,cAAc,KAAK;AAC5C,QAAI,YAAa,cAAa,MAAM,gBAAgB,WAAW;AAAA,EACjE;AACF;",
6
6
  "names": []
7
7
  }
@@ -7,7 +7,7 @@ const metadata = {
7
7
  author: "Open Mercato Team",
8
8
  license: "MIT",
9
9
  ejectable: true,
10
- requires: ["catalog", "sales", "feature_toggles"]
10
+ requires: ["catalog", "customers", "sales", "feature_toggles"]
11
11
  };
12
12
  import { features } from "./acl.js";
13
13
  export {