@open-mercato/core 0.6.1-develop.3139.9fc38487c8 → 0.6.1-develop.3144.b39fb4dfa6

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 (190) hide show
  1. package/dist/modules/catalog/api/dictionaries/[key]/route.js +2 -2
  2. package/dist/modules/catalog/api/dictionaries/[key]/route.js.map +2 -2
  3. package/dist/modules/customers/api/activities/route.js +5 -5
  4. package/dist/modules/customers/api/activities/route.js.map +2 -2
  5. package/dist/modules/customers/api/assignable-staff/route.js +2 -2
  6. package/dist/modules/customers/api/assignable-staff/route.js.map +2 -2
  7. package/dist/modules/customers/api/companies/[id]/people/route.js +2 -2
  8. package/dist/modules/customers/api/companies/[id]/people/route.js.map +2 -2
  9. package/dist/modules/customers/api/dashboard/widgets/customer-todos/route.js +2 -2
  10. package/dist/modules/customers/api/dashboard/widgets/customer-todos/route.js.map +2 -2
  11. package/dist/modules/customers/api/dashboard/widgets/new-customers/route.js +2 -2
  12. package/dist/modules/customers/api/dashboard/widgets/new-customers/route.js.map +2 -2
  13. package/dist/modules/customers/api/dashboard/widgets/new-deals/route.js +2 -2
  14. package/dist/modules/customers/api/dashboard/widgets/new-deals/route.js.map +2 -2
  15. package/dist/modules/customers/api/dashboard/widgets/next-interactions/route.js +2 -2
  16. package/dist/modules/customers/api/dashboard/widgets/next-interactions/route.js.map +2 -2
  17. package/dist/modules/customers/api/deals/[id]/companies/route.js +2 -2
  18. package/dist/modules/customers/api/deals/[id]/companies/route.js.map +2 -2
  19. package/dist/modules/customers/api/deals/[id]/people/route.js +2 -2
  20. package/dist/modules/customers/api/deals/[id]/people/route.js.map +2 -2
  21. package/dist/modules/customers/api/dictionaries/[kind]/[id]/route.js +6 -6
  22. package/dist/modules/customers/api/dictionaries/[kind]/[id]/route.js.map +2 -2
  23. package/dist/modules/customers/api/dictionaries/[kind]/route.js +3 -3
  24. package/dist/modules/customers/api/dictionaries/[kind]/route.js.map +2 -2
  25. package/dist/modules/customers/api/dictionaries/currency/route.js +2 -2
  26. package/dist/modules/customers/api/dictionaries/currency/route.js.map +2 -2
  27. package/dist/modules/customers/api/dictionaries/kind-settings/route.js +3 -3
  28. package/dist/modules/customers/api/dictionaries/kind-settings/route.js.map +2 -2
  29. package/dist/modules/customers/api/entity-roles-factory.js +5 -5
  30. package/dist/modules/customers/api/entity-roles-factory.js.map +2 -2
  31. package/dist/modules/customers/api/interactions/cancel/route.js +2 -2
  32. package/dist/modules/customers/api/interactions/cancel/route.js.map +2 -2
  33. package/dist/modules/customers/api/interactions/complete/route.js +2 -2
  34. package/dist/modules/customers/api/interactions/complete/route.js.map +2 -2
  35. package/dist/modules/customers/api/interactions/conflicts/route.js +2 -2
  36. package/dist/modules/customers/api/interactions/conflicts/route.js.map +2 -2
  37. package/dist/modules/customers/api/interactions/counts/route.js +2 -2
  38. package/dist/modules/customers/api/interactions/counts/route.js.map +2 -2
  39. package/dist/modules/customers/api/interactions/route.js +2 -2
  40. package/dist/modules/customers/api/interactions/route.js.map +2 -2
  41. package/dist/modules/customers/api/interactions/tasks/route.js +2 -2
  42. package/dist/modules/customers/api/interactions/tasks/route.js.map +2 -2
  43. package/dist/modules/customers/api/labels/assign/route.js +2 -2
  44. package/dist/modules/customers/api/labels/assign/route.js.map +2 -2
  45. package/dist/modules/customers/api/labels/route.js +3 -3
  46. package/dist/modules/customers/api/labels/route.js.map +2 -2
  47. package/dist/modules/customers/api/labels/unassign/route.js +2 -2
  48. package/dist/modules/customers/api/labels/unassign/route.js.map +2 -2
  49. package/dist/modules/customers/api/people/[id]/companies/[linkId]/route.js +3 -3
  50. package/dist/modules/customers/api/people/[id]/companies/[linkId]/route.js.map +2 -2
  51. package/dist/modules/customers/api/people/[id]/companies/enriched/route.js +2 -2
  52. package/dist/modules/customers/api/people/[id]/companies/enriched/route.js.map +2 -2
  53. package/dist/modules/customers/api/people/[id]/companies/route.js +3 -3
  54. package/dist/modules/customers/api/people/[id]/companies/route.js.map +2 -2
  55. package/dist/modules/customers/api/pipeline-stages/reorder/route.js +2 -2
  56. package/dist/modules/customers/api/pipeline-stages/reorder/route.js.map +2 -2
  57. package/dist/modules/customers/api/pipeline-stages/route.js +5 -5
  58. package/dist/modules/customers/api/pipeline-stages/route.js.map +2 -2
  59. package/dist/modules/customers/api/pipelines/route.js +5 -5
  60. package/dist/modules/customers/api/pipelines/route.js.map +2 -2
  61. package/dist/modules/customers/api/settings/address-format/route.js +3 -3
  62. package/dist/modules/customers/api/settings/address-format/route.js.map +2 -2
  63. package/dist/modules/customers/api/tags/assign/route.js +2 -2
  64. package/dist/modules/customers/api/tags/assign/route.js.map +2 -2
  65. package/dist/modules/customers/api/tags/unassign/route.js +2 -2
  66. package/dist/modules/customers/api/tags/unassign/route.js.map +2 -2
  67. package/dist/modules/customers/api/todos/route.js +5 -5
  68. package/dist/modules/customers/api/todos/route.js.map +2 -2
  69. package/dist/modules/dictionaries/api/[dictionaryId]/entries/[entryId]/route.js +3 -3
  70. package/dist/modules/dictionaries/api/[dictionaryId]/entries/[entryId]/route.js.map +2 -2
  71. package/dist/modules/dictionaries/api/[dictionaryId]/entries/reorder/route.js +2 -2
  72. package/dist/modules/dictionaries/api/[dictionaryId]/entries/reorder/route.js.map +2 -2
  73. package/dist/modules/dictionaries/api/[dictionaryId]/entries/route.js +3 -3
  74. package/dist/modules/dictionaries/api/[dictionaryId]/entries/route.js.map +2 -2
  75. package/dist/modules/dictionaries/api/[dictionaryId]/entries/set-default/route.js +2 -2
  76. package/dist/modules/dictionaries/api/[dictionaryId]/entries/set-default/route.js.map +2 -2
  77. package/dist/modules/dictionaries/api/[dictionaryId]/route.js +4 -4
  78. package/dist/modules/dictionaries/api/[dictionaryId]/route.js.map +2 -2
  79. package/dist/modules/dictionaries/api/route.js +3 -3
  80. package/dist/modules/dictionaries/api/route.js.map +2 -2
  81. package/dist/modules/feature_toggles/api/overrides/route.js +2 -2
  82. package/dist/modules/feature_toggles/api/overrides/route.js.map +2 -2
  83. package/dist/modules/planner/api/availability-date-specific.js +2 -2
  84. package/dist/modules/planner/api/availability-date-specific.js.map +2 -2
  85. package/dist/modules/planner/api/availability-weekly.js +2 -2
  86. package/dist/modules/planner/api/availability-weekly.js.map +2 -2
  87. package/dist/modules/resources/api/resources/tags/assign/route.js +2 -2
  88. package/dist/modules/resources/api/resources/tags/assign/route.js.map +2 -2
  89. package/dist/modules/resources/api/resources/tags/unassign/route.js +2 -2
  90. package/dist/modules/resources/api/resources/tags/unassign/route.js.map +2 -2
  91. package/dist/modules/sales/api/document-history/route.js +2 -2
  92. package/dist/modules/sales/api/document-history/route.js.map +2 -2
  93. package/dist/modules/sales/api/document-numbers/route.js +2 -2
  94. package/dist/modules/sales/api/document-numbers/route.js.map +2 -2
  95. package/dist/modules/sales/api/quotes/accept/route.js +2 -2
  96. package/dist/modules/sales/api/quotes/accept/route.js.map +2 -2
  97. package/dist/modules/sales/api/quotes/convert/route.js +2 -2
  98. package/dist/modules/sales/api/quotes/convert/route.js.map +2 -2
  99. package/dist/modules/sales/api/quotes/public/[token]/route.js +2 -2
  100. package/dist/modules/sales/api/quotes/public/[token]/route.js.map +2 -2
  101. package/dist/modules/sales/api/quotes/send/route.js +2 -2
  102. package/dist/modules/sales/api/quotes/send/route.js.map +2 -2
  103. package/dist/modules/sales/api/returns/[id]/route.js +2 -2
  104. package/dist/modules/sales/api/returns/[id]/route.js.map +2 -2
  105. package/dist/modules/sales/api/settings/document-numbers/route.js +3 -3
  106. package/dist/modules/sales/api/settings/document-numbers/route.js.map +2 -2
  107. package/dist/modules/sales/api/settings/order-editing/route.js +3 -3
  108. package/dist/modules/sales/api/settings/order-editing/route.js.map +2 -2
  109. package/dist/modules/sales/widgets/dashboard/makeDashboardWidgetRoute.js +2 -2
  110. package/dist/modules/sales/widgets/dashboard/makeDashboardWidgetRoute.js.map +2 -2
  111. package/dist/modules/staff/api/leave-requests/accept/route.js +2 -2
  112. package/dist/modules/staff/api/leave-requests/accept/route.js.map +2 -2
  113. package/dist/modules/staff/api/leave-requests/reject/route.js +2 -2
  114. package/dist/modules/staff/api/leave-requests/reject/route.js.map +2 -2
  115. package/dist/modules/staff/api/team-members/self/route.js +3 -3
  116. package/dist/modules/staff/api/team-members/self/route.js.map +2 -2
  117. package/dist/modules/staff/api/team-members/tags/assign/route.js +2 -2
  118. package/dist/modules/staff/api/team-members/tags/assign/route.js.map +2 -2
  119. package/dist/modules/staff/api/team-members/tags/unassign/route.js +2 -2
  120. package/dist/modules/staff/api/team-members/tags/unassign/route.js.map +2 -2
  121. package/dist/modules/translations/api/[entityType]/[entityId]/route.js +4 -4
  122. package/dist/modules/translations/api/[entityType]/[entityId]/route.js.map +2 -2
  123. package/dist/modules/translations/api/get/locales.js +2 -2
  124. package/dist/modules/translations/api/get/locales.js.map +2 -2
  125. package/dist/modules/translations/api/put/locales.js +2 -2
  126. package/dist/modules/translations/api/put/locales.js.map +2 -2
  127. package/package.json +5 -5
  128. package/src/modules/catalog/api/dictionaries/[key]/route.ts +2 -2
  129. package/src/modules/customers/api/activities/route.ts +5 -5
  130. package/src/modules/customers/api/assignable-staff/route.ts +2 -2
  131. package/src/modules/customers/api/companies/[id]/people/route.ts +2 -2
  132. package/src/modules/customers/api/dashboard/widgets/customer-todos/route.ts +2 -2
  133. package/src/modules/customers/api/dashboard/widgets/new-customers/route.ts +2 -2
  134. package/src/modules/customers/api/dashboard/widgets/new-deals/route.ts +2 -2
  135. package/src/modules/customers/api/dashboard/widgets/next-interactions/route.ts +2 -2
  136. package/src/modules/customers/api/deals/[id]/companies/route.ts +2 -2
  137. package/src/modules/customers/api/deals/[id]/people/route.ts +2 -2
  138. package/src/modules/customers/api/dictionaries/[kind]/[id]/route.ts +6 -6
  139. package/src/modules/customers/api/dictionaries/[kind]/route.ts +3 -3
  140. package/src/modules/customers/api/dictionaries/currency/route.ts +2 -2
  141. package/src/modules/customers/api/dictionaries/kind-settings/route.ts +3 -3
  142. package/src/modules/customers/api/entity-roles-factory.ts +5 -5
  143. package/src/modules/customers/api/interactions/cancel/route.ts +2 -2
  144. package/src/modules/customers/api/interactions/complete/route.ts +2 -2
  145. package/src/modules/customers/api/interactions/conflicts/route.ts +2 -2
  146. package/src/modules/customers/api/interactions/counts/route.ts +2 -2
  147. package/src/modules/customers/api/interactions/route.ts +2 -2
  148. package/src/modules/customers/api/interactions/tasks/route.ts +2 -2
  149. package/src/modules/customers/api/labels/assign/route.ts +2 -2
  150. package/src/modules/customers/api/labels/route.ts +3 -3
  151. package/src/modules/customers/api/labels/unassign/route.ts +2 -2
  152. package/src/modules/customers/api/people/[id]/companies/[linkId]/route.ts +3 -3
  153. package/src/modules/customers/api/people/[id]/companies/enriched/route.ts +2 -2
  154. package/src/modules/customers/api/people/[id]/companies/route.ts +3 -3
  155. package/src/modules/customers/api/pipeline-stages/reorder/route.ts +2 -2
  156. package/src/modules/customers/api/pipeline-stages/route.ts +5 -5
  157. package/src/modules/customers/api/pipelines/route.ts +5 -5
  158. package/src/modules/customers/api/settings/address-format/route.ts +3 -3
  159. package/src/modules/customers/api/tags/assign/route.ts +2 -2
  160. package/src/modules/customers/api/tags/unassign/route.ts +2 -2
  161. package/src/modules/customers/api/todos/route.ts +5 -5
  162. package/src/modules/dictionaries/api/[dictionaryId]/entries/[entryId]/route.ts +3 -3
  163. package/src/modules/dictionaries/api/[dictionaryId]/entries/reorder/route.ts +2 -2
  164. package/src/modules/dictionaries/api/[dictionaryId]/entries/route.ts +3 -3
  165. package/src/modules/dictionaries/api/[dictionaryId]/entries/set-default/route.ts +2 -2
  166. package/src/modules/dictionaries/api/[dictionaryId]/route.ts +4 -4
  167. package/src/modules/dictionaries/api/route.ts +3 -3
  168. package/src/modules/feature_toggles/api/overrides/route.ts +2 -2
  169. package/src/modules/planner/api/availability-date-specific.ts +2 -2
  170. package/src/modules/planner/api/availability-weekly.ts +2 -2
  171. package/src/modules/resources/api/resources/tags/assign/route.ts +2 -2
  172. package/src/modules/resources/api/resources/tags/unassign/route.ts +2 -2
  173. package/src/modules/sales/api/document-history/route.ts +2 -2
  174. package/src/modules/sales/api/document-numbers/route.ts +2 -2
  175. package/src/modules/sales/api/quotes/accept/route.ts +2 -2
  176. package/src/modules/sales/api/quotes/convert/route.ts +2 -2
  177. package/src/modules/sales/api/quotes/public/[token]/route.ts +2 -2
  178. package/src/modules/sales/api/quotes/send/route.ts +2 -2
  179. package/src/modules/sales/api/returns/[id]/route.ts +2 -2
  180. package/src/modules/sales/api/settings/document-numbers/route.ts +3 -3
  181. package/src/modules/sales/api/settings/order-editing/route.ts +3 -3
  182. package/src/modules/sales/widgets/dashboard/makeDashboardWidgetRoute.ts +2 -2
  183. package/src/modules/staff/api/leave-requests/accept/route.ts +2 -2
  184. package/src/modules/staff/api/leave-requests/reject/route.ts +2 -2
  185. package/src/modules/staff/api/team-members/self/route.ts +3 -3
  186. package/src/modules/staff/api/team-members/tags/assign/route.ts +2 -2
  187. package/src/modules/staff/api/team-members/tags/unassign/route.ts +2 -2
  188. package/src/modules/translations/api/[entityType]/[entityId]/route.ts +4 -4
  189. package/src/modules/translations/api/get/locales.ts +2 -2
  190. package/src/modules/translations/api/put/locales.ts +2 -2
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/customers/api/todos/route.ts"],
4
- "sourcesContent": ["/**\n * @deprecated Use /api/customers/interactions instead. This route is maintained\n * as a compatibility bridge per SPEC-046b. Will be removed in a future release.\n */\nimport { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport type { QueryEngine } from '@open-mercato/shared/lib/query/types'\nimport { createCustomersCrudOpenApi, createPagedListResponseSchema, defaultOkResponseSchema } from '../openapi'\nimport { CustomerInteraction, CustomerTodoLink } from '../../data/entities'\nimport { todoLinkWithTodoCreateSchema } from '../../data/validators'\nimport { resolveCustomerInteractionFeatureFlags } from '../../lib/interactionFeatureFlags'\nimport { resolveCustomersRequestContext } from '../../lib/interactionRequestContext'\nimport {\n EXAMPLE_TODO_SOURCE,\n CUSTOMER_INTERACTION_TODO_ADAPTER_SOURCE,\n} from '../../lib/interactionCompatibility'\nimport {\n filterTodoRows,\n listCanonicalTodoRows,\n listLegacyTodoRows,\n normalizeTodoSearch,\n paginateTodoRows,\n sortTodoRows,\n resolveLegacyTodoDetails,\n} from '../../lib/todoCompatibility'\n\nconst querySchema = z.object({\n page: z.coerce.number().min(1).default(1),\n pageSize: z.coerce.number().min(1).max(100).default(50),\n search: z.string().optional(),\n all: z.string().optional(),\n entityId: z.string().uuid().optional(),\n})\n\nconst todoCreateBodySchema = todoLinkWithTodoCreateSchema.omit({\n tenantId: true,\n organizationId: true,\n}).passthrough()\n\nconst todoUpdateBodySchema = z\n .object({\n id: z.string().uuid(),\n linkId: z.string().uuid().optional(),\n title: z.string().trim().min(1).max(200).optional(),\n isDone: z.boolean().optional(),\n is_done: z.boolean().optional(),\n customFields: z.record(z.string(), z.unknown()).optional(),\n customValues: z.record(z.string(), z.unknown()).optional(),\n })\n .passthrough()\n\nconst todoDeleteBodySchema = z.object({\n id: z.string().uuid(),\n todoId: z.string().uuid().optional(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['customers.view'] },\n POST: { requireAuth: true, requireFeatures: ['customers.interactions.manage'] },\n PUT: { requireAuth: true, requireFeatures: ['customers.interactions.manage'] },\n DELETE: { requireAuth: true, requireFeatures: ['customers.interactions.manage'] },\n}\n\nconst DEPRECATION_HEADERS = {\n Deprecation: 'true',\n Sunset: 'Tue, 30 Jun 2026 00:00:00 GMT',\n Link: '</api/customers/interactions>; rel=\"successor-version\"',\n}\n\n// Caps the per-source fetch window used by the deprecated merged (legacy +\n// canonical bridge) read path. Keeps memory bounded on tenants with large\n// todo history; deep-pagination beyond this window is not supported here \u2014\n// use /api/customers/interactions instead.\nconst MERGED_TODO_FETCH_CAP = 2000\n\nfunction resolveGuardUserId(auth: {\n sub?: string | null\n userId?: string | null\n keyId?: string | null\n}): string {\n if (typeof auth.sub === 'string' && auth.sub.trim().length > 0) return auth.sub\n if (typeof auth.userId === 'string' && auth.userId.trim().length > 0) return auth.userId\n if (typeof auth.keyId === 'string' && auth.keyId.trim().length > 0) return auth.keyId\n return 'system'\n}\n\nfunction withAdapterHeaders(response: Response): Response {\n const headers = new Headers(response.headers)\n Object.entries(DEPRECATION_HEADERS).forEach(([key, value]) => headers.set(key, value))\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n })\n}\n\nasync function legacyAdaptersDisabledResponse(): Promise<Response> {\n const { translate } = await resolveTranslations()\n return withAdapterHeaders(NextResponse.json(\n {\n error: translate(\n 'customers.interactions.legacyAdapters.disabled',\n 'This legacy adapter has been disabled. Use /api/customers/interactions instead.',\n ),\n },\n { status: 410 },\n ))\n}\n\nfunction normalizeTodoStatusInput(body: z.infer<typeof todoUpdateBodySchema>): boolean | undefined {\n if (typeof body.isDone === 'boolean') return body.isDone\n if (typeof body.is_done === 'boolean') return body.is_done\n return undefined\n}\n\nfunction collectTodoCustomValues(\n body: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n const direct =\n body.customValues && typeof body.customValues === 'object'\n ? { ...(body.customValues as Record<string, unknown>) }\n : {}\n if (body.todoCustom && typeof body.todoCustom === 'object') {\n Object.assign(direct, body.todoCustom as Record<string, unknown>)\n }\n if (body.customFields && typeof body.customFields === 'object') {\n Object.assign(direct, body.customFields as Record<string, unknown>)\n }\n return Object.keys(direct).length > 0 ? direct : undefined\n}\n\nasync function findLegacyTodoLink(\n em: EntityManager,\n target: { linkId?: string; todoId?: string },\n tenantId: string,\n): Promise<CustomerTodoLink | null> {\n if (target.linkId) {\n const byLinkId = await em.findOne(CustomerTodoLink, { id: target.linkId, tenantId }, { populate: ['entity'] })\n if (byLinkId) return byLinkId\n }\n if (target.todoId) {\n return await em.findOne(CustomerTodoLink, { todoId: target.todoId, tenantId }, { populate: ['entity'] })\n }\n return null\n}\n\nasync function ensureCanonicalTodoBridge(\n em: EntityManager,\n queryEngine: QueryEngine,\n commandBus: CommandBus,\n commandContext: Parameters<CommandBus['execute']>[1]['ctx'],\n link: CustomerTodoLink,\n): Promise<string> {\n const existing = await em.findOne(CustomerInteraction, { id: link.todoId, tenantId: link.tenantId })\n if (existing) return existing.id\n\n const detailMap = await resolveLegacyTodoDetails(\n queryEngine,\n [link],\n link.tenantId,\n [link.organizationId],\n )\n const source =\n typeof link.todoSource === 'string' && link.todoSource.trim().length > 0\n ? link.todoSource\n : EXAMPLE_TODO_SOURCE\n const detail = detailMap.get(`${source}:${link.todoId}`) ?? null\n const entityId = typeof link.entity === 'string' ? link.entity : link.entity.id\n\n await commandBus.execute('customers.interactions.create', {\n input: {\n id: link.todoId,\n tenantId: link.tenantId,\n organizationId: link.organizationId,\n entityId,\n interactionType: 'task',\n title: detail?.title ?? null,\n body: detail?.description ?? null,\n status: detail?.isDone ? 'done' : 'planned',\n scheduledAt: detail?.dueAt ?? null,\n priority: detail?.priority ?? null,\n source: CUSTOMER_INTERACTION_TODO_ADAPTER_SOURCE,\n ...(detail?.customValues ? { customValues: detail.customValues } : {}),\n },\n ctx: commandContext,\n })\n\n return link.todoId\n}\n\nasync function resolveCanonicalTodoTargetId(\n em: EntityManager,\n queryEngine: QueryEngine,\n commandBus: CommandBus,\n commandContext: Parameters<CommandBus['execute']>[1]['ctx'],\n target: { todoId?: string; linkId?: string },\n tenantId: string,\n): Promise<string> {\n if (target.todoId) {\n const interaction = await em.findOne(CustomerInteraction, { id: target.todoId, tenantId })\n if (interaction) return interaction.id\n }\n\n const legacyLink = await findLegacyTodoLink(em, target, tenantId)\n if (!legacyLink) {\n if (!target.todoId) throw new CrudHttpError(404, { error: 'Todo not found' })\n return target.todoId\n }\n\n return ensureCanonicalTodoBridge(\n em,\n queryEngine,\n commandBus,\n commandContext,\n legacyLink,\n )\n}\n\nexport async function GET(request: Request): Promise<Response> {\n try {\n const { auth, em, organizationIds, container, selectedOrganizationId } =\n await resolveCustomersRequestContext(request)\n const query = querySchema.parse(Object.fromEntries(new URL(request.url).searchParams))\n const flags = await resolveCustomerInteractionFeatureFlags(container, auth.tenantId)\n if (!flags.legacyAdapters) {\n return await legacyAdaptersDisabledResponse()\n }\n const queryEngine = container.resolve('queryEngine') as QueryEngine\n const exportAll = parseBooleanToken(query.all) === true\n const search = normalizeTodoSearch(query.search)\n\n if (flags.unified) {\n const canonical = await listCanonicalTodoRows(\n em,\n container,\n auth,\n selectedOrganizationId,\n organizationIds,\n {\n entityId: query.entityId,\n pagination: exportAll ? null : { page: query.page, pageSize: query.pageSize },\n searchText: search,\n },\n )\n const total = canonical.total\n return withAdapterHeaders(\n NextResponse.json({\n items: canonical.items,\n total,\n page: exportAll ? 1 : query.page,\n pageSize: exportAll ? canonical.items.length : query.pageSize,\n totalPages: exportAll ? 1 : Math.max(1, Math.ceil(total / query.pageSize)),\n }),\n )\n }\n\n const legacyWindow = exportAll\n ? null\n : Math.min(MERGED_TODO_FETCH_CAP, Math.max(query.pageSize, query.page * query.pageSize + query.pageSize))\n const [legacyRows, canonicalRows] = await Promise.all([\n listLegacyTodoRows(em, queryEngine, auth.tenantId, organizationIds, query.entityId, {\n limit: legacyWindow,\n }),\n listCanonicalTodoRows(\n em,\n container,\n auth,\n selectedOrganizationId,\n organizationIds,\n {\n entityId: query.entityId,\n includeDeleted: true,\n source: CUSTOMER_INTERACTION_TODO_ADAPTER_SOURCE,\n limit: legacyWindow,\n },\n ),\n ])\n const mergedRows = [\n ...legacyRows.filter((row) => !canonicalRows.bridgeIds.has(row.todoId)),\n ...canonicalRows.items,\n ]\n const filteredRows = filterTodoRows(sortTodoRows(mergedRows), search)\n const paged = paginateTodoRows(filteredRows, query.page, query.pageSize, exportAll)\n\n return withAdapterHeaders(\n NextResponse.json({\n items: paged.items,\n total: paged.total,\n page: paged.page,\n pageSize: paged.pageSize,\n totalPages: paged.totalPages,\n }),\n )\n } catch (err) {\n if (err instanceof CrudHttpError) {\n return withAdapterHeaders(NextResponse.json(err.body, { status: err.status }))\n }\n if (err instanceof z.ZodError) {\n return withAdapterHeaders(\n NextResponse.json({ error: 'Validation failed', details: err.issues }, { status: 400 }),\n )\n }\n console.error('customers.todos.get failed', err)\n return withAdapterHeaders(\n NextResponse.json({ error: 'Internal server error' }, { status: 500 }),\n )\n }\n}\n\nexport async function POST(request: Request): Promise<Response> {\n try {\n const { commandContext, container, auth, selectedOrganizationId } = await resolveCustomersRequestContext(request)\n const flags = await resolveCustomerInteractionFeatureFlags(container, auth.tenantId)\n if (!flags.legacyAdapters) {\n return await legacyAdaptersDisabledResponse()\n }\n const commandBus = container.resolve('commandBus') as CommandBus\n const body = todoCreateBodySchema.parse(await readJsonSafe<Record<string, unknown>>(request, {}))\n const guardUserId = resolveGuardUserId(auth)\n const guardResult = await validateCrudMutationGuard(container, {\n tenantId: auth.tenantId,\n organizationId: selectedOrganizationId,\n userId: guardUserId,\n resourceKind: 'customers.todoLink',\n resourceId: body.entityId,\n operation: 'create',\n requestMethod: request.method,\n requestHeaders: request.headers,\n mutationPayload: body,\n })\n if (guardResult && !guardResult.ok) {\n return withAdapterHeaders(NextResponse.json(guardResult.body, { status: guardResult.status }))\n }\n const customValues = collectTodoCustomValues(body as Record<string, unknown>)\n\n const { result } = await commandBus.execute('customers.interactions.create', {\n input: {\n tenantId: auth.tenantId,\n organizationId: selectedOrganizationId ?? auth.orgId,\n entityId: body.entityId,\n interactionType: 'task',\n title: body.title,\n status: body.is_done === true || body.isDone === true ? 'done' : 'planned',\n source: CUSTOMER_INTERACTION_TODO_ADAPTER_SOURCE,\n ...(customValues ? {\n customValues,\n priority: typeof customValues.priority === 'number' ? customValues.priority : null,\n body: typeof customValues.description === 'string' ? customValues.description : null,\n scheduledAt:\n typeof customValues.due_at === 'string'\n ? customValues.due_at\n : typeof customValues.dueAt === 'string'\n ? customValues.dueAt\n : null,\n } : {}),\n },\n ctx: commandContext,\n })\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(container, {\n tenantId: auth.tenantId,\n organizationId: selectedOrganizationId,\n userId: guardUserId,\n resourceKind: 'customers.todoLink',\n resourceId: body.entityId,\n operation: 'create',\n requestMethod: request.method,\n requestHeaders: request.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n const interactionId =\n result &&\n typeof result === 'object' &&\n 'interactionId' in result &&\n typeof result.interactionId === 'string'\n ? result.interactionId\n : result &&\n typeof result === 'object' &&\n 'id' in result &&\n typeof result.id === 'string'\n ? result.id\n : null\n return withAdapterHeaders(\n NextResponse.json(\n {\n linkId: interactionId,\n todoId: interactionId,\n },\n { status: 201 },\n ),\n )\n } catch (err) {\n if (err instanceof CrudHttpError) {\n return withAdapterHeaders(NextResponse.json(err.body, { status: err.status }))\n }\n if (err instanceof z.ZodError) {\n return withAdapterHeaders(\n NextResponse.json({ error: 'Validation failed', details: err.issues }, { status: 400 }),\n )\n }\n console.error('customers.todos.post failed', err)\n return withAdapterHeaders(\n NextResponse.json({ error: 'Internal server error' }, { status: 500 }),\n )\n }\n}\n\nexport async function PUT(request: Request): Promise<Response> {\n try {\n const { commandContext, container, em, auth, selectedOrganizationId } = await resolveCustomersRequestContext(request)\n const flags = await resolveCustomerInteractionFeatureFlags(container, auth.tenantId)\n if (!flags.legacyAdapters) {\n return await legacyAdaptersDisabledResponse()\n }\n const commandBus = container.resolve('commandBus') as CommandBus\n const queryEngine = container.resolve('queryEngine') as QueryEngine\n const body = todoUpdateBodySchema.parse(await readJsonSafe<Record<string, unknown>>(request, {}))\n const guardUserId = resolveGuardUserId(auth)\n const guardResult = await validateCrudMutationGuard(container, {\n tenantId: auth.tenantId,\n organizationId: selectedOrganizationId,\n userId: guardUserId,\n resourceKind: 'customers.todoLink',\n resourceId: body.linkId ?? body.id,\n operation: 'update',\n requestMethod: request.method,\n requestHeaders: request.headers,\n mutationPayload: body,\n })\n if (guardResult && !guardResult.ok) {\n return withAdapterHeaders(NextResponse.json(guardResult.body, { status: guardResult.status }))\n }\n const interactionId = flags.unified\n ? body.id\n : await resolveCanonicalTodoTargetId(\n em,\n queryEngine,\n commandBus,\n commandContext,\n {\n todoId: body.id,\n linkId: body.linkId,\n },\n auth.tenantId,\n )\n const customValues = collectTodoCustomValues(body as Record<string, unknown>)\n const nextDone = normalizeTodoStatusInput(body)\n\n await commandBus.execute('customers.interactions.update', {\n input: {\n id: interactionId,\n ...(body.title !== undefined ? { title: body.title } : {}),\n ...(nextDone !== undefined ? { status: nextDone ? 'done' : 'planned' } : {}),\n ...(customValues ? {\n customValues,\n priority: typeof customValues.priority === 'number' ? customValues.priority : null,\n body: typeof customValues.description === 'string' ? customValues.description : null,\n scheduledAt:\n typeof customValues.due_at === 'string'\n ? customValues.due_at\n : typeof customValues.dueAt === 'string'\n ? customValues.dueAt\n : null,\n } : {}),\n },\n ctx: commandContext,\n })\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(container, {\n tenantId: auth.tenantId,\n organizationId: selectedOrganizationId,\n userId: guardUserId,\n resourceKind: 'customers.todoLink',\n resourceId: body.linkId ?? body.id,\n operation: 'update',\n requestMethod: request.method,\n requestHeaders: request.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n return withAdapterHeaders(NextResponse.json({ ok: true }))\n } catch (err) {\n if (err instanceof CrudHttpError) {\n return withAdapterHeaders(NextResponse.json(err.body, { status: err.status }))\n }\n if (err instanceof z.ZodError) {\n return withAdapterHeaders(\n NextResponse.json({ error: 'Validation failed', details: err.issues }, { status: 400 }),\n )\n }\n console.error('customers.todos.put failed', err)\n return withAdapterHeaders(\n NextResponse.json({ error: 'Internal server error' }, { status: 500 }),\n )\n }\n}\n\nexport async function DELETE(request: Request): Promise<Response> {\n try {\n const { commandContext, container, em, auth, selectedOrganizationId } = await resolveCustomersRequestContext(request)\n const flags = await resolveCustomerInteractionFeatureFlags(container, auth.tenantId)\n if (!flags.legacyAdapters) {\n return await legacyAdaptersDisabledResponse()\n }\n const commandBus = container.resolve('commandBus') as CommandBus\n const queryEngine = container.resolve('queryEngine') as QueryEngine\n const body = todoDeleteBodySchema.parse(await readJsonSafe<Record<string, unknown>>(request, {}))\n const guardUserId = resolveGuardUserId(auth)\n const guardResult = await validateCrudMutationGuard(container, {\n tenantId: auth.tenantId,\n organizationId: selectedOrganizationId,\n userId: guardUserId,\n resourceKind: 'customers.todoLink',\n resourceId: body.id,\n operation: 'delete',\n requestMethod: request.method,\n requestHeaders: request.headers,\n mutationPayload: body,\n })\n if (guardResult && !guardResult.ok) {\n return withAdapterHeaders(NextResponse.json(guardResult.body, { status: guardResult.status }))\n }\n const interactionId = flags.unified\n ? body.todoId ?? body.id\n : await resolveCanonicalTodoTargetId(\n em,\n queryEngine,\n commandBus,\n commandContext,\n {\n linkId: body.id,\n todoId: body.todoId ?? body.id,\n },\n auth.tenantId,\n )\n\n await commandBus.execute('customers.interactions.delete', {\n input: { id: interactionId },\n ctx: commandContext,\n })\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(container, {\n tenantId: auth.tenantId,\n organizationId: selectedOrganizationId,\n userId: guardUserId,\n resourceKind: 'customers.todoLink',\n resourceId: body.id,\n operation: 'delete',\n requestMethod: request.method,\n requestHeaders: request.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n return withAdapterHeaders(NextResponse.json({ ok: true }))\n } catch (err) {\n if (err instanceof CrudHttpError) {\n return withAdapterHeaders(NextResponse.json(err.body, { status: err.status }))\n }\n if (err instanceof z.ZodError) {\n return withAdapterHeaders(\n NextResponse.json({ error: 'Validation failed', details: err.issues }, { status: 400 }),\n )\n }\n console.error('customers.todos.delete failed', err)\n return withAdapterHeaders(\n NextResponse.json({ error: 'Internal server error' }, { status: 500 }),\n )\n }\n}\n\nconst todoItemSchema = z.object({\n id: z.string(),\n todoId: z.string(),\n todoSource: z.string(),\n todoTitle: z.string().nullable(),\n todoIsDone: z.boolean().nullable(),\n todoPriority: z.number().nullable().optional(),\n todoSeverity: z.string().nullable().optional(),\n todoDescription: z.string().nullable().optional(),\n todoDueAt: z.string().nullable().optional(),\n todoCustomValues: z.record(z.string(), z.unknown()).nullable().optional(),\n todoOrganizationId: z.string().nullable(),\n organizationId: z.string(),\n tenantId: z.string(),\n createdAt: z.string(),\n externalHref: z.string().nullable().optional(),\n _integrations: z.record(z.string(), z.unknown()).optional(),\n customer: z.object({\n id: z.string().nullable(),\n displayName: z.string().nullable(),\n kind: z.string().nullable(),\n }),\n})\n\nconst todoCreateResponseSchema = z.object({\n linkId: z.string().uuid().nullable(),\n todoId: z.string().uuid().nullable(),\n})\n\nexport const openApi: OpenApiRouteDoc = createCustomersCrudOpenApi({\n resourceName: 'CustomerTodo',\n querySchema,\n listResponseSchema: createPagedListResponseSchema(todoItemSchema),\n create: {\n schema: todoCreateBodySchema,\n responseSchema: todoCreateResponseSchema,\n description: 'DEPRECATED (sunset 2026-06-30): Creates a customer task. Use POST /api/customers/interactions instead.',\n },\n update: {\n schema: todoUpdateBodySchema,\n responseSchema: defaultOkResponseSchema,\n description: 'DEPRECATED (sunset 2026-06-30): Updates a customer task. Use PUT /api/customers/interactions instead.',\n },\n del: {\n schema: todoDeleteBodySchema,\n responseSchema: defaultOkResponseSchema,\n description: 'DEPRECATED (sunset 2026-06-30): Deletes a customer task. Use DELETE /api/customers/interactions instead.',\n },\n})\n"],
5
- "mappings": "AAIA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAIlB,SAAS,qBAAqB;AAC9B,SAAS,y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Ac,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS;AAAA,EAC7C,eAAe,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,EAAE,SAAS;AAAA,EAC1D,UAAU,EAAE,OAAO;AAAA,IACjB,IAAI,EAAE,OAAO,EAAE,SAAS;AAAA,IACxB,aAAa,EAAE,OAAO,EAAE,SAAS;AAAA,IACjC,MAAM,EAAE,OAAO,EAAE,SAAS;AAAA,EAC5B,CAAC;AACH,CAAC;AAED,MAAM,2BAA2B,EAAE,OAAO;AAAA,EACxC,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAAA,EACnC,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AACrC,CAAC;AAEM,MAAM,UAA2B,2BAA2B;AAAA,EACjE,cAAc;AAAA,EACd;AAAA,EACA,oBAAoB,8BAA8B,cAAc;AAAA,EAChE,QAAQ;AAAA,IACN,QAAQ;AAAA,IACR,gBAAgB;AAAA,IAChB,aAAa;AAAA,EACf;AAAA,EACA,QAAQ;AAAA,IACN,QAAQ;AAAA,IACR,gBAAgB;AAAA,IAChB,aAAa;AAAA,EACf;AAAA,EACA,KAAK;AAAA,IACH,QAAQ;AAAA,IACR,gBAAgB;AAAA,IAChB,aAAa;AAAA,EACf;AACF,CAAC;",
4
+ "sourcesContent": ["/**\n * @deprecated Use /api/customers/interactions instead. This route is maintained\n * as a compatibility bridge per SPEC-046b. Will be removed in a future release.\n */\nimport { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport type { QueryEngine } from '@open-mercato/shared/lib/query/types'\nimport { createCustomersCrudOpenApi, createPagedListResponseSchema, defaultOkResponseSchema } from '../openapi'\nimport { CustomerInteraction, CustomerTodoLink } from '../../data/entities'\nimport { todoLinkWithTodoCreateSchema } from '../../data/validators'\nimport { resolveCustomerInteractionFeatureFlags } from '../../lib/interactionFeatureFlags'\nimport { resolveCustomersRequestContext } from '../../lib/interactionRequestContext'\nimport {\n EXAMPLE_TODO_SOURCE,\n CUSTOMER_INTERACTION_TODO_ADAPTER_SOURCE,\n} from '../../lib/interactionCompatibility'\nimport {\n filterTodoRows,\n listCanonicalTodoRows,\n listLegacyTodoRows,\n normalizeTodoSearch,\n paginateTodoRows,\n sortTodoRows,\n resolveLegacyTodoDetails,\n} from '../../lib/todoCompatibility'\n\nconst querySchema = z.object({\n page: z.coerce.number().min(1).default(1),\n pageSize: z.coerce.number().min(1).max(100).default(50),\n search: z.string().optional(),\n all: z.string().optional(),\n entityId: z.string().uuid().optional(),\n})\n\nconst todoCreateBodySchema = todoLinkWithTodoCreateSchema.omit({\n tenantId: true,\n organizationId: true,\n}).passthrough()\n\nconst todoUpdateBodySchema = z\n .object({\n id: z.string().uuid(),\n linkId: z.string().uuid().optional(),\n title: z.string().trim().min(1).max(200).optional(),\n isDone: z.boolean().optional(),\n is_done: z.boolean().optional(),\n customFields: z.record(z.string(), z.unknown()).optional(),\n customValues: z.record(z.string(), z.unknown()).optional(),\n })\n .passthrough()\n\nconst todoDeleteBodySchema = z.object({\n id: z.string().uuid(),\n todoId: z.string().uuid().optional(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['customers.view'] },\n POST: { requireAuth: true, requireFeatures: ['customers.interactions.manage'] },\n PUT: { requireAuth: true, requireFeatures: ['customers.interactions.manage'] },\n DELETE: { requireAuth: true, requireFeatures: ['customers.interactions.manage'] },\n}\n\nconst DEPRECATION_HEADERS = {\n Deprecation: 'true',\n Sunset: 'Tue, 30 Jun 2026 00:00:00 GMT',\n Link: '</api/customers/interactions>; rel=\"successor-version\"',\n}\n\n// Caps the per-source fetch window used by the deprecated merged (legacy +\n// canonical bridge) read path. Keeps memory bounded on tenants with large\n// todo history; deep-pagination beyond this window is not supported here \u2014\n// use /api/customers/interactions instead.\nconst MERGED_TODO_FETCH_CAP = 2000\n\nfunction resolveGuardUserId(auth: {\n sub?: string | null\n userId?: string | null\n keyId?: string | null\n}): string {\n if (typeof auth.sub === 'string' && auth.sub.trim().length > 0) return auth.sub\n if (typeof auth.userId === 'string' && auth.userId.trim().length > 0) return auth.userId\n if (typeof auth.keyId === 'string' && auth.keyId.trim().length > 0) return auth.keyId\n return 'system'\n}\n\nfunction withAdapterHeaders(response: Response): Response {\n const headers = new Headers(response.headers)\n Object.entries(DEPRECATION_HEADERS).forEach(([key, value]) => headers.set(key, value))\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n })\n}\n\nasync function legacyAdaptersDisabledResponse(): Promise<Response> {\n const { translate } = await resolveTranslations()\n return withAdapterHeaders(NextResponse.json(\n {\n error: translate(\n 'customers.interactions.legacyAdapters.disabled',\n 'This legacy adapter has been disabled. Use /api/customers/interactions instead.',\n ),\n },\n { status: 410 },\n ))\n}\n\nfunction normalizeTodoStatusInput(body: z.infer<typeof todoUpdateBodySchema>): boolean | undefined {\n if (typeof body.isDone === 'boolean') return body.isDone\n if (typeof body.is_done === 'boolean') return body.is_done\n return undefined\n}\n\nfunction collectTodoCustomValues(\n body: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n const direct =\n body.customValues && typeof body.customValues === 'object'\n ? { ...(body.customValues as Record<string, unknown>) }\n : {}\n if (body.todoCustom && typeof body.todoCustom === 'object') {\n Object.assign(direct, body.todoCustom as Record<string, unknown>)\n }\n if (body.customFields && typeof body.customFields === 'object') {\n Object.assign(direct, body.customFields as Record<string, unknown>)\n }\n return Object.keys(direct).length > 0 ? direct : undefined\n}\n\nasync function findLegacyTodoLink(\n em: EntityManager,\n target: { linkId?: string; todoId?: string },\n tenantId: string,\n): Promise<CustomerTodoLink | null> {\n if (target.linkId) {\n const byLinkId = await em.findOne(CustomerTodoLink, { id: target.linkId, tenantId }, { populate: ['entity'] })\n if (byLinkId) return byLinkId\n }\n if (target.todoId) {\n return await em.findOne(CustomerTodoLink, { todoId: target.todoId, tenantId }, { populate: ['entity'] })\n }\n return null\n}\n\nasync function ensureCanonicalTodoBridge(\n em: EntityManager,\n queryEngine: QueryEngine,\n commandBus: CommandBus,\n commandContext: Parameters<CommandBus['execute']>[1]['ctx'],\n link: CustomerTodoLink,\n): Promise<string> {\n const existing = await em.findOne(CustomerInteraction, { id: link.todoId, tenantId: link.tenantId })\n if (existing) return existing.id\n\n const detailMap = await resolveLegacyTodoDetails(\n queryEngine,\n [link],\n link.tenantId,\n [link.organizationId],\n )\n const source =\n typeof link.todoSource === 'string' && link.todoSource.trim().length > 0\n ? link.todoSource\n : EXAMPLE_TODO_SOURCE\n const detail = detailMap.get(`${source}:${link.todoId}`) ?? null\n const entityId = typeof link.entity === 'string' ? link.entity : link.entity.id\n\n await commandBus.execute('customers.interactions.create', {\n input: {\n id: link.todoId,\n tenantId: link.tenantId,\n organizationId: link.organizationId,\n entityId,\n interactionType: 'task',\n title: detail?.title ?? null,\n body: detail?.description ?? null,\n status: detail?.isDone ? 'done' : 'planned',\n scheduledAt: detail?.dueAt ?? null,\n priority: detail?.priority ?? null,\n source: CUSTOMER_INTERACTION_TODO_ADAPTER_SOURCE,\n ...(detail?.customValues ? { customValues: detail.customValues } : {}),\n },\n ctx: commandContext,\n })\n\n return link.todoId\n}\n\nasync function resolveCanonicalTodoTargetId(\n em: EntityManager,\n queryEngine: QueryEngine,\n commandBus: CommandBus,\n commandContext: Parameters<CommandBus['execute']>[1]['ctx'],\n target: { todoId?: string; linkId?: string },\n tenantId: string,\n): Promise<string> {\n if (target.todoId) {\n const interaction = await em.findOne(CustomerInteraction, { id: target.todoId, tenantId })\n if (interaction) return interaction.id\n }\n\n const legacyLink = await findLegacyTodoLink(em, target, tenantId)\n if (!legacyLink) {\n if (!target.todoId) throw new CrudHttpError(404, { error: 'Todo not found' })\n return target.todoId\n }\n\n return ensureCanonicalTodoBridge(\n em,\n queryEngine,\n commandBus,\n commandContext,\n legacyLink,\n )\n}\n\nexport async function GET(request: Request): Promise<Response> {\n try {\n const { auth, em, organizationIds, container, selectedOrganizationId } =\n await resolveCustomersRequestContext(request)\n const query = querySchema.parse(Object.fromEntries(new URL(request.url).searchParams))\n const flags = await resolveCustomerInteractionFeatureFlags(container, auth.tenantId)\n if (!flags.legacyAdapters) {\n return await legacyAdaptersDisabledResponse()\n }\n const queryEngine = container.resolve('queryEngine') as QueryEngine\n const exportAll = parseBooleanToken(query.all) === true\n const search = normalizeTodoSearch(query.search)\n\n if (flags.unified) {\n const canonical = await listCanonicalTodoRows(\n em,\n container,\n auth,\n selectedOrganizationId,\n organizationIds,\n {\n entityId: query.entityId,\n pagination: exportAll ? null : { page: query.page, pageSize: query.pageSize },\n searchText: search,\n },\n )\n const total = canonical.total\n return withAdapterHeaders(\n NextResponse.json({\n items: canonical.items,\n total,\n page: exportAll ? 1 : query.page,\n pageSize: exportAll ? canonical.items.length : query.pageSize,\n totalPages: exportAll ? 1 : Math.max(1, Math.ceil(total / query.pageSize)),\n }),\n )\n }\n\n const legacyWindow = exportAll\n ? null\n : Math.min(MERGED_TODO_FETCH_CAP, Math.max(query.pageSize, query.page * query.pageSize + query.pageSize))\n const [legacyRows, canonicalRows] = await Promise.all([\n listLegacyTodoRows(em, queryEngine, auth.tenantId, organizationIds, query.entityId, {\n limit: legacyWindow,\n }),\n listCanonicalTodoRows(\n em,\n container,\n auth,\n selectedOrganizationId,\n organizationIds,\n {\n entityId: query.entityId,\n includeDeleted: true,\n source: CUSTOMER_INTERACTION_TODO_ADAPTER_SOURCE,\n limit: legacyWindow,\n },\n ),\n ])\n const mergedRows = [\n ...legacyRows.filter((row) => !canonicalRows.bridgeIds.has(row.todoId)),\n ...canonicalRows.items,\n ]\n const filteredRows = filterTodoRows(sortTodoRows(mergedRows), search)\n const paged = paginateTodoRows(filteredRows, query.page, query.pageSize, exportAll)\n\n return withAdapterHeaders(\n NextResponse.json({\n items: paged.items,\n total: paged.total,\n page: paged.page,\n pageSize: paged.pageSize,\n totalPages: paged.totalPages,\n }),\n )\n } catch (err) {\n if (isCrudHttpError(err)) {\n return withAdapterHeaders(NextResponse.json(err.body, { status: err.status }))\n }\n if (err instanceof z.ZodError) {\n return withAdapterHeaders(\n NextResponse.json({ error: 'Validation failed', details: err.issues }, { status: 400 }),\n )\n }\n console.error('customers.todos.get failed', err)\n return withAdapterHeaders(\n NextResponse.json({ error: 'Internal server error' }, { status: 500 }),\n )\n }\n}\n\nexport async function POST(request: Request): Promise<Response> {\n try {\n const { commandContext, container, auth, selectedOrganizationId } = await resolveCustomersRequestContext(request)\n const flags = await resolveCustomerInteractionFeatureFlags(container, auth.tenantId)\n if (!flags.legacyAdapters) {\n return await legacyAdaptersDisabledResponse()\n }\n const commandBus = container.resolve('commandBus') as CommandBus\n const body = todoCreateBodySchema.parse(await readJsonSafe<Record<string, unknown>>(request, {}))\n const guardUserId = resolveGuardUserId(auth)\n const guardResult = await validateCrudMutationGuard(container, {\n tenantId: auth.tenantId,\n organizationId: selectedOrganizationId,\n userId: guardUserId,\n resourceKind: 'customers.todoLink',\n resourceId: body.entityId,\n operation: 'create',\n requestMethod: request.method,\n requestHeaders: request.headers,\n mutationPayload: body,\n })\n if (guardResult && !guardResult.ok) {\n return withAdapterHeaders(NextResponse.json(guardResult.body, { status: guardResult.status }))\n }\n const customValues = collectTodoCustomValues(body as Record<string, unknown>)\n\n const { result } = await commandBus.execute('customers.interactions.create', {\n input: {\n tenantId: auth.tenantId,\n organizationId: selectedOrganizationId ?? auth.orgId,\n entityId: body.entityId,\n interactionType: 'task',\n title: body.title,\n status: body.is_done === true || body.isDone === true ? 'done' : 'planned',\n source: CUSTOMER_INTERACTION_TODO_ADAPTER_SOURCE,\n ...(customValues ? {\n customValues,\n priority: typeof customValues.priority === 'number' ? customValues.priority : null,\n body: typeof customValues.description === 'string' ? customValues.description : null,\n scheduledAt:\n typeof customValues.due_at === 'string'\n ? customValues.due_at\n : typeof customValues.dueAt === 'string'\n ? customValues.dueAt\n : null,\n } : {}),\n },\n ctx: commandContext,\n })\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(container, {\n tenantId: auth.tenantId,\n organizationId: selectedOrganizationId,\n userId: guardUserId,\n resourceKind: 'customers.todoLink',\n resourceId: body.entityId,\n operation: 'create',\n requestMethod: request.method,\n requestHeaders: request.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n const interactionId =\n result &&\n typeof result === 'object' &&\n 'interactionId' in result &&\n typeof result.interactionId === 'string'\n ? result.interactionId\n : result &&\n typeof result === 'object' &&\n 'id' in result &&\n typeof result.id === 'string'\n ? result.id\n : null\n return withAdapterHeaders(\n NextResponse.json(\n {\n linkId: interactionId,\n todoId: interactionId,\n },\n { status: 201 },\n ),\n )\n } catch (err) {\n if (isCrudHttpError(err)) {\n return withAdapterHeaders(NextResponse.json(err.body, { status: err.status }))\n }\n if (err instanceof z.ZodError) {\n return withAdapterHeaders(\n NextResponse.json({ error: 'Validation failed', details: err.issues }, { status: 400 }),\n )\n }\n console.error('customers.todos.post failed', err)\n return withAdapterHeaders(\n NextResponse.json({ error: 'Internal server error' }, { status: 500 }),\n )\n }\n}\n\nexport async function PUT(request: Request): Promise<Response> {\n try {\n const { commandContext, container, em, auth, selectedOrganizationId } = await resolveCustomersRequestContext(request)\n const flags = await resolveCustomerInteractionFeatureFlags(container, auth.tenantId)\n if (!flags.legacyAdapters) {\n return await legacyAdaptersDisabledResponse()\n }\n const commandBus = container.resolve('commandBus') as CommandBus\n const queryEngine = container.resolve('queryEngine') as QueryEngine\n const body = todoUpdateBodySchema.parse(await readJsonSafe<Record<string, unknown>>(request, {}))\n const guardUserId = resolveGuardUserId(auth)\n const guardResult = await validateCrudMutationGuard(container, {\n tenantId: auth.tenantId,\n organizationId: selectedOrganizationId,\n userId: guardUserId,\n resourceKind: 'customers.todoLink',\n resourceId: body.linkId ?? body.id,\n operation: 'update',\n requestMethod: request.method,\n requestHeaders: request.headers,\n mutationPayload: body,\n })\n if (guardResult && !guardResult.ok) {\n return withAdapterHeaders(NextResponse.json(guardResult.body, { status: guardResult.status }))\n }\n const interactionId = flags.unified\n ? body.id\n : await resolveCanonicalTodoTargetId(\n em,\n queryEngine,\n commandBus,\n commandContext,\n {\n todoId: body.id,\n linkId: body.linkId,\n },\n auth.tenantId,\n )\n const customValues = collectTodoCustomValues(body as Record<string, unknown>)\n const nextDone = normalizeTodoStatusInput(body)\n\n await commandBus.execute('customers.interactions.update', {\n input: {\n id: interactionId,\n ...(body.title !== undefined ? { title: body.title } : {}),\n ...(nextDone !== undefined ? { status: nextDone ? 'done' : 'planned' } : {}),\n ...(customValues ? {\n customValues,\n priority: typeof customValues.priority === 'number' ? customValues.priority : null,\n body: typeof customValues.description === 'string' ? customValues.description : null,\n scheduledAt:\n typeof customValues.due_at === 'string'\n ? customValues.due_at\n : typeof customValues.dueAt === 'string'\n ? customValues.dueAt\n : null,\n } : {}),\n },\n ctx: commandContext,\n })\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(container, {\n tenantId: auth.tenantId,\n organizationId: selectedOrganizationId,\n userId: guardUserId,\n resourceKind: 'customers.todoLink',\n resourceId: body.linkId ?? body.id,\n operation: 'update',\n requestMethod: request.method,\n requestHeaders: request.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n return withAdapterHeaders(NextResponse.json({ ok: true }))\n } catch (err) {\n if (isCrudHttpError(err)) {\n return withAdapterHeaders(NextResponse.json(err.body, { status: err.status }))\n }\n if (err instanceof z.ZodError) {\n return withAdapterHeaders(\n NextResponse.json({ error: 'Validation failed', details: err.issues }, { status: 400 }),\n )\n }\n console.error('customers.todos.put failed', err)\n return withAdapterHeaders(\n NextResponse.json({ error: 'Internal server error' }, { status: 500 }),\n )\n }\n}\n\nexport async function DELETE(request: Request): Promise<Response> {\n try {\n const { commandContext, container, em, auth, selectedOrganizationId } = await resolveCustomersRequestContext(request)\n const flags = await resolveCustomerInteractionFeatureFlags(container, auth.tenantId)\n if (!flags.legacyAdapters) {\n return await legacyAdaptersDisabledResponse()\n }\n const commandBus = container.resolve('commandBus') as CommandBus\n const queryEngine = container.resolve('queryEngine') as QueryEngine\n const body = todoDeleteBodySchema.parse(await readJsonSafe<Record<string, unknown>>(request, {}))\n const guardUserId = resolveGuardUserId(auth)\n const guardResult = await validateCrudMutationGuard(container, {\n tenantId: auth.tenantId,\n organizationId: selectedOrganizationId,\n userId: guardUserId,\n resourceKind: 'customers.todoLink',\n resourceId: body.id,\n operation: 'delete',\n requestMethod: request.method,\n requestHeaders: request.headers,\n mutationPayload: body,\n })\n if (guardResult && !guardResult.ok) {\n return withAdapterHeaders(NextResponse.json(guardResult.body, { status: guardResult.status }))\n }\n const interactionId = flags.unified\n ? body.todoId ?? body.id\n : await resolveCanonicalTodoTargetId(\n em,\n queryEngine,\n commandBus,\n commandContext,\n {\n linkId: body.id,\n todoId: body.todoId ?? body.id,\n },\n auth.tenantId,\n )\n\n await commandBus.execute('customers.interactions.delete', {\n input: { id: interactionId },\n ctx: commandContext,\n })\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(container, {\n tenantId: auth.tenantId,\n organizationId: selectedOrganizationId,\n userId: guardUserId,\n resourceKind: 'customers.todoLink',\n resourceId: body.id,\n operation: 'delete',\n requestMethod: request.method,\n requestHeaders: request.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n return withAdapterHeaders(NextResponse.json({ ok: true }))\n } catch (err) {\n if (isCrudHttpError(err)) {\n return withAdapterHeaders(NextResponse.json(err.body, { status: err.status }))\n }\n if (err instanceof z.ZodError) {\n return withAdapterHeaders(\n NextResponse.json({ error: 'Validation failed', details: err.issues }, { status: 400 }),\n )\n }\n console.error('customers.todos.delete failed', err)\n return withAdapterHeaders(\n NextResponse.json({ error: 'Internal server error' }, { status: 500 }),\n )\n }\n}\n\nconst todoItemSchema = z.object({\n id: z.string(),\n todoId: z.string(),\n todoSource: z.string(),\n todoTitle: z.string().nullable(),\n todoIsDone: z.boolean().nullable(),\n todoPriority: z.number().nullable().optional(),\n todoSeverity: z.string().nullable().optional(),\n todoDescription: z.string().nullable().optional(),\n todoDueAt: z.string().nullable().optional(),\n todoCustomValues: z.record(z.string(), z.unknown()).nullable().optional(),\n todoOrganizationId: z.string().nullable(),\n organizationId: z.string(),\n tenantId: z.string(),\n createdAt: z.string(),\n externalHref: z.string().nullable().optional(),\n _integrations: z.record(z.string(), z.unknown()).optional(),\n customer: z.object({\n id: z.string().nullable(),\n displayName: z.string().nullable(),\n kind: z.string().nullable(),\n }),\n})\n\nconst todoCreateResponseSchema = z.object({\n linkId: z.string().uuid().nullable(),\n todoId: z.string().uuid().nullable(),\n})\n\nexport const openApi: OpenApiRouteDoc = createCustomersCrudOpenApi({\n resourceName: 'CustomerTodo',\n querySchema,\n listResponseSchema: createPagedListResponseSchema(todoItemSchema),\n create: {\n schema: todoCreateBodySchema,\n responseSchema: todoCreateResponseSchema,\n description: 'DEPRECATED (sunset 2026-06-30): Creates a customer task. Use POST /api/customers/interactions instead.',\n },\n update: {\n schema: todoUpdateBodySchema,\n responseSchema: defaultOkResponseSchema,\n description: 'DEPRECATED (sunset 2026-06-30): Updates a customer task. Use PUT /api/customers/interactions instead.',\n },\n del: {\n schema: todoDeleteBodySchema,\n responseSchema: defaultOkResponseSchema,\n description: 'DEPRECATED (sunset 2026-06-30): Deletes a customer task. Use DELETE /api/customers/interactions instead.',\n },\n})\n"],
5
+ "mappings": "AAIA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AA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AAA,EACzB,UAAU,EAAE,OAAO;AAAA,EACnB,WAAW,EAAE,OAAO;AAAA,EACpB,cAAc,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS;AAAA,EAC7C,eAAe,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,EAAE,SAAS;AAAA,EAC1D,UAAU,EAAE,OAAO;AAAA,IACjB,IAAI,EAAE,OAAO,EAAE,SAAS;AAAA,IACxB,aAAa,EAAE,OAAO,EAAE,SAAS;AAAA,IACjC,MAAM,EAAE,OAAO,EAAE,SAAS;AAAA,EAC5B,CAAC;AACH,CAAC;AAED,MAAM,2BAA2B,EAAE,OAAO;AAAA,EACxC,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAAA,EACnC,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AACrC,CAAC;AAEM,MAAM,UAA2B,2BAA2B;AAAA,EACjE,cAAc;AAAA,EACd;AAAA,EACA,oBAAoB,8BAA8B,cAAc;AAAA,EAChE,QAAQ;AAAA,IACN,QAAQ;AAAA,IACR,gBAAgB;AAAA,IAChB,aAAa;AAAA,EACf;AAAA,EACA,QAAQ;AAAA,IACN,QAAQ;AAAA,IACR,gBAAgB;AAAA,IAChB,aAAa;AAAA,EACf;AAAA,EACA,KAAK;AAAA,IACH,QAAQ;AAAA,IACR,gBAAgB;AAAA,IAChB,aAAa;AAAA,EACf;AACF,CAAC;",
6
6
  "names": []
