@open-mercato/core 0.9.0 → 0.9.1-develop.7459.1.99e3accd30

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 (243) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/generated/entities/customer_dictionary_entry/index.js +2 -0
  3. package/dist/generated/entities/customer_dictionary_entry/index.js.map +2 -2
  4. package/dist/generated/entities/customer_interaction/index.js +2 -0
  5. package/dist/generated/entities/customer_interaction/index.js.map +2 -2
  6. package/dist/generated/entity-fields-registry.js +2 -0
  7. package/dist/generated/entity-fields-registry.js.map +2 -2
  8. package/dist/modules/catalog/commands/categories.js +1 -1
  9. package/dist/modules/catalog/commands/categories.js.map +2 -2
  10. package/dist/modules/catalog/commands/productDeleteChildren.js +389 -0
  11. package/dist/modules/catalog/commands/productDeleteChildren.js.map +7 -0
  12. package/dist/modules/catalog/commands/products.js +52 -17
  13. package/dist/modules/catalog/commands/products.js.map +2 -2
  14. package/dist/modules/communication_channels/api/post/channels/connect/credentials/route.js +4 -6
  15. package/dist/modules/communication_channels/api/post/channels/connect/credentials/route.js.map +2 -2
  16. package/dist/modules/communication_channels/api/post/channels/connect/tenant-credentials/route.js +4 -6
  17. package/dist/modules/communication_channels/api/post/channels/connect/tenant-credentials/route.js.map +2 -2
  18. package/dist/modules/communication_channels/api/post/oauth/[provider]/initiate/route.js +47 -11
  19. package/dist/modules/communication_channels/api/post/oauth/[provider]/initiate/route.js.map +3 -3
  20. package/dist/modules/communication_channels/commands/deliver-outbound-message.js +5 -1
  21. package/dist/modules/communication_channels/commands/deliver-outbound-message.js.map +2 -2
  22. package/dist/modules/communication_channels/lib/inbound-message-origin.js +1 -1
  23. package/dist/modules/communication_channels/lib/inbound-message-origin.js.map +2 -2
  24. package/dist/modules/communication_channels/lib/oauth-state.js +4 -1
  25. package/dist/modules/communication_channels/lib/oauth-state.js.map +2 -2
  26. package/dist/modules/communication_channels/lib/use-connect-channel.js +10 -0
  27. package/dist/modules/communication_channels/lib/use-connect-channel.js.map +2 -2
  28. package/dist/modules/customers/api/activity-types/route.js +151 -0
  29. package/dist/modules/customers/api/activity-types/route.js.map +7 -0
  30. package/dist/modules/customers/api/deals/[id]/people/route.js +58 -5
  31. package/dist/modules/customers/api/deals/[id]/people/route.js.map +2 -2
  32. package/dist/modules/customers/api/dictionaries/[kind]/[id]/route.js +13 -5
  33. package/dist/modules/customers/api/dictionaries/[kind]/[id]/route.js.map +2 -2
  34. package/dist/modules/customers/api/dictionaries/[kind]/route.js +20 -5
  35. package/dist/modules/customers/api/dictionaries/[kind]/route.js.map +2 -2
  36. package/dist/modules/customers/api/interactions/route.js +3 -0
  37. package/dist/modules/customers/api/interactions/route.js.map +2 -2
  38. package/dist/modules/customers/api/interactions/tasks/route.js +1 -0
  39. package/dist/modules/customers/api/interactions/tasks/route.js.map +2 -2
  40. package/dist/modules/customers/backend/config/customers/pipeline-stages/page.meta.js +18 -0
  41. package/dist/modules/customers/backend/config/customers/pipeline-stages/page.meta.js.map +2 -2
  42. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealAssociations.js +0 -23
  43. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealAssociations.js.map +2 -2
  44. package/dist/modules/customers/backend/customers/deals/[id]/page.js +15 -17
  45. package/dist/modules/customers/backend/customers/deals/[id]/page.js.map +2 -2
  46. package/dist/modules/customers/calendar-event-types.js +548 -0
  47. package/dist/modules/customers/calendar-event-types.js.map +7 -0
  48. package/dist/modules/customers/commands/dictionaries.js +70 -10
  49. package/dist/modules/customers/commands/dictionaries.js.map +2 -2
  50. package/dist/modules/customers/commands/interactions.js +187 -22
  51. package/dist/modules/customers/commands/interactions.js.map +3 -3
  52. package/dist/modules/customers/components/ActivityTypeEditor.js +288 -0
  53. package/dist/modules/customers/components/ActivityTypeEditor.js.map +7 -0
  54. package/dist/modules/customers/components/DictionarySettings.js +3 -1
  55. package/dist/modules/customers/components/DictionarySettings.js.map +2 -2
  56. package/dist/modules/customers/components/calendar/CalendarEventEditor.js +391 -297
  57. package/dist/modules/customers/components/calendar/CalendarEventEditor.js.map +3 -3
  58. package/dist/modules/customers/components/calendar/CalendarSettingsModal.js +9 -74
  59. package/dist/modules/customers/components/calendar/CalendarSettingsModal.js.map +2 -2
  60. package/dist/modules/customers/components/calendar/TimeGrid.js +20 -16
  61. package/dist/modules/customers/components/calendar/TimeGrid.js.map +2 -2
  62. package/dist/modules/customers/components/calendar/editor/EventTypePanel.js +218 -0
  63. package/dist/modules/customers/components/calendar/editor/EventTypePanel.js.map +7 -0
  64. package/dist/modules/customers/components/calendar/editor/LocationField.js +7 -3
  65. package/dist/modules/customers/components/calendar/editor/LocationField.js.map +2 -2
  66. package/dist/modules/customers/components/calendar/editor/PeopleField.js +5 -2
  67. package/dist/modules/customers/components/calendar/editor/PeopleField.js.map +2 -2
  68. package/dist/modules/customers/components/calendar/editor/PriorityField.js +3 -1
  69. package/dist/modules/customers/components/calendar/editor/PriorityField.js.map +2 -2
  70. package/dist/modules/customers/components/calendar/editor/RepeatField.js +9 -1
  71. package/dist/modules/customers/components/calendar/editor/RepeatField.js.map +2 -2
  72. package/dist/modules/customers/components/calendar/editor/ResourcesField.js +4 -1
  73. package/dist/modules/customers/components/calendar/editor/ResourcesField.js.map +2 -2
  74. package/dist/modules/customers/components/calendar/editor/ScheduleSection.js +15 -7
  75. package/dist/modules/customers/components/calendar/editor/ScheduleSection.js.map +2 -2
  76. package/dist/modules/customers/components/calendar/editor/SegmentGroup.js +3 -1
  77. package/dist/modules/customers/components/calendar/editor/SegmentGroup.js.map +2 -2
  78. package/dist/modules/customers/components/calendar/editor/hooks.js +28 -13
  79. package/dist/modules/customers/components/calendar/editor/hooks.js.map +3 -3
  80. package/dist/modules/customers/components/calendar/editor/inputs.js +14 -6
  81. package/dist/modules/customers/components/calendar/editor/inputs.js.map +2 -2
  82. package/dist/modules/customers/components/calendar/editor/useCalendarCustomFields.js +54 -0
  83. package/dist/modules/customers/components/calendar/editor/useCalendarCustomFields.js.map +7 -0
  84. package/dist/modules/customers/components/calendar/editor/useEventTypeCatalog.js +82 -0
  85. package/dist/modules/customers/components/calendar/editor/useEventTypeCatalog.js.map +7 -0
  86. package/dist/modules/customers/components/calendar/types.js +1 -0
  87. package/dist/modules/customers/components/calendar/types.js.map +2 -2
  88. package/dist/modules/customers/components/detail/CompanyPeopleSection.js +78 -343
  89. package/dist/modules/customers/components/detail/CompanyPeopleSection.js.map +2 -2
  90. package/dist/modules/customers/components/detail/CreatePersonDialog.js +12 -11
  91. package/dist/modules/customers/components/detail/CreatePersonDialog.js.map +2 -2
  92. package/dist/modules/customers/components/detail/DealForm.js +7 -3
  93. package/dist/modules/customers/components/detail/DealForm.js.map +2 -2
  94. package/dist/modules/customers/components/detail/DealPeopleSection.js +206 -0
  95. package/dist/modules/customers/components/detail/DealPeopleSection.js.map +7 -0
  96. package/dist/modules/customers/components/detail/LinkedPeopleSection.js +342 -0
  97. package/dist/modules/customers/components/detail/LinkedPeopleSection.js.map +7 -0
  98. package/dist/modules/customers/components/detail/PersonCard.js +5 -2
  99. package/dist/modules/customers/components/detail/PersonCard.js.map +2 -2
  100. package/dist/modules/customers/components/linking/adapters/personAdapter.js +3 -0
  101. package/dist/modules/customers/components/linking/adapters/personAdapter.js.map +2 -2
  102. package/dist/modules/customers/data/entities.js +6 -0
  103. package/dist/modules/customers/data/entities.js.map +2 -2
  104. package/dist/modules/customers/data/validators.js +39 -10
  105. package/dist/modules/customers/data/validators.js.map +2 -2
  106. package/dist/modules/customers/di.js +20 -1
  107. package/dist/modules/customers/di.js.map +2 -2
  108. package/dist/modules/customers/extension-points.js +13 -0
  109. package/dist/modules/customers/extension-points.js.map +2 -2
  110. package/dist/modules/customers/lib/calendar/conflicts.js +59 -16
  111. package/dist/modules/customers/lib/calendar/conflicts.js.map +2 -2
  112. package/dist/modules/customers/lib/calendar/editorPayload.js +34 -16
  113. package/dist/modules/customers/lib/calendar/editorPayload.js.map +2 -2
  114. package/dist/modules/customers/lib/calendar/eventTypeResolver.js +197 -0
  115. package/dist/modules/customers/lib/calendar/eventTypeResolver.js.map +7 -0
  116. package/dist/modules/customers/lib/calendar/interactionApplicability.js +67 -0
  117. package/dist/modules/customers/lib/calendar/interactionApplicability.js.map +7 -0
  118. package/dist/modules/customers/lib/calendar/mapItem.js +5 -2
  119. package/dist/modules/customers/lib/calendar/mapItem.js.map +2 -2
  120. package/dist/modules/customers/lib/calendar/recurrence.js +62 -1
  121. package/dist/modules/customers/lib/calendar/recurrence.js.map +2 -2
  122. package/dist/modules/customers/lib/calendar/timezone.js +111 -0
  123. package/dist/modules/customers/lib/calendar/timezone.js.map +7 -0
  124. package/dist/modules/customers/lib/interactionReadModel.js +1 -0
  125. package/dist/modules/customers/lib/interactionReadModel.js.map +2 -2
  126. package/dist/modules/customers/lib/todoCompatibility.js +1 -0
  127. package/dist/modules/customers/lib/todoCompatibility.js.map +2 -2
  128. package/dist/modules/customers/migrations/Migration20260928175058_customers.js +17 -0
  129. package/dist/modules/customers/migrations/Migration20260928175058_customers.js.map +7 -0
  130. package/dist/modules/customers/migrations/Migration20260930110235_customers.js +17 -0
  131. package/dist/modules/customers/migrations/Migration20260930110235_customers.js.map +7 -0
  132. package/dist/modules/dictionaries/components/DictionaryTable.js +60 -51
  133. package/dist/modules/dictionaries/components/DictionaryTable.js.map +2 -2
  134. package/dist/modules/messages/subscribers/message-notification.js +13 -1
  135. package/dist/modules/messages/subscribers/message-notification.js.map +2 -2
  136. package/dist/modules/payment_gateways/api/webhook/[provider]/route.js +201 -53
  137. package/dist/modules/payment_gateways/api/webhook/[provider]/route.js.map +2 -2
  138. package/dist/modules/payment_gateways/lib/gateway-service.js +37 -11
  139. package/dist/modules/payment_gateways/lib/gateway-service.js.map +2 -2
  140. package/dist/modules/planner/lib/availabilityMerge.js +101 -38
  141. package/dist/modules/planner/lib/availabilityMerge.js.map +3 -3
  142. package/dist/modules/planner/services/plannerAvailabilityService.js.map +2 -2
  143. package/dist/modules/sales/components/documents/LineItemDialog.js +159 -81
  144. package/dist/modules/sales/components/documents/LineItemDialog.js.map +2 -2
  145. package/dist/modules/sales/components/documents/lineItemUtils.js +7 -0
  146. package/dist/modules/sales/components/documents/lineItemUtils.js.map +2 -2
  147. package/dist/modules/staff/backend/staff/time-tracking/projects/[id]/page.js +12 -7
  148. package/dist/modules/staff/backend/staff/time-tracking/projects/[id]/page.js.map +2 -2
  149. package/dist/modules/sync_excel/lib/adapters/customers.js +28 -25
  150. package/dist/modules/sync_excel/lib/adapters/customers.js.map +2 -2
  151. package/generated/entities/customer_dictionary_entry/index.ts +1 -0
  152. package/generated/entities/customer_interaction/index.ts +1 -0
  153. package/generated/entity-fields-registry.ts +2 -0
  154. package/package.json +9 -8
  155. package/src/modules/auth/i18n/de.json +3 -0
  156. package/src/modules/auth/i18n/en.json +3 -0
  157. package/src/modules/auth/i18n/es.json +3 -0
  158. package/src/modules/auth/i18n/ko.json +3 -0
  159. package/src/modules/auth/i18n/pl.json +3 -0
  160. package/src/modules/catalog/commands/categories.ts +1 -1
  161. package/src/modules/catalog/commands/productDeleteChildren.ts +557 -0
  162. package/src/modules/catalog/commands/products.ts +58 -17
  163. package/src/modules/communication_channels/api/post/channels/connect/credentials/route.ts +4 -6
  164. package/src/modules/communication_channels/api/post/channels/connect/tenant-credentials/route.ts +4 -6
  165. package/src/modules/communication_channels/api/post/oauth/[provider]/initiate/route.ts +46 -10
  166. package/src/modules/communication_channels/commands/deliver-outbound-message.ts +6 -1
  167. package/src/modules/communication_channels/i18n/de.json +4 -0
  168. package/src/modules/communication_channels/i18n/en.json +4 -0
  169. package/src/modules/communication_channels/i18n/es.json +4 -0
  170. package/src/modules/communication_channels/i18n/ko.json +4 -0
  171. package/src/modules/communication_channels/i18n/pl.json +4 -0
  172. package/src/modules/communication_channels/lib/inbound-message-origin.ts +2 -6
  173. package/src/modules/communication_channels/lib/oauth-state.ts +4 -1
  174. package/src/modules/communication_channels/lib/use-connect-channel.ts +10 -0
  175. package/src/modules/customers/api/activity-types/route.ts +154 -0
  176. package/src/modules/customers/api/deals/[id]/people/route.ts +82 -3
  177. package/src/modules/customers/api/dictionaries/[kind]/[id]/route.ts +9 -1
  178. package/src/modules/customers/api/dictionaries/[kind]/route.ts +18 -2
  179. package/src/modules/customers/api/interactions/route.ts +4 -0
  180. package/src/modules/customers/api/interactions/tasks/route.ts +1 -0
  181. package/src/modules/customers/backend/config/customers/pipeline-stages/page.meta.ts +20 -0
  182. package/src/modules/customers/backend/customers/deals/[id]/hooks/useDealAssociations.ts +0 -29
  183. package/src/modules/customers/backend/customers/deals/[id]/page.tsx +15 -17
  184. package/src/modules/customers/calendar-event-types.ts +674 -0
  185. package/src/modules/customers/commands/dictionaries.ts +84 -8
  186. package/src/modules/customers/commands/interactions.ts +244 -21
  187. package/src/modules/customers/components/ActivityTypeEditor.tsx +239 -0
  188. package/src/modules/customers/components/DictionarySettings.tsx +5 -3
  189. package/src/modules/customers/components/calendar/CalendarEventEditor.tsx +347 -218
  190. package/src/modules/customers/components/calendar/CalendarSettingsModal.tsx +18 -96
  191. package/src/modules/customers/components/calendar/TimeGrid.tsx +20 -18
  192. package/src/modules/customers/components/calendar/editor/EventTypePanel.tsx +230 -0
  193. package/src/modules/customers/components/calendar/editor/LocationField.tsx +7 -1
  194. package/src/modules/customers/components/calendar/editor/PeopleField.tsx +4 -0
  195. package/src/modules/customers/components/calendar/editor/PriorityField.tsx +3 -0
  196. package/src/modules/customers/components/calendar/editor/RepeatField.tsx +10 -0
  197. package/src/modules/customers/components/calendar/editor/ResourcesField.tsx +4 -0
  198. package/src/modules/customers/components/calendar/editor/ScheduleSection.tsx +16 -4
  199. package/src/modules/customers/components/calendar/editor/SegmentGroup.tsx +3 -0
  200. package/src/modules/customers/components/calendar/editor/hooks.ts +29 -13
  201. package/src/modules/customers/components/calendar/editor/inputs.tsx +17 -5
  202. package/src/modules/customers/components/calendar/editor/useCalendarCustomFields.ts +49 -0
  203. package/src/modules/customers/components/calendar/editor/useEventTypeCatalog.ts +100 -0
  204. package/src/modules/customers/components/calendar/types.ts +1 -0
  205. package/src/modules/customers/components/detail/CompanyPeopleSection.tsx +94 -388
  206. package/src/modules/customers/components/detail/CreatePersonDialog.tsx +39 -19
  207. package/src/modules/customers/components/detail/DealForm.tsx +7 -3
  208. package/src/modules/customers/components/detail/DealPeopleSection.tsx +256 -0
  209. package/src/modules/customers/components/detail/LinkedPeopleSection.tsx +474 -0
  210. package/src/modules/customers/components/detail/PersonCard.tsx +12 -4
  211. package/src/modules/customers/components/detail/types.ts +1 -0
  212. package/src/modules/customers/components/linking/adapters/personAdapter.tsx +4 -0
  213. package/src/modules/customers/data/entities.ts +8 -1
  214. package/src/modules/customers/data/validators.ts +42 -7
  215. package/src/modules/customers/di.ts +21 -0
  216. package/src/modules/customers/extension-points.ts +13 -0
  217. package/src/modules/customers/i18n/de.json +104 -8
  218. package/src/modules/customers/i18n/en.json +104 -8
  219. package/src/modules/customers/i18n/es.json +104 -8
  220. package/src/modules/customers/i18n/ko.json +104 -8
  221. package/src/modules/customers/i18n/pl.json +104 -8
  222. package/src/modules/customers/lib/calendar/conflicts.ts +106 -27
  223. package/src/modules/customers/lib/calendar/editorPayload.ts +39 -19
  224. package/src/modules/customers/lib/calendar/eventTypeResolver.ts +258 -0
  225. package/src/modules/customers/lib/calendar/interactionApplicability.ts +99 -0
  226. package/src/modules/customers/lib/calendar/mapItem.ts +6 -2
  227. package/src/modules/customers/lib/calendar/recurrence.ts +65 -1
  228. package/src/modules/customers/lib/calendar/timezone.ts +117 -0
  229. package/src/modules/customers/lib/interactionReadModel.ts +1 -0
  230. package/src/modules/customers/lib/todoCompatibility.ts +2 -0
  231. package/src/modules/customers/migrations/.snapshot-open-mercato.json +34 -0
  232. package/src/modules/customers/migrations/Migration20260928175058_customers.ts +15 -0
  233. package/src/modules/customers/migrations/Migration20260930110235_customers.ts +15 -0
  234. package/src/modules/dictionaries/components/DictionaryTable.tsx +63 -56
  235. package/src/modules/messages/subscribers/message-notification.ts +13 -3
  236. package/src/modules/payment_gateways/api/webhook/[provider]/route.ts +243 -62
  237. package/src/modules/payment_gateways/lib/gateway-service.ts +39 -12
  238. package/src/modules/planner/lib/availabilityMerge.ts +106 -41
  239. package/src/modules/planner/services/plannerAvailabilityService.ts +4 -0
  240. package/src/modules/sales/components/documents/LineItemDialog.tsx +194 -111
  241. package/src/modules/sales/components/documents/lineItemUtils.ts +18 -0
  242. package/src/modules/staff/backend/staff/time-tracking/projects/[id]/page.tsx +25 -13
  243. package/src/modules/sync_excel/lib/adapters/customers.ts +33 -27