7
7
  }
@@ -3,7 +3,7 @@ import { z } from "zod";
3
3
  import { Dictionary, DictionaryEntry } from "@open-mercato/core/modules/dictionaries/data/entities";
4
4
  import { resolveDictionariesRouteContext } from "@open-mercato/core/modules/dictionaries/api/context";
5
5
  import { updateDictionaryEntrySchema } from "@open-mercato/core/modules/dictionaries/data/validators";
6
- import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
6
+ import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
7
7
  import { serializeOperationMetadata } from "@open-mercato/shared/lib/commands/operationMetadata";
8
8
  import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
9
9
  import {
@@ -111,7 +111,7 @@ async function PATCH(req, ctx) {
111
111
  }
112
112
  return response;
113
113
  } catch (err) {
114
- if (err instanceof CrudHttpError) {
114
+ if (isCrudHttpError(err)) {
115
115
  return NextResponse.json(err.body, { status: err.status });
116
116
  }
117
117
  console.error("[dictionaries/:id/entries/:entryId.PATCH] Unexpected error", err);
@@ -149,7 +149,7 @@ async function DELETE(req, ctx) {
149
149
  }
150
150
  return response;
151
151
  } catch (err) {
152
- if (err instanceof CrudHttpError) {
152
+ if (isCrudHttpError(err)) {
153
153
  return NextResponse.json(err.body, { status: err.status });
154
154
  }
155
155
  console.error("[dictionaries/:id/entries/:entryId.DELETE] Unexpected error", err);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../../src/modules/dictionaries/api/%5BdictionaryId%5D/entries/%5BentryId%5D/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { Dictionary, DictionaryEntry } from '@open-mercato/core/modules/dictionaries/data/entities'\nimport { resolveDictionariesRouteContext } from '@open-mercato/core/modules/dictionaries/api/context'\nimport { updateDictionaryEntrySchema } from '@open-mercato/core/modules/dictionaries/data/validators'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands'\nimport { serializeOperationMetadata } from '@open-mercato/shared/lib/commands/operationMetadata'\nimport type { OpenApiMethodDoc, OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n dictionaryEntryParamsSchema,\n dictionaryEntryResponseSchema,\n dictionariesErrorSchema,\n dictionariesOkSchema,\n dictionariesTag,\n updateDictionaryEntrySchema as updateEntryDocSchema,\n} from '../../../openapi'\nconst paramsSchema = z.object({\n dictionaryId: z.string().uuid(),\n entryId: z.string().uuid(),\n})\n\nasync function loadDictionary(context: Awaited<ReturnType<typeof resolveDictionariesRouteContext>>, id: string) {\n if (!context.organizationId) {\n throw new CrudHttpError(400, { error: context.translate('dictionaries.errors.organization_required', 'Organization context is required') })\n }\n const dictionary = await context.em.findOne(Dictionary, {\n id,\n organizationId: context.organizationId,\n tenantId: context.tenantId,\n deletedAt: null,\n })\n if (!dictionary) {\n throw new CrudHttpError(404, { error: context.translate('dictionaries.errors.not_found', 'Dictionary not found') })\n }\n return dictionary\n}\n\nasync function loadEntry(\n context: Awaited<ReturnType<typeof resolveDictionariesRouteContext>>,\n dictionary: Dictionary,\n entryId: string,\n) {\n const entry = await context.em.findOne(DictionaryEntry, {\n id: entryId,\n dictionary,\n organizationId: dictionary.organizationId,\n tenantId: context.tenantId,\n })\n if (!entry) {\n throw new CrudHttpError(404, { error: context.translate('dictionaries.errors.entry_not_found', 'Dictionary entry not found') })\n }\n return entry\n}\n\nexport const metadata = {\n PATCH: { requireAuth: true, requireFeatures: ['dictionaries.manage'] },\n DELETE: { requireAuth: true, requireFeatures: ['dictionaries.manage'] },\n}\n\nexport async function PATCH(req: Request, ctx: { params?: { dictionaryId?: string; entryId?: string } }) {\n try {\n const context = await resolveDictionariesRouteContext(req)\n if (!context.auth) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n const { dictionaryId, entryId } = paramsSchema.parse({\n dictionaryId: ctx.params?.dictionaryId,\n entryId: ctx.params?.entryId,\n })\n const dictionary = await loadDictionary(context, dictionaryId)\n await loadEntry(context, dictionary, entryId)\n const rawBody = await req.json().catch(() => ({}))\n const payload = updateDictionaryEntrySchema.parse(rawBody)\n // These nested routes don't use the CRUD factory, so invoke the command bus explicitly.\n const commandBus = (context.container.resolve('commandBus') as CommandBus)\n const input = { ...(payload as Record<string, unknown>), id: entryId }\n const { result, logEntry } = await commandBus.execute('dictionaries.entries.update', {\n input,\n ctx: context.ctx,\n })\n const updateResult = (result ?? {}) as { entryId?: string | null }\n const updatedEntryId = typeof updateResult.entryId === 'string' ? updateResult.entryId : null\n if (!updatedEntryId) {\n throw new CrudHttpError(500, { error: context.translate('dictionaries.errors.entry_update_failed', 'Failed to update dictionary entry') })\n }\n const updated = await findOneWithDecryption(\n context.em.fork(),\n DictionaryEntry,\n updatedEntryId,\n { populate: ['dictionary'] },\n { tenantId: context.auth.tenantId ?? null, organizationId: context.auth.orgId ?? null },\n )\n if (!updated) {\n throw new CrudHttpError(500, { error: context.translate('dictionaries.errors.entry_update_failed', 'Failed to update dictionary entry') })\n }\n const response = NextResponse.json({\n id: updated.id,\n value: updated.value,\n label: updated.label,\n color: updated.color,\n icon: updated.icon,\n position: updated.position ?? 0,\n isDefault: updated.isDefault ?? false,\n createdAt: updated.createdAt,\n updatedAt: updated.updatedAt,\n })\n if (logEntry?.undoToken && logEntry?.id && logEntry?.commandId) {\n response.headers.set(\n 'x-om-operation',\n serializeOperationMetadata({\n id: logEntry.id,\n undoToken: logEntry.undoToken,\n commandId: logEntry.commandId,\n actionLabel: logEntry.actionLabel ?? null,\n resourceKind: logEntry.resourceKind ?? 'dictionaries.entry',\n resourceId: updatedEntryId,\n executedAt: logEntry.createdAt instanceof Date ? logEntry.createdAt.toISOString() : undefined,\n })\n )\n }\n return response\n } catch (err) {\n if (err instanceof CrudHttpError) {\n return NextResponse.json(err.body, { status: err.status })\n }\n console.error('[dictionaries/:id/entries/:entryId.PATCH] Unexpected error', err)\n return NextResponse.json({ error: 'Failed to update dictionary entry' }, { status: 500 })\n }\n}\n\nexport async function DELETE(req: Request, ctx: { params?: { dictionaryId?: string; entryId?: string } }) {\n try {\n const context = await resolveDictionariesRouteContext(req)\n const { dictionaryId, entryId } = paramsSchema.parse({\n dictionaryId: ctx.params?.dictionaryId,\n entryId: ctx.params?.entryId,\n })\n const dictionary = await loadDictionary(context, dictionaryId)\n const entry = await loadEntry(context, dictionary, entryId)\n const commandBus = (context.container.resolve('commandBus') as CommandBus)\n const { logEntry } = await commandBus.execute('dictionaries.entries.delete', {\n input: { body: { id: entry.id } },\n ctx: context.ctx,\n })\n const response = NextResponse.json({ ok: true })\n if (logEntry?.undoToken && logEntry?.id && logEntry?.commandId) {\n response.headers.set(\n 'x-om-operation',\n serializeOperationMetadata({\n id: logEntry.id,\n undoToken: logEntry.undoToken,\n commandId: logEntry.commandId,\n actionLabel: logEntry.actionLabel ?? null,\n resourceKind: logEntry.resourceKind ?? 'dictionaries.entry',\n resourceId: entry.id,\n executedAt: logEntry.createdAt instanceof Date ? logEntry.createdAt.toISOString() : undefined,\n })\n )\n }\n return response\n } catch (err) {\n if (err instanceof CrudHttpError) {\n return NextResponse.json(err.body, { status: err.status })\n }\n console.error('[dictionaries/:id/entries/:entryId.DELETE] Unexpected error', err)\n return NextResponse.json({ error: 'Failed to delete dictionary entry' }, { status: 500 })\n }\n}\n\nconst dictionaryEntryPatchDoc: OpenApiMethodDoc = {\n summary: 'Update dictionary entry',\n description: 'Updates the specified dictionary entry using the command bus pipeline.',\n tags: [dictionariesTag],\n requestBody: {\n contentType: 'application/json',\n schema: updateEntryDocSchema,\n description: 'Fields to update on the dictionary entry.',\n },\n responses: [\n { status: 200, description: 'Dictionary entry updated.', schema: dictionaryEntryResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Validation failed', schema: dictionariesErrorSchema },\n { status: 401, description: 'Authentication required', schema: dictionariesErrorSchema },\n { status: 404, description: 'Dictionary or entry not found', schema: dictionariesErrorSchema },\n { status: 500, description: 'Failed to update entry', schema: dictionariesErrorSchema },\n ],\n}\n\nconst dictionaryEntryDeleteDoc: OpenApiMethodDoc = {\n summary: 'Delete dictionary entry',\n description: 'Deletes the specified dictionary entry via the command bus.',\n tags: [dictionariesTag],\n responses: [\n { status: 200, description: 'Entry deleted.', schema: dictionariesOkSchema },\n ],\n errors: [\n { status: 400, description: 'Validation failed', schema: dictionariesErrorSchema },\n { status: 401, description: 'Authentication required', schema: dictionariesErrorSchema },\n { status: 404, description: 'Dictionary or entry not found', schema: dictionariesErrorSchema },\n { status: 500, description: 'Failed to delete entry', schema: dictionariesErrorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: dictionariesTag,\n summary: 'Dictionary entry resource',\n pathParams: dictionaryEntryParamsSchema,\n methods: {\n PATCH: dictionaryEntryPatchDoc,\n DELETE: dictionaryEntryDeleteDoc,\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,YAAY,uBAAuB;AAC5C,SAAS,uCAAuC;AAChD,SAAS,mCAAmC;AAC5C,SAAS,qBAAqB;AAE9B,SAAS,kCAAkC;AAE3C,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,+BAA+B;AAAA,OAC1B;AACP,MAAM,eAAe,EAAE,OAAO;AAAA,EAC5B,cAAc,EAAE,OAAO,EAAE,KAAK;AAAA,EAC9B,SAAS,EAAE,OAAO,EAAE,KAAK;AAC3B,CAAC;AAED,eAAe,eAAe,SAAsE,IAAY;AAC9G,MAAI,CAAC,QAAQ,gBAAgB;AAC3B,UAAM,IAAI,cAAc,KAAK,EAAE,OAAO,QAAQ,UAAU,6CAA6C,kCAAkC,EAAE,CAAC;AAAA,EAC5I;AACA,QAAM,aAAa,MAAM,QAAQ,GAAG,QAAQ,YAAY;AAAA,IACtD;AAAA,IACA,gBAAgB,QAAQ;AAAA,IACxB,UAAU,QAAQ;AAAA,IAClB,WAAW;AAAA,EACb,CAAC;AACD,MAAI,CAAC,YAAY;AACf,UAAM,IAAI,cAAc,KAAK,EAAE,OAAO,QAAQ,UAAU,iCAAiC,sBAAsB,EAAE,CAAC;AAAA,EACpH;AACA,SAAO;AACT;AAEA,eAAe,UACb,SACA,YACA,SACA;AACA,QAAM,QAAQ,MAAM,QAAQ,GAAG,QAAQ,iBAAiB;AAAA,IACtD,IAAI;AAAA,IACJ;AAAA,IACA,gBAAgB,WAAW;AA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AEA,MAAM,0BAA4C;AAAA,EAChD,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,eAAe;AAAA,EACtB,aAAa;AAAA,IACX,aAAa;AAAA,IACb,QAAQ;AAAA,IACR,aAAa;AAAA,EACf;AAAA,EACA,WAAW;AAAA,IACT,EAAE,QAAQ,KAAK,aAAa,6BAA6B,QAAQ,8BAA8B;AAAA,EACjG;AAAA,EACA,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,wBAAwB;AAAA,IACjF,EAAE,QAAQ,KAAK,aAAa,2BAA2B,QAAQ,wBAAwB;AAAA,IACvF,EAAE,QAAQ,KAAK,aAAa,iCAAiC,QAAQ,wBAAwB;AAAA,IAC7F,EAAE,QAAQ,KAAK,aAAa,0BAA0B,QAAQ,wBAAwB;AAAA,EACxF;AACF;AAEA,MAAM,2BAA6C;AAAA,EACjD,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,eAAe;AAAA,EACtB,WAAW;AAAA,IACT,EAAE,QAAQ,KAAK,aAAa,kBAAkB,QAAQ,qBAAqB;AAAA,EAC7E;AAAA,EACA,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,wBAAwB;AAAA,IACjF,EAAE,QAAQ,KAAK,aAAa,2BAA2B,QAAQ,wBAAwB;AAAA,IACvF,EAAE,QAAQ,KAAK,aAAa,iCAAiC,QAAQ,wBAAwB;AAAA,IAC7F,EAAE,QAAQ,KAAK,aAAa,0BAA0B,QAAQ,wBAAwB;AAAA,EACxF;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,SAAS;AAAA,IACP,OAAO;AAAA,IACP,QAAQ;AAAA,EACV;AACF;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { Dictionary, DictionaryEntry } from '@open-mercato/core/modules/dictionaries/data/entities'\nimport { resolveDictionariesRouteContext } from '@open-mercato/core/modules/dictionaries/api/context'\nimport { updateDictionaryEntrySchema } from '@open-mercato/core/modules/dictionaries/data/validators'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands'\nimport { serializeOperationMetadata } from '@open-mercato/shared/lib/commands/operationMetadata'\nimport type { OpenApiMethodDoc, OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n dictionaryEntryParamsSchema,\n dictionaryEntryResponseSchema,\n dictionariesErrorSchema,\n dictionariesOkSchema,\n dictionariesTag,\n updateDictionaryEntrySchema as updateEntryDocSchema,\n} from '../../../openapi'\nconst paramsSchema = z.object({\n dictionaryId: z.string().uuid(),\n entryId: z.string().uuid(),\n})\n\nasync function loadDictionary(context: Awaited<ReturnType<typeof resolveDictionariesRouteContext>>, id: string) {\n if (!context.organizationId) {\n throw new CrudHttpError(400, { error: context.translate('dictionaries.errors.organization_required', 'Organization context is required') })\n }\n const dictionary = await context.em.findOne(Dictionary, {\n id,\n organizationId: context.organizationId,\n tenantId: context.tenantId,\n deletedAt: null,\n })\n if (!dictionary) {\n throw new CrudHttpError(404, { error: context.translate('dictionaries.errors.not_found', 'Dictionary not found') })\n }\n return dictionary\n}\n\nasync function loadEntry(\n context: Awaited<ReturnType<typeof resolveDictionariesRouteContext>>,\n dictionary: Dictionary,\n entryId: string,\n) {\n const entry = await context.em.findOne(DictionaryEntry, {\n id: entryId,\n dictionary,\n organizationId: dictionary.organizationId,\n tenantId: context.tenantId,\n })\n if (!entry) {\n throw new CrudHttpError(404, { error: context.translate('dictionaries.errors.entry_not_found', 'Dictionary entry not found') })\n }\n return entry\n}\n\nexport const metadata = {\n PATCH: { requireAuth: true, requireFeatures: ['dictionaries.manage'] },\n DELETE: { requireAuth: true, requireFeatures: ['dictionaries.manage'] },\n}\n\nexport async function PATCH(req: Request, ctx: { params?: { dictionaryId?: string; entryId?: string } }) {\n try {\n const context = await resolveDictionariesRouteContext(req)\n if (!context.auth) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n const { dictionaryId, entryId } = paramsSchema.parse({\n dictionaryId: ctx.params?.dictionaryId,\n entryId: ctx.params?.entryId,\n })\n const dictionary = await loadDictionary(context, dictionaryId)\n await loadEntry(context, dictionary, entryId)\n const rawBody = await req.json().catch(() => ({}))\n const payload = updateDictionaryEntrySchema.parse(rawBody)\n // These nested routes don't use the CRUD factory, so invoke the command bus explicitly.\n const commandBus = (context.container.resolve('commandBus') as CommandBus)\n const input = { ...(payload as Record<string, unknown>), id: entryId }\n const { result, logEntry } = await commandBus.execute('dictionaries.entries.update', {\n input,\n ctx: context.ctx,\n })\n const updateResult = (result ?? {}) as { entryId?: string | null }\n const updatedEntryId = typeof updateResult.entryId === 'string' ? updateResult.entryId : null\n if (!updatedEntryId) {\n throw new CrudHttpError(500, { error: context.translate('dictionaries.errors.entry_update_failed', 'Failed to update dictionary entry') })\n }\n const updated = await findOneWithDecryption(\n context.em.fork(),\n DictionaryEntry,\n updatedEntryId,\n { populate: ['dictionary'] },\n { tenantId: context.auth.tenantId ?? null, organizationId: context.auth.orgId ?? null },\n )\n if (!updated) {\n throw new CrudHttpError(500, { error: context.translate('dictionaries.errors.entry_update_failed', 'Failed to update dictionary entry') })\n }\n const response = NextResponse.json({\n id: updated.id,\n value: updated.value,\n label: updated.label,\n color: updated.color,\n icon: updated.icon,\n position: updated.position ?? 0,\n isDefault: updated.isDefault ?? false,\n createdAt: updated.createdAt,\n updatedAt: updated.updatedAt,\n })\n if (logEntry?.undoToken && logEntry?.id && logEntry?.commandId) {\n response.headers.set(\n 'x-om-operation',\n serializeOperationMetadata({\n id: logEntry.id,\n undoToken: logEntry.undoToken,\n commandId: logEntry.commandId,\n actionLabel: logEntry.actionLabel ?? null,\n resourceKind: logEntry.resourceKind ?? 'dictionaries.entry',\n resourceId: updatedEntryId,\n executedAt: logEntry.createdAt instanceof Date ? logEntry.createdAt.toISOString() : undefined,\n })\n )\n }\n return response\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n console.error('[dictionaries/:id/entries/:entryId.PATCH] Unexpected error', err)\n return NextResponse.json({ error: 'Failed to update dictionary entry' }, { status: 500 })\n }\n}\n\nexport async function DELETE(req: Request, ctx: { params?: { dictionaryId?: string; entryId?: string } }) {\n try {\n const context = await resolveDictionariesRouteContext(req)\n const { dictionaryId, entryId } = paramsSchema.parse({\n dictionaryId: ctx.params?.dictionaryId,\n entryId: ctx.params?.entryId,\n })\n const dictionary = await loadDictionary(context, dictionaryId)\n const entry = await loadEntry(context, dictionary, entryId)\n const commandBus = (context.container.resolve('commandBus') as CommandBus)\n const { logEntry } = await commandBus.execute('dictionaries.entries.delete', {\n input: { body: { id: entry.id } },\n ctx: context.ctx,\n })\n const response = NextResponse.json({ ok: true })\n if (logEntry?.undoToken && logEntry?.id && logEntry?.commandId) {\n response.headers.set(\n 'x-om-operation',\n serializeOperationMetadata({\n id: logEntry.id,\n undoToken: logEntry.undoToken,\n commandId: logEntry.commandId,\n actionLabel: logEntry.actionLabel ?? null,\n resourceKind: logEntry.resourceKind ?? 'dictionaries.entry',\n resourceId: entry.id,\n executedAt: logEntry.createdAt instanceof Date ? logEntry.createdAt.toISOString() : undefined,\n })\n )\n }\n return response\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n console.error('[dictionaries/:id/entries/:entryId.DELETE] Unexpected error', err)\n return NextResponse.json({ error: 'Failed to delete dictionary entry' }, { status: 500 })\n }\n}\n\nconst dictionaryEntryPatchDoc: OpenApiMethodDoc = {\n summary: 'Update dictionary entry',\n description: 'Updates the specified dictionary entry using the command bus pipeline.',\n tags: [dictionariesTag],\n requestBody: {\n contentType: 'application/json',\n schema: updateEntryDocSchema,\n description: 'Fields to update on the dictionary entry.',\n },\n responses: [\n { status: 200, description: 'Dictionary entry updated.', schema: dictionaryEntryResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Validation failed', schema: dictionariesErrorSchema },\n { status: 401, description: 'Authentication required', schema: dictionariesErrorSchema },\n { status: 404, description: 'Dictionary or entry not found', schema: dictionariesErrorSchema },\n { status: 500, description: 'Failed to update entry', schema: dictionariesErrorSchema },\n ],\n}\n\nconst dictionaryEntryDeleteDoc: OpenApiMethodDoc = {\n summary: 'Delete dictionary entry',\n description: 'Deletes the specified dictionary entry via the command bus.',\n tags: [dictionariesTag],\n responses: [\n { status: 200, description: 'Entry deleted.', schema: dictionariesOkSchema },\n ],\n errors: [\n { status: 400, description: 'Validation failed', schema: dictionariesErrorSchema },\n { status: 401, description: 'Authentication required', schema: dictionariesErrorSchema },\n { status: 404, description: 'Dictionary or entry not found', schema: dictionariesErrorSchema },\n { status: 500, description: 'Failed to delete entry', schema: dictionariesErrorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: dictionariesTag,\n summary: 'Dictionary entry resource',\n pathParams: dictionaryEntryParamsSchema,\n methods: {\n PATCH: dictionaryEntryPatchDoc,\n DELETE: dictionaryEntryDeleteDoc,\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,YAAY,uBAAuB;AAC5C,SAAS,uCAAuC;AAChD,SAAS,mCAAmC;AAC5C,SAAS,eAAe,uBAAuB;AAE/C,SAAS,kCAAkC;AAE3C,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,+BAA+B;AAAA,OAC1B;AACP,MAAM,eAAe,EAAE,OAAO;AAAA,EAC5B,cAAc,EAAE,OAAO,EAAE,KAAK;AAAA,EAC9B,SAAS,EAAE,OAAO,EAAE,KAAK;AAC3B,CAAC;AAED,eAAe,eAAe,SAAsE,IAAY;AAC9G,MAAI,CAAC,QAAQ,gBAAgB;A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;AAAA,EAC7E;AAAA,EACA,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,wBAAwB;AAAA,IACjF,EAAE,QAAQ,KAAK,aAAa,2BAA2B,QAAQ,wBAAwB;AAAA,IACvF,EAAE,QAAQ,KAAK,aAAa,iCAAiC,QAAQ,wBAAwB;AAAA,IAC7F,EAAE,QAAQ,KAAK,aAAa,0BAA0B,QAAQ,wBAAwB;AAAA,EACxF;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,SAAS;AAAA,IACP,OAAO;AAAA,IACP,QAAQ;AAAA,EACV;AACF;",
6
6
  "names": []
7
7
  }
@@ -6,7 +6,7 @@ import {
6
6
  reorderDictionaryEntriesCommandSchema,
7
7
  reorderDictionaryEntriesSchema
8
8
  } from "@open-mercato/core/modules/dictionaries/data/validators";
9
- import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
9
+ import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
10
10
  import { serializeOperationMetadata } from "@open-mercato/shared/lib/commands/operationMetadata";
11
11
  import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
12
12
  import { readJsonSafe } from "@open-mercato/shared/lib/http/readJsonSafe";
@@ -112,7 +112,7 @@ async function POST(req, ctx) {
112
112
  }
113
113
  return response;
114
114
  } catch (err) {
115
- if (err instanceof CrudHttpError) {
115
+ if (isCrudHttpError(err)) {
116
116
  return NextResponse.json(err.body, { status: err.status });
117
117
  }
118
118
  console.error("[dictionaries/:id/entries/reorder.POST] Unexpected error", err);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../../src/modules/dictionaries/api/%5BdictionaryId%5D/entries/reorder/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { Dictionary } from '@open-mercato/core/modules/dictionaries/data/entities'\nimport { resolveDictionariesRouteContext } from '@open-mercato/core/modules/dictionaries/api/context'\nimport {\n reorderDictionaryEntriesCommandSchema,\n reorderDictionaryEntriesSchema,\n type ReorderDictionaryEntriesCommandInput,\n} from '@open-mercato/core/modules/dictionaries/data/validators'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands'\nimport type { OpenApiMethodDoc, OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { serializeOperationMetadata } from '@open-mercato/shared/lib/commands/operationMetadata'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport {\n dictionaryIdParamsSchema,\n dictionariesErrorSchema,\n dictionariesOkSchema,\n dictionariesTag,\n reorderEntriesRequestSchema,\n} from '../../../openapi'\nimport { resolveDictionaryActorId } from '../../../context'\n\nconst paramsSchema = z.object({ dictionaryId: z.string().uuid() })\n\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: ['dictionaries.manage'] },\n}\n\nexport async function POST(req: Request, ctx: { params?: { dictionaryId?: string } }) {\n try {\n const context = await resolveDictionariesRouteContext(req)\n if (!context.auth) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n const { dictionaryId } = paramsSchema.parse({ dictionaryId: ctx.params?.dictionaryId })\n\n if (!context.organizationId) {\n throw new CrudHttpError(400, { error: context.translate('dictionaries.errors.organization_required', 'Organization context is required') })\n }\n const dictionaryEm = context.em.fork()\n const dictionary = await findOneWithDecryption(\n dictionaryEm,\n Dictionary,\n {\n id: dictionaryId,\n organizationId: context.organizationId,\n tenantId: context.tenantId,\n deletedAt: null,\n },\n undefined,\n { tenantId: context.tenantId, organizationId: context.organizationId },\n )\n if (!dictionary) {\n throw new CrudHttpError(404, { error: context.translate('dictionaries.errors.not_found', 'Dictionary not found') })\n }\n\n const payload = reorderDictionaryEntriesSchema.parse(await readJsonSafe(req, {}))\n const guardUserId = resolveDictionaryActorId(context.auth)\n const guardResult = await validateCrudMutationGuard(context.container, {\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n userId: guardUserId,\n resourceKind: 'dictionaries.dictionary',\n resourceId: dictionaryId,\n operation: 'custom',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: payload,\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n\n const commandInput = reorderDictionaryEntriesCommandSchema.parse({\n dictionaryId,\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n entries: payload.entries,\n } satisfies ReorderDictionaryEntriesCommandInput)\n\n const commandBus = context.container.resolve('commandBus') as CommandBus\n const { logEntry } = await commandBus.execute<ReorderDictionaryEntriesCommandInput, { dictionaryId: string; updatedIds: string[] }>(\n 'dictionaries.entries.reorder',\n {\n input: commandInput,\n ctx: context.ctx,\n },\n )\n\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(context.container, {\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n userId: guardUserId,\n resourceKind: 'dictionaries.dictionary',\n resourceId: dictionaryId,\n operation: 'custom',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n const response = NextResponse.json({ ok: true })\n if (logEntry?.undoToken && logEntry.id && logEntry.commandId) {\n response.headers.set(\n 'x-om-operation',\n serializeOperationMetadata({\n id: logEntry.id,\n undoToken: logEntry.undoToken,\n commandId: logEntry.commandId,\n actionLabel: logEntry.actionLabel ?? null,\n resourceKind: logEntry.resourceKind ?? 'dictionaries.dictionary',\n resourceId: logEntry.resourceId ?? dictionaryId,\n executedAt: logEntry.createdAt instanceof Date ? logEntry.createdAt.toISOString() : new Date().toISOString(),\n }),\n )\n }\n return response\n } catch (err) {\n if (err instanceof CrudHttpError) {\n return NextResponse.json(err.body, { status: err.status })\n }\n console.error('[dictionaries/:id/entries/reorder.POST] Unexpected error', err)\n return NextResponse.json({ error: 'Failed to reorder dictionary entries' }, { status: 500 })\n }\n}\n\nconst reorderPostDoc: OpenApiMethodDoc = {\n summary: 'Reorder dictionary entries',\n description: 'Updates the position of dictionary entries for drag-and-drop reordering.',\n tags: [dictionariesTag],\n requestBody: {\n contentType: 'application/json',\n schema: reorderEntriesRequestSchema,\n description: 'Array of entry IDs with their new positions.',\n },\n responses: [\n { status: 200, description: 'Entries reordered.', schema: dictionariesOkSchema },\n ],\n errors: [\n { status: 400, description: 'Validation failed', schema: dictionariesErrorSchema },\n { status: 401, description: 'Authentication required', schema: dictionariesErrorSchema },\n { status: 404, description: 'Dictionary not found', schema: dictionariesErrorSchema },\n { status: 500, description: 'Failed to reorder entries', schema: dictionariesErrorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: dictionariesTag,\n summary: 'Reorder dictionary entries',\n pathParams: dictionaryIdParamsSchema,\n methods: {\n POST: reorderPostDoc,\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,kBAAkB;AAC3B,SAAS,uCAAuC;AAChD;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,qBAAqB;AAG9B,SAAS,kCAAkC;AAC3C,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gCAAgC;AAEzC,MAAM,eAAe,EAAE,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAE1D,MAAM,WAAW;AAAA,EACtB,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,qBAAqB,EAAE;AACtE;AAEA,eAAsB,KAAK,KAAc,KAA6C;A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,MAAM,4DAA4D,GAAG;AAC7E,WAAO,aAAa,KAAK,EAAE,OAAO,uCAAuC,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC7F;AACF;AAEA,MAAM,iBAAmC;AAAA,EACvC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,eAAe;AAAA,EACtB,aAAa;AAAA,IACX,aAAa;AAAA,IACb,QAAQ;AAAA,IACR,aAAa;AAAA,EACf;AAAA,EACA,WAAW;AAAA,IACT,EAAE,QAAQ,KAAK,aAAa,sBAAsB,QAAQ,qBAAqB;AAAA,EACjF;AAAA,EACA,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,wBAAwB;AAAA,IACjF,EAAE,QAAQ,KAAK,aAAa,2BAA2B,QAAQ,wBAAwB;AAAA,IACvF,EAAE,QAAQ,KAAK,aAAa,wBAAwB,QAAQ,wBAAwB;AAAA,IACpF,EAAE,QAAQ,KAAK,aAAa,6BAA6B,QAAQ,wBAAwB;AAAA,EAC3F;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,SAAS;AAAA,IACP,MAAM;AAAA,EACR;AACF;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { Dictionary } from '@open-mercato/core/modules/dictionaries/data/entities'\nimport { resolveDictionariesRouteContext } from '@open-mercato/core/modules/dictionaries/api/context'\nimport {\n reorderDictionaryEntriesCommandSchema,\n reorderDictionaryEntriesSchema,\n type ReorderDictionaryEntriesCommandInput,\n} from '@open-mercato/core/modules/dictionaries/data/validators'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands'\nimport type { OpenApiMethodDoc, OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { serializeOperationMetadata } from '@open-mercato/shared/lib/commands/operationMetadata'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport {\n dictionaryIdParamsSchema,\n dictionariesErrorSchema,\n dictionariesOkSchema,\n dictionariesTag,\n reorderEntriesRequestSchema,\n} from '../../../openapi'\nimport { resolveDictionaryActorId } from '../../../context'\n\nconst paramsSchema = z.object({ dictionaryId: z.string().uuid() })\n\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: ['dictionaries.manage'] },\n}\n\nexport async function POST(req: Request, ctx: { params?: { dictionaryId?: string } }) {\n try {\n const context = await resolveDictionariesRouteContext(req)\n if (!context.auth) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n const { dictionaryId } = paramsSchema.parse({ dictionaryId: ctx.params?.dictionaryId })\n\n if (!context.organizationId) {\n throw new CrudHttpError(400, { error: context.translate('dictionaries.errors.organization_required', 'Organization context is required') })\n }\n const dictionaryEm = context.em.fork()\n const dictionary = await findOneWithDecryption(\n dictionaryEm,\n Dictionary,\n {\n id: dictionaryId,\n organizationId: context.organizationId,\n tenantId: context.tenantId,\n deletedAt: null,\n },\n undefined,\n { tenantId: context.tenantId, organizationId: context.organizationId },\n )\n if (!dictionary) {\n throw new CrudHttpError(404, { error: context.translate('dictionaries.errors.not_found', 'Dictionary not found') })\n }\n\n const payload = reorderDictionaryEntriesSchema.parse(await readJsonSafe(req, {}))\n const guardUserId = resolveDictionaryActorId(context.auth)\n const guardResult = await validateCrudMutationGuard(context.container, {\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n userId: guardUserId,\n resourceKind: 'dictionaries.dictionary',\n resourceId: dictionaryId,\n operation: 'custom',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: payload,\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n\n const commandInput = reorderDictionaryEntriesCommandSchema.parse({\n dictionaryId,\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n entries: payload.entries,\n } satisfies ReorderDictionaryEntriesCommandInput)\n\n const commandBus = context.container.resolve('commandBus') as CommandBus\n const { logEntry } = await commandBus.execute<ReorderDictionaryEntriesCommandInput, { dictionaryId: string; updatedIds: string[] }>(\n 'dictionaries.entries.reorder',\n {\n input: commandInput,\n ctx: context.ctx,\n },\n )\n\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(context.container, {\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n userId: guardUserId,\n resourceKind: 'dictionaries.dictionary',\n resourceId: dictionaryId,\n operation: 'custom',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n const response = NextResponse.json({ ok: true })\n if (logEntry?.undoToken && logEntry.id && logEntry.commandId) {\n response.headers.set(\n 'x-om-operation',\n serializeOperationMetadata({\n id: logEntry.id,\n undoToken: logEntry.undoToken,\n commandId: logEntry.commandId,\n actionLabel: logEntry.actionLabel ?? null,\n resourceKind: logEntry.resourceKind ?? 'dictionaries.dictionary',\n resourceId: logEntry.resourceId ?? dictionaryId,\n executedAt: logEntry.createdAt instanceof Date ? logEntry.createdAt.toISOString() : new Date().toISOString(),\n }),\n )\n }\n return response\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n console.error('[dictionaries/:id/entries/reorder.POST] Unexpected error', err)\n return NextResponse.json({ error: 'Failed to reorder dictionary entries' }, { status: 500 })\n }\n}\n\nconst reorderPostDoc: OpenApiMethodDoc = {\n summary: 'Reorder dictionary entries',\n description: 'Updates the position of dictionary entries for drag-and-drop reordering.',\n tags: [dictionariesTag],\n requestBody: {\n contentType: 'application/json',\n schema: reorderEntriesRequestSchema,\n description: 'Array of entry IDs with their new positions.',\n },\n responses: [\n { status: 200, description: 'Entries reordered.', schema: dictionariesOkSchema },\n ],\n errors: [\n { status: 400, description: 'Validation failed', schema: dictionariesErrorSchema },\n { status: 401, description: 'Authentication required', schema: dictionariesErrorSchema },\n { status: 404, description: 'Dictionary not found', schema: dictionariesErrorSchema },\n { status: 500, description: 'Failed to reorder entries', schema: dictionariesErrorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: dictionariesTag,\n summary: 'Reorder dictionary entries',\n pathParams: dictionaryIdParamsSchema,\n methods: {\n POST: reorderPostDoc,\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,kBAAkB;AAC3B,SAAS,uCAAuC;AAChD;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,eAAe,uBAAuB;AAG/C,SAAS,kCAAkC;AAC3C,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gCAAgC;AAEzC,MAAM,eAAe,EAAE,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAE1D,MAAM,WAAW;AAAA,EACtB,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,qBAAqB,EAAE;AACtE;AAEA,eAAsB,KAAK,KAAc,KAA6C;AACpF,MAAI;AACF,UAAM,UAAU,MAAM,gCAAgC,GAAG;AACzD,QAAI,CAAC,QAAQ,MAAM;AACjB,aAAO,aAAa,KAAK,EAAE,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IACrE;AACA,UAAM,EAAE,aAAa,IAAI,aAAa,MAAM,EAAE,cAAc,IAAI,QAAQ,aAAa,CAAC;AAEtF,QAAI,CAAC,QAAQ,gBAAgB;AAC3B,YAAM,IAAI,cAAc,KAAK,EAAE,OAAO,QAAQ,UAAU,6CAA6C,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sBAAsB,QAAQ,qBAAqB;AAAA,EACjF;AAAA,EACA,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,wBAAwB;AAAA,IACjF,EAAE,QAAQ,KAAK,aAAa,2BAA2B,QAAQ,wBAAwB;AAAA,IACvF,EAAE,QAAQ,KAAK,aAAa,wBAAwB,QAAQ,wBAAwB;AAAA,IACpF,EAAE,QAAQ,KAAK,aAAa,6BAA6B,QAAQ,wBAAwB;AAAA,EAC3F;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,SAAS;AAAA,IACP,MAAM;AAAA,EACR;AACF;",
6
6
  "names": []
7
7
  }
@@ -3,7 +3,7 @@ import { z } from "zod";
3
3
  import { Dictionary, DictionaryEntry } from "@open-mercato/core/modules/dictionaries/data/entities";
4
4
  import { resolveDictionariesRouteContext } from "@open-mercato/core/modules/dictionaries/api/context";
5
5
  import { createDictionaryEntrySchema } from "@open-mercato/core/modules/dictionaries/data/validators";
6
- import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
6
+ import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
7
7
  import { serializeOperationMetadata } from "@open-mercato/shared/lib/commands/operationMetadata";
8
8
  import {
9
9
  createDictionaryEntrySchema as createEntryDocSchema,
@@ -73,7 +73,7 @@ async function GET(req, ctx) {
73
73
  }))
74
74
  });
75
75
  } catch (err) {
76
- if (err instanceof CrudHttpError) {
76
+ if (isCrudHttpError(err)) {
77
77
  return NextResponse.json(err.body, { status: err.status });
78
78
  }
79
79
  console.error("[dictionaries/:id/entries.GET] Unexpected error", err);
@@ -135,7 +135,7 @@ async function POST(req, ctx) {
135
135
  }
136
136
  return response;
137
137
  } catch (err) {
138
- if (err instanceof CrudHttpError) {
138
+ if (isCrudHttpError(err)) {
139
139
  return NextResponse.json(err.body, { status: err.status });
140
140
  }
141
141
  console.error("[dictionaries/:id/entries.POST] Unexpected error", err);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/modules/dictionaries/api/%5BdictionaryId%5D/entries/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { Dictionary, DictionaryEntry } from '@open-mercato/core/modules/dictionaries/data/entities'\nimport { resolveDictionariesRouteContext } from '@open-mercato/core/modules/dictionaries/api/context'\nimport { createDictionaryEntrySchema } from '@open-mercato/core/modules/dictionaries/data/validators'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands'\nimport { serializeOperationMetadata } from '@open-mercato/shared/lib/commands/operationMetadata'\nimport type { OpenApiMethodDoc, OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport {\n createDictionaryEntrySchema as createEntryDocSchema,\n dictionaryEntryListResponseSchema,\n dictionaryEntryResponseSchema,\n dictionaryIdParamsSchema,\n dictionariesErrorSchema,\n dictionariesTag,\n} from '../../openapi'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\nconst paramsSchema = z.object({ dictionaryId: z.string().uuid() })\n\nasync function loadDictionary(\n context: Awaited<ReturnType<typeof resolveDictionariesRouteContext>>,\n id: string,\n options: { allowInherited?: boolean } = {},\n) {\n const { allowInherited = false } = options\n if (!allowInherited && !context.organizationId) {\n throw new CrudHttpError(400, { error: context.translate('dictionaries.errors.organization_required', 'Organization context is required') })\n }\n const baseFilter = {\n id,\n tenantId: context.tenantId,\n deletedAt: null,\n }\n const filter = allowInherited\n ? {\n ...baseFilter,\n ...(context.readableOrganizationIds.length\n ? { organizationId: { $in: context.readableOrganizationIds } }\n : {}),\n }\n : {\n ...baseFilter,\n organizationId: context.organizationId,\n }\n const dictionary = await context.em.findOne(Dictionary, filter)\n if (!dictionary) {\n throw new CrudHttpError(404, { error: context.translate('dictionaries.errors.not_found', 'Dictionary not found') })\n }\n return dictionary\n}\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['dictionaries.view'] },\n POST: { requireAuth: true, requireFeatures: ['dictionaries.manage'] },\n}\n\nexport async function GET(req: Request, ctx: { params?: { dictionaryId?: string } }) {\n try {\n const context = await resolveDictionariesRouteContext(req)\n if (!context.auth) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n const { dictionaryId } = paramsSchema.parse({ dictionaryId: ctx.params?.dictionaryId })\n const dictionary = await loadDictionary(context, dictionaryId, { allowInherited: true })\n const entries = await context.em.find(\n DictionaryEntry,\n {\n dictionary,\n organizationId: dictionary.organizationId,\n tenantId: dictionary.tenantId,\n },\n { orderBy: { position: 'asc', label: 'asc' } },\n )\n\n return NextResponse.json({\n items: entries.map((entry) => ({\n id: entry.id,\n value: entry.value,\n label: entry.label,\n color: entry.color,\n icon: entry.icon,\n position: entry.position ?? 0,\n isDefault: entry.isDefault ?? false,\n createdAt: entry.createdAt,\n updatedAt: entry.updatedAt,\n })),\n })\n } catch (err) {\n if (err instanceof CrudHttpError) {\n return NextResponse.json(err.body, { status: err.status })\n }\n console.error('[dictionaries/:id/entries.GET] Unexpected error', err)\n return NextResponse.json({ error: 'Failed to load dictionary entries' }, { status: 500 })\n }\n}\n\nexport async function POST(req: Request, ctx: { params?: { dictionaryId?: string } }) {\n try {\n const context = await resolveDictionariesRouteContext(req)\n if (!context.auth) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n const { dictionaryId } = paramsSchema.parse({ dictionaryId: ctx.params?.dictionaryId })\n const payload = createDictionaryEntrySchema.parse(await req.json().catch(() => ({})))\n // These nested routes do not use makeCrudRoute, so we invoke the command bus directly.\n const commandBus = (context.container.resolve('commandBus') as CommandBus)\n const { result, logEntry } = await commandBus.execute('dictionaries.entries.create', {\n input: { ...payload, dictionaryId },\n ctx: context.ctx,\n })\n const createResult = (result ?? {}) as { entryId?: string | null }\n const createdEntryId = typeof createResult.entryId === 'string' ? createResult.entryId : null\n if (!createdEntryId) {\n throw new CrudHttpError(500, { error: context.translate('dictionaries.errors.entry_create_failed', 'Failed to create dictionary entry') })\n }\n const entry = await findOneWithDecryption(\n context.em.fork(),\n DictionaryEntry,\n createdEntryId,\n { populate: ['dictionary'] },\n { tenantId: context.auth.tenantId ?? null, organizationId: context.auth.orgId ?? null },\n )\n if (!entry) {\n throw new CrudHttpError(500, { error: context.translate('dictionaries.errors.entry_create_failed', 'Failed to create dictionary entry') })\n }\n const response = NextResponse.json({\n id: entry.id,\n value: entry.value,\n label: entry.label,\n color: entry.color,\n icon: entry.icon,\n position: entry.position ?? 0,\n isDefault: entry.isDefault ?? false,\n createdAt: entry.createdAt,\n updatedAt: entry.updatedAt,\n }, { status: 201 })\n if (logEntry?.undoToken && logEntry?.id && logEntry?.commandId) {\n response.headers.set(\n 'x-om-operation',\n serializeOperationMetadata({\n id: logEntry.id,\n undoToken: logEntry.undoToken,\n commandId: logEntry.commandId,\n actionLabel: logEntry.actionLabel ?? null,\n resourceKind: logEntry.resourceKind ?? 'dictionaries.entry',\n resourceId: createdEntryId,\n executedAt: logEntry.createdAt instanceof Date ? logEntry.createdAt.toISOString() : undefined,\n })\n )\n }\n return response\n } catch (err) {\n if (err instanceof CrudHttpError) {\n return NextResponse.json(err.body, { status: err.status })\n }\n console.error('[dictionaries/:id/entries.POST] Unexpected error', err)\n return NextResponse.json({ error: 'Failed to create dictionary entry' }, { status: 500 })\n }\n}\n\nconst dictionaryEntriesGetDoc: OpenApiMethodDoc = {\n summary: 'List dictionary entries',\n description: 'Returns entries for the specified dictionary ordered by position.',\n tags: [dictionariesTag],\n responses: [\n { status: 200, description: 'Dictionary entries.', schema: dictionaryEntryListResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Invalid parameters', schema: dictionariesErrorSchema },\n { status: 401, description: 'Authentication required', schema: dictionariesErrorSchema },\n { status: 404, description: 'Dictionary not found', schema: dictionariesErrorSchema },\n { status: 500, description: 'Failed to load dictionary entries', schema: dictionariesErrorSchema },\n ],\n}\n\nconst dictionaryEntriesPostDoc: OpenApiMethodDoc = {\n summary: 'Create dictionary entry',\n description: 'Creates a new entry in the specified dictionary.',\n tags: [dictionariesTag],\n requestBody: {\n contentType: 'application/json',\n schema: createEntryDocSchema,\n description: 'Entry value, label, and optional presentation metadata.',\n },\n responses: [\n { status: 201, description: 'Dictionary entry created.', schema: dictionaryEntryResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Validation failed', schema: dictionariesErrorSchema },\n { status: 401, description: 'Authentication required', schema: dictionariesErrorSchema },\n { status: 404, description: 'Dictionary not found', schema: dictionariesErrorSchema },\n { status: 500, description: 'Failed to create dictionary entry', schema: dictionariesErrorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: dictionariesTag,\n summary: 'Dictionary entries collection',\n pathParams: dictionaryIdParamsSchema,\n methods: {\n GET: dictionaryEntriesGetDoc,\n POST: dictionaryEntriesPostDoc,\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,YAAY,uBAAuB;AAC5C,SAAS,uCAAuC;AAChD,SAAS,mCAAmC;AAC5C,SAAS,qBAAqB;AAE9B,SAAS,kCAAkC;AAE3C;AAAA,EACE,+BAA+B;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,6BAA6B;AAEtC,MAAM,eAAe,EAAE,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAEjE,eAAe,eACb,SACA,IACA,UAAwC,CAAC,GACzC;AACA,QAAM,EAAE,iBAAiB,MAAM,IAAI;AACnC,MAAI,CAAC,kBAAkB,CAAC,QAAQ,gBAAgB;AAC9C,UAAM,IAAI,cAAc,KAAK,EAAE,OAAO,QAAQ,UAAU,6CAA6C,kCAAkC,EAAE,CAAC;AAAA,EAC5I;AACA,QAAM,aAAa;AAAA,IACjB;AAAA,IACA,UAAU,QAAQ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port { Dictionary, DictionaryEntry } from '@open-mercato/core/modules/dictionaries/data/entities'\nimport { resolveDictionariesRouteContext } from '@open-mercato/core/modules/dictionaries/api/context'\nimport { createDictionaryEntrySchema } from '@open-mercato/core/modules/dictionaries/data/validators'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands'\nimport { serializeOperationMetadata } from '@open-mercato/shared/lib/commands/operationMetadata'\nimport type { OpenApiMethodDoc, OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport {\n createDictionaryEntrySchema as createEntryDocSchema,\n dictionaryEntryListResponseSchema,\n dictionaryEntryResponseSchema,\n dictionaryIdParamsSchema,\n dictionariesErrorSchema,\n dictionariesTag,\n} from '../../openapi'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\nconst paramsSchema = z.object({ dictionaryId: z.string().uuid() })\n\nasync function loadDictionary(\n context: Awaited<ReturnType<typeof resolveDictionariesRouteContext>>,\n id: string,\n options: { allowInherited?: boolean } = {},\n) {\n const { allowInherited = false } = options\n if (!allowInherited && !context.organizationId) {\n throw new CrudHttpError(400, { error: context.translate('dictionaries.errors.organization_required', 'Organization context is required') })\n }\n const baseFilter = {\n id,\n tenantId: context.tenantId,\n deletedAt: null,\n }\n const filter = allowInherited\n ? {\n ...baseFilter,\n ...(context.readableOrganizationIds.length\n ? { organizationId: { $in: context.readableOrganizationIds } }\n : {}),\n }\n : {\n ...baseFilter,\n organizationId: context.organizationId,\n }\n const dictionary = await context.em.findOne(Dictionary, filter)\n if (!dictionary) {\n throw new CrudHttpError(404, { error: context.translate('dictionaries.errors.not_found', 'Dictionary not found') })\n }\n return dictionary\n}\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['dictionaries.view'] },\n POST: { requireAuth: true, requireFeatures: ['dictionaries.manage'] },\n}\n\nexport async function GET(req: Request, ctx: { params?: { dictionaryId?: string } }) {\n try {\n const context = await resolveDictionariesRouteContext(req)\n if (!context.auth) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n const { dictionaryId } = paramsSchema.parse({ dictionaryId: ctx.params?.dictionaryId })\n const dictionary = await loadDictionary(context, dictionaryId, { allowInherited: true })\n const entries = await context.em.find(\n DictionaryEntry,\n {\n dictionary,\n organizationId: dictionary.organizationId,\n tenantId: dictionary.tenantId,\n },\n { orderBy: { position: 'asc', label: 'asc' } },\n )\n\n return NextResponse.json({\n items: entries.map((entry) => ({\n id: entry.id,\n value: entry.value,\n label: entry.label,\n color: entry.color,\n icon: entry.icon,\n position: entry.position ?? 0,\n isDefault: entry.isDefault ?? false,\n createdAt: entry.createdAt,\n updatedAt: entry.updatedAt,\n })),\n })\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n console.error('[dictionaries/:id/entries.GET] Unexpected error', err)\n return NextResponse.json({ error: 'Failed to load dictionary entries' }, { status: 500 })\n }\n}\n\nexport async function POST(req: Request, ctx: { params?: { dictionaryId?: string } }) {\n try {\n const context = await resolveDictionariesRouteContext(req)\n if (!context.auth) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n const { dictionaryId } = paramsSchema.parse({ dictionaryId: ctx.params?.dictionaryId })\n const payload = createDictionaryEntrySchema.parse(await req.json().catch(() => ({})))\n // These nested routes do not use makeCrudRoute, so we invoke the command bus directly.\n const commandBus = (context.container.resolve('commandBus') as CommandBus)\n const { result, logEntry } = await commandBus.execute('dictionaries.entries.create', {\n input: { ...payload, dictionaryId },\n ctx: context.ctx,\n })\n const createResult = (result ?? {}) as { entryId?: string | null }\n const createdEntryId = typeof createResult.entryId === 'string' ? createResult.entryId : null\n if (!createdEntryId) {\n throw new CrudHttpError(500, { error: context.translate('dictionaries.errors.entry_create_failed', 'Failed to create dictionary entry') })\n }\n const entry = await findOneWithDecryption(\n context.em.fork(),\n DictionaryEntry,\n createdEntryId,\n { populate: ['dictionary'] },\n { tenantId: context.auth.tenantId ?? null, organizationId: context.auth.orgId ?? null },\n )\n if (!entry) {\n throw new CrudHttpError(500, { error: context.translate('dictionaries.errors.entry_create_failed', 'Failed to create dictionary entry') })\n }\n const response = NextResponse.json({\n id: entry.id,\n value: entry.value,\n label: entry.label,\n color: entry.color,\n icon: entry.icon,\n position: entry.position ?? 0,\n isDefault: entry.isDefault ?? false,\n createdAt: entry.createdAt,\n updatedAt: entry.updatedAt,\n }, { status: 201 })\n if (logEntry?.undoToken && logEntry?.id && logEntry?.commandId) {\n response.headers.set(\n 'x-om-operation',\n serializeOperationMetadata({\n id: logEntry.id,\n undoToken: logEntry.undoToken,\n commandId: logEntry.commandId,\n actionLabel: logEntry.actionLabel ?? null,\n resourceKind: logEntry.resourceKind ?? 'dictionaries.entry',\n resourceId: createdEntryId,\n executedAt: logEntry.createdAt instanceof Date ? logEntry.createdAt.toISOString() : undefined,\n })\n )\n }\n return response\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n console.error('[dictionaries/:id/entries.POST] Unexpected error', err)\n return NextResponse.json({ error: 'Failed to create dictionary entry' }, { status: 500 })\n }\n}\n\nconst dictionaryEntriesGetDoc: OpenApiMethodDoc = {\n summary: 'List dictionary entries',\n description: 'Returns entries for the specified dictionary ordered by position.',\n tags: [dictionariesTag],\n responses: [\n { status: 200, description: 'Dictionary entries.', schema: dictionaryEntryListResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Invalid parameters', schema: dictionariesErrorSchema },\n { status: 401, description: 'Authentication required', schema: dictionariesErrorSchema },\n { status: 404, description: 'Dictionary not found', schema: dictionariesErrorSchema },\n { status: 500, description: 'Failed to load dictionary entries', schema: dictionariesErrorSchema },\n ],\n}\n\nconst dictionaryEntriesPostDoc: OpenApiMethodDoc = {\n summary: 'Create dictionary entry',\n description: 'Creates a new entry in the specified dictionary.',\n tags: [dictionariesTag],\n requestBody: {\n contentType: 'application/json',\n schema: createEntryDocSchema,\n description: 'Entry value, label, and optional presentation metadata.',\n },\n responses: [\n { status: 201, description: 'Dictionary entry created.', schema: dictionaryEntryResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Validation failed', schema: dictionariesErrorSchema },\n { status: 401, description: 'Authentication required', schema: dictionariesErrorSchema },\n { status: 404, description: 'Dictionary not found', schema: dictionariesErrorSchema },\n { status: 500, description: 'Failed to create dictionary entry', schema: dictionariesErrorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: dictionariesTag,\n summary: 'Dictionary entries collection',\n pathParams: dictionaryIdParamsSchema,\n methods: {\n GET: dictionaryEntriesGetDoc,\n POST: dictionaryEntriesPostDoc,\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,YAAY,uBAAuB;AAC5C,SAAS,uCAAuC;AAChD,SAAS,mCAAmC;AAC5C,SAAS,eAAe,uBAAuB;AAE/C,SAAS,kCAAkC;AAE3C;AAAA,EACE,+BAA+B;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,6BAA6B;AAEtC,MAAM,eAAe,EAAE,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAEjE,eAAe,eACb,SACA,IACA,UAAwC,CAAC,GACzC;AACA,QAAM,EAAE,iBAAiB,MAAM,IAAI;AACnC,MAAI,CAAC,kBAAkB,CAAC,QAAQ,gBAAgB;AAC9C,UAAM,IAAI,cAAc,KAAK,EAAE,OAAO,QAAQ,UAAU,6CAA6C,kCAAkC,EAAE,CAAC;AAAA,EAC5I;AACA,QAAM,aAAa;AAAA,IACjB;AAAA,IACA,UAAU,QAAQ;AAAA,IAClB,WAAW;AAAA,EACb;AACA,QAAM,SAAS,iBACX;AAAA,IACE,GAAG;AAAA,IACH,GAAI,QAAQ,wBAAwB,SAChC,EAAE,gBAAgB,EAAE,KAAK,QAAQ,wBAAwB,EAAE,IAC3D,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AAW;AAAA,IACT,EAAE,QAAQ,KAAK,aAAa,uBAAuB,QAAQ,kCAAkC;AAAA,EAC/F;AAAA,EACA,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,sBAAsB,QAAQ,wBAAwB;AAAA,IAClF,EAAE,QAAQ,KAAK,aAAa,2BAA2B,QAAQ,wBAAwB;AAAA,IACvF,EAAE,QAAQ,KAAK,aAAa,wBAAwB,QAAQ,wBAAwB;AAAA,IACpF,EAAE,QAAQ,KAAK,aAAa,qCAAqC,QAAQ,wBAAwB;AAAA,EACnG;AACF;AAEA,MAAM,2BAA6C;AAAA,EACjD,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,eAAe;AAAA,EACtB,aAAa;AAAA,IACX,aAAa;AAAA,IACb,QAAQ;AAAA,IACR,aAAa;AAAA,EACf;AAAA,EACA,WAAW;AAAA,IACT,EAAE,QAAQ,KAAK,aAAa,6BAA6B,QAAQ,8BAA8B;AAAA,EACjG;AAAA,EACA,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,wBAAwB;AAAA,IACjF,EAAE,QAAQ,KAAK,aAAa,2BAA2B,QAAQ,wBAAwB;AAAA,IACvF,EAAE,QAAQ,KAAK,aAAa,wBAAwB,QAAQ,wBAAwB;AAAA,IACpF,EAAE,QAAQ,KAAK,aAAa,qCAAqC,QAAQ,wBAAwB;AAAA,EACnG;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,SAAS;AAAA,IACP,KAAK;AAAA,IACL,MAAM;AAAA,EACR;AACF;",
6
6
  "names": []
7
7
  }
@@ -6,7 +6,7 @@ import {
6
6
  setDefaultDictionaryEntryCommandSchema,
7
7
  setDefaultDictionaryEntrySchema
8
8
  } from "@open-mercato/core/modules/dictionaries/data/validators";
9
- import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
9
+ import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
10
10
  import { serializeOperationMetadata } from "@open-mercato/shared/lib/commands/operationMetadata";
11
11
  import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
12
12
  import { readJsonSafe } from "@open-mercato/shared/lib/http/readJsonSafe";
@@ -112,7 +112,7 @@ async function POST(req, ctx) {
112
112
  }
113
113
  return response;
114
114
  } catch (err) {
115
- if (err instanceof CrudHttpError) {
115
+ if (isCrudHttpError(err)) {
116
116
  return NextResponse.json(err.body, { status: err.status });
117
117
  }
118
118
  console.error("[dictionaries/:id/entries/set-default.POST] Unexpected error", err);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../../src/modules/dictionaries/api/%5BdictionaryId%5D/entries/set-default/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { Dictionary } from '@open-mercato/core/modules/dictionaries/data/entities'\nimport { resolveDictionariesRouteContext } from '@open-mercato/core/modules/dictionaries/api/context'\nimport {\n setDefaultDictionaryEntryCommandSchema,\n setDefaultDictionaryEntrySchema,\n type SetDefaultDictionaryEntryCommandInput,\n} from '@open-mercato/core/modules/dictionaries/data/validators'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands'\nimport type { OpenApiMethodDoc, OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { serializeOperationMetadata } from '@open-mercato/shared/lib/commands/operationMetadata'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport {\n dictionaryIdParamsSchema,\n dictionariesErrorSchema,\n dictionariesOkSchema,\n dictionariesTag,\n setDefaultEntryRequestSchema,\n} from '../../../openapi'\nimport { resolveDictionaryActorId } from '../../../context'\n\nconst paramsSchema = z.object({ dictionaryId: z.string().uuid() })\n\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: ['dictionaries.manage'] },\n}\n\nexport async function POST(req: Request, ctx: { params?: { dictionaryId?: string } }) {\n try {\n const context = await resolveDictionariesRouteContext(req)\n if (!context.auth) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n const { dictionaryId } = paramsSchema.parse({ dictionaryId: ctx.params?.dictionaryId })\n\n if (!context.organizationId) {\n throw new CrudHttpError(400, { error: context.translate('dictionaries.errors.organization_required', 'Organization context is required') })\n }\n const dictionaryEm = context.em.fork()\n const dictionary = await findOneWithDecryption(\n dictionaryEm,\n Dictionary,\n {\n id: dictionaryId,\n organizationId: context.organizationId,\n tenantId: context.tenantId,\n deletedAt: null,\n },\n undefined,\n { tenantId: context.tenantId, organizationId: context.organizationId },\n )\n if (!dictionary) {\n throw new CrudHttpError(404, { error: context.translate('dictionaries.errors.not_found', 'Dictionary not found') })\n }\n\n const payload = setDefaultDictionaryEntrySchema.parse(await readJsonSafe(req, {}))\n const guardUserId = resolveDictionaryActorId(context.auth)\n const guardResult = await validateCrudMutationGuard(context.container, {\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n userId: guardUserId,\n resourceKind: 'dictionaries.dictionary',\n resourceId: dictionaryId,\n operation: 'custom',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: payload,\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n\n const commandInput = setDefaultDictionaryEntryCommandSchema.parse({\n dictionaryId,\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n entryId: payload.entryId,\n } satisfies SetDefaultDictionaryEntryCommandInput)\n\n const commandBus = context.container.resolve('commandBus') as CommandBus\n const { logEntry } = await commandBus.execute<SetDefaultDictionaryEntryCommandInput, { dictionaryId: string; entryId: string; clearedIds: string[] }>(\n 'dictionaries.entries.set_default',\n {\n input: commandInput,\n ctx: context.ctx,\n },\n )\n\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(context.container, {\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n userId: guardUserId,\n resourceKind: 'dictionaries.dictionary',\n resourceId: dictionaryId,\n operation: 'custom',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n const response = NextResponse.json({ ok: true })\n if (logEntry?.undoToken && logEntry.id && logEntry.commandId) {\n response.headers.set(\n 'x-om-operation',\n serializeOperationMetadata({\n id: logEntry.id,\n undoToken: logEntry.undoToken,\n commandId: logEntry.commandId,\n actionLabel: logEntry.actionLabel ?? null,\n resourceKind: logEntry.resourceKind ?? 'dictionaries.dictionary',\n resourceId: logEntry.resourceId ?? dictionaryId,\n executedAt: logEntry.createdAt instanceof Date ? logEntry.createdAt.toISOString() : new Date().toISOString(),\n }),\n )\n }\n return response\n } catch (err) {\n if (err instanceof CrudHttpError) {\n return NextResponse.json(err.body, { status: err.status })\n }\n console.error('[dictionaries/:id/entries/set-default.POST] Unexpected error', err)\n return NextResponse.json({ error: 'Failed to set default entry' }, { status: 500 })\n }\n}\n\nconst setDefaultPostDoc: OpenApiMethodDoc = {\n summary: 'Set default dictionary entry',\n description: 'Marks the specified entry as the default for this dictionary, clearing any previous default.',\n tags: [dictionariesTag],\n requestBody: {\n contentType: 'application/json',\n schema: setDefaultEntryRequestSchema,\n description: 'ID of the entry to set as default.',\n },\n responses: [\n { status: 200, description: 'Default entry set.', schema: dictionariesOkSchema },\n ],\n errors: [\n { status: 400, description: 'Validation failed', schema: dictionariesErrorSchema },\n { status: 401, description: 'Authentication required', schema: dictionariesErrorSchema },\n { status: 404, description: 'Dictionary or entry not found', schema: dictionariesErrorSchema },\n { status: 500, description: 'Failed to set default entry', schema: dictionariesErrorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: dictionariesTag,\n summary: 'Set default dictionary entry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AQ,wBAAwB;AAAA,EAC7F;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,SAAS;AAAA,IACP,MAAM;AAAA,EACR;AACF;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { Dictionary } from '@open-mercato/core/modules/dictionaries/data/entities'\nimport { resolveDictionariesRouteContext } from '@open-mercato/core/modules/dictionaries/api/context'\nimport {\n setDefaultDictionaryEntryCommandSchema,\n setDefaultDictionaryEntrySchema,\n type SetDefaultDictionaryEntryCommandInput,\n} from '@open-mercato/core/modules/dictionaries/data/validators'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands'\nimport type { OpenApiMethodDoc, OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { serializeOperationMetadata } from '@open-mercato/shared/lib/commands/operationMetadata'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport {\n dictionaryIdParamsSchema,\n dictionariesErrorSchema,\n dictionariesOkSchema,\n dictionariesTag,\n setDefaultEntryRequestSchema,\n} from '../../../openapi'\nimport { resolveDictionaryActorId } from '../../../context'\n\nconst paramsSchema = z.object({ dictionaryId: z.string().uuid() })\n\nexport const metadata = {\n POST: { requireAuth: true, requireFeatures: ['dictionaries.manage'] },\n}\n\nexport async function POST(req: Request, ctx: { params?: { dictionaryId?: string } }) {\n try {\n const context = await resolveDictionariesRouteContext(req)\n if (!context.auth) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n const { dictionaryId } = paramsSchema.parse({ dictionaryId: ctx.params?.dictionaryId })\n\n if (!context.organizationId) {\n throw new CrudHttpError(400, { error: context.translate('dictionaries.errors.organization_required', 'Organization context is required') })\n }\n const dictionaryEm = context.em.fork()\n const dictionary = await findOneWithDecryption(\n dictionaryEm,\n Dictionary,\n {\n id: dictionaryId,\n organizationId: context.organizationId,\n tenantId: context.tenantId,\n deletedAt: null,\n },\n undefined,\n { tenantId: context.tenantId, organizationId: context.organizationId },\n )\n if (!dictionary) {\n throw new CrudHttpError(404, { error: context.translate('dictionaries.errors.not_found', 'Dictionary not found') })\n }\n\n const payload = setDefaultDictionaryEntrySchema.parse(await readJsonSafe(req, {}))\n const guardUserId = resolveDictionaryActorId(context.auth)\n const guardResult = await validateCrudMutationGuard(context.container, {\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n userId: guardUserId,\n resourceKind: 'dictionaries.dictionary',\n resourceId: dictionaryId,\n operation: 'custom',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: payload,\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n\n const commandInput = setDefaultDictionaryEntryCommandSchema.parse({\n dictionaryId,\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n entryId: payload.entryId,\n } satisfies SetDefaultDictionaryEntryCommandInput)\n\n const commandBus = context.container.resolve('commandBus') as CommandBus\n const { logEntry } = await commandBus.execute<SetDefaultDictionaryEntryCommandInput, { dictionaryId: string; entryId: string; clearedIds: string[] }>(\n 'dictionaries.entries.set_default',\n {\n input: commandInput,\n ctx: context.ctx,\n },\n )\n\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(context.container, {\n tenantId: context.tenantId,\n organizationId: context.organizationId,\n userId: guardUserId,\n resourceKind: 'dictionaries.dictionary',\n resourceId: dictionaryId,\n operation: 'custom',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n const response = NextResponse.json({ ok: true })\n if (logEntry?.undoToken && logEntry.id && logEntry.commandId) {\n response.headers.set(\n 'x-om-operation',\n serializeOperationMetadata({\n id: logEntry.id,\n undoToken: logEntry.undoToken,\n commandId: logEntry.commandId,\n actionLabel: logEntry.actionLabel ?? null,\n resourceKind: logEntry.resourceKind ?? 'dictionaries.dictionary',\n resourceId: logEntry.resourceId ?? dictionaryId,\n executedAt: logEntry.createdAt instanceof Date ? logEntry.createdAt.toISOString() : new Date().toISOString(),\n }),\n )\n }\n return response\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n console.error('[dictionaries/:id/entries/set-default.POST] Unexpected error', err)\n return NextResponse.json({ error: 'Failed to set default entry' }, { status: 500 })\n }\n}\n\nconst setDefaultPostDoc: OpenApiMethodDoc = {\n summary: 'Set default dictionary entry',\n description: 'Marks the specified entry as the default for this dictionary, clearing any previous default.',\n tags: [dictionariesTag],\n requestBody: {\n contentType: 'application/json',\n schema: setDefaultEntryRequestSchema,\n description: 'ID of the entry to set as default.',\n },\n responses: [\n { status: 200, description: 'Default entry set.', schema: dictionariesOkSchema },\n ],\n errors: [\n { status: 400, description: 'Validation failed', schema: dictionariesErrorSchema },\n { status: 401, description: 'Authentication required', schema: dictionariesErrorSchema },\n { status: 404, description: 'Dictionary or entry not found', schema: dictionariesErrorSchema },\n { status: 500, description: 'Failed to set default entry', schema: dictionariesErrorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: dictionariesTag,\n summary: 'Set default dictionary entry',\n pathParams: dictionaryIdParamsSchema,\n methods: {\n POST: setDefaultPostDoc,\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,kBAAkB;AAC3B,SAAS,uCAAuC;AAChD;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,eAAe,uBAAuB;AAG/C,SAAS,kCAAkC;AAC3C,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;A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,cAAc;AAAA,UACnC,YAAY,SAAS,qBAAqB,OAAO,SAAS,UAAU,YAAY,KAAI,oBAAI,KAAK,GAAE,YAAY;AAAA,QAC7G,CAAC;AAAA,MACH;AAAA,IACF;AACA,WAAO;AAAA,EACT,SAAS,KAAK;AACZ,QAAI,gBAAgB,GAAG,GAAG;AACxB,aAAO,aAAa,KAAK,IAAI,MAAM,EAAE,QAAQ,IAAI,OAAO,CAAC;AAAA,IAC3D;AACA,YAAQ,MAAM,gEAAgE,GAAG;AACjF,WAAO,aAAa,KAAK,EAAE,OAAO,8BAA8B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACpF;AACF;AAEA,MAAM,oBAAsC;AAAA,EAC1C,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,eAAe;AAAA,EACtB,aAAa;AAAA,IACX,aAAa;AAAA,IACb,QAAQ;AAAA,IACR,aAAa;AAAA,EACf;AAAA,EACA,WAAW;AAAA,IACT,EAAE,QAAQ,KAAK,aAAa,sBAAsB,QAAQ,qBAAqB;AAAA,EACjF;AAAA,EACA,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,wBAAwB;AAAA,IACjF,EAAE,QAAQ,KAAK,aAAa,2BAA2B,QAAQ,wBAAwB;AAAA,IACvF,EAAE,QAAQ,KAAK,aAAa,iCAAiC,QAAQ,wBAAwB;AAAA,IAC7F,EAAE,QAAQ,KAAK,aAAa,+BAA+B,QAAQ,wBAAwB;AAAA,EAC7F;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,SAAS;AAAA,IACP,MAAM;AAAA,EACR;AACF;",
6
6
  "names": []
7
7
  }
@@ -2,7 +2,7 @@ import { NextResponse } from "next/server";
2
2
  import { z } from "zod";
3
3
  import { Dictionary } from "@open-mercato/core/modules/dictionaries/data/entities";
4
4
  import { resolveDictionariesRouteContext } from "@open-mercato/core/modules/dictionaries/api/context";
5
- import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
5
+ import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
6
6
  import {
7
7
  dictionariesErrorSchema,
8
8
  dictionariesOkSchema,
@@ -67,7 +67,7 @@ async function GET(req, ctx) {
67
67
  updatedAt: dictionary.updatedAt
68
68
  });
69
69
  } catch (err) {
70
- if (err instanceof CrudHttpError) {
70
+ if (isCrudHttpError(err)) {
71
71
  return NextResponse.json(err.body, { status: err.status });
72
72
  }
73
73
  console.error("[dictionaries/:id.GET] Unexpected error", err);
@@ -135,7 +135,7 @@ async function PATCH(req, ctx) {
135
135
  updatedAt: dictionary.updatedAt
136
136
  });
137
137
  } catch (err) {
138
- if (err instanceof CrudHttpError) {
138
+ if (isCrudHttpError(err)) {
139
139
  return NextResponse.json(err.body, { status: err.status });
140
140
  }
141
141
  console.error("[dictionaries/:id.PATCH] Unexpected error", err);
@@ -155,7 +155,7 @@ async function DELETE(req, ctx) {
155
155
  await context.em.flush();
156
156
  return NextResponse.json({ ok: true });
157
157
  } catch (err) {
158
- if (err instanceof CrudHttpError) {
158
+ if (isCrudHttpError(err)) {
159
159
  return NextResponse.json(err.body, { status: err.status });
160
160
  }
161
161
  console.error("[dictionaries/:id.DELETE] Unexpected error", err);