@@ -403,7 +403,7 @@ const updateCategoryCommand = {
403
403
  ],
404
404
  { transaction: true }
405
405
  );
406
- const resetValues = buildCustomFieldResetMap(payload?.after?.custom ?? void 0, before.custom ?? void 0);
406
+ const resetValues = buildCustomFieldResetMap(before.custom ?? void 0, payload?.after?.custom ?? void 0);
407
407
  if (Object.keys(resetValues).length) {
408
408
  await setCustomFieldsIfAny({
409
409
  dataEngine: ctx.container.resolve("dataEngine"),
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/catalog/commands/categories.ts"],
4
- "sourcesContent": ["import { registerCommand } from '@open-mercato/shared/lib/commands'\nimport type { CommandHandler } from '@open-mercato/shared/lib/commands'\nimport { buildChanges, requireId, parseWithCustomFields, setCustomFieldsIfAny, emitCrudSideEffects } from '@open-mercato/shared/lib/commands/helpers'\nimport { loadCustomFieldSnapshot, buildCustomFieldResetMap } from '@open-mercato/shared/lib/commands/customFieldSnapshots'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CatalogProductCategory } from '../data/entities'\nimport {\n categoryCreateSchema,\n categoryUpdateSchema,\n type CategoryCreateInput,\n type CategoryUpdateInput,\n} from '../data/validators'\nimport { ensureOrganizationScope, ensureTenantScope, extractUndoPayload } from './shared'\nimport { makeCreateRedo } from '@open-mercato/shared/lib/commands/redo'\nimport { rebuildCategoryHierarchyForOrganization } from '../lib/categoryHierarchy'\nimport type { CrudEventsConfig } from '@open-mercato/shared/lib/crud/types'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport { E } from '#generated/entities.ids.generated'\n\nconst categoryCrudEvents: CrudEventsConfig = {\n module: 'catalog',\n entity: 'category',\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n}\n\ntype CategorySnapshot = {\n id: string\n organizationId: string\n tenantId: string\n name: string\n slug: string | null\n description: string | null\n parentId: string | null\n rootId: string | null\n treePath: string | null\n depth: number\n ancestorIds: string[]\n childIds: string[]\n descendantIds: string[]\n isActive: boolean\n createdAt: string\n updatedAt: string\n custom?: Record<string, unknown> | null\n}\n\ntype CategoryUndoPayload = {\n before?: CategorySnapshot | null\n after?: CategorySnapshot | null\n}\n\nconst CATEGORY_CHANGE_KEYS = [\n 'name',\n 'slug',\n 'description',\n 'parentId',\n 'rootId',\n 'treePath',\n 'isActive',\n] as const satisfies readonly string[]\n\nasync function loadCategorySnapshot(em: EntityManager, id: string): Promise<CategorySnapshot | null> {\n const record = await em.findOne(CatalogProductCategory, { id })\n if (!record) return null\n const custom = await loadCustomFieldSnapshot(em, {\n entityId: E.catalog.catalog_product_category,\n recordId: record.id,\n tenantId: record.tenantId,\n organizationId: record.organizationId,\n })\n return {\n id: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n name: record.name,\n slug: record.slug ?? null,\n description: record.description ?? null,\n parentId: record.parentId ?? null,\n rootId: record.rootId ?? null,\n treePath: record.treePath ?? null,\n depth: record.depth ?? 0,\n ancestorIds: Array.isArray(record.ancestorIds) ? [...record.ancestorIds] : [],\n childIds: Array.isArray(record.childIds) ? [...record.childIds] : [],\n descendantIds: Array.isArray(record.descendantIds) ? [...record.descendantIds] : [],\n isActive: !!record.isActive,\n createdAt: record.createdAt.toISOString(),\n updatedAt: record.updatedAt.toISOString(),\n custom: custom && Object.keys(custom).length ? custom : null,\n }\n}\n\nasync function assertParentScope(\n em: EntityManager,\n parentId: string | null,\n organizationId: string,\n tenantId: string\n): Promise<string | null> {\n if (!parentId) return null\n const parent = await em.findOne(CatalogProductCategory, {\n id: parentId,\n organizationId,\n tenantId,\n deletedAt: null,\n })\n if (!parent) {\n throw new CrudHttpError(400, { error: 'Parent category not found or inaccessible.' })\n }\n if (parent.id === parentId) return parent.id\n return String(parent.id)\n}\n\nfunction normalizeSlug(slug?: string | null): string | null {\n if (typeof slug !== 'string') return null\n const trimmed = slug.trim().toLowerCase()\n return trimmed.length ? trimmed : null\n}\n\nfunction categorySeedFromSnapshot(snapshot: CategorySnapshot): Record<string, unknown> {\n return {\n id: snapshot.id,\n organizationId: snapshot.organizationId,\n tenantId: snapshot.tenantId,\n name: snapshot.name,\n slug: snapshot.slug,\n description: snapshot.description,\n parentId: snapshot.parentId,\n rootId: snapshot.rootId,\n treePath: snapshot.treePath,\n depth: snapshot.depth,\n ancestorIds: snapshot.ancestorIds,\n childIds: snapshot.childIds,\n descendantIds: snapshot.descendantIds,\n isActive: snapshot.isActive,\n createdAt: new Date(snapshot.createdAt),\n updatedAt: new Date(snapshot.updatedAt),\n }\n}\n\nconst createCategoryCommand: CommandHandler<CategoryCreateInput, { categoryId: string }> = {\n id: 'catalog.categories.create',\n async execute(input, ctx) {\n const { parsed, custom } = parseWithCustomFields(categoryCreateSchema, input)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const slug = normalizeSlug(parsed.slug ?? null)\n if (slug) {\n const conflict = await em.findOne(CatalogProductCategory, {\n slug,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n deletedAt: null,\n })\n if (conflict) {\n throw new CrudHttpError(400, { error: 'Category slug already exists for this organization.' })\n }\n }\n const parentId = parsed.parentId ? String(parsed.parentId) : null\n const resolvedParent = await assertParentScope(em, parentId, parsed.organizationId, parsed.tenantId)\n\n const now = new Date()\n const record = em.create(CatalogProductCategory, {\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n name: parsed.name,\n slug,\n description: parsed.description?.trim()?.length ? parsed.description.trim() : null,\n parentId: resolvedParent,\n depth: 0,\n ancestorIds: [],\n childIds: [],\n descendantIds: [],\n isActive: parsed.isActive !== false,\n createdAt: now,\n updatedAt: now,\n })\n em.persist(record)\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n if (ctx.bulkImport?.skipDerivedRebuild) return\n await rebuildCategoryHierarchyForOrganization(em, record.organizationId, record.tenantId)\n },\n ],\n { transaction: true }\n )\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n values: custom,\n })\n const de = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'created',\n entity: record,\n identifiers: {\n id: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n },\n events: categoryCrudEvents,\n })\n return { categoryId: record.id }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadCategorySnapshot(em, result.categoryId)\n },\n buildLog: async ({ snapshots }) => {\n const after = snapshots.after as CategorySnapshot | undefined\n if (!after) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('catalog.audit.categories.create', 'Create catalog category'),\n resourceKind: 'catalog.category',\n resourceId: after.id,\n tenantId: after.tenantId,\n organizationId: after.organizationId,\n snapshotAfter: after,\n payload: {\n undo: { after } satisfies CategoryUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CategoryUndoPayload>(logEntry)\n const after = payload?.after\n if (!after) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const record = await em.findOne(CatalogProductCategory, { id: after.id })\n if (!record) return\n ensureTenantScope(ctx, record.tenantId)\n ensureOrganizationScope(ctx, record.organizationId)\n record.deletedAt = new Date()\n record.isActive = false\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n await rebuildCategoryHierarchyForOrganization(em, record.organizationId, record.tenantId)\n },\n ],\n { transaction: true }\n )\n const resetValues = buildCustomFieldResetMap(undefined, after.custom ?? undefined)\n if (Object.keys(resetValues).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: after.id,\n organizationId: after.organizationId,\n tenantId: after.tenantId,\n values: resetValues,\n })\n }\n },\n redo: makeCreateRedo<CatalogProductCategory, CategorySnapshot, CategoryCreateInput, { categoryId: string }>({\n entityClass: CatalogProductCategory,\n getSnapshotId: (snapshot) => snapshot.id,\n seedFromSnapshot: categorySeedFromSnapshot,\n buildResult: (entity) => ({ categoryId: entity.id }),\n events: categoryCrudEvents,\n afterRestore: async ({ em, ctx, entity, snapshot }) => {\n await rebuildCategoryHierarchyForOrganization(em, entity.organizationId, entity.tenantId)\n if (snapshot.custom && Object.keys(snapshot.custom).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: entity.id,\n organizationId: entity.organizationId,\n tenantId: entity.tenantId,\n values: snapshot.custom,\n })\n }\n },\n }),\n}\n\nconst updateCategoryCommand: CommandHandler<CategoryUpdateInput, { categoryId: string }> = {\n id: 'catalog.categories.update',\n async prepare(input, ctx) {\n const id = requireId(input, 'Category id is required')\n const em = ctx.container.resolve('em') as EntityManager\n const snapshot = await loadCategorySnapshot(em, id)\n if (snapshot) {\n ensureTenantScope(ctx, snapshot.tenantId)\n ensureOrganizationScope(ctx, snapshot.organizationId)\n }\n return snapshot ? { before: snapshot } : {}\n },\n async execute(input, ctx) {\n const { parsed, custom } = parseWithCustomFields(categoryUpdateSchema, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const record = await em.findOne(CatalogProductCategory, { id: parsed.id, deletedAt: null })\n if (!record) throw new CrudHttpError(404, { error: 'Catalog category not found' })\n ensureTenantScope(ctx, record.tenantId)\n ensureOrganizationScope(ctx, record.organizationId)\n\n if (parsed.name !== undefined) {\n record.name = parsed.name\n }\n\n if (parsed.slug !== undefined) {\n const slug = normalizeSlug(parsed.slug ?? null)\n if (slug !== record.slug) {\n if (slug) {\n const conflict = await em.findOne(CatalogProductCategory, {\n slug,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n deletedAt: null,\n id: { $ne: record.id },\n })\n if (conflict) {\n throw new CrudHttpError(400, { error: 'Category slug already exists.' })\n }\n }\n record.slug = slug\n }\n }\n\n if (parsed.description !== undefined) {\n record.description = parsed.description?.trim()?.length ? parsed.description.trim() : null\n }\n\n if (parsed.parentId !== undefined) {\n const requestedParent = parsed.parentId ? String(parsed.parentId) : null\n const safeParent = requestedParent && requestedParent !== record.id ? requestedParent : null\n record.parentId = await assertParentScope(em, safeParent, record.organizationId, record.tenantId)\n }\n\n if (parsed.isActive !== undefined) {\n record.isActive = parsed.isActive\n }\n\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n await rebuildCategoryHierarchyForOrganization(em, record.organizationId, record.tenantId)\n },\n ],\n { transaction: true }\n )\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n values: custom,\n })\n const de = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'updated',\n entity: record,\n identifiers: {\n id: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n },\n events: categoryCrudEvents,\n })\n return { categoryId: record.id }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadCategorySnapshot(em, result.categoryId)\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as CategorySnapshot | undefined\n const after = snapshots.after as CategorySnapshot | undefined\n if (!before || !after) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('catalog.audit.categories.update', 'Update catalog category'),\n resourceKind: 'catalog.category',\n resourceId: before.id,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n changes: buildChanges(before as Record<string, unknown>, after as Record<string, unknown>, CATEGORY_CHANGE_KEYS),\n payload: {\n undo: { before, after } satisfies CategoryUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CategoryUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let record = await em.findOne(CatalogProductCategory, { id: before.id })\n if (!record) {\n record = em.create(CatalogProductCategory, {\n id: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n name: before.name,\n slug: before.slug,\n description: before.description,\n parentId: before.parentId,\n rootId: before.rootId,\n treePath: before.treePath,\n depth: before.depth,\n ancestorIds: before.ancestorIds,\n childIds: before.childIds,\n descendantIds: before.descendantIds,\n isActive: before.isActive,\n createdAt: new Date(before.createdAt),\n updatedAt: new Date(before.updatedAt),\n })\n em.persist(record)\n } else {\n ensureTenantScope(ctx, before.tenantId)\n ensureOrganizationScope(ctx, before.organizationId)\n record.name = before.name\n record.slug = before.slug\n record.description = before.description\n record.parentId = before.parentId\n record.rootId = before.rootId\n record.treePath = before.treePath\n record.depth = before.depth\n record.ancestorIds = before.ancestorIds\n record.childIds = before.childIds\n record.descendantIds = before.descendantIds\n record.isActive = before.isActive\n record.deletedAt = null\n }\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n await rebuildCategoryHierarchyForOrganization(em, before.organizationId, before.tenantId)\n },\n ],\n { transaction: true }\n )\n const resetValues = buildCustomFieldResetMap(payload?.after?.custom ?? undefined, before.custom ?? undefined)\n if (Object.keys(resetValues).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n values: resetValues,\n })\n }\n },\n}\n\nconst deleteCategoryCommand: CommandHandler<{ id?: string }, { categoryId: string }> = {\n id: 'catalog.categories.delete',\n async prepare(input, ctx) {\n const id = requireId(input, 'Category id is required')\n const em = ctx.container.resolve('em') as EntityManager\n const snapshot = await loadCategorySnapshot(em, id)\n if (snapshot) {\n ensureTenantScope(ctx, snapshot.tenantId)\n ensureOrganizationScope(ctx, snapshot.organizationId)\n }\n return snapshot ? { before: snapshot } : {}\n },\n async execute(input, ctx) {\n const id = requireId(input, 'Category id is required')\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const record = await em.findOne(CatalogProductCategory, { id, deletedAt: null })\n if (!record) throw new CrudHttpError(404, { error: 'Catalog category not found' })\n ensureTenantScope(ctx, record.tenantId)\n ensureOrganizationScope(ctx, record.organizationId)\n const baseEm = ctx.container.resolve('em') as EntityManager\n const snapshot = await loadCategorySnapshot(baseEm, id)\n\n record.deletedAt = new Date()\n record.isActive = false\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n await rebuildCategoryHierarchyForOrganization(em, record.organizationId, record.tenantId)\n },\n ],\n { transaction: true }\n )\n if (snapshot?.custom && Object.keys(snapshot.custom).length) {\n const resetValues = buildCustomFieldResetMap(snapshot.custom, undefined)\n if (Object.keys(resetValues).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: snapshot.id,\n organizationId: snapshot.organizationId,\n tenantId: snapshot.tenantId,\n values: resetValues,\n })\n }\n }\n const de = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'deleted',\n entity: record,\n identifiers: {\n id: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n },\n events: categoryCrudEvents,\n })\n return { categoryId: record.id }\n },\n buildLog: async ({ ctx, snapshots }) => {\n const before = snapshots.before as CategorySnapshot | undefined\n if (!before) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('catalog.audit.categories.delete', 'Delete catalog category'),\n resourceKind: 'catalog.category',\n resourceId: before.id,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n snapshotBefore: before,\n payload: {\n undo: { before } satisfies CategoryUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CategoryUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let record = await em.findOne(CatalogProductCategory, { id: before.id })\n if (!record) {\n record = em.create(CatalogProductCategory, {\n id: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n name: before.name,\n slug: before.slug,\n description: before.description,\n parentId: before.parentId,\n rootId: before.rootId,\n treePath: before.treePath,\n depth: before.depth,\n ancestorIds: before.ancestorIds,\n childIds: before.childIds,\n descendantIds: before.descendantIds,\n isActive: before.isActive,\n createdAt: new Date(before.createdAt),\n updatedAt: new Date(before.updatedAt),\n })\n em.persist(record)\n } else {\n ensureTenantScope(ctx, before.tenantId)\n ensureOrganizationScope(ctx, before.organizationId)\n record.deletedAt = null\n record.isActive = before.isActive\n record.name = before.name\n record.slug = before.slug\n record.description = before.description\n record.parentId = before.parentId\n record.rootId = before.rootId\n record.treePath = before.treePath\n record.depth = before.depth\n record.ancestorIds = before.ancestorIds\n record.childIds = before.childIds\n record.descendantIds = before.descendantIds\n }\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n await rebuildCategoryHierarchyForOrganization(em, before.organizationId, before.tenantId)\n },\n ],\n { transaction: true }\n )\n if (before.custom && Object.keys(before.custom).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n values: before.custom,\n })\n }\n },\n}\n\nregisterCommand(createCategoryCommand)\nregisterCommand(updateCategoryCommand)\nregisterCommand(deleteCategoryCommand)\n"],
5
- "mappings": "AAAA,SAAS,uBAAuB;AAEhC,SAAS,cAAc,WAAW,uBAAuB,sBAAsB,2BAA2B;AAC1G,SAAS,yBAAyB,gCAAgC;AAClE,SAAS,uBAAuB;AAEhC,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC,SAAS,8BAA8B;AACvC;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AACP,SAAS,yBAAyB,mBAAmB,0BAA0B;AAC/E,SAAS,sBAAsB;AAC/B,SAAS,+CAA+C;AAGxD,SAAS,SAAS;AAElB,MAAM,qBAAuC;AAAA,EAC3C,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,cAAc,CAAC,SAAS;AAAA,IACtB,IAAI,IAAI,YAAY;AAAA,IACpB,gBAAgB,IAAI,YAAY;AAAA,IAChC,UAAU,IAAI,YAAY;AAAA,EAC5B;AACF;AA2BA,MAAM,uBAAuB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,eAAe,qBAAqB,IAAmB,IAA8C;AACnG,QAAM,SAAS,MAAM,GAAG,QAAQ,wBAAwB,EAAE,GAAG,CAAC;AAC9D,MAAI,CAAC,OAAQ,QAAO;AACpB,QAAM,SAAS,MAAM,wBAAwB,IAAI;AAAA,IAC/C,UAAU,EAAE,QAAQ;AAAA,IACpB,UAAU,OAAO;AAAA,IACjB,UAAU,OAAO;AAAA,IACjB,gBAAgB,OAAO;AAAA,EACzB,CAAC;AACD,SAAO;AAAA,IACL,IAAI,OAAO;AAAA,IACX,gBAAgB,OAAO;AAAA,IACvB,UAAU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AAW,OAAO;AACzB,aAAO,gBAAgB,OAAO;AAAA,IAChC;AACA,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,QACE,MAAM,GAAG,MAAM;AAAA,QACf,YAAY;AACV,gBAAM,wCAAwC,IAAI,OAAO,gBAAgB,OAAO,QAAQ;AAAA,QAC1F;AAAA,MACF;AAAA,MACA,EAAE,aAAa,KAAK;AAAA,IACtB;AACA,QAAI,OAAO,UAAU,OAAO,KAAK,OAAO,MAAM,EAAE,QAAQ;AACtD,YAAM,qBAAqB;AAAA,QACzB,YAAY,IAAI,UAAU,QAAQ,YAAY;AAAA,QAC9C,UAAU,EAAE,QAAQ;AAAA,QACpB,UAAU,OAAO;AAAA,QACjB,gBAAgB,OAAO;AAAA,QACvB,UAAU,OAAO;AAAA,QACjB,QAAQ,OAAO;AAAA,MACjB,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAEA,gBAAgB,qBAAqB;AACrC,gBAAgB,qBAAqB;AACrC,gBAAgB,qBAAqB;",
4
+ "sourcesContent": ["import { registerCommand } from '@open-mercato/shared/lib/commands'\nimport type { CommandHandler } from '@open-mercato/shared/lib/commands'\nimport { buildChanges, requireId, parseWithCustomFields, setCustomFieldsIfAny, emitCrudSideEffects } from '@open-mercato/shared/lib/commands/helpers'\nimport { loadCustomFieldSnapshot, buildCustomFieldResetMap } from '@open-mercato/shared/lib/commands/customFieldSnapshots'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CatalogProductCategory } from '../data/entities'\nimport {\n categoryCreateSchema,\n categoryUpdateSchema,\n type CategoryCreateInput,\n type CategoryUpdateInput,\n} from '../data/validators'\nimport { ensureOrganizationScope, ensureTenantScope, extractUndoPayload } from './shared'\nimport { makeCreateRedo } from '@open-mercato/shared/lib/commands/redo'\nimport { rebuildCategoryHierarchyForOrganization } from '../lib/categoryHierarchy'\nimport type { CrudEventsConfig } from '@open-mercato/shared/lib/crud/types'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport { E } from '#generated/entities.ids.generated'\n\nconst categoryCrudEvents: CrudEventsConfig = {\n module: 'catalog',\n entity: 'category',\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n}\n\ntype CategorySnapshot = {\n id: string\n organizationId: string\n tenantId: string\n name: string\n slug: string | null\n description: string | null\n parentId: string | null\n rootId: string | null\n treePath: string | null\n depth: number\n ancestorIds: string[]\n childIds: string[]\n descendantIds: string[]\n isActive: boolean\n createdAt: string\n updatedAt: string\n custom?: Record<string, unknown> | null\n}\n\ntype CategoryUndoPayload = {\n before?: CategorySnapshot | null\n after?: CategorySnapshot | null\n}\n\nconst CATEGORY_CHANGE_KEYS = [\n 'name',\n 'slug',\n 'description',\n 'parentId',\n 'rootId',\n 'treePath',\n 'isActive',\n] as const satisfies readonly string[]\n\nasync function loadCategorySnapshot(em: EntityManager, id: string): Promise<CategorySnapshot | null> {\n const record = await em.findOne(CatalogProductCategory, { id })\n if (!record) return null\n const custom = await loadCustomFieldSnapshot(em, {\n entityId: E.catalog.catalog_product_category,\n recordId: record.id,\n tenantId: record.tenantId,\n organizationId: record.organizationId,\n })\n return {\n id: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n name: record.name,\n slug: record.slug ?? null,\n description: record.description ?? null,\n parentId: record.parentId ?? null,\n rootId: record.rootId ?? null,\n treePath: record.treePath ?? null,\n depth: record.depth ?? 0,\n ancestorIds: Array.isArray(record.ancestorIds) ? [...record.ancestorIds] : [],\n childIds: Array.isArray(record.childIds) ? [...record.childIds] : [],\n descendantIds: Array.isArray(record.descendantIds) ? [...record.descendantIds] : [],\n isActive: !!record.isActive,\n createdAt: record.createdAt.toISOString(),\n updatedAt: record.updatedAt.toISOString(),\n custom: custom && Object.keys(custom).length ? custom : null,\n }\n}\n\nasync function assertParentScope(\n em: EntityManager,\n parentId: string | null,\n organizationId: string,\n tenantId: string\n): Promise<string | null> {\n if (!parentId) return null\n const parent = await em.findOne(CatalogProductCategory, {\n id: parentId,\n organizationId,\n tenantId,\n deletedAt: null,\n })\n if (!parent) {\n throw new CrudHttpError(400, { error: 'Parent category not found or inaccessible.' })\n }\n if (parent.id === parentId) return parent.id\n return String(parent.id)\n}\n\nfunction normalizeSlug(slug?: string | null): string | null {\n if (typeof slug !== 'string') return null\n const trimmed = slug.trim().toLowerCase()\n return trimmed.length ? trimmed : null\n}\n\nfunction categorySeedFromSnapshot(snapshot: CategorySnapshot): Record<string, unknown> {\n return {\n id: snapshot.id,\n organizationId: snapshot.organizationId,\n tenantId: snapshot.tenantId,\n name: snapshot.name,\n slug: snapshot.slug,\n description: snapshot.description,\n parentId: snapshot.parentId,\n rootId: snapshot.rootId,\n treePath: snapshot.treePath,\n depth: snapshot.depth,\n ancestorIds: snapshot.ancestorIds,\n childIds: snapshot.childIds,\n descendantIds: snapshot.descendantIds,\n isActive: snapshot.isActive,\n createdAt: new Date(snapshot.createdAt),\n updatedAt: new Date(snapshot.updatedAt),\n }\n}\n\nconst createCategoryCommand: CommandHandler<CategoryCreateInput, { categoryId: string }> = {\n id: 'catalog.categories.create',\n async execute(input, ctx) {\n const { parsed, custom } = parseWithCustomFields(categoryCreateSchema, input)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const slug = normalizeSlug(parsed.slug ?? null)\n if (slug) {\n const conflict = await em.findOne(CatalogProductCategory, {\n slug,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n deletedAt: null,\n })\n if (conflict) {\n throw new CrudHttpError(400, { error: 'Category slug already exists for this organization.' })\n }\n }\n const parentId = parsed.parentId ? String(parsed.parentId) : null\n const resolvedParent = await assertParentScope(em, parentId, parsed.organizationId, parsed.tenantId)\n\n const now = new Date()\n const record = em.create(CatalogProductCategory, {\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n name: parsed.name,\n slug,\n description: parsed.description?.trim()?.length ? parsed.description.trim() : null,\n parentId: resolvedParent,\n depth: 0,\n ancestorIds: [],\n childIds: [],\n descendantIds: [],\n isActive: parsed.isActive !== false,\n createdAt: now,\n updatedAt: now,\n })\n em.persist(record)\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n if (ctx.bulkImport?.skipDerivedRebuild) return\n await rebuildCategoryHierarchyForOrganization(em, record.organizationId, record.tenantId)\n },\n ],\n { transaction: true }\n )\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n values: custom,\n })\n const de = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'created',\n entity: record,\n identifiers: {\n id: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n },\n events: categoryCrudEvents,\n })\n return { categoryId: record.id }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadCategorySnapshot(em, result.categoryId)\n },\n buildLog: async ({ snapshots }) => {\n const after = snapshots.after as CategorySnapshot | undefined\n if (!after) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('catalog.audit.categories.create', 'Create catalog category'),\n resourceKind: 'catalog.category',\n resourceId: after.id,\n tenantId: after.tenantId,\n organizationId: after.organizationId,\n snapshotAfter: after,\n payload: {\n undo: { after } satisfies CategoryUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CategoryUndoPayload>(logEntry)\n const after = payload?.after\n if (!after) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const record = await em.findOne(CatalogProductCategory, { id: after.id })\n if (!record) return\n ensureTenantScope(ctx, record.tenantId)\n ensureOrganizationScope(ctx, record.organizationId)\n record.deletedAt = new Date()\n record.isActive = false\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n await rebuildCategoryHierarchyForOrganization(em, record.organizationId, record.tenantId)\n },\n ],\n { transaction: true }\n )\n const resetValues = buildCustomFieldResetMap(undefined, after.custom ?? undefined)\n if (Object.keys(resetValues).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: after.id,\n organizationId: after.organizationId,\n tenantId: after.tenantId,\n values: resetValues,\n })\n }\n },\n redo: makeCreateRedo<CatalogProductCategory, CategorySnapshot, CategoryCreateInput, { categoryId: string }>({\n entityClass: CatalogProductCategory,\n getSnapshotId: (snapshot) => snapshot.id,\n seedFromSnapshot: categorySeedFromSnapshot,\n buildResult: (entity) => ({ categoryId: entity.id }),\n events: categoryCrudEvents,\n afterRestore: async ({ em, ctx, entity, snapshot }) => {\n await rebuildCategoryHierarchyForOrganization(em, entity.organizationId, entity.tenantId)\n if (snapshot.custom && Object.keys(snapshot.custom).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: entity.id,\n organizationId: entity.organizationId,\n tenantId: entity.tenantId,\n values: snapshot.custom,\n })\n }\n },\n }),\n}\n\nconst updateCategoryCommand: CommandHandler<CategoryUpdateInput, { categoryId: string }> = {\n id: 'catalog.categories.update',\n async prepare(input, ctx) {\n const id = requireId(input, 'Category id is required')\n const em = ctx.container.resolve('em') as EntityManager\n const snapshot = await loadCategorySnapshot(em, id)\n if (snapshot) {\n ensureTenantScope(ctx, snapshot.tenantId)\n ensureOrganizationScope(ctx, snapshot.organizationId)\n }\n return snapshot ? { before: snapshot } : {}\n },\n async execute(input, ctx) {\n const { parsed, custom } = parseWithCustomFields(categoryUpdateSchema, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const record = await em.findOne(CatalogProductCategory, { id: parsed.id, deletedAt: null })\n if (!record) throw new CrudHttpError(404, { error: 'Catalog category not found' })\n ensureTenantScope(ctx, record.tenantId)\n ensureOrganizationScope(ctx, record.organizationId)\n\n if (parsed.name !== undefined) {\n record.name = parsed.name\n }\n\n if (parsed.slug !== undefined) {\n const slug = normalizeSlug(parsed.slug ?? null)\n if (slug !== record.slug) {\n if (slug) {\n const conflict = await em.findOne(CatalogProductCategory, {\n slug,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n deletedAt: null,\n id: { $ne: record.id },\n })\n if (conflict) {\n throw new CrudHttpError(400, { error: 'Category slug already exists.' })\n }\n }\n record.slug = slug\n }\n }\n\n if (parsed.description !== undefined) {\n record.description = parsed.description?.trim()?.length ? parsed.description.trim() : null\n }\n\n if (parsed.parentId !== undefined) {\n const requestedParent = parsed.parentId ? String(parsed.parentId) : null\n const safeParent = requestedParent && requestedParent !== record.id ? requestedParent : null\n record.parentId = await assertParentScope(em, safeParent, record.organizationId, record.tenantId)\n }\n\n if (parsed.isActive !== undefined) {\n record.isActive = parsed.isActive\n }\n\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n await rebuildCategoryHierarchyForOrganization(em, record.organizationId, record.tenantId)\n },\n ],\n { transaction: true }\n )\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n values: custom,\n })\n const de = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'updated',\n entity: record,\n identifiers: {\n id: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n },\n events: categoryCrudEvents,\n })\n return { categoryId: record.id }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadCategorySnapshot(em, result.categoryId)\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as CategorySnapshot | undefined\n const after = snapshots.after as CategorySnapshot | undefined\n if (!before || !after) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('catalog.audit.categories.update', 'Update catalog category'),\n resourceKind: 'catalog.category',\n resourceId: before.id,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n changes: buildChanges(before as Record<string, unknown>, after as Record<string, unknown>, CATEGORY_CHANGE_KEYS),\n payload: {\n undo: { before, after } satisfies CategoryUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CategoryUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let record = await em.findOne(CatalogProductCategory, { id: before.id })\n if (!record) {\n record = em.create(CatalogProductCategory, {\n id: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n name: before.name,\n slug: before.slug,\n description: before.description,\n parentId: before.parentId,\n rootId: before.rootId,\n treePath: before.treePath,\n depth: before.depth,\n ancestorIds: before.ancestorIds,\n childIds: before.childIds,\n descendantIds: before.descendantIds,\n isActive: before.isActive,\n createdAt: new Date(before.createdAt),\n updatedAt: new Date(before.updatedAt),\n })\n em.persist(record)\n } else {\n ensureTenantScope(ctx, before.tenantId)\n ensureOrganizationScope(ctx, before.organizationId)\n record.name = before.name\n record.slug = before.slug\n record.description = before.description\n record.parentId = before.parentId\n record.rootId = before.rootId\n record.treePath = before.treePath\n record.depth = before.depth\n record.ancestorIds = before.ancestorIds\n record.childIds = before.childIds\n record.descendantIds = before.descendantIds\n record.isActive = before.isActive\n record.deletedAt = null\n }\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n await rebuildCategoryHierarchyForOrganization(em, before.organizationId, before.tenantId)\n },\n ],\n { transaction: true }\n )\n const resetValues = buildCustomFieldResetMap(before.custom ?? undefined, payload?.after?.custom ?? undefined)\n if (Object.keys(resetValues).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n values: resetValues,\n })\n }\n },\n}\n\nconst deleteCategoryCommand: CommandHandler<{ id?: string }, { categoryId: string }> = {\n id: 'catalog.categories.delete',\n async prepare(input, ctx) {\n const id = requireId(input, 'Category id is required')\n const em = ctx.container.resolve('em') as EntityManager\n const snapshot = await loadCategorySnapshot(em, id)\n if (snapshot) {\n ensureTenantScope(ctx, snapshot.tenantId)\n ensureOrganizationScope(ctx, snapshot.organizationId)\n }\n return snapshot ? { before: snapshot } : {}\n },\n async execute(input, ctx) {\n const id = requireId(input, 'Category id is required')\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const record = await em.findOne(CatalogProductCategory, { id, deletedAt: null })\n if (!record) throw new CrudHttpError(404, { error: 'Catalog category not found' })\n ensureTenantScope(ctx, record.tenantId)\n ensureOrganizationScope(ctx, record.organizationId)\n const baseEm = ctx.container.resolve('em') as EntityManager\n const snapshot = await loadCategorySnapshot(baseEm, id)\n\n record.deletedAt = new Date()\n record.isActive = false\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n await rebuildCategoryHierarchyForOrganization(em, record.organizationId, record.tenantId)\n },\n ],\n { transaction: true }\n )\n if (snapshot?.custom && Object.keys(snapshot.custom).length) {\n const resetValues = buildCustomFieldResetMap(snapshot.custom, undefined)\n if (Object.keys(resetValues).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: snapshot.id,\n organizationId: snapshot.organizationId,\n tenantId: snapshot.tenantId,\n values: resetValues,\n })\n }\n }\n const de = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'deleted',\n entity: record,\n identifiers: {\n id: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n },\n events: categoryCrudEvents,\n })\n return { categoryId: record.id }\n },\n buildLog: async ({ ctx, snapshots }) => {\n const before = snapshots.before as CategorySnapshot | undefined\n if (!before) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('catalog.audit.categories.delete', 'Delete catalog category'),\n resourceKind: 'catalog.category',\n resourceId: before.id,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n snapshotBefore: before,\n payload: {\n undo: { before } satisfies CategoryUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CategoryUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let record = await em.findOne(CatalogProductCategory, { id: before.id })\n if (!record) {\n record = em.create(CatalogProductCategory, {\n id: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n name: before.name,\n slug: before.slug,\n description: before.description,\n parentId: before.parentId,\n rootId: before.rootId,\n treePath: before.treePath,\n depth: before.depth,\n ancestorIds: before.ancestorIds,\n childIds: before.childIds,\n descendantIds: before.descendantIds,\n isActive: before.isActive,\n createdAt: new Date(before.createdAt),\n updatedAt: new Date(before.updatedAt),\n })\n em.persist(record)\n } else {\n ensureTenantScope(ctx, before.tenantId)\n ensureOrganizationScope(ctx, before.organizationId)\n record.deletedAt = null\n record.isActive = before.isActive\n record.name = before.name\n record.slug = before.slug\n record.description = before.description\n record.parentId = before.parentId\n record.rootId = before.rootId\n record.treePath = before.treePath\n record.depth = before.depth\n record.ancestorIds = before.ancestorIds\n record.childIds = before.childIds\n record.descendantIds = before.descendantIds\n }\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n await rebuildCategoryHierarchyForOrganization(em, before.organizationId, before.tenantId)\n },\n ],\n { transaction: true }\n )\n if (before.custom && Object.keys(before.custom).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n values: before.custom,\n })\n }\n },\n}\n\nregisterCommand(createCategoryCommand)\nregisterCommand(updateCategoryCommand)\nregisterCommand(deleteCategoryCommand)\n"],
5
+ "mappings": "AAAA,SAAS,uBAAuB;AAEhC,SAAS,cAAc,WAAW,uBAAuB,sBAAsB,2BAA2B;AAC1G,SAAS,yBAAyB,gCAAgC;AAClE,SAAS,uBAAuB;AAEhC,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC,SAAS,8BAA8B;AACvC;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AACP,SAAS,yBAAyB,mBAAmB,0BAA0B;AAC/E,SAAS,sBAAsB;AAC/B,SAAS,+CAA+C;AAGxD,SAAS,SAAS;AAElB,MAAM,qBAAuC;AAAA,EAC3C,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,cAAc,CAAC,SAAS;AAAA,IACtB,IAAI,IAAI,YAAY;AAAA,IACpB,gBAAgB,IAAI,YAAY;AAAA,IAChC,UAAU,IAAI,YAAY;AAAA,EAC5B;AACF;AA2BA,MAAM,uBAAuB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,eAAe,qBAAqB,IAAmB,IAA8C;AACnG,QAAM,SAAS,MAAM,GAAG,QAAQ,wBAAwB,EAAE,GAAG,CAAC;AAC9D,MAAI,CAAC,OAAQ,QAAO;AACpB,QAAM,SAAS,MAAM,wBAAwB,IAAI;AAAA,IAC/C,UAAU,EAAE,QAAQ;AAAA,IACpB,UAAU,OAAO;AAAA,IACjB,UAAU,OAAO;AAAA,IACjB,gBAAgB,OAAO;AAAA,EACzB,CAAC;AACD,SAAO;AAAA,IACL,IAAI,OAAO;AAAA,IACX,gBAAgB,OAAO;AAAA,IACvB,UAAU,OAAO;AAAA,IACjB,MAAM,OAAO;AAAA,IACb,MAAM,OAAO,QAAQ;AAAA,IACrB,aAAa,OAAO,eAAe;AAAA,IAC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GAAG,MAAM;AAAA,QACf,YAAY;AACV,gBAAM,wCAAwC,IAAI,OAAO,gBAAgB,OAAO,QAAQ;AAAA,QAC1F;AAAA,MACF;AAAA,MACA,EAAE,aAAa,KAAK;AAAA,IACtB;AACA,QAAI,OAAO,UAAU,OAAO,KAAK,OAAO,MAAM,EAAE,QAAQ;AACtD,YAAM,qBAAqB;AAAA,QACzB,YAAY,IAAI,UAAU,QAAQ,YAAY;AAAA,QAC9C,UAAU,EAAE,QAAQ;AAAA,QACpB,UAAU,OAAO;AAAA,QACjB,gBAAgB,OAAO;AAAA,QACvB,UAAU,OAAO;AAAA,QACjB,QAAQ,OAAO;AAAA,MACjB,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAEA,gBAAgB,qBAAqB;AACrC,gBAAgB,qBAAqB;AACrC,gBAAgB,qBAAqB;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,389 @@
1
+ import { loadCustomFieldSnapshot } from "@open-mercato/shared/lib/commands/customFieldSnapshots";
2
+ import { setCustomFieldsIfAny } from "@open-mercato/shared/lib/commands/helpers";
3
+ import { findOneWithDecryption, findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
4
+ import { E } from "../../../generated/entities.ids.generated.js";
5
+ import {
6
+ CatalogOffer,
7
+ CatalogOptionSchemaTemplate,
8
+ CatalogPriceKind,
9
+ CatalogProduct,
10
+ CatalogProductPrice,
11
+ CatalogProductUnitConversion,
12
+ CatalogProductVariant
13
+ } from "../data/entities.js";
14
+ import { cloneJson, emitCatalogQueryIndexEvent } from "./shared.js";
15
+ function refId(ref) {
16
+ if (!ref) return null;
17
+ return typeof ref === "string" ? ref : ref.id;
18
+ }
19
+ function toIso(value) {
20
+ return value ? value.toISOString() : null;
21
+ }
22
+ function toDate(value) {
23
+ return value ? new Date(value) : null;
24
+ }
25
+ function isProductOwnedOptionSchemaTemplate(template) {
26
+ if (!template || typeof template === "string") return false;
27
+ const metadata = template.metadata;
28
+ if (!metadata || typeof metadata !== "object") return false;
29
+ const source = metadata.source;
30
+ return source === "product";
31
+ }
32
+ async function captureProductDeleteChildren(em, owner) {
33
+ const scope = { tenantId: owner.tenantId, organizationId: owner.organizationId };
34
+ const variantRecords = await findWithDecryption(em, CatalogProductVariant, { product: owner.id }, {}, scope);
35
+ const variantIds = variantRecords.map((variant) => variant.id);
36
+ const priceRecords = await findWithDecryption(
37
+ em,
38
+ CatalogProductPrice,
39
+ variantIds.length ? { $or: [{ variant: { $in: variantIds } }, { product: owner.id }] } : { product: owner.id },
40
+ {},
41
+ scope
42
+ );
43
+ const conversionRecords = await findWithDecryption(em, CatalogProductUnitConversion, { product: owner.id }, {}, scope);
44
+ const template = owner.optionSchemaId ? await findOneWithDecryption(em, CatalogOptionSchemaTemplate, { id: owner.optionSchemaId }, {}, scope) : null;
45
+ const variants = [];
46
+ for (const variant of variantRecords) {
47
+ const custom = await loadCustomFieldSnapshot(em, {
48
+ entityId: E.catalog.catalog_product_variant,
49
+ recordId: variant.id,
50
+ tenantId: variant.tenantId,
51
+ organizationId: variant.organizationId
52
+ });
53
+ variants.push({
54
+ id: variant.id,
55
+ productId: refId(variant.product) ?? owner.id,
56
+ name: variant.name ?? null,
57
+ sku: variant.sku ?? null,
58
+ barcode: variant.barcode ?? null,
59
+ gtinType: variant.gtinType ?? null,
60
+ hsCode: variant.hsCode ?? null,
61
+ statusEntryId: variant.statusEntryId ?? null,
62
+ isDefault: variant.isDefault,
63
+ isActive: variant.isActive,
64
+ weightValue: variant.weightValue ?? null,
65
+ weightUnit: variant.weightUnit ?? null,
66
+ dimensions: variant.dimensions ? cloneJson(variant.dimensions) : null,
67
+ metadata: variant.metadata ? cloneJson(variant.metadata) : null,
68
+ taxRateId: variant.taxRateId ?? null,
69
+ taxRate: variant.taxRate ?? null,
70
+ optionValues: variant.optionValues ? cloneJson(variant.optionValues) : null,
71
+ defaultMediaId: variant.defaultMediaId ?? null,
72
+ defaultMediaUrl: variant.defaultMediaUrl ?? null,
73
+ customFieldsetCode: variant.customFieldsetCode ?? null,
74
+ createdAt: variant.createdAt.toISOString(),
75
+ updatedAt: variant.updatedAt.toISOString(),
76
+ deletedAt: toIso(variant.deletedAt),
77
+ custom: Object.keys(custom).length ? custom : null
78
+ });
79
+ }
80
+ const prices = [];
81
+ for (const price of priceRecords) {
82
+ const priceKindId = refId(price.priceKind);
83
+ if (!priceKindId) throw new Error(`[internal] Catalog price ${price.id} has no price kind`);
84
+ prices.push({
85
+ id: price.id,
86
+ variantId: refId(price.variant),
87
+ productId: refId(price.product),
88
+ offerId: refId(price.offer),
89
+ priceKindId,
90
+ currencyCode: price.currencyCode,
91
+ kind: price.kind,
92
+ minQuantity: price.minQuantity,
93
+ maxQuantity: price.maxQuantity ?? null,
94
+ unitPriceNet: price.unitPriceNet ?? null,
95
+ unitPriceGross: price.unitPriceGross ?? null,
96
+ taxRate: price.taxRate ?? null,
97
+ taxAmount: price.taxAmount ?? null,
98
+ channelId: price.channelId ?? null,
99
+ userId: price.userId ?? null,
100
+ userGroupId: price.userGroupId ?? null,
101
+ customerId: price.customerId ?? null,
102
+ customerGroupId: price.customerGroupId ?? null,
103
+ metadata: price.metadata ? cloneJson(price.metadata) : null,
104
+ startsAt: toIso(price.startsAt),
105
+ endsAt: toIso(price.endsAt),
106
+ createdAt: price.createdAt.toISOString(),
107
+ updatedAt: price.updatedAt.toISOString()
108
+ });
109
+ }
110
+ const unitConversions = conversionRecords.map((conversion) => ({
111
+ id: conversion.id,
112
+ productId: refId(conversion.product) ?? owner.id,
113
+ unitCode: conversion.unitCode,
114
+ toBaseFactor: conversion.toBaseFactor,
115
+ sortOrder: conversion.sortOrder,
116
+ isActive: conversion.isActive,
117
+ metadata: conversion.metadata ? cloneJson(conversion.metadata) : null,
118
+ createdAt: conversion.createdAt.toISOString(),
119
+ updatedAt: conversion.updatedAt.toISOString(),
120
+ deletedAt: toIso(conversion.deletedAt)
121
+ }));
122
+ return {
123
+ variants,
124
+ prices,
125
+ unitConversions,
126
+ optionSchemaTemplate: isProductOwnedOptionSchemaTemplate(template) ? {
127
+ id: template.id,
128
+ name: template.name,
129
+ code: template.code,
130
+ description: template.description ?? null,
131
+ schema: cloneJson(template.schema),
132
+ metadata: template.metadata ? cloneJson(template.metadata) : null,
133
+ isActive: template.isActive,
134
+ createdAt: template.createdAt.toISOString(),
135
+ updatedAt: template.updatedAt.toISOString(),
136
+ deletedAt: toIso(template.deletedAt)
137
+ } : null
138
+ };
139
+ }
140
+ function restoreConflict(kind, id) {
141
+ return new Error(`[internal] Cannot restore catalog product ${kind} ${id}: it does not belong to the restored product`);
142
+ }
143
+ function sameScope(row, owner) {
144
+ return row.tenantId === owner.tenantId && row.organizationId === owner.organizationId;
145
+ }
146
+ function asList(value) {
147
+ return Array.isArray(value) ? value : [];
148
+ }
149
+ async function planProductDeleteChildrenRestore(em, owner, children) {
150
+ if (!children) return null;
151
+ const scope = { tenantId: owner.tenantId, organizationId: owner.organizationId };
152
+ const variantSnapshots = asList(children.variants);
153
+ const priceSnapshots = asList(children.prices);
154
+ const conversionSnapshots = asList(children.unitConversions);
155
+ const templateSnapshot = children.optionSchemaTemplate && children.optionSchemaTemplate.id === owner.optionSchemaId ? children.optionSchemaTemplate : null;
156
+ const ownVariantIds = new Set(variantSnapshots.map((variant) => variant.id));
157
+ const offerIds = new Set(owner.offerIds);
158
+ const priceOwned = (price) => price.variantId !== null && ownVariantIds.has(price.variantId) || price.productId === owner.id;
159
+ for (const variant of variantSnapshots) {
160
+ if (variant.productId !== owner.id) throw restoreConflict("variant", variant.id);
161
+ }
162
+ for (const conversion of conversionSnapshots) {
163
+ if (conversion.productId !== owner.id) throw restoreConflict("unit conversion", conversion.id);
164
+ }
165
+ for (const price of priceSnapshots) {
166
+ if (!priceOwned(price)) throw restoreConflict("price", price.id);
167
+ }
168
+ const foreignVariantIds = /* @__PURE__ */ new Set();
169
+ const foreignProductIds = /* @__PURE__ */ new Set();
170
+ const trackVariant = (id) => {
171
+ if (id && !ownVariantIds.has(id)) foreignVariantIds.add(id);
172
+ };
173
+ const trackProduct = (id) => {
174
+ if (id && id !== owner.id) foreignProductIds.add(id);
175
+ };
176
+ for (const price of priceSnapshots) {
177
+ trackVariant(price.variantId);
178
+ trackProduct(price.productId);
179
+ }
180
+ const existingVariants = variantSnapshots.length ? await findWithDecryption(em, CatalogProductVariant, { id: { $in: variantSnapshots.map((entry) => entry.id) } }, {}, scope) : [];
181
+ const existingPrices = priceSnapshots.length ? await findWithDecryption(em, CatalogProductPrice, { id: { $in: priceSnapshots.map((entry) => entry.id) } }, {}, scope) : [];
182
+ const existingConversions = conversionSnapshots.length ? await findWithDecryption(
183
+ em,
184
+ CatalogProductUnitConversion,
185
+ { id: { $in: conversionSnapshots.map((entry) => entry.id) } },
186
+ {},
187
+ scope
188
+ ) : [];
189
+ const existingTemplate = templateSnapshot ? await findOneWithDecryption(em, CatalogOptionSchemaTemplate, { id: templateSnapshot.id }, {}, scope) : null;
190
+ const foreignVariants = foreignVariantIds.size ? await findWithDecryption(
191
+ em,
192
+ CatalogProductVariant,
193
+ { id: { $in: Array.from(foreignVariantIds) }, tenantId: owner.tenantId, organizationId: owner.organizationId },
194
+ {},
195
+ scope
196
+ ) : [];
197
+ const foreignProducts = foreignProductIds.size ? await findWithDecryption(
198
+ em,
199
+ CatalogProduct,
200
+ { id: { $in: Array.from(foreignProductIds) }, tenantId: owner.tenantId, organizationId: owner.organizationId },
201
+ {},
202
+ scope
203
+ ) : [];
204
+ for (const variant of existingVariants) {
205
+ if (!sameScope(variant, owner) || refId(variant.product) !== owner.id) throw restoreConflict("variant", variant.id);
206
+ }
207
+ for (const conversion of existingConversions) {
208
+ if (!sameScope(conversion, owner) || refId(conversion.product) !== owner.id) {
209
+ throw restoreConflict("unit conversion", conversion.id);
210
+ }
211
+ }
212
+ for (const price of existingPrices) {
213
+ if (!sameScope(price, owner) || !priceOwned({ variantId: refId(price.variant), productId: refId(price.product) })) {
214
+ throw restoreConflict("price", price.id);
215
+ }
216
+ }
217
+ if (existingTemplate && !sameScope(existingTemplate, owner)) {
218
+ throw restoreConflict("option schema", existingTemplate.id);
219
+ }
220
+ const existingVariantIds = new Set(existingVariants.map((entry) => entry.id));
221
+ const existingPriceIds = new Set(existingPrices.map((entry) => entry.id));
222
+ const existingConversionIds = new Set(existingConversions.map((entry) => entry.id));
223
+ const availableForeignVariantIds = new Set(foreignVariants.map((entry) => entry.id));
224
+ const availableForeignProductIds = new Set(foreignProducts.map((entry) => entry.id));
225
+ const variantAvailable = (id) => id === null || ownVariantIds.has(id) || availableForeignVariantIds.has(id);
226
+ const productAvailable = (id) => id === null || id === owner.id || availableForeignProductIds.has(id);
227
+ return {
228
+ optionSchemaTemplate: templateSnapshot && !existingTemplate ? templateSnapshot : null,
229
+ unitConversions: conversionSnapshots.filter((entry) => !existingConversionIds.has(entry.id)),
230
+ variants: variantSnapshots.filter((entry) => !existingVariantIds.has(entry.id)),
231
+ prices: priceSnapshots.filter(
232
+ (entry) => !existingPriceIds.has(entry.id) && variantAvailable(entry.variantId) && productAvailable(entry.productId)
233
+ ).map((entry) => ({ ...entry, offerId: entry.offerId && offerIds.has(entry.offerId) ? entry.offerId : null }))
234
+ };
235
+ }
236
+ function restoreProductOptionSchemaTemplate(em, owner, plan) {
237
+ const snapshot = plan?.optionSchemaTemplate;
238
+ if (!snapshot) return;
239
+ const template = em.create(CatalogOptionSchemaTemplate, {
240
+ id: snapshot.id,
241
+ organizationId: owner.organizationId,
242
+ tenantId: owner.tenantId,
243
+ name: snapshot.name,
244
+ code: snapshot.code,
245
+ description: snapshot.description ?? null,
246
+ schema: cloneJson(snapshot.schema),
247
+ metadata: snapshot.metadata ? cloneJson(snapshot.metadata) : null,
248
+ isActive: snapshot.isActive,
249
+ createdAt: new Date(snapshot.createdAt),
250
+ updatedAt: new Date(snapshot.updatedAt),
251
+ deletedAt: toDate(snapshot.deletedAt)
252
+ });
253
+ em.persist(template);
254
+ }
255
+ function buildProductDeleteChildrenRestorePhases(em, owner, plan) {
256
+ if (!plan) return [];
257
+ const scope = { organizationId: owner.organizationId, tenantId: owner.tenantId };
258
+ let childEm = null;
259
+ const resolveChildEm = () => {
260
+ childEm ??= em.fork({ keepTransactionContext: true });
261
+ return childEm;
262
+ };
263
+ return [
264
+ async () => {
265
+ const target = resolveChildEm();
266
+ for (const snapshot of plan.unitConversions) {
267
+ target.persist(
268
+ target.create(CatalogProductUnitConversion, {
269
+ id: snapshot.id,
270
+ ...scope,
271
+ product: target.getReference(CatalogProduct, snapshot.productId),
272
+ unitCode: snapshot.unitCode,
273
+ toBaseFactor: snapshot.toBaseFactor,
274
+ sortOrder: snapshot.sortOrder,
275
+ isActive: snapshot.isActive,
276
+ metadata: snapshot.metadata ? cloneJson(snapshot.metadata) : null,
277
+ createdAt: new Date(snapshot.createdAt),
278
+ updatedAt: new Date(snapshot.updatedAt),
279
+ deletedAt: toDate(snapshot.deletedAt)
280
+ })
281
+ );
282
+ }
283
+ await target.flush();
284
+ },
285
+ async () => {
286
+ const target = resolveChildEm();
287
+ for (const snapshot of plan.variants) {
288
+ target.persist(
289
+ target.create(CatalogProductVariant, {
290
+ id: snapshot.id,
291
+ ...scope,
292
+ product: target.getReference(CatalogProduct, snapshot.productId),
293
+ name: snapshot.name ?? null,
294
+ sku: snapshot.sku ?? null,
295
+ barcode: snapshot.barcode ?? null,
296
+ gtinType: snapshot.gtinType ?? null,
297
+ hsCode: snapshot.hsCode ?? null,
298
+ statusEntryId: snapshot.statusEntryId ?? null,
299
+ isDefault: snapshot.isDefault,
300
+ isActive: snapshot.isActive,
301
+ weightValue: snapshot.weightValue ?? null,
302
+ weightUnit: snapshot.weightUnit ?? null,
303
+ dimensions: snapshot.dimensions ? cloneJson(snapshot.dimensions) : null,
304
+ metadata: snapshot.metadata ? cloneJson(snapshot.metadata) : null,
305
+ taxRateId: snapshot.taxRateId ?? null,
306
+ taxRate: snapshot.taxRate ?? null,
307
+ optionValues: snapshot.optionValues ? cloneJson(snapshot.optionValues) : null,
308
+ defaultMediaId: snapshot.defaultMediaId ?? null,
309
+ defaultMediaUrl: snapshot.defaultMediaUrl ?? null,
310
+ customFieldsetCode: snapshot.customFieldsetCode ?? null,
311
+ createdAt: new Date(snapshot.createdAt),
312
+ updatedAt: new Date(snapshot.updatedAt),
313
+ deletedAt: toDate(snapshot.deletedAt)
314
+ })
315
+ );
316
+ }
317
+ await target.flush();
318
+ },
319
+ async () => {
320
+ const target = resolveChildEm();
321
+ for (const snapshot of plan.prices) {
322
+ target.persist(
323
+ target.create(CatalogProductPrice, {
324
+ id: snapshot.id,
325
+ ...scope,
326
+ variant: snapshot.variantId ? target.getReference(CatalogProductVariant, snapshot.variantId) : null,
327
+ product: snapshot.productId ? target.getReference(CatalogProduct, snapshot.productId) : null,
328
+ offer: snapshot.offerId ? target.getReference(CatalogOffer, snapshot.offerId) : null,
329
+ priceKind: target.getReference(CatalogPriceKind, snapshot.priceKindId),
330
+ currencyCode: snapshot.currencyCode,
331
+ kind: snapshot.kind,
332
+ minQuantity: snapshot.minQuantity,
333
+ maxQuantity: snapshot.maxQuantity ?? null,
334
+ unitPriceNet: snapshot.unitPriceNet ?? null,
335
+ unitPriceGross: snapshot.unitPriceGross ?? null,
336
+ taxRate: snapshot.taxRate ?? null,
337
+ taxAmount: snapshot.taxAmount ?? null,
338
+ channelId: snapshot.channelId ?? null,
339
+ userId: snapshot.userId ?? null,
340
+ userGroupId: snapshot.userGroupId ?? null,
341
+ customerId: snapshot.customerId ?? null,
342
+ customerGroupId: snapshot.customerGroupId ?? null,
343
+ metadata: snapshot.metadata ? cloneJson(snapshot.metadata) : null,
344
+ startsAt: toDate(snapshot.startsAt),
345
+ endsAt: toDate(snapshot.endsAt),
346
+ createdAt: new Date(snapshot.createdAt),
347
+ updatedAt: new Date(snapshot.updatedAt)
348
+ })
349
+ );
350
+ }
351
+ await target.flush();
352
+ }
353
+ ];
354
+ }
355
+ async function emitProductDeleteChildrenRestoreSideEffects(opts) {
356
+ const { ctx, dataEngine, owner, children, plan } = opts;
357
+ const variants = asList(children?.variants);
358
+ const createdVariantIds = new Set(asList(plan?.variants).map((variant) => variant.id));
359
+ for (const variant of variants) {
360
+ if (!variant.custom || !Object.keys(variant.custom).length) continue;
361
+ await setCustomFieldsIfAny({
362
+ dataEngine,
363
+ entityId: E.catalog.catalog_product_variant,
364
+ recordId: variant.id,
365
+ organizationId: owner.organizationId,
366
+ tenantId: owner.tenantId,
367
+ values: variant.custom
368
+ });
369
+ }
370
+ for (const variant of variants) {
371
+ await emitCatalogQueryIndexEvent(ctx, {
372
+ entityType: E.catalog.catalog_product_variant,
373
+ recordId: variant.id,
374
+ organizationId: owner.organizationId,
375
+ tenantId: owner.tenantId,
376
+ action: "created",
377
+ ...createdVariantIds.has(variant.id) ? {} : { coverageBaseDelta: 0 }
378
+ });
379
+ }
380
+ }
381
+ export {
382
+ buildProductDeleteChildrenRestorePhases,
383
+ captureProductDeleteChildren,
384
+ emitProductDeleteChildrenRestoreSideEffects,
385
+ isProductOwnedOptionSchemaTemplate,
386
+ planProductDeleteChildrenRestore,
387
+ restoreProductOptionSchemaTemplate
388
+ };
389
+ //# sourceMappingURL=productDeleteChildren.js.map