@open-mercato/core 0.6.4-develop.4371.1.8f3030407e → 0.6.4

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 (1795) hide show
  1. package/.turbo/turbo-build.log +2 -2
  2. package/AGENTS.md +37 -0
  3. package/dist/generated/entities/channel_ingest_dead_letter/index.js +25 -0
  4. package/dist/generated/entities/channel_ingest_dead_letter/index.js.map +7 -0
  5. package/dist/generated/entities/channel_thread_mapping/index.js +25 -0
  6. package/dist/generated/entities/channel_thread_mapping/index.js.map +7 -0
  7. package/dist/generated/entities/channel_thread_token/index.js +17 -0
  8. package/dist/generated/entities/channel_thread_token/index.js.map +7 -0
  9. package/dist/generated/entities/communication_channel/index.js +43 -0
  10. package/dist/generated/entities/communication_channel/index.js.map +7 -0
  11. package/dist/generated/entities/customer_interaction/index.js +4 -0
  12. package/dist/generated/entities/customer_interaction/index.js.map +2 -2
  13. package/dist/generated/entities/customer_settings/index.js +2 -0
  14. package/dist/generated/entities/customer_settings/index.js.map +2 -2
  15. package/dist/generated/entities/dictionary/index.js +2 -0
  16. package/dist/generated/entities/dictionary/index.js.map +2 -2
  17. package/dist/generated/entities/external_conversation/index.js +25 -0
  18. package/dist/generated/entities/external_conversation/index.js.map +7 -0
  19. package/dist/generated/entities/external_message/index.js +25 -0
  20. package/dist/generated/entities/external_message/index.js.map +7 -0
  21. package/dist/generated/entities/inbox_settings/index.js +2 -0
  22. package/dist/generated/entities/inbox_settings/index.js.map +2 -2
  23. package/dist/generated/entities/integration_credentials/index.js +3 -1
  24. package/dist/generated/entities/integration_credentials/index.js.map +2 -2
  25. package/dist/generated/entities/message/index.js +2 -0
  26. package/dist/generated/entities/message/index.js.map +2 -2
  27. package/dist/generated/entities/message_channel_link/index.js +33 -0
  28. package/dist/generated/entities/message_channel_link/index.js.map +7 -0
  29. package/dist/generated/entities/message_reaction/index.js +25 -0
  30. package/dist/generated/entities/message_reaction/index.js.map +7 -0
  31. package/dist/generated/entities/role/index.js +3 -1
  32. package/dist/generated/entities/role/index.js.map +2 -2
  33. package/dist/generated/entities/step_instance/index.js +2 -0
  34. package/dist/generated/entities/step_instance/index.js.map +2 -2
  35. package/dist/generated/entities/user/index.js +3 -1
  36. package/dist/generated/entities/user/index.js.map +2 -2
  37. package/dist/generated/entities/user_task/index.js +2 -0
  38. package/dist/generated/entities/user_task/index.js.map +2 -2
  39. package/dist/generated/entities/workflow_branch_instance/index.js +39 -0
  40. package/dist/generated/entities/workflow_branch_instance/index.js.map +7 -0
  41. package/dist/generated/entities/workflow_event/index.js +2 -0
  42. package/dist/generated/entities/workflow_event/index.js.map +2 -2
  43. package/dist/generated/entities/workflow_instance/index.js +2 -0
  44. package/dist/generated/entities/workflow_instance/index.js.map +2 -2
  45. package/dist/generated/entities.ids.generated.js +12 -0
  46. package/dist/generated/entities.ids.generated.js.map +2 -2
  47. package/dist/generated/entity-fields-registry.js +146 -0
  48. package/dist/generated/entity-fields-registry.js.map +2 -2
  49. package/dist/helpers/integration/api.js +14 -1
  50. package/dist/helpers/integration/api.js.map +2 -2
  51. package/dist/helpers/integration/authFixtures.js +2 -1
  52. package/dist/helpers/integration/authFixtures.js.map +2 -2
  53. package/dist/helpers/integration/communicationChannelsFixtures.js +58 -0
  54. package/dist/helpers/integration/communicationChannelsFixtures.js.map +7 -0
  55. package/dist/helpers/integration/crudFormFields.js +33 -0
  56. package/dist/helpers/integration/crudFormFields.js.map +7 -0
  57. package/dist/helpers/integration/crudFormPersistence.js +107 -0
  58. package/dist/helpers/integration/crudFormPersistence.js.map +7 -0
  59. package/dist/helpers/integration/currenciesFixtures.js +52 -1
  60. package/dist/helpers/integration/currenciesFixtures.js.map +2 -2
  61. package/dist/helpers/integration/customerAccountsFixtures.js +124 -0
  62. package/dist/helpers/integration/customerAccountsFixtures.js.map +7 -0
  63. package/dist/helpers/integration/dbFixtures.js +9 -1
  64. package/dist/helpers/integration/dbFixtures.js.map +2 -2
  65. package/dist/helpers/integration/inboxFixtures.js +11 -0
  66. package/dist/helpers/integration/inboxFixtures.js.map +2 -2
  67. package/dist/helpers/integration/optimisticLockUi.js +104 -0
  68. package/dist/helpers/integration/optimisticLockUi.js.map +7 -0
  69. package/dist/helpers/integration/salesFixtures.js +17 -0
  70. package/dist/helpers/integration/salesFixtures.js.map +2 -2
  71. package/dist/helpers/integration/salesUi.js +17 -9
  72. package/dist/helpers/integration/salesUi.js.map +2 -2
  73. package/dist/helpers/integration/standaloneEnv.js +58 -0
  74. package/dist/helpers/integration/standaloneEnv.js.map +7 -0
  75. package/dist/helpers/integration/undoHarness.js +177 -0
  76. package/dist/helpers/integration/undoHarness.js.map +7 -0
  77. package/dist/helpers/integration/workflowsFixtures.js +161 -0
  78. package/dist/helpers/integration/workflowsFixtures.js.map +2 -2
  79. package/dist/modules/api_keys/backend/api-keys/page.js +18 -5
  80. package/dist/modules/api_keys/backend/api-keys/page.js.map +2 -2
  81. package/dist/modules/api_keys/data/validators.js +3 -1
  82. package/dist/modules/api_keys/data/validators.js.map +2 -2
  83. package/dist/modules/attachments/components/AttachmentPartitionSettings.js +17 -9
  84. package/dist/modules/attachments/components/AttachmentPartitionSettings.js.map +2 -2
  85. package/dist/modules/attachments/lib/ocrQueue.js +6 -1
  86. package/dist/modules/attachments/lib/ocrQueue.js.map +2 -2
  87. package/dist/modules/attachments/lib/security.js +1 -1
  88. package/dist/modules/attachments/lib/security.js.map +2 -2
  89. package/dist/modules/audit_logs/api/audit-logs/actions/redo/route.js +4 -2
  90. package/dist/modules/audit_logs/api/audit-logs/actions/redo/route.js.map +2 -2
  91. package/dist/modules/audit_logs/api/audit-logs/actions/undo/route.js +3 -2
  92. package/dist/modules/audit_logs/api/audit-logs/actions/undo/route.js.map +2 -2
  93. package/dist/modules/audit_logs/data/entities.js.map +1 -1
  94. package/dist/modules/audit_logs/services/actionLogService.js +16 -0
  95. package/dist/modules/audit_logs/services/actionLogService.js.map +2 -2
  96. package/dist/modules/auth/api/logout.js +0 -12
  97. package/dist/modules/auth/api/logout.js.map +2 -2
  98. package/dist/modules/auth/api/roles/acl/route.js +32 -13
  99. package/dist/modules/auth/api/roles/acl/route.js.map +2 -2
  100. package/dist/modules/auth/api/roles/route.js +52 -3
  101. package/dist/modules/auth/api/roles/route.js.map +2 -2
  102. package/dist/modules/auth/api/sidebar/preferences/route.js +73 -4
  103. package/dist/modules/auth/api/sidebar/preferences/route.js.map +2 -2
  104. package/dist/modules/auth/api/users/acl/route.js +88 -34
  105. package/dist/modules/auth/api/users/acl/route.js.map +2 -2
  106. package/dist/modules/auth/api/users/consents/route.js +17 -0
  107. package/dist/modules/auth/api/users/consents/route.js.map +2 -2
  108. package/dist/modules/auth/api/users/resend-invite/route.js +18 -0
  109. package/dist/modules/auth/api/users/resend-invite/route.js.map +2 -2
  110. package/dist/modules/auth/api/users/route.js +40 -2
  111. package/dist/modules/auth/api/users/route.js.map +2 -2
  112. package/dist/modules/auth/backend/roles/[id]/edit/page.js +24 -4
  113. package/dist/modules/auth/backend/roles/[id]/edit/page.js.map +2 -2
  114. package/dist/modules/auth/backend/roles/page.js +17 -4
  115. package/dist/modules/auth/backend/roles/page.js.map +2 -2
  116. package/dist/modules/auth/backend/users/[id]/edit/page.js +72 -7
  117. package/dist/modules/auth/backend/users/[id]/edit/page.js.map +2 -2
  118. package/dist/modules/auth/backend/users/page.js +15 -2
  119. package/dist/modules/auth/backend/users/page.js.map +2 -2
  120. package/dist/modules/auth/cli.js +19 -21
  121. package/dist/modules/auth/cli.js.map +2 -2
  122. package/dist/modules/auth/commands/roles.js +78 -1
  123. package/dist/modules/auth/commands/roles.js.map +2 -2
  124. package/dist/modules/auth/commands/users.js +106 -6
  125. package/dist/modules/auth/commands/users.js.map +3 -3
  126. package/dist/modules/auth/components/AclEditor.js +3 -1
  127. package/dist/modules/auth/components/AclEditor.js.map +2 -2
  128. package/dist/modules/auth/data/entities.js +6 -0
  129. package/dist/modules/auth/data/entities.js.map +2 -2
  130. package/dist/modules/auth/frontend/reset/[token]/page.js +6 -2
  131. package/dist/modules/auth/frontend/reset/[token]/page.js.map +2 -2
  132. package/dist/modules/auth/lib/consentIntegrity.js +15 -2
  133. package/dist/modules/auth/lib/consentIntegrity.js.map +2 -2
  134. package/dist/modules/auth/lib/emailHash.js +6 -2
  135. package/dist/modules/auth/lib/emailHash.js.map +2 -2
  136. package/dist/modules/auth/lib/grantChecks.js +44 -1
  137. package/dist/modules/auth/lib/grantChecks.js.map +2 -2
  138. package/dist/modules/auth/lib/sessionIntegrity.js +11 -1
  139. package/dist/modules/auth/lib/sessionIntegrity.js.map +2 -2
  140. package/dist/modules/auth/services/authService.js +10 -19
  141. package/dist/modules/auth/services/authService.js.map +2 -2
  142. package/dist/modules/auth/services/sidebarPreferencesService.js +32 -4
  143. package/dist/modules/auth/services/sidebarPreferencesService.js.map +2 -2
  144. package/dist/modules/business_rules/api/rules/route.js +28 -0
  145. package/dist/modules/business_rules/api/rules/route.js.map +2 -2
  146. package/dist/modules/business_rules/api/sets/route.js +28 -0
  147. package/dist/modules/business_rules/api/sets/route.js.map +2 -2
  148. package/dist/modules/business_rules/backend/rules/[id]/page.js +11 -4
  149. package/dist/modules/business_rules/backend/rules/[id]/page.js.map +3 -3
  150. package/dist/modules/business_rules/backend/rules/page.js +30 -12
  151. package/dist/modules/business_rules/backend/rules/page.js.map +2 -2
  152. package/dist/modules/business_rules/backend/sets/[id]/page.js +11 -4
  153. package/dist/modules/business_rules/backend/sets/[id]/page.js.map +2 -2
  154. package/dist/modules/business_rules/backend/sets/page.js +29 -11
  155. package/dist/modules/business_rules/backend/sets/page.js.map +2 -2
  156. package/dist/modules/catalog/api/categories/route.js +2 -0
  157. package/dist/modules/catalog/api/categories/route.js.map +2 -2
  158. package/dist/modules/catalog/api/products/route.js +2 -1
  159. package/dist/modules/catalog/api/products/route.js.map +2 -2
  160. package/dist/modules/catalog/backend/catalog/categories/[id]/edit/page.js +2 -0
  161. package/dist/modules/catalog/backend/catalog/categories/[id]/edit/page.js.map +2 -2
  162. package/dist/modules/catalog/backend/catalog/products/[id]/page.js +138 -75
  163. package/dist/modules/catalog/backend/catalog/products/[id]/page.js.map +2 -2
  164. package/dist/modules/catalog/backend/catalog/products/[productId]/variants/[variantId]/page.js +87 -24
  165. package/dist/modules/catalog/backend/catalog/products/[productId]/variants/[variantId]/page.js.map +2 -2
  166. package/dist/modules/catalog/backend/catalog/products/[productId]/variants/create/page.js +18 -3
  167. package/dist/modules/catalog/backend/catalog/products/[productId]/variants/create/page.js.map +2 -2
  168. package/dist/modules/catalog/backend/catalog/products/create/page.js +4 -17
  169. package/dist/modules/catalog/backend/catalog/products/create/page.js.map +2 -2
  170. package/dist/modules/catalog/backend/catalog/products/optionSchemaClient.js.map +2 -2
  171. package/dist/modules/catalog/commands/categories.js +42 -1
  172. package/dist/modules/catalog/commands/categories.js.map +2 -2
  173. package/dist/modules/catalog/commands/offers.js +44 -1
  174. package/dist/modules/catalog/commands/offers.js.map +2 -2
  175. package/dist/modules/catalog/commands/optionSchemas.js +6 -1
  176. package/dist/modules/catalog/commands/optionSchemas.js.map +2 -2
  177. package/dist/modules/catalog/commands/priceKinds.js +6 -1
  178. package/dist/modules/catalog/commands/priceKinds.js.map +2 -2
  179. package/dist/modules/catalog/commands/prices.js +50 -1
  180. package/dist/modules/catalog/commands/prices.js.map +2 -2
  181. package/dist/modules/catalog/commands/productUnitConversions.js +25 -1
  182. package/dist/modules/catalog/commands/productUnitConversions.js.map +2 -2
  183. package/dist/modules/catalog/commands/products.js +84 -0
  184. package/dist/modules/catalog/commands/products.js.map +2 -2
  185. package/dist/modules/catalog/commands/variants.js +117 -31
  186. package/dist/modules/catalog/commands/variants.js.map +2 -2
  187. package/dist/modules/catalog/components/PriceKindSettings.js +14 -6
  188. package/dist/modules/catalog/components/PriceKindSettings.js.map +2 -2
  189. package/dist/modules/catalog/components/categories/CategoriesDataTable.js +9 -0
  190. package/dist/modules/catalog/components/categories/CategoriesDataTable.js.map +2 -2
  191. package/dist/modules/catalog/components/products/ProductMediaManager.js.map +2 -2
  192. package/dist/modules/catalog/components/products/ProductsDataTable.js +14 -3
  193. package/dist/modules/catalog/components/products/ProductsDataTable.js.map +2 -2
  194. package/dist/modules/catalog/components/products/VariantBuilder.js +38 -11
  195. package/dist/modules/catalog/components/products/VariantBuilder.js.map +2 -2
  196. package/dist/modules/catalog/components/products/productForm.js +21 -0
  197. package/dist/modules/catalog/components/products/productForm.js.map +2 -2
  198. package/dist/modules/catalog/components/products/variantForm.js +2 -1
  199. package/dist/modules/catalog/components/products/variantForm.js.map +2 -2
  200. package/dist/modules/catalog/lib/pricing.js +3 -0
  201. package/dist/modules/catalog/lib/pricing.js.map +2 -2
  202. package/dist/modules/communication_channels/acl.js +47 -0
  203. package/dist/modules/communication_channels/acl.js.map +7 -0
  204. package/dist/modules/communication_channels/api/delete/channels/[id]/route.js +133 -0
  205. package/dist/modules/communication_channels/api/delete/channels/[id]/route.js.map +7 -0
  206. package/dist/modules/communication_channels/api/delete/messages/[messageId]/reactions/[reactionId]/route.js +113 -0
  207. package/dist/modules/communication_channels/api/delete/messages/[messageId]/reactions/[reactionId]/route.js.map +7 -0
  208. package/dist/modules/communication_channels/api/get/channels/[id]/health/route.js +138 -0
  209. package/dist/modules/communication_channels/api/get/channels/[id]/health/route.js.map +7 -0
  210. package/dist/modules/communication_channels/api/get/channels/[id]/route.js +93 -0
  211. package/dist/modules/communication_channels/api/get/channels/[id]/route.js.map +7 -0
  212. package/dist/modules/communication_channels/api/get/channels/route.js +96 -0
  213. package/dist/modules/communication_channels/api/get/channels/route.js.map +7 -0
  214. package/dist/modules/communication_channels/api/get/me/channels/route.js +82 -0
  215. package/dist/modules/communication_channels/api/get/me/channels/route.js.map +7 -0
  216. package/dist/modules/communication_channels/api/get/oauth/[provider]/callback/route.js +274 -0
  217. package/dist/modules/communication_channels/api/get/oauth/[provider]/callback/route.js.map +7 -0
  218. package/dist/modules/communication_channels/api/post/channels/[id]/import-history/route.js +168 -0
  219. package/dist/modules/communication_channels/api/post/channels/[id]/import-history/route.js.map +7 -0
  220. package/dist/modules/communication_channels/api/post/channels/[id]/poll-now/route.js +143 -0
  221. package/dist/modules/communication_channels/api/post/channels/[id]/poll-now/route.js.map +7 -0
  222. package/dist/modules/communication_channels/api/post/channels/[id]/push/register/route.js +127 -0
  223. package/dist/modules/communication_channels/api/post/channels/[id]/push/register/route.js.map +7 -0
  224. package/dist/modules/communication_channels/api/post/channels/[id]/set-primary/route.js +99 -0
  225. package/dist/modules/communication_channels/api/post/channels/[id]/set-primary/route.js.map +7 -0
  226. package/dist/modules/communication_channels/api/post/channels/[id]/test-send/route.js +197 -0
  227. package/dist/modules/communication_channels/api/post/channels/[id]/test-send/route.js.map +7 -0
  228. package/dist/modules/communication_channels/api/post/channels/connect/credentials/route.js +124 -0
  229. package/dist/modules/communication_channels/api/post/channels/connect/credentials/route.js.map +7 -0
  230. package/dist/modules/communication_channels/api/post/messages/[messageId]/reactions/route.js +120 -0
  231. package/dist/modules/communication_channels/api/post/messages/[messageId]/reactions/route.js.map +7 -0
  232. package/dist/modules/communication_channels/api/post/oauth/[provider]/initiate/route.js +157 -0
  233. package/dist/modules/communication_channels/api/post/oauth/[provider]/initiate/route.js.map +7 -0
  234. package/dist/modules/communication_channels/api/post/send-as-user/route.js +115 -0
  235. package/dist/modules/communication_channels/api/post/send-as-user/route.js.map +7 -0
  236. package/dist/modules/communication_channels/api/post/test-seed/route.js +238 -0
  237. package/dist/modules/communication_channels/api/post/test-seed/route.js.map +7 -0
  238. package/dist/modules/communication_channels/api/post/webhook/[provider]/route.js +175 -0
  239. package/dist/modules/communication_channels/api/post/webhook/[provider]/route.js.map +7 -0
  240. package/dist/modules/communication_channels/api/post/webhooks/gmail/route.js +123 -0
  241. package/dist/modules/communication_channels/api/post/webhooks/gmail/route.js.map +7 -0
  242. package/dist/modules/communication_channels/api/put/threads/[threadId]/assign/route.js +117 -0
  243. package/dist/modules/communication_channels/api/put/threads/[threadId]/assign/route.js.map +7 -0
  244. package/dist/modules/communication_channels/backend/communication_channels/channels/[id]/page.js +180 -0
  245. package/dist/modules/communication_channels/backend/communication_channels/channels/[id]/page.js.map +7 -0
  246. package/dist/modules/communication_channels/backend/communication_channels/channels/[id]/page.meta.js +36 -0
  247. package/dist/modules/communication_channels/backend/communication_channels/channels/[id]/page.meta.js.map +7 -0
  248. package/dist/modules/communication_channels/backend/communication_channels/channels/page.js +107 -0
  249. package/dist/modules/communication_channels/backend/communication_channels/channels/page.js.map +7 -0
  250. package/dist/modules/communication_channels/backend/communication_channels/channels/page.meta.js +38 -0
  251. package/dist/modules/communication_channels/backend/communication_channels/channels/page.meta.js.map +7 -0
  252. package/dist/modules/communication_channels/backend/profile/communication-channels/page.js +732 -0
  253. package/dist/modules/communication_channels/backend/profile/communication-channels/page.js.map +7 -0
  254. package/dist/modules/communication_channels/backend/profile/communication-channels/page.meta.js +38 -0
  255. package/dist/modules/communication_channels/backend/profile/communication-channels/page.meta.js.map +7 -0
  256. package/dist/modules/communication_channels/commands/connect-credential-channel.js +154 -0
  257. package/dist/modules/communication_channels/commands/connect-credential-channel.js.map +7 -0
  258. package/dist/modules/communication_channels/commands/delete-channel.js +137 -0
  259. package/dist/modules/communication_channels/commands/delete-channel.js.map +7 -0
  260. package/dist/modules/communication_channels/commands/deliver-outbound-message.js +400 -0
  261. package/dist/modules/communication_channels/commands/deliver-outbound-message.js.map +7 -0
  262. package/dist/modules/communication_channels/commands/disconnect-channel.js +163 -0
  263. package/dist/modules/communication_channels/commands/disconnect-channel.js.map +7 -0
  264. package/dist/modules/communication_channels/commands/ingest-inbound-message.js +413 -0
  265. package/dist/modules/communication_channels/commands/ingest-inbound-message.js.map +7 -0
  266. package/dist/modules/communication_channels/commands/interceptors.js +68 -0
  267. package/dist/modules/communication_channels/commands/interceptors.js.map +7 -0
  268. package/dist/modules/communication_channels/commands/process-inbound-reaction.js +198 -0
  269. package/dist/modules/communication_channels/commands/process-inbound-reaction.js.map +7 -0
  270. package/dist/modules/communication_channels/commands/push-register.js +146 -0
  271. package/dist/modules/communication_channels/commands/push-register.js.map +7 -0
  272. package/dist/modules/communication_channels/commands/push-renew.js +23 -0
  273. package/dist/modules/communication_channels/commands/push-renew.js.map +7 -0
  274. package/dist/modules/communication_channels/commands/push-unregister.js +108 -0
  275. package/dist/modules/communication_channels/commands/push-unregister.js.map +7 -0
  276. package/dist/modules/communication_channels/commands/queue-import-history.js +113 -0
  277. package/dist/modules/communication_channels/commands/queue-import-history.js.map +7 -0
  278. package/dist/modules/communication_channels/commands/reassign-conversation.js +193 -0
  279. package/dist/modules/communication_channels/commands/reassign-conversation.js.map +7 -0
  280. package/dist/modules/communication_channels/commands/set-primary-channel.js +115 -0
  281. package/dist/modules/communication_channels/commands/set-primary-channel.js.map +7 -0
  282. package/dist/modules/communication_channels/commands/toggle-outbound-reaction.js +260 -0
  283. package/dist/modules/communication_channels/commands/toggle-outbound-reaction.js.map +7 -0
  284. package/dist/modules/communication_channels/data/enrichers.js +286 -0
  285. package/dist/modules/communication_channels/data/enrichers.js.map +7 -0
  286. package/dist/modules/communication_channels/data/entities.js +447 -0
  287. package/dist/modules/communication_channels/data/entities.js.map +7 -0
  288. package/dist/modules/communication_channels/data/extensions.js +67 -0
  289. package/dist/modules/communication_channels/data/extensions.js.map +7 -0
  290. package/dist/modules/communication_channels/data/validators.js +123 -0
  291. package/dist/modules/communication_channels/data/validators.js.map +7 -0
  292. package/dist/modules/communication_channels/di.js +35 -0
  293. package/dist/modules/communication_channels/di.js.map +7 -0
  294. package/dist/modules/communication_channels/encryption.js +12 -0
  295. package/dist/modules/communication_channels/encryption.js.map +7 -0
  296. package/dist/modules/communication_channels/events.js +124 -0
  297. package/dist/modules/communication_channels/events.js.map +7 -0
  298. package/dist/modules/communication_channels/index.js +20 -0
  299. package/dist/modules/communication_channels/index.js.map +7 -0
  300. package/dist/modules/communication_channels/lib/access-control.js +43 -0
  301. package/dist/modules/communication_channels/lib/access-control.js.map +7 -0
  302. package/dist/modules/communication_channels/lib/adapter-compat.js +36 -0
  303. package/dist/modules/communication_channels/lib/adapter-compat.js.map +7 -0
  304. package/dist/modules/communication_channels/lib/adapter-registry-singleton.js +22 -0
  305. package/dist/modules/communication_channels/lib/adapter-registry-singleton.js.map +7 -0
  306. package/dist/modules/communication_channels/lib/adapter.js +1 -0
  307. package/dist/modules/communication_channels/lib/adapter.js.map +7 -0
  308. package/dist/modules/communication_channels/lib/connect-channel.js +95 -0
  309. package/dist/modules/communication_channels/lib/connect-channel.js.map +7 -0
  310. package/dist/modules/communication_channels/lib/contact-resolver.js +79 -0
  311. package/dist/modules/communication_channels/lib/contact-resolver.js.map +7 -0
  312. package/dist/modules/communication_channels/lib/credential-refresh.js +97 -0
  313. package/dist/modules/communication_channels/lib/credential-refresh.js.map +7 -0
  314. package/dist/modules/communication_channels/lib/dead-letter.js +62 -0
  315. package/dist/modules/communication_channels/lib/dead-letter.js.map +7 -0
  316. package/dist/modules/communication_channels/lib/email-capabilities.js +47 -0
  317. package/dist/modules/communication_channels/lib/email-capabilities.js.map +7 -0
  318. package/dist/modules/communication_channels/lib/email-contact.js +14 -0
  319. package/dist/modules/communication_channels/lib/email-contact.js.map +7 -0
  320. package/dist/modules/communication_channels/lib/email-mime.js +299 -0
  321. package/dist/modules/communication_channels/lib/email-mime.js.map +7 -0
  322. package/dist/modules/communication_channels/lib/error-classification.js +101 -0
  323. package/dist/modules/communication_channels/lib/error-classification.js.map +7 -0
  324. package/dist/modules/communication_channels/lib/gmail-pubsub-jwt.js +185 -0
  325. package/dist/modules/communication_channels/lib/gmail-pubsub-jwt.js.map +7 -0
  326. package/dist/modules/communication_channels/lib/mutation-guards.js +114 -0
  327. package/dist/modules/communication_channels/lib/mutation-guards.js.map +7 -0
  328. package/dist/modules/communication_channels/lib/oauth-client-config.js +32 -0
  329. package/dist/modules/communication_channels/lib/oauth-client-config.js.map +7 -0
  330. package/dist/modules/communication_channels/lib/oauth-state.js +128 -0
  331. package/dist/modules/communication_channels/lib/oauth-state.js.map +7 -0
  332. package/dist/modules/communication_channels/lib/oauth-token.js +45 -0
  333. package/dist/modules/communication_channels/lib/oauth-token.js.map +7 -0
  334. package/dist/modules/communication_channels/lib/pg-errors.js +11 -0
  335. package/dist/modules/communication_channels/lib/pg-errors.js.map +7 -0
  336. package/dist/modules/communication_channels/lib/provider-health.js +24 -0
  337. package/dist/modules/communication_channels/lib/provider-health.js.map +7 -0
  338. package/dist/modules/communication_channels/lib/push-state.js +19 -0
  339. package/dist/modules/communication_channels/lib/push-state.js.map +7 -0
  340. package/dist/modules/communication_channels/lib/queue.js +54 -0
  341. package/dist/modules/communication_channels/lib/queue.js.map +7 -0
  342. package/dist/modules/communication_channels/lib/reaction-processor-types.js +5 -0
  343. package/dist/modules/communication_channels/lib/reaction-processor-types.js.map +7 -0
  344. package/dist/modules/communication_channels/lib/reaction-semantics.js +11 -0
  345. package/dist/modules/communication_channels/lib/reaction-semantics.js.map +7 -0
  346. package/dist/modules/communication_channels/lib/registry.js +67 -0
  347. package/dist/modules/communication_channels/lib/registry.js.map +7 -0
  348. package/dist/modules/communication_channels/lib/route-mutation-guard.js +43 -0
  349. package/dist/modules/communication_channels/lib/route-mutation-guard.js.map +7 -0
  350. package/dist/modules/communication_channels/lib/sanitize-channel-html.js +96 -0
  351. package/dist/modules/communication_channels/lib/sanitize-channel-html.js.map +7 -0
  352. package/dist/modules/communication_channels/lib/send-as-user.js +194 -0
  353. package/dist/modules/communication_channels/lib/send-as-user.js.map +7 -0
  354. package/dist/modules/communication_channels/lib/system-user.js +22 -0
  355. package/dist/modules/communication_channels/lib/system-user.js.map +7 -0
  356. package/dist/modules/communication_channels/lib/test-seed.js +68 -0
  357. package/dist/modules/communication_channels/lib/test-seed.js.map +7 -0
  358. package/dist/modules/communication_channels/lib/thread-matcher.js +263 -0
  359. package/dist/modules/communication_channels/lib/thread-matcher.js.map +7 -0
  360. package/dist/modules/communication_channels/lib/thread-token.js +219 -0
  361. package/dist/modules/communication_channels/lib/thread-token.js.map +7 -0
  362. package/dist/modules/communication_channels/lib/use-connect-channel.js +61 -0
  363. package/dist/modules/communication_channels/lib/use-connect-channel.js.map +7 -0
  364. package/dist/modules/communication_channels/migrations/Migration20260526134719_communication_channels.js +50 -0
  365. package/dist/modules/communication_channels/migrations/Migration20260526134719_communication_channels.js.map +7 -0
  366. package/dist/modules/communication_channels/migrations/Migration20260527195446_communication_channels.js +19 -0
  367. package/dist/modules/communication_channels/migrations/Migration20260527195446_communication_channels.js.map +7 -0
  368. package/dist/modules/communication_channels/migrations/Migration20260529231848_communication_channels.js +13 -0
  369. package/dist/modules/communication_channels/migrations/Migration20260529231848_communication_channels.js.map +7 -0
  370. package/dist/modules/communication_channels/migrations/Migration20260531120000_communication_channels.js +17 -0
  371. package/dist/modules/communication_channels/migrations/Migration20260531120000_communication_channels.js.map +7 -0
  372. package/dist/modules/communication_channels/notifications.client.js +51 -0
  373. package/dist/modules/communication_channels/notifications.client.js.map +7 -0
  374. package/dist/modules/communication_channels/notifications.handlers.js +53 -0
  375. package/dist/modules/communication_channels/notifications.handlers.js.map +7 -0
  376. package/dist/modules/communication_channels/notifications.js +56 -0
  377. package/dist/modules/communication_channels/notifications.js.map +7 -0
  378. package/dist/modules/communication_channels/setup.js +105 -0
  379. package/dist/modules/communication_channels/setup.js.map +7 -0
  380. package/dist/modules/communication_channels/subscribers/channel-requires-reauth-notification.js +71 -0
  381. package/dist/modules/communication_channels/subscribers/channel-requires-reauth-notification.js.map +7 -0
  382. package/dist/modules/communication_channels/subscribers/outbound-bridge.js +103 -0
  383. package/dist/modules/communication_channels/subscribers/outbound-bridge.js.map +7 -0
  384. package/dist/modules/communication_channels/subscribers/user-deleted-cascade.js +51 -0
  385. package/dist/modules/communication_channels/subscribers/user-deleted-cascade.js.map +7 -0
  386. package/dist/modules/communication_channels/widgets/components.js +7 -0
  387. package/dist/modules/communication_channels/widgets/components.js.map +7 -0
  388. package/dist/modules/communication_channels/widgets/injection/channel-badge/widget.client.js +18 -0
  389. package/dist/modules/communication_channels/widgets/injection/channel-badge/widget.client.js.map +7 -0
  390. package/dist/modules/communication_channels/widgets/injection/channel-badge/widget.js +30 -0
  391. package/dist/modules/communication_channels/widgets/injection/channel-badge/widget.js.map +7 -0
  392. package/dist/modules/communication_channels/widgets/injection/channel-info-panel/widget.client.js +185 -0
  393. package/dist/modules/communication_channels/widgets/injection/channel-info-panel/widget.client.js.map +7 -0
  394. package/dist/modules/communication_channels/widgets/injection/channel-info-panel/widget.js +17 -0
  395. package/dist/modules/communication_channels/widgets/injection/channel-info-panel/widget.js.map +7 -0
  396. package/dist/modules/communication_channels/widgets/injection/channel-payload-renderer/widget.client.js +44 -0
  397. package/dist/modules/communication_channels/widgets/injection/channel-payload-renderer/widget.client.js.map +7 -0
  398. package/dist/modules/communication_channels/widgets/injection/channel-payload-renderer/widget.js +17 -0
  399. package/dist/modules/communication_channels/widgets/injection/channel-payload-renderer/widget.js.map +7 -0
  400. package/dist/modules/communication_channels/widgets/injection/profile-channels-menu/widget.js +23 -0
  401. package/dist/modules/communication_channels/widgets/injection/profile-channels-menu/widget.js.map +7 -0
  402. package/dist/modules/communication_channels/widgets/injection/reaction-bar/widget.client.js +141 -0
  403. package/dist/modules/communication_channels/widgets/injection/reaction-bar/widget.client.js.map +7 -0
  404. package/dist/modules/communication_channels/widgets/injection/reaction-bar/widget.js +17 -0
  405. package/dist/modules/communication_channels/widgets/injection/reaction-bar/widget.js.map +7 -0
  406. package/dist/modules/communication_channels/widgets/injection-table.js +38 -0
  407. package/dist/modules/communication_channels/widgets/injection-table.js.map +7 -0
  408. package/dist/modules/communication_channels/widgets/notifications/ChannelRequiresReauthRenderer.js +25 -0
  409. package/dist/modules/communication_channels/widgets/notifications/ChannelRequiresReauthRenderer.js.map +7 -0
  410. package/dist/modules/communication_channels/widgets/notifications/MessageReceivedRenderer.js +19 -0
  411. package/dist/modules/communication_channels/widgets/notifications/MessageReceivedRenderer.js.map +7 -0
  412. package/dist/modules/communication_channels/widgets/notifications/index.js +7 -0
  413. package/dist/modules/communication_channels/widgets/notifications/index.js.map +7 -0
  414. package/dist/modules/communication_channels/workers/channel-import-history.js +185 -0
  415. package/dist/modules/communication_channels/workers/channel-import-history.js.map +7 -0
  416. package/dist/modules/communication_channels/workers/gmail-history-sync.js +154 -0
  417. package/dist/modules/communication_channels/workers/gmail-history-sync.js.map +7 -0
  418. package/dist/modules/communication_channels/workers/gmail-renew-watch.js +95 -0
  419. package/dist/modules/communication_channels/workers/gmail-renew-watch.js.map +7 -0
  420. package/dist/modules/communication_channels/workers/inbound-processor.js +56 -0
  421. package/dist/modules/communication_channels/workers/inbound-processor.js.map +7 -0
  422. package/dist/modules/communication_channels/workers/outbound-delivery.js +85 -0
  423. package/dist/modules/communication_channels/workers/outbound-delivery.js.map +7 -0
  424. package/dist/modules/communication_channels/workers/poll-channel.js +240 -0
  425. package/dist/modules/communication_channels/workers/poll-channel.js.map +7 -0
  426. package/dist/modules/communication_channels/workers/poll-tick.js +132 -0
  427. package/dist/modules/communication_channels/workers/poll-tick.js.map +7 -0
  428. package/dist/modules/communication_channels/workers/reaction-processor.js +192 -0
  429. package/dist/modules/communication_channels/workers/reaction-processor.js.map +7 -0
  430. package/dist/modules/configs/api/openapi.js +11 -2
  431. package/dist/modules/configs/api/openapi.js.map +2 -2
  432. package/dist/modules/currencies/backend/currencies/[id]/page.js +6 -3
  433. package/dist/modules/currencies/backend/currencies/[id]/page.js.map +2 -2
  434. package/dist/modules/currencies/backend/currencies/page.js +27 -11
  435. package/dist/modules/currencies/backend/currencies/page.js.map +2 -2
  436. package/dist/modules/currencies/backend/exchange-rates/[id]/page.js +1 -0
  437. package/dist/modules/currencies/backend/exchange-rates/[id]/page.js.map +2 -2
  438. package/dist/modules/currencies/backend/exchange-rates/page.js +21 -7
  439. package/dist/modules/currencies/backend/exchange-rates/page.js.map +2 -2
  440. package/dist/modules/currencies/commands/currencies.js +37 -16
  441. package/dist/modules/currencies/commands/currencies.js.map +2 -2
  442. package/dist/modules/currencies/commands/exchange-rates.js +19 -9
  443. package/dist/modules/currencies/commands/exchange-rates.js.map +2 -2
  444. package/dist/modules/currencies/components/CurrencyFetchingConfig.js +26 -19
  445. package/dist/modules/currencies/components/CurrencyFetchingConfig.js.map +2 -2
  446. package/dist/modules/customer_accounts/api/admin/roles/[id].js +28 -5
  447. package/dist/modules/customer_accounts/api/admin/roles/[id].js.map +2 -2
  448. package/dist/modules/customer_accounts/api/admin/roles.js +4 -2
  449. package/dist/modules/customer_accounts/api/admin/roles.js.map +2 -2
  450. package/dist/modules/customer_accounts/api/admin/users/[id].js +39 -5
  451. package/dist/modules/customer_accounts/api/admin/users/[id].js.map +2 -2
  452. package/dist/modules/customer_accounts/api/admin/users-invite.js +17 -1
  453. package/dist/modules/customer_accounts/api/admin/users-invite.js.map +2 -2
  454. package/dist/modules/customer_accounts/api/admin/users.js +60 -23
  455. package/dist/modules/customer_accounts/api/admin/users.js.map +2 -2
  456. package/dist/modules/customer_accounts/api/login.js +11 -4
  457. package/dist/modules/customer_accounts/api/login.js.map +2 -2
  458. package/dist/modules/customer_accounts/api/portal/users-invite.js +17 -1
  459. package/dist/modules/customer_accounts/api/portal/users-invite.js.map +2 -2
  460. package/dist/modules/customer_accounts/api/signup.js +3 -1
  461. package/dist/modules/customer_accounts/api/signup.js.map +2 -2
  462. package/dist/modules/customer_accounts/backend/customer_accounts/roles/[id]/page.js +16 -8
  463. package/dist/modules/customer_accounts/backend/customer_accounts/roles/[id]/page.js.map +2 -2
  464. package/dist/modules/customer_accounts/backend/customer_accounts/roles/page.js +19 -5
  465. package/dist/modules/customer_accounts/backend/customer_accounts/roles/page.js.map +2 -2
  466. package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/page.js +8 -4
  467. package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/page.js.map +2 -2
  468. package/dist/modules/customer_accounts/backend/customer_accounts/users/[id]/page.js +29 -18
  469. package/dist/modules/customer_accounts/backend/customer_accounts/users/[id]/page.js.map +2 -2
  470. package/dist/modules/customer_accounts/backend/customer_accounts/users/page.js +27 -11
  471. package/dist/modules/customer_accounts/backend/customer_accounts/users/page.js.map +2 -2
  472. package/dist/modules/customer_accounts/data/validators.js +2 -1
  473. package/dist/modules/customer_accounts/data/validators.js.map +2 -2
  474. package/dist/modules/customer_accounts/lib/customerEntityOwnership.js +22 -0
  475. package/dist/modules/customer_accounts/lib/customerEntityOwnership.js.map +7 -0
  476. package/dist/modules/customer_accounts/lib/rateLimiter.js +14 -0
  477. package/dist/modules/customer_accounts/lib/rateLimiter.js.map +2 -2
  478. package/dist/modules/customer_accounts/lib/resolveTenantContext.js +44 -1
  479. package/dist/modules/customer_accounts/lib/resolveTenantContext.js.map +3 -3
  480. package/dist/modules/customer_accounts/services/customerInvitationService.js +28 -1
  481. package/dist/modules/customer_accounts/services/customerInvitationService.js.map +2 -2
  482. package/dist/modules/customer_accounts/services/customerUserService.js +13 -7
  483. package/dist/modules/customer_accounts/services/customerUserService.js.map +2 -2
  484. package/dist/modules/customer_accounts/subscribers/autoLinkCrmReverse.js +3 -3
  485. package/dist/modules/customer_accounts/subscribers/autoLinkCrmReverse.js.map +2 -2
  486. package/dist/modules/customers/acl.js +18 -0
  487. package/dist/modules/customers/acl.js.map +2 -2
  488. package/dist/modules/customers/api/activities/route.js +32 -10
  489. package/dist/modules/customers/api/activities/route.js.map +2 -2
  490. package/dist/modules/customers/api/addresses/route.js +2 -0
  491. package/dist/modules/customers/api/addresses/route.js.map +2 -2
  492. package/dist/modules/customers/api/companies/[id]/route.js +22 -9
  493. package/dist/modules/customers/api/companies/[id]/route.js.map +2 -2
  494. package/dist/modules/customers/api/companies/route.js +18 -7
  495. package/dist/modules/customers/api/companies/route.js.map +2 -2
  496. package/dist/modules/customers/api/deals/route.js +2 -0
  497. package/dist/modules/customers/api/deals/route.js.map +2 -2
  498. package/dist/modules/customers/api/dictionaries/[kind]/route.js +22 -38
  499. package/dist/modules/customers/api/dictionaries/[kind]/route.js.map +2 -2
  500. package/dist/modules/customers/api/dictionaries/cache.js +2 -1
  501. package/dist/modules/customers/api/dictionaries/cache.js.map +2 -2
  502. package/dist/modules/customers/api/dictionaries/context.js +1 -0
  503. package/dist/modules/customers/api/dictionaries/context.js.map +2 -2
  504. package/dist/modules/customers/api/interactions/[id]/visibility/route.js +151 -0
  505. package/dist/modules/customers/api/interactions/[id]/visibility/route.js.map +7 -0
  506. package/dist/modules/customers/api/interactions/counts/route.js +6 -0
  507. package/dist/modules/customers/api/interactions/counts/route.js.map +2 -2
  508. package/dist/modules/customers/api/interactions/route.js +33 -12
  509. package/dist/modules/customers/api/interactions/route.js.map +2 -2
  510. package/dist/modules/customers/api/people/[id]/email-threads/route.js +82 -0
  511. package/dist/modules/customers/api/people/[id]/email-threads/route.js.map +7 -0
  512. package/dist/modules/customers/api/people/[id]/emails/route.js +157 -0
  513. package/dist/modules/customers/api/people/[id]/emails/route.js.map +7 -0
  514. package/dist/modules/customers/api/people/[id]/route.js +20 -10
  515. package/dist/modules/customers/api/people/[id]/route.js.map +2 -2
  516. package/dist/modules/customers/api/people/route.js +16 -7
  517. package/dist/modules/customers/api/people/route.js.map +2 -2
  518. package/dist/modules/customers/api/pipeline-stages/route.js +0 -13
  519. package/dist/modules/customers/api/pipeline-stages/route.js.map +2 -2
  520. package/dist/modules/customers/api/settings/dictionary-sort-modes/route.js +223 -0
  521. package/dist/modules/customers/api/settings/dictionary-sort-modes/route.js.map +7 -0
  522. package/dist/modules/customers/api/todos/route.js +29 -11
  523. package/dist/modules/customers/api/todos/route.js.map +2 -2
  524. package/dist/modules/customers/backend/config/customers/deals/page.js.map +2 -2
  525. package/dist/modules/customers/backend/config/customers/pipeline-stages/page.js +34 -21
  526. package/dist/modules/customers/backend/config/customers/pipeline-stages/page.js.map +2 -2
  527. package/dist/modules/customers/backend/customers/companies/[id]/page.js +45 -27
  528. package/dist/modules/customers/backend/customers/companies/[id]/page.js.map +2 -2
  529. package/dist/modules/customers/backend/customers/companies/page.js +10 -1
  530. package/dist/modules/customers/backend/customers/companies/page.js.map +2 -2
  531. package/dist/modules/customers/backend/customers/companies-v2/[id]/page.js +22 -5
  532. package/dist/modules/customers/backend/customers/companies-v2/[id]/page.js.map +2 -2
  533. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealFormHandlers.js +30 -8
  534. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealFormHandlers.js.map +2 -2
  535. package/dist/modules/customers/backend/customers/deals/[id]/page.js +1 -0
  536. package/dist/modules/customers/backend/customers/deals/[id]/page.js.map +2 -2
  537. package/dist/modules/customers/backend/customers/deals/page.js +26 -7
  538. package/dist/modules/customers/backend/customers/deals/page.js.map +2 -2
  539. package/dist/modules/customers/backend/customers/deals/pipeline/page.js +62 -39
  540. package/dist/modules/customers/backend/customers/deals/pipeline/page.js.map +2 -2
  541. package/dist/modules/customers/backend/customers/people/[id]/page.js +41 -26
  542. package/dist/modules/customers/backend/customers/people/[id]/page.js.map +2 -2
  543. package/dist/modules/customers/backend/customers/people/page.js +10 -1
  544. package/dist/modules/customers/backend/customers/people/page.js.map +2 -2
  545. package/dist/modules/customers/backend/customers/people-v2/[id]/page.js +60 -23
  546. package/dist/modules/customers/backend/customers/people-v2/[id]/page.js.map +2 -2
  547. package/dist/modules/customers/commands/activities.js +19 -0
  548. package/dist/modules/customers/commands/activities.js.map +2 -2
  549. package/dist/modules/customers/commands/addresses.js +98 -14
  550. package/dist/modules/customers/commands/addresses.js.map +2 -2
  551. package/dist/modules/customers/commands/comments.js +30 -1
  552. package/dist/modules/customers/commands/comments.js.map +2 -2
  553. package/dist/modules/customers/commands/companies.js +113 -1
  554. package/dist/modules/customers/commands/companies.js.map +2 -2
  555. package/dist/modules/customers/commands/deals.js +196 -77
  556. package/dist/modules/customers/commands/deals.js.map +2 -2
  557. package/dist/modules/customers/commands/dictionaries.js +44 -0
  558. package/dist/modules/customers/commands/dictionaries.js.map +2 -2
  559. package/dist/modules/customers/commands/entity-roles.js +47 -0
  560. package/dist/modules/customers/commands/entity-roles.js.map +2 -2
  561. package/dist/modules/customers/commands/interactions.js +200 -8
  562. package/dist/modules/customers/commands/interactions.js.map +2 -2
  563. package/dist/modules/customers/commands/labels.js +83 -1
  564. package/dist/modules/customers/commands/labels.js.map +2 -2
  565. package/dist/modules/customers/commands/people.js +167 -13
  566. package/dist/modules/customers/commands/people.js.map +2 -2
  567. package/dist/modules/customers/commands/personCompanyLinks.js +141 -69
  568. package/dist/modules/customers/commands/personCompanyLinks.js.map +2 -2
  569. package/dist/modules/customers/commands/pipeline-stages.js +13 -11
  570. package/dist/modules/customers/commands/pipeline-stages.js.map +3 -3
  571. package/dist/modules/customers/commands/settings.js +31 -0
  572. package/dist/modules/customers/commands/settings.js.map +2 -2
  573. package/dist/modules/customers/commands/tags.js +56 -1
  574. package/dist/modules/customers/commands/tags.js.map +2 -2
  575. package/dist/modules/customers/commands/todos.js +19 -0
  576. package/dist/modules/customers/commands/todos.js.map +2 -2
  577. package/dist/modules/customers/components/AddressFormatSettings.js.map +2 -2
  578. package/dist/modules/customers/components/CustomersConfigurationSections.js +3 -0
  579. package/dist/modules/customers/components/CustomersConfigurationSections.js.map +2 -2
  580. package/dist/modules/customers/components/DictionarySettings.js +20 -13
  581. package/dist/modules/customers/components/DictionarySettings.js.map +2 -2
  582. package/dist/modules/customers/components/DictionarySortSettings.js +214 -0
  583. package/dist/modules/customers/components/DictionarySortSettings.js.map +7 -0
  584. package/dist/modules/customers/components/PipelineSettings.js +38 -23
  585. package/dist/modules/customers/components/PipelineSettings.js.map +2 -2
  586. package/dist/modules/customers/components/detail/ActivityCard.js +32 -0
  587. package/dist/modules/customers/components/detail/ActivityCard.js.map +2 -2
  588. package/dist/modules/customers/components/detail/ActivityForm.js +1 -0
  589. package/dist/modules/customers/components/detail/ActivityForm.js.map +2 -2
  590. package/dist/modules/customers/components/detail/ActivityTimeline.js +1 -1
  591. package/dist/modules/customers/components/detail/ActivityTimeline.js.map +2 -2
  592. package/dist/modules/customers/components/detail/AddressesSection.js +4 -0
  593. package/dist/modules/customers/components/detail/AddressesSection.js.map +2 -2
  594. package/dist/modules/customers/components/detail/AnnualRevenueField.js +1 -0
  595. package/dist/modules/customers/components/detail/AnnualRevenueField.js.map +2 -2
  596. package/dist/modules/customers/components/detail/CompanyPeopleSection.js +28 -22
  597. package/dist/modules/customers/components/detail/CompanyPeopleSection.js.map +2 -2
  598. package/dist/modules/customers/components/detail/ComposeEmailDialog.js +242 -0
  599. package/dist/modules/customers/components/detail/ComposeEmailDialog.js.map +7 -0
  600. package/dist/modules/customers/components/detail/DealForm.js +3 -1
  601. package/dist/modules/customers/components/detail/DealForm.js.map +2 -2
  602. package/dist/modules/customers/components/detail/DealsSection.js +46 -24
  603. package/dist/modules/customers/components/detail/DealsSection.js.map +2 -2
  604. package/dist/modules/customers/components/detail/EmailCardActions.js +184 -0
  605. package/dist/modules/customers/components/detail/EmailCardActions.js.map +7 -0
  606. package/dist/modules/customers/components/detail/EmailReplyForwardActions.js +52 -0
  607. package/dist/modules/customers/components/detail/EmailReplyForwardActions.js.map +7 -0
  608. package/dist/modules/customers/components/detail/EntityTagsDialog.js +7 -0
  609. package/dist/modules/customers/components/detail/EntityTagsDialog.js.map +2 -2
  610. package/dist/modules/customers/components/detail/ManageTagsDialog.js +34 -22
  611. package/dist/modules/customers/components/detail/ManageTagsDialog.js.map +2 -2
  612. package/dist/modules/customers/components/detail/PersonCompaniesSection.js +41 -29
  613. package/dist/modules/customers/components/detail/PersonCompaniesSection.js.map +2 -2
  614. package/dist/modules/customers/components/detail/PersonDetailTabs.js +7 -1
  615. package/dist/modules/customers/components/detail/PersonDetailTabs.js.map +2 -2
  616. package/dist/modules/customers/components/detail/PersonEmailThreadsTab.js +366 -0
  617. package/dist/modules/customers/components/detail/PersonEmailThreadsTab.js.map +7 -0
  618. package/dist/modules/customers/components/detail/RoleAssignmentRow.js +14 -8
  619. package/dist/modules/customers/components/detail/RoleAssignmentRow.js.map +2 -2
  620. package/dist/modules/customers/components/detail/ScheduleActivityDialog.js +14 -6
  621. package/dist/modules/customers/components/detail/ScheduleActivityDialog.js.map +2 -2
  622. package/dist/modules/customers/components/detail/create/DealCurrencyField.js +1 -0
  623. package/dist/modules/customers/components/detail/create/DealCurrencyField.js.map +2 -2
  624. package/dist/modules/customers/components/detail/hooks/useCustomerDictionary.js +2 -1
  625. package/dist/modules/customers/components/detail/hooks/useCustomerDictionary.js.map +2 -2
  626. package/dist/modules/customers/components/detail/hooks/useInteractionMutations.js +29 -13
  627. package/dist/modules/customers/components/detail/hooks/useInteractionMutations.js.map +2 -2
  628. package/dist/modules/customers/components/detail/hooks/useInteractions.js +77 -35
  629. package/dist/modules/customers/components/detail/hooks/useInteractions.js.map +2 -2
  630. package/dist/modules/customers/components/detail/hooks/usePersonTasks.js +25 -17
  631. package/dist/modules/customers/components/detail/hooks/usePersonTasks.js.map +2 -2
  632. package/dist/modules/customers/components/detail/schedule/useScheduleFormState.js.map +2 -2
  633. package/dist/modules/customers/components/formConfig.js +62 -12
  634. package/dist/modules/customers/components/formConfig.js.map +2 -2
  635. package/dist/modules/customers/data/enrichers.js +133 -2
  636. package/dist/modules/customers/data/enrichers.js.map +2 -2
  637. package/dist/modules/customers/data/entities.js +21 -0
  638. package/dist/modules/customers/data/entities.js.map +2 -2
  639. package/dist/modules/customers/data/extensions.js +16 -0
  640. package/dist/modules/customers/data/extensions.js.map +7 -0
  641. package/dist/modules/customers/data/guards.js +66 -0
  642. package/dist/modules/customers/data/guards.js.map +7 -0
  643. package/dist/modules/customers/data/validators.js +33 -8
  644. package/dist/modules/customers/data/validators.js.map +2 -2
  645. package/dist/modules/customers/di.js +37 -0
  646. package/dist/modules/customers/di.js.map +2 -2
  647. package/dist/modules/customers/encryption.js +11 -0
  648. package/dist/modules/customers/encryption.js.map +2 -2
  649. package/dist/modules/customers/events.js +4 -1
  650. package/dist/modules/customers/events.js.map +2 -2
  651. package/dist/modules/customers/lib/detailTenantScope.js +15 -0
  652. package/dist/modules/customers/lib/detailTenantScope.js.map +7 -0
  653. package/dist/modules/customers/lib/findPeopleByAddresses.js +64 -0
  654. package/dist/modules/customers/lib/findPeopleByAddresses.js.map +7 -0
  655. package/dist/modules/customers/lib/kysely.js.map +2 -2
  656. package/dist/modules/customers/lib/link-channel-message-handler.js +303 -0
  657. package/dist/modules/customers/lib/link-channel-message-handler.js.map +7 -0
  658. package/dist/modules/customers/lib/personCompanyLinkTable.js +15 -1
  659. package/dist/modules/customers/lib/personCompanyLinkTable.js.map +2 -2
  660. package/dist/modules/customers/lib/personEmailThreads.js +205 -0
  661. package/dist/modules/customers/lib/personEmailThreads.js.map +7 -0
  662. package/dist/modules/customers/lib/todoCompatibility.js +11 -0
  663. package/dist/modules/customers/lib/todoCompatibility.js.map +2 -2
  664. package/dist/modules/customers/lib/visibilityFilter.js +51 -0
  665. package/dist/modules/customers/lib/visibilityFilter.js.map +7 -0
  666. package/dist/modules/customers/migrations/Migration20260527012240_customers.js +20 -0
  667. package/dist/modules/customers/migrations/Migration20260527012240_customers.js.map +7 -0
  668. package/dist/modules/customers/migrations/Migration20260602202147_customers.js +13 -0
  669. package/dist/modules/customers/migrations/Migration20260602202147_customers.js.map +7 -0
  670. package/dist/modules/customers/search.js +12 -6
  671. package/dist/modules/customers/search.js.map +2 -2
  672. package/dist/modules/customers/setup.js +2 -1
  673. package/dist/modules/customers/setup.js.map +2 -2
  674. package/dist/modules/customers/subscribers/link-channel-message-received.js +12 -0
  675. package/dist/modules/customers/subscribers/link-channel-message-received.js.map +7 -0
  676. package/dist/modules/customers/subscribers/link-channel-message-sent.js +12 -0
  677. package/dist/modules/customers/subscribers/link-channel-message-sent.js.map +7 -0
  678. package/dist/modules/dashboards/components/WidgetVisibilityEditor.js.map +2 -2
  679. package/dist/modules/data_sync/api/options.js +4 -4
  680. package/dist/modules/data_sync/api/options.js.map +2 -2
  681. package/dist/modules/data_sync/api/schedules/route.js +9 -1
  682. package/dist/modules/data_sync/api/schedules/route.js.map +2 -2
  683. package/dist/modules/data_sync/backend/data-sync/page.js +17 -8
  684. package/dist/modules/data_sync/backend/data-sync/page.js.map +2 -2
  685. package/dist/modules/data_sync/components/IntegrationScheduleTab.js +43 -22
  686. package/dist/modules/data_sync/components/IntegrationScheduleTab.js.map +2 -2
  687. package/dist/modules/data_sync/lib/sync-schedule-service.js +9 -0
  688. package/dist/modules/data_sync/lib/sync-schedule-service.js.map +2 -2
  689. package/dist/modules/dictionaries/api/[dictionaryId]/entries/[entryId]/route.js +8 -1
  690. package/dist/modules/dictionaries/api/[dictionaryId]/entries/[entryId]/route.js.map +2 -2
  691. package/dist/modules/dictionaries/api/[dictionaryId]/entries/route.js +12 -5
  692. package/dist/modules/dictionaries/api/[dictionaryId]/entries/route.js.map +2 -2
  693. package/dist/modules/dictionaries/api/[dictionaryId]/route.js +25 -1
  694. package/dist/modules/dictionaries/api/[dictionaryId]/route.js.map +2 -2
  695. package/dist/modules/dictionaries/api/openapi.js +2 -0
  696. package/dist/modules/dictionaries/api/openapi.js.map +2 -2
  697. package/dist/modules/dictionaries/api/route.js +7 -0
  698. package/dist/modules/dictionaries/api/route.js.map +2 -2
  699. package/dist/modules/dictionaries/commands/entry-operations.js +8 -0
  700. package/dist/modules/dictionaries/commands/entry-operations.js.map +2 -2
  701. package/dist/modules/dictionaries/components/DictionariesManager.js +95 -16
  702. package/dist/modules/dictionaries/components/DictionariesManager.js.map +2 -2
  703. package/dist/modules/dictionaries/components/DictionaryEntriesEditor.js +29 -16
  704. package/dist/modules/dictionaries/components/DictionaryEntriesEditor.js.map +2 -2
  705. package/dist/modules/dictionaries/components/DictionaryEntrySelect.js +51 -11
  706. package/dist/modules/dictionaries/components/DictionaryEntrySelect.js.map +2 -2
  707. package/dist/modules/dictionaries/components/DictionarySelectControl.js +9 -1
  708. package/dist/modules/dictionaries/components/DictionarySelectControl.js.map +2 -2
  709. package/dist/modules/dictionaries/components/dictionaryAppearance.js +2 -1
  710. package/dist/modules/dictionaries/components/dictionaryAppearance.js.map +2 -2
  711. package/dist/modules/dictionaries/components/hooks/useDictionaryEntries.js +2 -1
  712. package/dist/modules/dictionaries/components/hooks/useDictionaryEntries.js.map +2 -2
  713. package/dist/modules/dictionaries/data/entities.js +5 -0
  714. package/dist/modules/dictionaries/data/entities.js.map +2 -2
  715. package/dist/modules/dictionaries/data/validators.js +3 -1
  716. package/dist/modules/dictionaries/data/validators.js.map +2 -2
  717. package/dist/modules/dictionaries/fields/dictionary.js +2 -2
  718. package/dist/modules/dictionaries/fields/dictionary.js.map +1 -1
  719. package/dist/modules/dictionaries/lib/entrySort.js +61 -0
  720. package/dist/modules/dictionaries/lib/entrySort.js.map +7 -0
  721. package/dist/modules/dictionaries/migrations/Migration20260602202147_dictionaries.js +13 -0
  722. package/dist/modules/dictionaries/migrations/Migration20260602202147_dictionaries.js.map +7 -0
  723. package/dist/modules/directory/api/get/organizations/lookup.js +3 -7
  724. package/dist/modules/directory/api/get/organizations/lookup.js.map +2 -2
  725. package/dist/modules/directory/api/organizations/route.js +41 -16
  726. package/dist/modules/directory/api/organizations/route.js.map +2 -2
  727. package/dist/modules/directory/backend/directory/organizations/[id]/edit/page.js +2 -0
  728. package/dist/modules/directory/backend/directory/organizations/[id]/edit/page.js.map +2 -2
  729. package/dist/modules/directory/backend/directory/organizations/page.js +18 -5
  730. package/dist/modules/directory/backend/directory/organizations/page.js.map +2 -2
  731. package/dist/modules/directory/backend/directory/tenants/[id]/edit/page.js +7 -3
  732. package/dist/modules/directory/backend/directory/tenants/[id]/edit/page.js.map +2 -2
  733. package/dist/modules/directory/backend/directory/tenants/page.js +17 -4
  734. package/dist/modules/directory/backend/directory/tenants/page.js.map +2 -2
  735. package/dist/modules/directory/commands/organizations.js +70 -2
  736. package/dist/modules/directory/commands/organizations.js.map +2 -2
  737. package/dist/modules/directory/commands/tenants.js +16 -3
  738. package/dist/modules/directory/commands/tenants.js.map +2 -2
  739. package/dist/modules/entities/api/records.js +107 -7
  740. package/dist/modules/entities/api/records.js.map +2 -2
  741. package/dist/modules/entities/backend/entities/user/[entityId]/records/[recordId]/page.js +1 -0
  742. package/dist/modules/entities/backend/entities/user/[entityId]/records/[recordId]/page.js.map +2 -2
  743. package/dist/modules/entities/backend/entities/user/[entityId]/records/page.js +8 -4
  744. package/dist/modules/entities/backend/entities/user/[entityId]/records/page.js.map +2 -2
  745. package/dist/modules/entities/components/UserEntitiesTable.js +9 -0
  746. package/dist/modules/entities/components/UserEntitiesTable.js.map +2 -2
  747. package/dist/modules/entities/lib/entityAcl.js +82 -0
  748. package/dist/modules/entities/lib/entityAcl.js.map +7 -0
  749. package/dist/modules/entities/lib/helpers.js +79 -65
  750. package/dist/modules/entities/lib/helpers.js.map +2 -2
  751. package/dist/modules/feature_toggles/api/global/[id]/override/route.js +15 -10
  752. package/dist/modules/feature_toggles/api/global/[id]/override/route.js.map +2 -2
  753. package/dist/modules/feature_toggles/api/global/[id]/route.js +2 -1
  754. package/dist/modules/feature_toggles/api/global/[id]/route.js.map +2 -2
  755. package/dist/modules/feature_toggles/api/overrides/route.js +20 -7
  756. package/dist/modules/feature_toggles/api/overrides/route.js.map +2 -2
  757. package/dist/modules/feature_toggles/backend/feature-toggles/global/[id]/edit/page.js +21 -16
  758. package/dist/modules/feature_toggles/backend/feature-toggles/global/[id]/edit/page.js.map +2 -2
  759. package/dist/modules/feature_toggles/commands/global.js +127 -8
  760. package/dist/modules/feature_toggles/commands/global.js.map +2 -2
  761. package/dist/modules/feature_toggles/commands/overrides.js +8 -6
  762. package/dist/modules/feature_toggles/commands/overrides.js.map +2 -2
  763. package/dist/modules/feature_toggles/components/FeatureToggleOverrideCard.js +20 -12
  764. package/dist/modules/feature_toggles/components/FeatureToggleOverrideCard.js.map +2 -2
  765. package/dist/modules/feature_toggles/components/FeatureTogglesTable.js +15 -2
  766. package/dist/modules/feature_toggles/components/FeatureTogglesTable.js.map +2 -2
  767. package/dist/modules/feature_toggles/components/formConfig.js +2 -1
  768. package/dist/modules/feature_toggles/components/formConfig.js.map +2 -2
  769. package/dist/modules/feature_toggles/components/overrideFormConfig.js +5 -1
  770. package/dist/modules/feature_toggles/components/overrideFormConfig.js.map +2 -2
  771. package/dist/modules/feature_toggles/data/validators.js +7 -4
  772. package/dist/modules/feature_toggles/data/validators.js.map +2 -2
  773. package/dist/modules/feature_toggles/lib/queries.js +5 -5
  774. package/dist/modules/feature_toggles/lib/queries.js.map +2 -2
  775. package/dist/modules/feature_toggles/lib/utils.js.map +2 -2
  776. package/dist/modules/inbox_ops/api/proposals/[id]/replies/[replyId]/send/route.js +8 -1
  777. package/dist/modules/inbox_ops/api/proposals/[id]/replies/[replyId]/send/route.js.map +2 -2
  778. package/dist/modules/inbox_ops/api/settings/route.js +23 -2
  779. package/dist/modules/inbox_ops/api/settings/route.js.map +2 -2
  780. package/dist/modules/inbox_ops/api/webhook/inbound.js +53 -14
  781. package/dist/modules/inbox_ops/api/webhook/inbound.js.map +2 -2
  782. package/dist/modules/inbox_ops/backend/inbox-ops/settings/page.js +13 -8
  783. package/dist/modules/inbox_ops/backend/inbox-ops/settings/page.js.map +2 -2
  784. package/dist/modules/inbox_ops/components/proposals/EditActionDialog.js +9 -4
  785. package/dist/modules/inbox_ops/components/proposals/EditActionDialog.js.map +2 -2
  786. package/dist/modules/inbox_ops/data/entities.js +3 -0
  787. package/dist/modules/inbox_ops/data/entities.js.map +2 -2
  788. package/dist/modules/inbox_ops/data/validators.js +5 -1
  789. package/dist/modules/inbox_ops/data/validators.js.map +2 -2
  790. package/dist/modules/inbox_ops/encryption.js +9 -0
  791. package/dist/modules/inbox_ops/encryption.js.map +2 -2
  792. package/dist/modules/inbox_ops/lib/executionEngine.js +6 -1
  793. package/dist/modules/inbox_ops/lib/executionEngine.js.map +2 -2
  794. package/dist/modules/inbox_ops/lib/executionHelpers.js +2 -7
  795. package/dist/modules/inbox_ops/lib/executionHelpers.js.map +2 -2
  796. package/dist/modules/inbox_ops/lib/priceValidator.js +35 -7
  797. package/dist/modules/inbox_ops/lib/priceValidator.js.map +2 -2
  798. package/dist/modules/inbox_ops/lib/rateLimiter.js +58 -23
  799. package/dist/modules/inbox_ops/lib/rateLimiter.js.map +2 -2
  800. package/dist/modules/inbox_ops/lib/translationProvider.js +33 -5
  801. package/dist/modules/inbox_ops/lib/translationProvider.js.map +2 -2
  802. package/dist/modules/inbox_ops/migrations/Migration20260607205834.js +13 -0
  803. package/dist/modules/inbox_ops/migrations/Migration20260607205834.js.map +7 -0
  804. package/dist/modules/inbox_ops/subscribers/extractionWorker.js +2 -1
  805. package/dist/modules/inbox_ops/subscribers/extractionWorker.js.map +2 -2
  806. package/dist/modules/integrations/api/[id]/credentials/route.js +11 -0
  807. package/dist/modules/integrations/api/[id]/credentials/route.js.map +2 -2
  808. package/dist/modules/integrations/backend/integrations/[id]/page.js +8 -0
  809. package/dist/modules/integrations/backend/integrations/[id]/page.js.map +2 -2
  810. package/dist/modules/integrations/backend/integrations/bundle/[id]/page.js +18 -11
  811. package/dist/modules/integrations/backend/integrations/bundle/[id]/page.js.map +2 -2
  812. package/dist/modules/integrations/backend/integrations/page.js +12 -8
  813. package/dist/modules/integrations/backend/integrations/page.js.map +2 -2
  814. package/dist/modules/integrations/data/entities.js +8 -1
  815. package/dist/modules/integrations/data/entities.js.map +2 -2
  816. package/dist/modules/integrations/lib/credentials-field-validation.js +32 -0
  817. package/dist/modules/integrations/lib/credentials-field-validation.js.map +7 -0
  818. package/dist/modules/integrations/lib/credentials-service.js +29 -14
  819. package/dist/modules/integrations/lib/credentials-service.js.map +2 -2
  820. package/dist/modules/integrations/migrations/Migration20260526154136_integrations.js +15 -0
  821. package/dist/modules/integrations/migrations/Migration20260526154136_integrations.js.map +7 -0
  822. package/dist/modules/messages/api/route.js +2 -2
  823. package/dist/modules/messages/api/route.js.map +2 -2
  824. package/dist/modules/messages/api/token/[token]/route.js +1 -1
  825. package/dist/modules/messages/api/token/[token]/route.js.map +2 -2
  826. package/dist/modules/messages/commands/actions.js +9 -7
  827. package/dist/modules/messages/commands/actions.js.map +2 -2
  828. package/dist/modules/messages/commands/messages.js +83 -18
  829. package/dist/modules/messages/commands/messages.js.map +2 -2
  830. package/dist/modules/messages/commands/tokens.js +1 -1
  831. package/dist/modules/messages/commands/tokens.js.map +2 -2
  832. package/dist/modules/messages/components/ComposeMessagePageClient.js +24 -13
  833. package/dist/modules/messages/components/ComposeMessagePageClient.js.map +2 -2
  834. package/dist/modules/messages/components/MessageDetailPageClient.js +39 -2
  835. package/dist/modules/messages/components/MessageDetailPageClient.js.map +2 -2
  836. package/dist/modules/messages/components/MessagesInboxPageClient.js +10 -0
  837. package/dist/modules/messages/components/MessagesInboxPageClient.js.map +2 -2
  838. package/dist/modules/messages/components/message-detail/hooks/useMessageDetailsActions.js +2 -2
  839. package/dist/modules/messages/components/message-detail/hooks/useMessageDetailsActions.js.map +2 -2
  840. package/dist/modules/messages/components/message-detail/utils.js +17 -0
  841. package/dist/modules/messages/components/message-detail/utils.js.map +2 -2
  842. package/dist/modules/messages/data/entities.js +8 -1
  843. package/dist/modules/messages/data/entities.js.map +2 -2
  844. package/dist/modules/messages/data/validators.js +5 -1
  845. package/dist/modules/messages/data/validators.js.map +2 -2
  846. package/dist/modules/messages/lib/actions.js +5 -3
  847. package/dist/modules/messages/lib/actions.js.map +2 -2
  848. package/dist/modules/messages/migrations/Migration20260531130000.js +15 -0
  849. package/dist/modules/messages/migrations/Migration20260531130000.js.map +7 -0
  850. package/dist/modules/messages/widgets/injection-table.js +7 -0
  851. package/dist/modules/messages/widgets/injection-table.js.map +7 -0
  852. package/dist/modules/notifications/api/[id]/action/route.js +12 -2
  853. package/dist/modules/notifications/api/[id]/action/route.js.map +2 -2
  854. package/dist/modules/notifications/api/route.js +17 -4
  855. package/dist/modules/notifications/api/route.js.map +2 -2
  856. package/dist/modules/notifications/lib/notificationService.js +26 -21
  857. package/dist/modules/notifications/lib/notificationService.js.map +2 -2
  858. package/dist/modules/notifications/lib/routeHelpers.js +46 -8
  859. package/dist/modules/notifications/lib/routeHelpers.js.map +2 -2
  860. package/dist/modules/payment_gateways/api/status/route.js +6 -0
  861. package/dist/modules/payment_gateways/api/status/route.js.map +2 -2
  862. package/dist/modules/perspectives/api/[tableId]/route.js +39 -30
  863. package/dist/modules/perspectives/api/[tableId]/route.js.map +2 -2
  864. package/dist/modules/perspectives/services/perspectiveService.js +7 -0
  865. package/dist/modules/perspectives/services/perspectiveService.js.map +2 -2
  866. package/dist/modules/planner/backend/planner/availability-rulesets/[id]/page.js +6 -14
  867. package/dist/modules/planner/backend/planner/availability-rulesets/[id]/page.js.map +3 -3
  868. package/dist/modules/planner/backend/planner/availability-rulesets/page.js +4 -2
  869. package/dist/modules/planner/backend/planner/availability-rulesets/page.js.map +2 -2
  870. package/dist/modules/planner/commands/availability-rule-sets.js +20 -1
  871. package/dist/modules/planner/commands/availability-rule-sets.js.map +2 -2
  872. package/dist/modules/planner/commands/availability.js +9 -0
  873. package/dist/modules/planner/commands/availability.js.map +2 -2
  874. package/dist/modules/planner/components/AvailabilityRuleSetForm.js +3 -1
  875. package/dist/modules/planner/components/AvailabilityRuleSetForm.js.map +2 -2
  876. package/dist/modules/planner/components/AvailabilityRulesEditor.js +52 -13
  877. package/dist/modules/planner/components/AvailabilityRulesEditor.js.map +2 -2
  878. package/dist/modules/planner/components/AvailabilitySchedule.js +9 -5
  879. package/dist/modules/planner/components/AvailabilitySchedule.js.map +2 -2
  880. package/dist/modules/portal/frontend/[orgSlug]/portal/login/page.js +15 -14
  881. package/dist/modules/portal/frontend/[orgSlug]/portal/login/page.js.map +2 -2
  882. package/dist/modules/portal/frontend/[orgSlug]/portal/page.js +14 -21
  883. package/dist/modules/portal/frontend/[orgSlug]/portal/page.js.map +2 -2
  884. package/dist/modules/portal/frontend/[orgSlug]/portal/reset-password/page.js +11 -1
  885. package/dist/modules/portal/frontend/[orgSlug]/portal/reset-password/page.js.map +2 -2
  886. package/dist/modules/portal/frontend/[orgSlug]/portal/signup/page.js +15 -5
  887. package/dist/modules/portal/frontend/[orgSlug]/portal/signup/page.js.map +2 -2
  888. package/dist/modules/progress/api/jobs/[id]/route.js +7 -1
  889. package/dist/modules/progress/api/jobs/[id]/route.js.map +2 -2
  890. package/dist/modules/query_index/api/openapi.js +2 -1
  891. package/dist/modules/query_index/api/openapi.js.map +2 -2
  892. package/dist/modules/query_index/api/reindex.js +4 -0
  893. package/dist/modules/query_index/api/reindex.js.map +2 -2
  894. package/dist/modules/query_index/data/entities.js +5 -1
  895. package/dist/modules/query_index/data/entities.js.map +2 -2
  896. package/dist/modules/query_index/lib/engine.js +48 -15
  897. package/dist/modules/query_index/lib/engine.js.map +2 -2
  898. package/dist/modules/query_index/lib/indexer.js +50 -24
  899. package/dist/modules/query_index/lib/indexer.js.map +2 -2
  900. package/dist/modules/query_index/lib/jobs.js +28 -0
  901. package/dist/modules/query_index/lib/jobs.js.map +2 -2
  902. package/dist/modules/query_index/lib/reindexer.js +24 -15
  903. package/dist/modules/query_index/lib/reindexer.js.map +2 -2
  904. package/dist/modules/query_index/lib/search-tokens.js +3 -3
  905. package/dist/modules/query_index/lib/search-tokens.js.map +2 -2
  906. package/dist/modules/query_index/migrations/Migration20260606205453_query_index.js +35 -0
  907. package/dist/modules/query_index/migrations/Migration20260606205453_query_index.js.map +7 -0
  908. package/dist/modules/query_index/subscribers/delete_one.js +28 -15
  909. package/dist/modules/query_index/subscribers/delete_one.js.map +2 -2
  910. package/dist/modules/query_index/subscribers/upsert_one.js +31 -13
  911. package/dist/modules/query_index/subscribers/upsert_one.js.map +2 -2
  912. package/dist/modules/resources/backend/resources/resource-types/[id]/edit/page.js +18 -2
  913. package/dist/modules/resources/backend/resources/resource-types/[id]/edit/page.js.map +2 -2
  914. package/dist/modules/resources/backend/resources/resource-types/page.js +4 -2
  915. package/dist/modules/resources/backend/resources/resource-types/page.js.map +2 -2
  916. package/dist/modules/resources/backend/resources/resources/[id]/page.js +31 -4
  917. package/dist/modules/resources/backend/resources/resources/[id]/page.js.map +2 -2
  918. package/dist/modules/resources/backend/resources/resources/page.js +17 -4
  919. package/dist/modules/resources/backend/resources/resources/page.js.map +2 -2
  920. package/dist/modules/resources/commands/activities.js +64 -0
  921. package/dist/modules/resources/commands/activities.js.map +2 -2
  922. package/dist/modules/resources/commands/comments.js +21 -1
  923. package/dist/modules/resources/commands/comments.js.map +2 -2
  924. package/dist/modules/resources/commands/resource-types.js +22 -1
  925. package/dist/modules/resources/commands/resource-types.js.map +2 -2
  926. package/dist/modules/resources/commands/resources.js +87 -0
  927. package/dist/modules/resources/commands/resources.js.map +2 -2
  928. package/dist/modules/resources/commands/tag-assignments.js +53 -0
  929. package/dist/modules/resources/commands/tag-assignments.js.map +2 -2
  930. package/dist/modules/resources/components/ResourceCrudForm.js +90 -50
  931. package/dist/modules/resources/components/ResourceCrudForm.js.map +2 -2
  932. package/dist/modules/resources/components/ResourceTypeCrudForm.js +2 -1
  933. package/dist/modules/resources/components/ResourceTypeCrudForm.js.map +2 -2
  934. package/dist/modules/sales/api/documents/factory.js +7 -2
  935. package/dist/modules/sales/api/documents/factory.js.map +2 -2
  936. package/dist/modules/sales/api/shipping-methods/route.js +4 -0
  937. package/dist/modules/sales/api/shipping-methods/route.js.map +2 -2
  938. package/dist/modules/sales/api/tax-rates/route.js +4 -0
  939. package/dist/modules/sales/api/tax-rates/route.js.map +2 -2
  940. package/dist/modules/sales/backend/sales/channels/[channelId]/edit/page.js +3 -1
  941. package/dist/modules/sales/backend/sales/channels/[channelId]/edit/page.js.map +2 -2
  942. package/dist/modules/sales/backend/sales/channels/offers/page.js +13 -4
  943. package/dist/modules/sales/backend/sales/channels/offers/page.js.map +2 -2
  944. package/dist/modules/sales/backend/sales/channels/page.js +16 -4
  945. package/dist/modules/sales/backend/sales/channels/page.js.map +2 -2
  946. package/dist/modules/sales/backend/sales/documents/[id]/page.js +70 -22
  947. package/dist/modules/sales/backend/sales/documents/[id]/page.js.map +2 -2
  948. package/dist/modules/sales/backend/sales/documents/create/page.js.map +2 -2
  949. package/dist/modules/sales/commands/configuration.js +112 -7
  950. package/dist/modules/sales/commands/configuration.js.map +2 -2
  951. package/dist/modules/sales/commands/documentAddresses.js +181 -2
  952. package/dist/modules/sales/commands/documentAddresses.js.map +2 -2
  953. package/dist/modules/sales/commands/documents.js +46 -14
  954. package/dist/modules/sales/commands/documents.js.map +2 -2
  955. package/dist/modules/sales/commands/notes.js +39 -1
  956. package/dist/modules/sales/commands/notes.js.map +2 -2
  957. package/dist/modules/sales/commands/payments.js +121 -14
  958. package/dist/modules/sales/commands/payments.js.map +2 -2
  959. package/dist/modules/sales/commands/returns.js +178 -2
  960. package/dist/modules/sales/commands/returns.js.map +2 -2
  961. package/dist/modules/sales/commands/shared.js +15 -0
  962. package/dist/modules/sales/commands/shared.js.map +2 -2
  963. package/dist/modules/sales/commands/shipments.js +48 -6
  964. package/dist/modules/sales/commands/shipments.js.map +2 -2
  965. package/dist/modules/sales/components/AdjustmentKindSettings.js +19 -11
  966. package/dist/modules/sales/components/AdjustmentKindSettings.js.map +2 -2
  967. package/dist/modules/sales/components/DocumentNumberSettings.js.map +2 -2
  968. package/dist/modules/sales/components/OrderEditingSettings.js.map +2 -2
  969. package/dist/modules/sales/components/PaymentMethodsSettings.js +12 -4
  970. package/dist/modules/sales/components/PaymentMethodsSettings.js.map +2 -2
  971. package/dist/modules/sales/components/ShippingMethodsSettings.js +12 -4
  972. package/dist/modules/sales/components/ShippingMethodsSettings.js.map +2 -2
  973. package/dist/modules/sales/components/StatusSettings.js +18 -11
  974. package/dist/modules/sales/components/StatusSettings.js.map +2 -2
  975. package/dist/modules/sales/components/TaxRatesSettings.js +12 -4
  976. package/dist/modules/sales/components/TaxRatesSettings.js.map +2 -2
  977. package/dist/modules/sales/components/channels/ChannelOfferForm.js +65 -18
  978. package/dist/modules/sales/components/channels/ChannelOfferForm.js.map +2 -2
  979. package/dist/modules/sales/components/channels/SalesChannelOffersPanel.js +11 -4
  980. package/dist/modules/sales/components/channels/SalesChannelOffersPanel.js.map +2 -2
  981. package/dist/modules/sales/components/documents/AddressesSection.js +101 -36
  982. package/dist/modules/sales/components/documents/AddressesSection.js.map +2 -2
  983. package/dist/modules/sales/components/documents/AdjustmentDialog.js +37 -10
  984. package/dist/modules/sales/components/documents/AdjustmentDialog.js.map +2 -2
  985. package/dist/modules/sales/components/documents/AdjustmentsSection.js +43 -23
  986. package/dist/modules/sales/components/documents/AdjustmentsSection.js.map +2 -2
  987. package/dist/modules/sales/components/documents/ItemsSection.js +23 -14
  988. package/dist/modules/sales/components/documents/ItemsSection.js.map +2 -2
  989. package/dist/modules/sales/components/documents/LineItemDialog.js +70 -28
  990. package/dist/modules/sales/components/documents/LineItemDialog.js.map +2 -2
  991. package/dist/modules/sales/components/documents/PaymentDialog.js +29 -14
  992. package/dist/modules/sales/components/documents/PaymentDialog.js.map +2 -2
  993. package/dist/modules/sales/components/documents/PaymentsSection.js +20 -10
  994. package/dist/modules/sales/components/documents/PaymentsSection.js.map +2 -2
  995. package/dist/modules/sales/components/documents/ReturnDialog.js +26 -17
  996. package/dist/modules/sales/components/documents/ReturnDialog.js.map +2 -2
  997. package/dist/modules/sales/components/documents/ReturnsSection.js +3 -1
  998. package/dist/modules/sales/components/documents/ReturnsSection.js.map +2 -2
  999. package/dist/modules/sales/components/documents/SalesDocumentForm.js +1 -0
  1000. package/dist/modules/sales/components/documents/SalesDocumentForm.js.map +2 -2
  1001. package/dist/modules/sales/components/documents/SalesDocumentsTable.js +11 -6
  1002. package/dist/modules/sales/components/documents/SalesDocumentsTable.js.map +2 -2
  1003. package/dist/modules/sales/components/documents/ShipmentDialog.js +102 -17
  1004. package/dist/modules/sales/components/documents/ShipmentDialog.js.map +2 -2
  1005. package/dist/modules/sales/components/documents/ShipmentsSection.js +19 -10
  1006. package/dist/modules/sales/components/documents/ShipmentsSection.js.map +2 -2
  1007. package/dist/modules/sales/components/documents/optimisticLock.js +27 -0
  1008. package/dist/modules/sales/components/documents/optimisticLock.js.map +7 -0
  1009. package/dist/modules/sales/di.js +18 -0
  1010. package/dist/modules/sales/di.js.map +2 -2
  1011. package/dist/modules/sales/frontend/quote/[token]/page.js +11 -1
  1012. package/dist/modules/sales/frontend/quote/[token]/page.js.map +2 -2
  1013. package/dist/modules/sales/lib/calculations.js +18 -1
  1014. package/dist/modules/sales/lib/calculations.js.map +2 -2
  1015. package/dist/modules/sales/lib/dictionaries.js +2 -2
  1016. package/dist/modules/sales/lib/dictionaries.js.map +2 -2
  1017. package/dist/modules/sales/lib/makeStatusDictionaryRoute.js +2 -0
  1018. package/dist/modules/sales/lib/makeStatusDictionaryRoute.js.map +2 -2
  1019. package/dist/modules/shipping_carriers/api/cancel/route.js +2 -2
  1020. package/dist/modules/shipping_carriers/api/cancel/route.js.map +2 -2
  1021. package/dist/modules/shipping_carriers/lib/status-sync.js +8 -1
  1022. package/dist/modules/shipping_carriers/lib/status-sync.js.map +2 -2
  1023. package/dist/modules/staff/api/job-histories.js +11 -2
  1024. package/dist/modules/staff/api/job-histories.js.map +2 -2
  1025. package/dist/modules/staff/api/timesheets/time-entries/route.js +11 -4
  1026. package/dist/modules/staff/api/timesheets/time-entries/route.js.map +2 -2
  1027. package/dist/modules/staff/backend/staff/leave-requests/[id]/page.js +13 -8
  1028. package/dist/modules/staff/backend/staff/leave-requests/[id]/page.js.map +2 -2
  1029. package/dist/modules/staff/backend/staff/leave-requests/page.js +9 -1
  1030. package/dist/modules/staff/backend/staff/leave-requests/page.js.map +2 -2
  1031. package/dist/modules/staff/backend/staff/my-leave-requests/[id]/page.js +2 -1
  1032. package/dist/modules/staff/backend/staff/my-leave-requests/[id]/page.js.map +2 -2
  1033. package/dist/modules/staff/backend/staff/profile/create/page.js +1 -1
  1034. package/dist/modules/staff/backend/staff/profile/create/page.js.map +2 -2
  1035. package/dist/modules/staff/backend/staff/team-members/[id]/page.js +7 -4
  1036. package/dist/modules/staff/backend/staff/team-members/[id]/page.js.map +2 -2
  1037. package/dist/modules/staff/backend/staff/team-members/page.js +17 -27
  1038. package/dist/modules/staff/backend/staff/team-members/page.js.map +2 -2
  1039. package/dist/modules/staff/backend/staff/team-roles/[id]/edit/page.js +48 -2
  1040. package/dist/modules/staff/backend/staff/team-roles/[id]/edit/page.js.map +2 -2
  1041. package/dist/modules/staff/backend/staff/team-roles/page.js +17 -35
  1042. package/dist/modules/staff/backend/staff/team-roles/page.js.map +2 -2
  1043. package/dist/modules/staff/backend/staff/teams/[id]/edit/page.js +5 -2
  1044. package/dist/modules/staff/backend/staff/teams/[id]/edit/page.js.map +2 -2
  1045. package/dist/modules/staff/backend/staff/teams/page.js +24 -14
  1046. package/dist/modules/staff/backend/staff/teams/page.js.map +2 -2
  1047. package/dist/modules/staff/backend/staff/timesheets/page.js +4 -1
  1048. package/dist/modules/staff/backend/staff/timesheets/page.js.map +2 -2
  1049. package/dist/modules/staff/backend/staff/timesheets/projects/[id]/edit/page.js +18 -3
  1050. package/dist/modules/staff/backend/staff/timesheets/projects/[id]/edit/page.js.map +2 -2
  1051. package/dist/modules/staff/backend/staff/timesheets/projects/[id]/page.js +35 -5
  1052. package/dist/modules/staff/backend/staff/timesheets/projects/[id]/page.js.map +2 -2
  1053. package/dist/modules/staff/backend/staff/timesheets/projects/page.js +12 -3
  1054. package/dist/modules/staff/backend/staff/timesheets/projects/page.js.map +2 -2
  1055. package/dist/modules/staff/commands/activities.js +53 -0
  1056. package/dist/modules/staff/commands/activities.js.map +2 -2
  1057. package/dist/modules/staff/commands/addresses.js +70 -0
  1058. package/dist/modules/staff/commands/addresses.js.map +2 -2
  1059. package/dist/modules/staff/commands/comments.js +21 -1
  1060. package/dist/modules/staff/commands/comments.js.map +2 -2
  1061. package/dist/modules/staff/commands/job-histories.js +88 -3
  1062. package/dist/modules/staff/commands/job-histories.js.map +2 -2
  1063. package/dist/modules/staff/commands/leave-requests.js +39 -1
  1064. package/dist/modules/staff/commands/leave-requests.js.map +2 -2
  1065. package/dist/modules/staff/commands/tag-assignments.js +33 -0
  1066. package/dist/modules/staff/commands/tag-assignments.js.map +2 -2
  1067. package/dist/modules/staff/commands/team-members.js +43 -0
  1068. package/dist/modules/staff/commands/team-members.js.map +2 -2
  1069. package/dist/modules/staff/commands/team-roles.js +23 -0
  1070. package/dist/modules/staff/commands/team-roles.js.map +2 -2
  1071. package/dist/modules/staff/commands/teams.js +23 -0
  1072. package/dist/modules/staff/commands/teams.js.map +2 -2
  1073. package/dist/modules/staff/commands/timesheets-entries.js +31 -1
  1074. package/dist/modules/staff/commands/timesheets-entries.js.map +2 -2
  1075. package/dist/modules/staff/commands/timesheets-projects.js +56 -2
  1076. package/dist/modules/staff/commands/timesheets-projects.js.map +2 -2
  1077. package/dist/modules/staff/components/LeaveRequestForm.js +2 -0
  1078. package/dist/modules/staff/components/LeaveRequestForm.js.map +2 -2
  1079. package/dist/modules/staff/components/TeamForm.js +2 -1
  1080. package/dist/modules/staff/components/TeamForm.js.map +2 -2
  1081. package/dist/modules/staff/components/TeamMemberForm.js +35 -4
  1082. package/dist/modules/staff/components/TeamMemberForm.js.map +3 -3
  1083. package/dist/modules/staff/components/TeamRoleForm.js +4 -3
  1084. package/dist/modules/staff/components/TeamRoleForm.js.map +2 -2
  1085. package/dist/modules/staff/components/detail/JobHistorySection.js +20 -7
  1086. package/dist/modules/staff/components/detail/JobHistorySection.js.map +2 -2
  1087. package/dist/modules/staff/data/validators.js +7 -1
  1088. package/dist/modules/staff/data/validators.js.map +2 -2
  1089. package/dist/modules/staff/lib/leaveRequestHelpers.js +2 -1
  1090. package/dist/modules/staff/lib/leaveRequestHelpers.js.map +2 -2
  1091. package/dist/modules/translations/api/[entityType]/[entityId]/route.js +9 -1
  1092. package/dist/modules/translations/api/[entityType]/[entityId]/route.js.map +2 -2
  1093. package/dist/modules/translations/components/TranslationManager.js +12 -8
  1094. package/dist/modules/translations/components/TranslationManager.js.map +2 -2
  1095. package/dist/modules/workflows/acl.js +102 -17
  1096. package/dist/modules/workflows/acl.js.map +2 -2
  1097. package/dist/modules/workflows/api/definitions/[id]/route.js +106 -0
  1098. package/dist/modules/workflows/api/definitions/[id]/route.js.map +2 -2
  1099. package/dist/modules/workflows/backend/definitions/[id]/page.js +11 -3
  1100. package/dist/modules/workflows/backend/definitions/[id]/page.js.map +2 -2
  1101. package/dist/modules/workflows/backend/definitions/page.js +33 -13
  1102. package/dist/modules/workflows/backend/definitions/page.js.map +2 -2
  1103. package/dist/modules/workflows/backend/definitions/visual-editor/page.js +29 -16
  1104. package/dist/modules/workflows/backend/definitions/visual-editor/page.js.map +2 -2
  1105. package/dist/modules/workflows/components/NodeEditDialog.js +3 -1
  1106. package/dist/modules/workflows/components/NodeEditDialog.js.map +2 -2
  1107. package/dist/modules/workflows/components/WorkflowGraphImpl.js +4 -2
  1108. package/dist/modules/workflows/components/WorkflowGraphImpl.js.map +2 -2
  1109. package/dist/modules/workflows/components/formConfig.js +26 -13
  1110. package/dist/modules/workflows/components/formConfig.js.map +2 -2
  1111. package/dist/modules/workflows/components/nodes/ParallelForkNode.js +49 -0
  1112. package/dist/modules/workflows/components/nodes/ParallelForkNode.js.map +7 -0
  1113. package/dist/modules/workflows/components/nodes/ParallelJoinNode.js +49 -0
  1114. package/dist/modules/workflows/components/nodes/ParallelJoinNode.js.map +7 -0
  1115. package/dist/modules/workflows/components/nodes/index.js +4 -0
  1116. package/dist/modules/workflows/components/nodes/index.js.map +2 -2
  1117. package/dist/modules/workflows/data/entities.js +81 -0
  1118. package/dist/modules/workflows/data/entities.js.map +2 -2
  1119. package/dist/modules/workflows/data/validators.js +146 -1
  1120. package/dist/modules/workflows/data/validators.js.map +2 -2
  1121. package/dist/modules/workflows/di.js +12 -0
  1122. package/dist/modules/workflows/di.js.map +2 -2
  1123. package/dist/modules/workflows/events.js +7 -1
  1124. package/dist/modules/workflows/events.js.map +2 -2
  1125. package/dist/modules/workflows/lib/activity-executor.js +4 -2
  1126. package/dist/modules/workflows/lib/activity-executor.js.map +2 -2
  1127. package/dist/modules/workflows/lib/activity-queue-types.js.map +2 -2
  1128. package/dist/modules/workflows/lib/event-logger.js +2 -0
  1129. package/dist/modules/workflows/lib/event-logger.js.map +2 -2
  1130. package/dist/modules/workflows/lib/execution-token.js +98 -0
  1131. package/dist/modules/workflows/lib/execution-token.js.map +7 -0
  1132. package/dist/modules/workflows/lib/node-type-icons.js +14 -5
  1133. package/dist/modules/workflows/lib/node-type-icons.js.map +2 -2
  1134. package/dist/modules/workflows/lib/parallel-handler.js +364 -0
  1135. package/dist/modules/workflows/lib/parallel-handler.js.map +7 -0
  1136. package/dist/modules/workflows/lib/signal-handler.js +63 -1
  1137. package/dist/modules/workflows/lib/signal-handler.js.map +2 -2
  1138. package/dist/modules/workflows/lib/step-handler.js +74 -30
  1139. package/dist/modules/workflows/lib/step-handler.js.map +2 -2
  1140. package/dist/modules/workflows/lib/task-handler.js +26 -0
  1141. package/dist/modules/workflows/lib/task-handler.js.map +2 -2
  1142. package/dist/modules/workflows/lib/timer-handler.js +26 -1
  1143. package/dist/modules/workflows/lib/timer-handler.js.map +2 -2
  1144. package/dist/modules/workflows/lib/transition-handler.js +33 -21
  1145. package/dist/modules/workflows/lib/transition-handler.js.map +2 -2
  1146. package/dist/modules/workflows/lib/workflow-executor.js +54 -1
  1147. package/dist/modules/workflows/lib/workflow-executor.js.map +2 -2
  1148. package/dist/modules/workflows/migrations/Migration20260602120000.js +24 -0
  1149. package/dist/modules/workflows/migrations/Migration20260602120000.js.map +7 -0
  1150. package/dist/modules/workflows/workers/workflow-activities.worker.js +8 -4
  1151. package/dist/modules/workflows/workers/workflow-activities.worker.js.map +2 -2
  1152. package/generated/entities/channel_ingest_dead_letter/index.ts +11 -0
  1153. package/generated/entities/channel_thread_mapping/index.ts +11 -0
  1154. package/generated/entities/channel_thread_token/index.ts +7 -0
  1155. package/generated/entities/communication_channel/index.ts +20 -0
  1156. package/generated/entities/customer_interaction/index.ts +2 -0
  1157. package/generated/entities/customer_settings/index.ts +1 -0
  1158. package/generated/entities/dictionary/index.ts +1 -0
  1159. package/generated/entities/external_conversation/index.ts +11 -0
  1160. package/generated/entities/external_message/index.ts +11 -0
  1161. package/generated/entities/inbox_settings/index.ts +1 -0
  1162. package/generated/entities/integration_credentials/index.ts +1 -0
  1163. package/generated/entities/message/index.ts +1 -0
  1164. package/generated/entities/message_channel_link/index.ts +15 -0
  1165. package/generated/entities/message_reaction/index.ts +11 -0
  1166. package/generated/entities/role/index.ts +1 -0
  1167. package/generated/entities/step_instance/index.ts +1 -0
  1168. package/generated/entities/user/index.ts +1 -0
  1169. package/generated/entities/user_task/index.ts +1 -0
  1170. package/generated/entities/workflow_branch_instance/index.ts +18 -0
  1171. package/generated/entities/workflow_event/index.ts +1 -0
  1172. package/generated/entities/workflow_instance/index.ts +1 -0
  1173. package/generated/entities.ids.generated.ts +12 -0
  1174. package/generated/entity-fields-registry.ts +146 -0
  1175. package/jest.config.cjs +4 -0
  1176. package/jest.mocks/entities.ids.generated.js +9 -0
  1177. package/jest.setup.ts +17 -0
  1178. package/package.json +17 -15
  1179. package/src/helpers/integration/api.ts +15 -2
  1180. package/src/helpers/integration/authFixtures.ts +4 -1
  1181. package/src/helpers/integration/communicationChannelsFixtures.ts +130 -0
  1182. package/src/helpers/integration/crudFormFields.ts +48 -0
  1183. package/src/helpers/integration/crudFormPersistence.ts +178 -0
  1184. package/src/helpers/integration/currenciesFixtures.ts +60 -0
  1185. package/src/helpers/integration/customerAccountsFixtures.ts +256 -0
  1186. package/src/helpers/integration/dbFixtures.ts +15 -1
  1187. package/src/helpers/integration/inboxFixtures.ts +36 -0
  1188. package/src/helpers/integration/optimisticLockUi.ts +172 -0
  1189. package/src/helpers/integration/salesFixtures.ts +29 -0
  1190. package/src/helpers/integration/salesUi.ts +19 -12
  1191. package/src/helpers/integration/standaloneEnv.ts +62 -0
  1192. package/src/helpers/integration/undoHarness.ts +243 -0
  1193. package/src/helpers/integration/workflowsFixtures.ts +231 -0
  1194. package/src/modules/api_keys/backend/api-keys/page.tsx +18 -5
  1195. package/src/modules/api_keys/data/validators.ts +3 -1
  1196. package/src/modules/attachments/components/AttachmentPartitionSettings.tsx +19 -9
  1197. package/src/modules/attachments/lib/ocrQueue.ts +9 -1
  1198. package/src/modules/attachments/lib/security.ts +1 -1
  1199. package/src/modules/audit_logs/api/audit-logs/actions/redo/route.ts +3 -1
  1200. package/src/modules/audit_logs/api/audit-logs/actions/undo/route.ts +13 -2
  1201. package/src/modules/audit_logs/data/entities.ts +1 -1
  1202. package/src/modules/audit_logs/services/actionLogService.ts +18 -0
  1203. package/src/modules/auth/api/logout.ts +0 -12
  1204. package/src/modules/auth/api/roles/acl/route.ts +37 -11
  1205. package/src/modules/auth/api/roles/route.ts +56 -2
  1206. package/src/modules/auth/api/sidebar/preferences/route.ts +83 -3
  1207. package/src/modules/auth/api/users/acl/route.ts +94 -33
  1208. package/src/modules/auth/api/users/consents/route.ts +20 -0
  1209. package/src/modules/auth/api/users/resend-invite/route.ts +20 -0
  1210. package/src/modules/auth/api/users/route.ts +42 -1
  1211. package/src/modules/auth/backend/roles/[id]/edit/page.tsx +29 -4
  1212. package/src/modules/auth/backend/roles/page.tsx +17 -4
  1213. package/src/modules/auth/backend/users/[id]/edit/page.tsx +92 -6
  1214. package/src/modules/auth/backend/users/page.tsx +15 -2
  1215. package/src/modules/auth/cli.ts +20 -21
  1216. package/src/modules/auth/commands/roles.ts +81 -1
  1217. package/src/modules/auth/commands/users.ts +117 -6
  1218. package/src/modules/auth/components/AclEditor.tsx +10 -1
  1219. package/src/modules/auth/data/entities.ts +7 -1
  1220. package/src/modules/auth/frontend/reset/[token]/page.tsx +7 -2
  1221. package/src/modules/auth/lib/consentIntegrity.ts +18 -2
  1222. package/src/modules/auth/lib/emailHash.ts +5 -1
  1223. package/src/modules/auth/lib/grantChecks.ts +55 -1
  1224. package/src/modules/auth/lib/sessionIntegrity.ts +18 -1
  1225. package/src/modules/auth/services/authService.ts +10 -19
  1226. package/src/modules/auth/services/sidebarPreferencesService.ts +38 -4
  1227. package/src/modules/business_rules/api/rules/route.ts +30 -0
  1228. package/src/modules/business_rules/api/sets/route.ts +30 -0
  1229. package/src/modules/business_rules/backend/rules/[id]/page.tsx +16 -4
  1230. package/src/modules/business_rules/backend/rules/page.tsx +29 -12
  1231. package/src/modules/business_rules/backend/sets/[id]/page.tsx +16 -4
  1232. package/src/modules/business_rules/backend/sets/page.tsx +28 -11
  1233. package/src/modules/catalog/AGENTS.md +10 -0
  1234. package/src/modules/catalog/api/categories/route.ts +3 -0
  1235. package/src/modules/catalog/api/products/route.ts +4 -0
  1236. package/src/modules/catalog/backend/catalog/categories/[id]/edit/page.tsx +5 -0
  1237. package/src/modules/catalog/backend/catalog/products/[id]/page.tsx +174 -91
  1238. package/src/modules/catalog/backend/catalog/products/[productId]/variants/[variantId]/page.tsx +121 -34
  1239. package/src/modules/catalog/backend/catalog/products/[productId]/variants/create/page.tsx +22 -5
  1240. package/src/modules/catalog/backend/catalog/products/create/page.tsx +5 -28
  1241. package/src/modules/catalog/backend/catalog/products/optionSchemaClient.ts +2 -0
  1242. package/src/modules/catalog/commands/categories.ts +42 -0
  1243. package/src/modules/catalog/commands/offers.ts +44 -0
  1244. package/src/modules/catalog/commands/optionSchemas.ts +10 -0
  1245. package/src/modules/catalog/commands/priceKinds.ts +5 -0
  1246. package/src/modules/catalog/commands/prices.ts +50 -0
  1247. package/src/modules/catalog/commands/productUnitConversions.ts +32 -0
  1248. package/src/modules/catalog/commands/products.ts +87 -0
  1249. package/src/modules/catalog/commands/variants.ts +118 -32
  1250. package/src/modules/catalog/components/PriceKindSettings.tsx +21 -7
  1251. package/src/modules/catalog/components/categories/CategoriesDataTable.tsx +9 -0
  1252. package/src/modules/catalog/components/products/ProductMediaManager.tsx +2 -0
  1253. package/src/modules/catalog/components/products/ProductsDataTable.tsx +16 -4
  1254. package/src/modules/catalog/components/products/VariantBuilder.tsx +48 -9
  1255. package/src/modules/catalog/components/products/productForm.ts +41 -0
  1256. package/src/modules/catalog/components/products/variantForm.ts +10 -0
  1257. package/src/modules/catalog/lib/pricing.ts +8 -0
  1258. package/src/modules/communication_channels/acl.ts +43 -0
  1259. package/src/modules/communication_channels/api/delete/channels/[id]/route.ts +163 -0
  1260. package/src/modules/communication_channels/api/delete/messages/[messageId]/reactions/[reactionId]/route.ts +143 -0
  1261. package/src/modules/communication_channels/api/get/channels/[id]/health/route.ts +173 -0
  1262. package/src/modules/communication_channels/api/get/channels/[id]/route.ts +111 -0
  1263. package/src/modules/communication_channels/api/get/channels/route.ts +109 -0
  1264. package/src/modules/communication_channels/api/get/me/channels/route.ts +100 -0
  1265. package/src/modules/communication_channels/api/get/oauth/[provider]/callback/route.ts +355 -0
  1266. package/src/modules/communication_channels/api/post/channels/[id]/import-history/route.ts +206 -0
  1267. package/src/modules/communication_channels/api/post/channels/[id]/poll-now/route.ts +174 -0
  1268. package/src/modules/communication_channels/api/post/channels/[id]/push/register/route.ts +158 -0
  1269. package/src/modules/communication_channels/api/post/channels/[id]/set-primary/route.ts +114 -0
  1270. package/src/modules/communication_channels/api/post/channels/[id]/test-send/route.ts +241 -0
  1271. package/src/modules/communication_channels/api/post/channels/connect/credentials/route.ts +134 -0
  1272. package/src/modules/communication_channels/api/post/messages/[messageId]/reactions/route.ts +143 -0
  1273. package/src/modules/communication_channels/api/post/oauth/[provider]/initiate/route.ts +192 -0
  1274. package/src/modules/communication_channels/api/post/send-as-user/route.ts +125 -0
  1275. package/src/modules/communication_channels/api/post/test-seed/route.ts +294 -0
  1276. package/src/modules/communication_channels/api/post/webhook/[provider]/route.ts +227 -0
  1277. package/src/modules/communication_channels/api/post/webhooks/gmail/route.ts +161 -0
  1278. package/src/modules/communication_channels/api/put/threads/[threadId]/assign/route.ts +132 -0
  1279. package/src/modules/communication_channels/backend/communication_channels/channels/[id]/page.meta.ts +34 -0
  1280. package/src/modules/communication_channels/backend/communication_channels/channels/[id]/page.tsx +250 -0
  1281. package/src/modules/communication_channels/backend/communication_channels/channels/page.meta.ts +36 -0
  1282. package/src/modules/communication_channels/backend/communication_channels/channels/page.tsx +137 -0
  1283. package/src/modules/communication_channels/backend/profile/communication-channels/page.meta.ts +36 -0
  1284. package/src/modules/communication_channels/backend/profile/communication-channels/page.tsx +912 -0
  1285. package/src/modules/communication_channels/commands/connect-credential-channel.ts +243 -0
  1286. package/src/modules/communication_channels/commands/delete-channel.ts +193 -0
  1287. package/src/modules/communication_channels/commands/deliver-outbound-message.ts +579 -0
  1288. package/src/modules/communication_channels/commands/disconnect-channel.ts +241 -0
  1289. package/src/modules/communication_channels/commands/ingest-inbound-message.ts +602 -0
  1290. package/src/modules/communication_channels/commands/interceptors.ts +104 -0
  1291. package/src/modules/communication_channels/commands/process-inbound-reaction.ts +265 -0
  1292. package/src/modules/communication_channels/commands/push-register.ts +203 -0
  1293. package/src/modules/communication_channels/commands/push-renew.ts +49 -0
  1294. package/src/modules/communication_channels/commands/push-unregister.ts +168 -0
  1295. package/src/modules/communication_channels/commands/queue-import-history.ts +180 -0
  1296. package/src/modules/communication_channels/commands/reassign-conversation.ts +273 -0
  1297. package/src/modules/communication_channels/commands/set-primary-channel.ts +157 -0
  1298. package/src/modules/communication_channels/commands/toggle-outbound-reaction.ts +347 -0
  1299. package/src/modules/communication_channels/data/enrichers.ts +413 -0
  1300. package/src/modules/communication_channels/data/entities.ts +546 -0
  1301. package/src/modules/communication_channels/data/extensions.ts +76 -0
  1302. package/src/modules/communication_channels/data/validators.ts +138 -0
  1303. package/src/modules/communication_channels/di.ts +40 -0
  1304. package/src/modules/communication_channels/encryption.ts +44 -0
  1305. package/src/modules/communication_channels/events.ts +122 -0
  1306. package/src/modules/communication_channels/i18n/de.json +138 -0
  1307. package/src/modules/communication_channels/i18n/en.json +138 -0
  1308. package/src/modules/communication_channels/i18n/es.json +138 -0
  1309. package/src/modules/communication_channels/i18n/pl.json +138 -0
  1310. package/src/modules/communication_channels/index.ts +19 -0
  1311. package/src/modules/communication_channels/lib/access-control.ts +110 -0
  1312. package/src/modules/communication_channels/lib/adapter-compat.ts +57 -0
  1313. package/src/modules/communication_channels/lib/adapter-registry-singleton.ts +35 -0
  1314. package/src/modules/communication_channels/lib/adapter.ts +605 -0
  1315. package/src/modules/communication_channels/lib/connect-channel.ts +163 -0
  1316. package/src/modules/communication_channels/lib/contact-resolver.ts +162 -0
  1317. package/src/modules/communication_channels/lib/credential-refresh.ts +197 -0
  1318. package/src/modules/communication_channels/lib/dead-letter.ts +87 -0
  1319. package/src/modules/communication_channels/lib/email-capabilities.ts +60 -0
  1320. package/src/modules/communication_channels/lib/email-contact.ts +17 -0
  1321. package/src/modules/communication_channels/lib/email-mime.ts +501 -0
  1322. package/src/modules/communication_channels/lib/error-classification.ts +144 -0
  1323. package/src/modules/communication_channels/lib/gmail-pubsub-jwt.ts +278 -0
  1324. package/src/modules/communication_channels/lib/mutation-guards.ts +215 -0
  1325. package/src/modules/communication_channels/lib/oauth-client-config.ts +79 -0
  1326. package/src/modules/communication_channels/lib/oauth-state.ts +228 -0
  1327. package/src/modules/communication_channels/lib/oauth-token.ts +81 -0
  1328. package/src/modules/communication_channels/lib/pg-errors.ts +12 -0
  1329. package/src/modules/communication_channels/lib/provider-health.ts +47 -0
  1330. package/src/modules/communication_channels/lib/push-state.ts +38 -0
  1331. package/src/modules/communication_channels/lib/queue.ts +66 -0
  1332. package/src/modules/communication_channels/lib/reaction-processor-types.ts +51 -0
  1333. package/src/modules/communication_channels/lib/reaction-semantics.ts +48 -0
  1334. package/src/modules/communication_channels/lib/registry.ts +99 -0
  1335. package/src/modules/communication_channels/lib/route-mutation-guard.ts +68 -0
  1336. package/src/modules/communication_channels/lib/sanitize-channel-html.ts +129 -0
  1337. package/src/modules/communication_channels/lib/send-as-user.ts +284 -0
  1338. package/src/modules/communication_channels/lib/system-user.ts +74 -0
  1339. package/src/modules/communication_channels/lib/test-seed.ts +140 -0
  1340. package/src/modules/communication_channels/lib/thread-matcher.ts +430 -0
  1341. package/src/modules/communication_channels/lib/thread-token.ts +355 -0
  1342. package/src/modules/communication_channels/lib/use-connect-channel.ts +73 -0
  1343. package/src/modules/communication_channels/migrations/.snapshot-open-mercato.json +2142 -0
  1344. package/src/modules/communication_channels/migrations/Migration20260526134719_communication_channels.ts +55 -0
  1345. package/src/modules/communication_channels/migrations/Migration20260527195446_communication_channels.ts +20 -0
  1346. package/src/modules/communication_channels/migrations/Migration20260529231848_communication_channels.ts +13 -0
  1347. package/src/modules/communication_channels/migrations/Migration20260531120000_communication_channels.ts +24 -0
  1348. package/src/modules/communication_channels/notifications.client.ts +50 -0
  1349. package/src/modules/communication_channels/notifications.handlers.ts +86 -0
  1350. package/src/modules/communication_channels/notifications.ts +52 -0
  1351. package/src/modules/communication_channels/setup.ts +158 -0
  1352. package/src/modules/communication_channels/subscribers/channel-requires-reauth-notification.ts +118 -0
  1353. package/src/modules/communication_channels/subscribers/outbound-bridge.ts +175 -0
  1354. package/src/modules/communication_channels/subscribers/user-deleted-cascade.ts +100 -0
  1355. package/src/modules/communication_channels/widgets/components.ts +36 -0
  1356. package/src/modules/communication_channels/widgets/injection/channel-badge/widget.client.tsx +38 -0
  1357. package/src/modules/communication_channels/widgets/injection/channel-badge/widget.ts +51 -0
  1358. package/src/modules/communication_channels/widgets/injection/channel-info-panel/widget.client.tsx +278 -0
  1359. package/src/modules/communication_channels/widgets/injection/channel-info-panel/widget.ts +24 -0
  1360. package/src/modules/communication_channels/widgets/injection/channel-payload-renderer/widget.client.tsx +63 -0
  1361. package/src/modules/communication_channels/widgets/injection/channel-payload-renderer/widget.ts +29 -0
  1362. package/src/modules/communication_channels/widgets/injection/profile-channels-menu/widget.ts +34 -0
  1363. package/src/modules/communication_channels/widgets/injection/reaction-bar/widget.client.tsx +177 -0
  1364. package/src/modules/communication_channels/widgets/injection/reaction-bar/widget.ts +26 -0
  1365. package/src/modules/communication_channels/widgets/injection-table.ts +47 -0
  1366. package/src/modules/communication_channels/widgets/notifications/ChannelRequiresReauthRenderer.tsx +48 -0
  1367. package/src/modules/communication_channels/widgets/notifications/MessageReceivedRenderer.tsx +45 -0
  1368. package/src/modules/communication_channels/widgets/notifications/index.ts +2 -0
  1369. package/src/modules/communication_channels/workers/channel-import-history.ts +252 -0
  1370. package/src/modules/communication_channels/workers/gmail-history-sync.ts +223 -0
  1371. package/src/modules/communication_channels/workers/gmail-renew-watch.ts +141 -0
  1372. package/src/modules/communication_channels/workers/inbound-processor.ts +114 -0
  1373. package/src/modules/communication_channels/workers/outbound-delivery.ts +155 -0
  1374. package/src/modules/communication_channels/workers/poll-channel.ts +391 -0
  1375. package/src/modules/communication_channels/workers/poll-tick.ts +210 -0
  1376. package/src/modules/communication_channels/workers/reaction-processor.ts +264 -0
  1377. package/src/modules/configs/api/openapi.ts +12 -2
  1378. package/src/modules/currencies/backend/currencies/[id]/page.tsx +13 -6
  1379. package/src/modules/currencies/backend/currencies/page.tsx +26 -11
  1380. package/src/modules/currencies/backend/exchange-rates/[id]/page.tsx +3 -0
  1381. package/src/modules/currencies/backend/exchange-rates/page.tsx +21 -12
  1382. package/src/modules/currencies/commands/currencies.ts +42 -18
  1383. package/src/modules/currencies/commands/exchange-rates.ts +18 -8
  1384. package/src/modules/currencies/components/CurrencyFetchingConfig.tsx +31 -21
  1385. package/src/modules/currencies/i18n/de.json +1 -0
  1386. package/src/modules/currencies/i18n/en.json +1 -0
  1387. package/src/modules/currencies/i18n/es.json +1 -0
  1388. package/src/modules/currencies/i18n/pl.json +1 -0
  1389. package/src/modules/customer_accounts/api/admin/roles/[id].ts +35 -5
  1390. package/src/modules/customer_accounts/api/admin/roles.ts +2 -0
  1391. package/src/modules/customer_accounts/api/admin/users/[id].ts +57 -5
  1392. package/src/modules/customer_accounts/api/admin/users-invite.ts +17 -0
  1393. package/src/modules/customer_accounts/api/admin/users.ts +74 -23
  1394. package/src/modules/customer_accounts/api/login.ts +21 -4
  1395. package/src/modules/customer_accounts/api/portal/users-invite.ts +17 -0
  1396. package/src/modules/customer_accounts/api/signup.ts +3 -1
  1397. package/src/modules/customer_accounts/backend/customer_accounts/roles/[id]/page.tsx +34 -20
  1398. package/src/modules/customer_accounts/backend/customer_accounts/roles/page.tsx +20 -6
  1399. package/src/modules/customer_accounts/backend/customer_accounts/settings/domain/page.tsx +11 -4
  1400. package/src/modules/customer_accounts/backend/customer_accounts/users/[id]/page.tsx +28 -17
  1401. package/src/modules/customer_accounts/backend/customer_accounts/users/page.tsx +27 -11
  1402. package/src/modules/customer_accounts/data/validators.ts +1 -0
  1403. package/src/modules/customer_accounts/lib/customerEntityOwnership.ts +39 -0
  1404. package/src/modules/customer_accounts/lib/rateLimiter.ts +14 -0
  1405. package/src/modules/customer_accounts/lib/resolveTenantContext.ts +61 -4
  1406. package/src/modules/customer_accounts/services/customerInvitationService.ts +35 -2
  1407. package/src/modules/customer_accounts/services/customerUserService.ts +13 -7
  1408. package/src/modules/customer_accounts/subscribers/autoLinkCrmReverse.ts +3 -3
  1409. package/src/modules/customers/AGENTS.md +8 -2
  1410. package/src/modules/customers/acl.ts +18 -0
  1411. package/src/modules/customers/agentic/standalone-guide.md +1 -1
  1412. package/src/modules/customers/api/activities/route.ts +42 -21
  1413. package/src/modules/customers/api/addresses/route.ts +2 -0
  1414. package/src/modules/customers/api/companies/[id]/route.ts +26 -3
  1415. package/src/modules/customers/api/companies/route.ts +18 -5
  1416. package/src/modules/customers/api/deals/route.ts +3 -0
  1417. package/src/modules/customers/api/dictionaries/[kind]/route.ts +21 -46
  1418. package/src/modules/customers/api/dictionaries/cache.ts +3 -1
  1419. package/src/modules/customers/api/dictionaries/context.ts +1 -1
  1420. package/src/modules/customers/api/interactions/[id]/visibility/route.ts +179 -0
  1421. package/src/modules/customers/api/interactions/counts/route.ts +10 -0
  1422. package/src/modules/customers/api/interactions/route.ts +58 -11
  1423. package/src/modules/customers/api/people/[id]/email-threads/route.ts +92 -0
  1424. package/src/modules/customers/api/people/[id]/emails/route.ts +184 -0
  1425. package/src/modules/customers/api/people/[id]/route.ts +26 -8
  1426. package/src/modules/customers/api/people/route.ts +16 -5
  1427. package/src/modules/customers/api/pipeline-stages/route.ts +0 -14
  1428. package/src/modules/customers/api/settings/dictionary-sort-modes/route.ts +258 -0
  1429. package/src/modules/customers/api/todos/route.ts +29 -11
  1430. package/src/modules/customers/backend/config/customers/deals/page.tsx +1 -0
  1431. package/src/modules/customers/backend/config/customers/pipeline-stages/page.tsx +36 -21
  1432. package/src/modules/customers/backend/customers/companies/[id]/page.tsx +52 -27
  1433. package/src/modules/customers/backend/customers/companies/page.tsx +11 -1
  1434. package/src/modules/customers/backend/customers/companies-v2/[id]/page.tsx +27 -5
  1435. package/src/modules/customers/backend/customers/deals/[id]/hooks/useDealFormHandlers.ts +39 -7
  1436. package/src/modules/customers/backend/customers/deals/[id]/page.tsx +1 -0
  1437. package/src/modules/customers/backend/customers/deals/page.tsx +27 -7
  1438. package/src/modules/customers/backend/customers/deals/pipeline/page.tsx +64 -39
  1439. package/src/modules/customers/backend/customers/people/[id]/page.tsx +46 -26
  1440. package/src/modules/customers/backend/customers/people/page.tsx +11 -1
  1441. package/src/modules/customers/backend/customers/people-v2/[id]/page.tsx +95 -25
  1442. package/src/modules/customers/commands/activities.ts +28 -0
  1443. package/src/modules/customers/commands/addresses.ts +100 -14
  1444. package/src/modules/customers/commands/comments.ts +30 -0
  1445. package/src/modules/customers/commands/companies.ts +121 -1
  1446. package/src/modules/customers/commands/deals.ts +241 -101
  1447. package/src/modules/customers/commands/dictionaries.ts +45 -0
  1448. package/src/modules/customers/commands/entity-roles.ts +49 -0
  1449. package/src/modules/customers/commands/interactions.ts +264 -8
  1450. package/src/modules/customers/commands/labels.ts +85 -0
  1451. package/src/modules/customers/commands/people.ts +208 -13
  1452. package/src/modules/customers/commands/personCompanyLinks.ts +148 -70
  1453. package/src/modules/customers/commands/pipeline-stages.ts +16 -16
  1454. package/src/modules/customers/commands/settings.ts +41 -0
  1455. package/src/modules/customers/commands/tags.ts +59 -0
  1456. package/src/modules/customers/commands/todos.ts +28 -0
  1457. package/src/modules/customers/components/AddressFormatSettings.tsx +1 -0
  1458. package/src/modules/customers/components/CustomersConfigurationSections.tsx +3 -0
  1459. package/src/modules/customers/components/DictionarySettings.tsx +18 -13
  1460. package/src/modules/customers/components/DictionarySortSettings.tsx +268 -0
  1461. package/src/modules/customers/components/PipelineSettings.tsx +42 -21
  1462. package/src/modules/customers/components/detail/ActivityCard.tsx +48 -0
  1463. package/src/modules/customers/components/detail/ActivityForm.tsx +1 -0
  1464. package/src/modules/customers/components/detail/ActivityTimeline.tsx +3 -3
  1465. package/src/modules/customers/components/detail/AddressesSection.tsx +4 -0
  1466. package/src/modules/customers/components/detail/AnnualRevenueField.tsx +1 -0
  1467. package/src/modules/customers/components/detail/CompanyPeopleSection.tsx +2 -0
  1468. package/src/modules/customers/components/detail/ComposeEmailDialog.tsx +329 -0
  1469. package/src/modules/customers/components/detail/DealForm.tsx +3 -1
  1470. package/src/modules/customers/components/detail/DealsSection.tsx +30 -0
  1471. package/src/modules/customers/components/detail/EmailCardActions.tsx +263 -0
  1472. package/src/modules/customers/components/detail/EmailReplyForwardActions.tsx +53 -0
  1473. package/src/modules/customers/components/detail/EntityTagsDialog.tsx +7 -0
  1474. package/src/modules/customers/components/detail/ManageTagsDialog.tsx +4 -0
  1475. package/src/modules/customers/components/detail/PersonCompaniesSection.tsx +4 -0
  1476. package/src/modules/customers/components/detail/PersonDetailTabs.tsx +8 -1
  1477. package/src/modules/customers/components/detail/PersonEmailThreadsTab.tsx +448 -0
  1478. package/src/modules/customers/components/detail/RoleAssignmentRow.tsx +2 -0
  1479. package/src/modules/customers/components/detail/ScheduleActivityDialog.tsx +23 -7
  1480. package/src/modules/customers/components/detail/create/DealCurrencyField.tsx +1 -0
  1481. package/src/modules/customers/components/detail/hooks/useCustomerDictionary.ts +1 -0
  1482. package/src/modules/customers/components/detail/hooks/useInteractionMutations.ts +25 -15
  1483. package/src/modules/customers/components/detail/hooks/useInteractions.ts +76 -35
  1484. package/src/modules/customers/components/detail/hooks/usePersonTasks.ts +30 -17
  1485. package/src/modules/customers/components/detail/schedule/useScheduleFormState.ts +2 -0
  1486. package/src/modules/customers/components/detail/types.ts +1 -0
  1487. package/src/modules/customers/components/formConfig.tsx +134 -30
  1488. package/src/modules/customers/data/enrichers.ts +252 -1
  1489. package/src/modules/customers/data/entities.ts +51 -2
  1490. package/src/modules/customers/data/extensions.ts +26 -0
  1491. package/src/modules/customers/data/guards.ts +67 -0
  1492. package/src/modules/customers/data/validators.ts +46 -13
  1493. package/src/modules/customers/di.ts +66 -0
  1494. package/src/modules/customers/encryption.ts +11 -0
  1495. package/src/modules/customers/events.ts +4 -0
  1496. package/src/modules/customers/i18n/de.json +50 -0
  1497. package/src/modules/customers/i18n/en.json +50 -0
  1498. package/src/modules/customers/i18n/es.json +50 -0
  1499. package/src/modules/customers/i18n/pl.json +50 -0
  1500. package/src/modules/customers/lib/detailTenantScope.ts +36 -0
  1501. package/src/modules/customers/lib/findPeopleByAddresses.ts +107 -0
  1502. package/src/modules/customers/lib/kysely.ts +16 -0
  1503. package/src/modules/customers/lib/link-channel-message-handler.ts +571 -0
  1504. package/src/modules/customers/lib/personCompanyLinkTable.ts +39 -0
  1505. package/src/modules/customers/lib/personEmailThreads.ts +325 -0
  1506. package/src/modules/customers/lib/todoCompatibility.ts +14 -0
  1507. package/src/modules/customers/lib/visibilityFilter.ts +152 -0
  1508. package/src/modules/customers/migrations/.snapshot-open-mercato.json +392 -0
  1509. package/src/modules/customers/migrations/Migration20260527012240_customers.ts +23 -0
  1510. package/src/modules/customers/migrations/Migration20260602202147_customers.ts +13 -0
  1511. package/src/modules/customers/search.ts +6 -0
  1512. package/src/modules/customers/setup.ts +1 -0
  1513. package/src/modules/customers/subscribers/link-channel-message-received.ts +21 -0
  1514. package/src/modules/customers/subscribers/link-channel-message-sent.ts +21 -0
  1515. package/src/modules/dashboards/components/WidgetVisibilityEditor.tsx +2 -0
  1516. package/src/modules/data_sync/api/options.ts +7 -4
  1517. package/src/modules/data_sync/api/schedules/route.ts +9 -1
  1518. package/src/modules/data_sync/backend/data-sync/page.tsx +18 -5
  1519. package/src/modules/data_sync/components/IntegrationScheduleTab.tsx +46 -19
  1520. package/src/modules/data_sync/i18n/de.json +1 -0
  1521. package/src/modules/data_sync/i18n/en.json +1 -0
  1522. package/src/modules/data_sync/i18n/es.json +1 -0
  1523. package/src/modules/data_sync/i18n/pl.json +1 -0
  1524. package/src/modules/data_sync/lib/sync-schedule-service.ts +11 -0
  1525. package/src/modules/dictionaries/api/[dictionaryId]/entries/[entryId]/route.ts +8 -1
  1526. package/src/modules/dictionaries/api/[dictionaryId]/entries/route.ts +12 -5
  1527. package/src/modules/dictionaries/api/[dictionaryId]/route.ts +31 -0
  1528. package/src/modules/dictionaries/api/openapi.ts +2 -1
  1529. package/src/modules/dictionaries/api/route.ts +7 -0
  1530. package/src/modules/dictionaries/commands/entry-operations.ts +19 -0
  1531. package/src/modules/dictionaries/components/DictionariesManager.tsx +125 -14
  1532. package/src/modules/dictionaries/components/DictionaryEntriesEditor.tsx +31 -18
  1533. package/src/modules/dictionaries/components/DictionaryEntrySelect.tsx +56 -9
  1534. package/src/modules/dictionaries/components/DictionarySelectControl.tsx +9 -0
  1535. package/src/modules/dictionaries/components/dictionaryAppearance.tsx +5 -1
  1536. package/src/modules/dictionaries/components/hooks/useDictionaryEntries.ts +1 -0
  1537. package/src/modules/dictionaries/data/entities.ts +6 -0
  1538. package/src/modules/dictionaries/data/validators.ts +2 -0
  1539. package/src/modules/dictionaries/fields/dictionary.tsx +2 -2
  1540. package/src/modules/dictionaries/i18n/de.json +9 -0
  1541. package/src/modules/dictionaries/i18n/en.json +9 -0
  1542. package/src/modules/dictionaries/i18n/es.json +9 -0
  1543. package/src/modules/dictionaries/i18n/pl.json +9 -0
  1544. package/src/modules/dictionaries/lib/entrySort.ts +73 -0
  1545. package/src/modules/dictionaries/migrations/.snapshot-open-mercato.json +44 -0
  1546. package/src/modules/dictionaries/migrations/Migration20260602202147_dictionaries.ts +13 -0
  1547. package/src/modules/directory/api/get/organizations/lookup.ts +0 -8
  1548. package/src/modules/directory/api/organizations/route.ts +40 -16
  1549. package/src/modules/directory/backend/directory/organizations/[id]/edit/page.tsx +8 -0
  1550. package/src/modules/directory/backend/directory/organizations/page.tsx +18 -5
  1551. package/src/modules/directory/backend/directory/tenants/[id]/edit/page.tsx +16 -5
  1552. package/src/modules/directory/backend/directory/tenants/page.tsx +16 -4
  1553. package/src/modules/directory/commands/organizations.ts +74 -4
  1554. package/src/modules/directory/commands/tenants.ts +14 -1
  1555. package/src/modules/entities/api/records.ts +141 -6
  1556. package/src/modules/entities/backend/entities/user/[entityId]/records/[recordId]/page.tsx +7 -0
  1557. package/src/modules/entities/backend/entities/user/[entityId]/records/page.tsx +8 -4
  1558. package/src/modules/entities/components/UserEntitiesTable.tsx +8 -0
  1559. package/src/modules/entities/lib/entityAcl.ts +108 -0
  1560. package/src/modules/entities/lib/helpers.ts +40 -5
  1561. package/src/modules/feature_toggles/api/global/[id]/override/route.ts +18 -13
  1562. package/src/modules/feature_toggles/api/global/[id]/route.ts +1 -0
  1563. package/src/modules/feature_toggles/api/overrides/route.ts +26 -9
  1564. package/src/modules/feature_toggles/backend/feature-toggles/global/[id]/edit/page.tsx +42 -15
  1565. package/src/modules/feature_toggles/commands/global.ts +135 -10
  1566. package/src/modules/feature_toggles/commands/overrides.ts +8 -6
  1567. package/src/modules/feature_toggles/components/FeatureToggleOverrideCard.tsx +22 -12
  1568. package/src/modules/feature_toggles/components/FeatureTogglesTable.tsx +15 -2
  1569. package/src/modules/feature_toggles/components/formConfig.tsx +2 -1
  1570. package/src/modules/feature_toggles/components/overrideFormConfig.tsx +10 -1
  1571. package/src/modules/feature_toggles/data/validators.ts +11 -3
  1572. package/src/modules/feature_toggles/lib/queries.ts +5 -5
  1573. package/src/modules/feature_toggles/lib/utils.ts +3 -3
  1574. package/src/modules/inbox_ops/api/proposals/[id]/replies/[replyId]/send/route.ts +10 -1
  1575. package/src/modules/inbox_ops/api/settings/route.ts +25 -0
  1576. package/src/modules/inbox_ops/api/webhook/inbound.ts +99 -18
  1577. package/src/modules/inbox_ops/backend/inbox-ops/settings/page.tsx +15 -10
  1578. package/src/modules/inbox_ops/components/proposals/EditActionDialog.tsx +9 -4
  1579. package/src/modules/inbox_ops/data/entities.ts +7 -0
  1580. package/src/modules/inbox_ops/data/validators.ts +4 -0
  1581. package/src/modules/inbox_ops/encryption.ts +9 -0
  1582. package/src/modules/inbox_ops/i18n/de.json +2 -0
  1583. package/src/modules/inbox_ops/i18n/en.json +2 -0
  1584. package/src/modules/inbox_ops/i18n/es.json +2 -0
  1585. package/src/modules/inbox_ops/i18n/pl.json +2 -0
  1586. package/src/modules/inbox_ops/lib/executionEngine.ts +6 -1
  1587. package/src/modules/inbox_ops/lib/executionHelpers.ts +8 -7
  1588. package/src/modules/inbox_ops/lib/priceValidator.ts +82 -7
  1589. package/src/modules/inbox_ops/lib/rateLimiter.ts +84 -28
  1590. package/src/modules/inbox_ops/lib/translationProvider.ts +37 -5
  1591. package/src/modules/inbox_ops/migrations/.snapshot-open-mercato.json +16 -0
  1592. package/src/modules/inbox_ops/migrations/.snapshot-openmercato.json +16 -0
  1593. package/src/modules/inbox_ops/migrations/Migration20260607205834.ts +13 -0
  1594. package/src/modules/inbox_ops/subscribers/extractionWorker.ts +5 -2
  1595. package/src/modules/integrations/AGENTS.md +9 -0
  1596. package/src/modules/integrations/api/[id]/credentials/route.ts +12 -0
  1597. package/src/modules/integrations/backend/integrations/[id]/page.tsx +13 -0
  1598. package/src/modules/integrations/backend/integrations/bundle/[id]/page.tsx +20 -11
  1599. package/src/modules/integrations/backend/integrations/page.tsx +13 -8
  1600. package/src/modules/integrations/data/entities.ts +21 -1
  1601. package/src/modules/integrations/i18n/de.json +3 -0
  1602. package/src/modules/integrations/i18n/en.json +3 -0
  1603. package/src/modules/integrations/i18n/es.json +3 -0
  1604. package/src/modules/integrations/i18n/pl.json +3 -0
  1605. package/src/modules/integrations/lib/credentials-field-validation.ts +53 -0
  1606. package/src/modules/integrations/lib/credentials-service.ts +49 -13
  1607. package/src/modules/integrations/migrations/.snapshot-open-mercato.json +26 -1
  1608. package/src/modules/integrations/migrations/Migration20260526154136_integrations.ts +15 -0
  1609. package/src/modules/messages/api/route.ts +2 -2
  1610. package/src/modules/messages/api/token/[token]/route.ts +1 -3
  1611. package/src/modules/messages/commands/actions.ts +8 -6
  1612. package/src/modules/messages/commands/messages.ts +128 -23
  1613. package/src/modules/messages/commands/tokens.ts +1 -3
  1614. package/src/modules/messages/components/ComposeMessagePageClient.tsx +17 -0
  1615. package/src/modules/messages/components/MessageDetailPageClient.tsx +43 -0
  1616. package/src/modules/messages/components/MessagesInboxPageClient.tsx +12 -0
  1617. package/src/modules/messages/components/message-detail/hooks/useMessageDetailsActions.ts +6 -2
  1618. package/src/modules/messages/components/message-detail/utils.ts +18 -0
  1619. package/src/modules/messages/data/entities.ts +11 -0
  1620. package/src/modules/messages/data/validators.ts +8 -1
  1621. package/src/modules/messages/lib/actions.ts +9 -3
  1622. package/src/modules/messages/migrations/.snapshot-open-mercato.json +18 -0
  1623. package/src/modules/messages/migrations/Migration20260531130000.ts +15 -0
  1624. package/src/modules/messages/widgets/injection-table.ts +29 -0
  1625. package/src/modules/notifications/api/[id]/action/route.ts +13 -2
  1626. package/src/modules/notifications/api/route.ts +17 -4
  1627. package/src/modules/notifications/lib/notificationService.ts +31 -21
  1628. package/src/modules/notifications/lib/routeHelpers.ts +49 -8
  1629. package/src/modules/payment_gateways/api/status/route.ts +6 -0
  1630. package/src/modules/perspectives/api/[tableId]/route.ts +11 -2
  1631. package/src/modules/perspectives/services/perspectiveService.ts +13 -1
  1632. package/src/modules/planner/backend/planner/availability-rulesets/[id]/page.tsx +16 -14
  1633. package/src/modules/planner/backend/planner/availability-rulesets/page.tsx +6 -3
  1634. package/src/modules/planner/commands/availability-rule-sets.ts +19 -0
  1635. package/src/modules/planner/commands/availability.ts +9 -0
  1636. package/src/modules/planner/components/AvailabilityRuleSetForm.tsx +4 -1
  1637. package/src/modules/planner/components/AvailabilityRulesEditor.tsx +74 -17
  1638. package/src/modules/planner/components/AvailabilitySchedule.tsx +22 -7
  1639. package/src/modules/portal/frontend/[orgSlug]/portal/login/page.tsx +15 -16
  1640. package/src/modules/portal/frontend/[orgSlug]/portal/page.tsx +11 -31
  1641. package/src/modules/portal/frontend/[orgSlug]/portal/reset-password/page.tsx +8 -3
  1642. package/src/modules/portal/frontend/[orgSlug]/portal/signup/page.tsx +12 -9
  1643. package/src/modules/progress/api/jobs/[id]/route.ts +7 -0
  1644. package/src/modules/query_index/api/openapi.ts +2 -1
  1645. package/src/modules/query_index/api/reindex.ts +4 -0
  1646. package/src/modules/query_index/data/entities.ts +10 -0
  1647. package/src/modules/query_index/lib/engine.ts +66 -6
  1648. package/src/modules/query_index/lib/indexer.ts +71 -24
  1649. package/src/modules/query_index/lib/jobs.ts +57 -0
  1650. package/src/modules/query_index/lib/reindexer.ts +41 -15
  1651. package/src/modules/query_index/lib/search-tokens.ts +4 -4
  1652. package/src/modules/query_index/migrations/.snapshot-open-mercato.json +9 -0
  1653. package/src/modules/query_index/migrations/Migration20260606205453_query_index.ts +39 -0
  1654. package/src/modules/query_index/subscribers/delete_one.ts +36 -16
  1655. package/src/modules/query_index/subscribers/upsert_one.ts +44 -15
  1656. package/src/modules/resources/backend/resources/resource-types/[id]/edit/page.tsx +28 -3
  1657. package/src/modules/resources/backend/resources/resource-types/page.tsx +6 -3
  1658. package/src/modules/resources/backend/resources/resources/[id]/page.tsx +62 -4
  1659. package/src/modules/resources/backend/resources/resources/page.tsx +23 -4
  1660. package/src/modules/resources/commands/activities.ts +67 -0
  1661. package/src/modules/resources/commands/comments.ts +20 -0
  1662. package/src/modules/resources/commands/resource-types.ts +21 -0
  1663. package/src/modules/resources/commands/resources.ts +89 -0
  1664. package/src/modules/resources/commands/tag-assignments.ts +55 -0
  1665. package/src/modules/resources/components/ResourceCrudForm.tsx +103 -56
  1666. package/src/modules/resources/components/ResourceTypeCrudForm.tsx +3 -1
  1667. package/src/modules/resources/i18n/de.json +1 -0
  1668. package/src/modules/resources/i18n/en.json +1 -0
  1669. package/src/modules/resources/i18n/es.json +1 -0
  1670. package/src/modules/resources/i18n/pl.json +1 -0
  1671. package/src/modules/sales/api/documents/factory.ts +13 -1
  1672. package/src/modules/sales/api/shipping-methods/route.ts +4 -0
  1673. package/src/modules/sales/api/tax-rates/route.ts +4 -0
  1674. package/src/modules/sales/backend/sales/channels/[channelId]/edit/page.tsx +6 -0
  1675. package/src/modules/sales/backend/sales/channels/offers/page.tsx +10 -4
  1676. package/src/modules/sales/backend/sales/channels/page.tsx +19 -4
  1677. package/src/modules/sales/backend/sales/documents/[id]/page.tsx +75 -20
  1678. package/src/modules/sales/backend/sales/documents/create/page.tsx +2 -0
  1679. package/src/modules/sales/commands/configuration.ts +108 -2
  1680. package/src/modules/sales/commands/documentAddresses.ts +226 -4
  1681. package/src/modules/sales/commands/documents.ts +41 -9
  1682. package/src/modules/sales/commands/notes.ts +39 -0
  1683. package/src/modules/sales/commands/payments.ts +160 -14
  1684. package/src/modules/sales/commands/returns.ts +194 -3
  1685. package/src/modules/sales/commands/shared.ts +36 -0
  1686. package/src/modules/sales/commands/shipments.ts +63 -6
  1687. package/src/modules/sales/components/AdjustmentKindSettings.tsx +20 -11
  1688. package/src/modules/sales/components/DocumentNumberSettings.tsx +1 -0
  1689. package/src/modules/sales/components/OrderEditingSettings.tsx +1 -0
  1690. package/src/modules/sales/components/PaymentMethodsSettings.tsx +12 -4
  1691. package/src/modules/sales/components/ShippingMethodsSettings.tsx +12 -4
  1692. package/src/modules/sales/components/StatusSettings.tsx +20 -11
  1693. package/src/modules/sales/components/TaxRatesSettings.tsx +12 -5
  1694. package/src/modules/sales/components/channels/ChannelOfferForm.tsx +85 -20
  1695. package/src/modules/sales/components/channels/SalesChannelOffersPanel.tsx +10 -4
  1696. package/src/modules/sales/components/documents/AddressesSection.tsx +116 -48
  1697. package/src/modules/sales/components/documents/AdjustmentDialog.tsx +61 -18
  1698. package/src/modules/sales/components/documents/AdjustmentsSection.tsx +50 -25
  1699. package/src/modules/sales/components/documents/ItemsSection.tsx +25 -14
  1700. package/src/modules/sales/components/documents/LineItemDialog.tsx +107 -36
  1701. package/src/modules/sales/components/documents/PaymentDialog.tsx +33 -14
  1702. package/src/modules/sales/components/documents/PaymentsSection.tsx +22 -10
  1703. package/src/modules/sales/components/documents/ReturnDialog.tsx +28 -17
  1704. package/src/modules/sales/components/documents/ReturnsSection.tsx +4 -1
  1705. package/src/modules/sales/components/documents/SalesDocumentForm.tsx +1 -0
  1706. package/src/modules/sales/components/documents/SalesDocumentsTable.tsx +12 -5
  1707. package/src/modules/sales/components/documents/ShipmentDialog.tsx +132 -22
  1708. package/src/modules/sales/components/documents/ShipmentsSection.tsx +20 -10
  1709. package/src/modules/sales/components/documents/optimisticLock.ts +34 -0
  1710. package/src/modules/sales/components/documents/shipmentTypes.ts +1 -0
  1711. package/src/modules/sales/di.ts +35 -0
  1712. package/src/modules/sales/frontend/quote/[token]/page.tsx +8 -1
  1713. package/src/modules/sales/i18n/de.json +4 -0
  1714. package/src/modules/sales/i18n/en.json +4 -0
  1715. package/src/modules/sales/i18n/es.json +4 -0
  1716. package/src/modules/sales/i18n/pl.json +4 -0
  1717. package/src/modules/sales/lib/calculations.ts +32 -4
  1718. package/src/modules/sales/lib/dictionaries.ts +3 -2
  1719. package/src/modules/sales/lib/makeStatusDictionaryRoute.ts +2 -0
  1720. package/src/modules/shipping_carriers/api/cancel/route.ts +2 -2
  1721. package/src/modules/shipping_carriers/lib/status-sync.ts +19 -0
  1722. package/src/modules/staff/api/job-histories.ts +12 -2
  1723. package/src/modules/staff/api/timesheets/time-entries/route.ts +16 -4
  1724. package/src/modules/staff/backend/staff/leave-requests/[id]/page.tsx +12 -7
  1725. package/src/modules/staff/backend/staff/leave-requests/page.tsx +8 -1
  1726. package/src/modules/staff/backend/staff/my-leave-requests/[id]/page.tsx +2 -0
  1727. package/src/modules/staff/backend/staff/profile/create/page.tsx +1 -1
  1728. package/src/modules/staff/backend/staff/team-members/[id]/page.tsx +16 -5
  1729. package/src/modules/staff/backend/staff/team-members/page.tsx +18 -25
  1730. package/src/modules/staff/backend/staff/team-roles/[id]/edit/page.tsx +61 -6
  1731. package/src/modules/staff/backend/staff/team-roles/page.tsx +22 -34
  1732. package/src/modules/staff/backend/staff/teams/[id]/edit/page.tsx +13 -3
  1733. package/src/modules/staff/backend/staff/teams/page.tsx +24 -15
  1734. package/src/modules/staff/backend/staff/timesheets/page.tsx +10 -1
  1735. package/src/modules/staff/backend/staff/timesheets/projects/[id]/edit/page.tsx +22 -3
  1736. package/src/modules/staff/backend/staff/timesheets/projects/[id]/page.tsx +37 -7
  1737. package/src/modules/staff/backend/staff/timesheets/projects/page.tsx +9 -3
  1738. package/src/modules/staff/commands/activities.ts +56 -0
  1739. package/src/modules/staff/commands/addresses.ts +72 -0
  1740. package/src/modules/staff/commands/comments.ts +25 -0
  1741. package/src/modules/staff/commands/job-histories.ts +92 -3
  1742. package/src/modules/staff/commands/leave-requests.ts +40 -0
  1743. package/src/modules/staff/commands/tag-assignments.ts +35 -0
  1744. package/src/modules/staff/commands/team-members.ts +45 -0
  1745. package/src/modules/staff/commands/team-roles.ts +24 -0
  1746. package/src/modules/staff/commands/teams.ts +24 -0
  1747. package/src/modules/staff/commands/timesheets-entries.ts +31 -0
  1748. package/src/modules/staff/commands/timesheets-projects.ts +56 -0
  1749. package/src/modules/staff/components/LeaveRequestForm.tsx +3 -0
  1750. package/src/modules/staff/components/TeamForm.tsx +3 -1
  1751. package/src/modules/staff/components/TeamMemberForm.tsx +36 -3
  1752. package/src/modules/staff/components/TeamRoleForm.tsx +5 -3
  1753. package/src/modules/staff/components/detail/JobHistorySection.tsx +28 -6
  1754. package/src/modules/staff/data/validators.ts +6 -0
  1755. package/src/modules/staff/i18n/de.json +2 -0
  1756. package/src/modules/staff/i18n/en.json +2 -0
  1757. package/src/modules/staff/i18n/es.json +2 -0
  1758. package/src/modules/staff/i18n/pl.json +2 -0
  1759. package/src/modules/staff/lib/leaveRequestHelpers.ts +4 -0
  1760. package/src/modules/translations/api/[entityType]/[entityId]/route.ts +9 -1
  1761. package/src/modules/translations/components/TranslationManager.tsx +13 -8
  1762. package/src/modules/workflows/acl.ts +102 -17
  1763. package/src/modules/workflows/api/definitions/[id]/route.ts +112 -0
  1764. package/src/modules/workflows/backend/definitions/[id]/page.tsx +20 -4
  1765. package/src/modules/workflows/backend/definitions/page.tsx +34 -15
  1766. package/src/modules/workflows/backend/definitions/visual-editor/page.tsx +29 -16
  1767. package/src/modules/workflows/components/NodeEditDialog.tsx +2 -0
  1768. package/src/modules/workflows/components/WorkflowGraphImpl.tsx +3 -1
  1769. package/src/modules/workflows/components/formConfig.tsx +37 -17
  1770. package/src/modules/workflows/components/nodes/ParallelForkNode.tsx +66 -0
  1771. package/src/modules/workflows/components/nodes/ParallelJoinNode.tsx +66 -0
  1772. package/src/modules/workflows/components/nodes/index.ts +6 -0
  1773. package/src/modules/workflows/data/entities.ts +109 -0
  1774. package/src/modules/workflows/data/validators.ts +223 -0
  1775. package/src/modules/workflows/di.ts +20 -0
  1776. package/src/modules/workflows/events.ts +7 -0
  1777. package/src/modules/workflows/i18n/de.json +13 -0
  1778. package/src/modules/workflows/i18n/en.json +13 -0
  1779. package/src/modules/workflows/i18n/es.json +13 -0
  1780. package/src/modules/workflows/i18n/pl.json +13 -0
  1781. package/src/modules/workflows/lib/activity-executor.ts +8 -2
  1782. package/src/modules/workflows/lib/activity-queue-types.ts +3 -0
  1783. package/src/modules/workflows/lib/event-logger.ts +3 -0
  1784. package/src/modules/workflows/lib/execution-token.ts +166 -0
  1785. package/src/modules/workflows/lib/node-type-icons.ts +11 -2
  1786. package/src/modules/workflows/lib/parallel-handler.ts +575 -0
  1787. package/src/modules/workflows/lib/signal-handler.ts +72 -1
  1788. package/src/modules/workflows/lib/step-handler.ts +94 -34
  1789. package/src/modules/workflows/lib/task-handler.ts +32 -0
  1790. package/src/modules/workflows/lib/timer-handler.ts +30 -1
  1791. package/src/modules/workflows/lib/transition-handler.ts +56 -24
  1792. package/src/modules/workflows/lib/workflow-executor.ts +70 -1
  1793. package/src/modules/workflows/migrations/.snapshot-open-mercato.json +263 -0
  1794. package/src/modules/workflows/migrations/Migration20260602120000.ts +25 -0
  1795. package/src/modules/workflows/workers/workflow-activities.worker.ts +9 -4
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/sales/commands/documents.ts"],
4
- "sourcesContent": ["// @ts-nocheck\n\nimport { randomUUID } from \"crypto\";\nimport { z } from \"zod\";\nimport { registerCommand } from \"@open-mercato/shared/lib/commands\";\nimport type { CommandHandler } from \"@open-mercato/shared/lib/commands\";\nimport { withAtomicFlush } from \"@open-mercato/shared/lib/commands/flush\";\nimport {\n buildChanges,\n emitCrudSideEffects,\n requireId,\n type CrudEventsConfig,\n} from \"@open-mercato/shared/lib/commands/helpers\";\nimport { LockMode } from \"@mikro-orm/core\";\nimport type { EntityManager } from \"@mikro-orm/postgresql\";\nimport type { EventBus } from \"@open-mercato/events\";\nimport type { DataEngine } from \"@open-mercato/shared/lib/data/engine\";\nimport { CrudHttpError } from \"@open-mercato/shared/lib/crud/errors\";\nimport {\n deriveResourceFromCommandId,\n invalidateCrudCache,\n} from \"@open-mercato/shared/lib/crud/cache\";\nimport { resolveTranslations } from \"@open-mercato/shared/lib/i18n/server\";\nimport { resolveNotificationService } from \"../../notifications/lib/notificationService\";\nimport { buildFeatureNotificationFromType } from \"../../notifications/lib/notificationBuilder\";\nimport { setRecordCustomFields } from \"@open-mercato/core/modules/entities/lib/helpers\";\nimport { loadCustomFieldValues } from \"@open-mercato/shared/lib/crud/custom-fields\";\nimport { normalizeCustomFieldValues } from \"@open-mercato/shared/lib/custom-fields/normalize\";\nimport { E } from \"#generated/entities.ids.generated\";\nimport { findWithDecryption, findOneWithDecryption } from \"@open-mercato/shared/lib/encryption/find\";\nimport {\n SalesQuote,\n SalesQuoteLine,\n SalesQuoteAdjustment,\n SalesOrder,\n SalesOrderLine,\n SalesOrderAdjustment,\n SalesShipment,\n SalesShipmentItem,\n SalesPayment,\n SalesPaymentAllocation,\n SalesInvoice,\n SalesInvoiceLine,\n SalesCreditMemo,\n SalesCreditMemoLine,\n SalesDocumentAddress,\n SalesNote,\n SalesChannel,\n SalesShippingMethod,\n SalesDeliveryWindow,\n SalesPaymentMethod,\n SalesDocumentTag,\n SalesDocumentTagAssignment,\n type SalesLineKind,\n type SalesAdjustmentKind,\n type SalesSettings,\n} from \"../data/entities\";\nimport {\n CatalogProduct,\n CatalogProductUnitConversion,\n} from \"../../catalog/data/entities\";\nimport { Dictionary, DictionaryEntry } from \"../../dictionaries/data/entities\";\nimport { CustomFieldValue } from \"@open-mercato/core/modules/entities/data/entities\";\nimport {\n CustomerAddress,\n CustomerEntity,\n CustomerPersonProfile,\n} from \"../../customers/data/entities\";\nimport {\n enforceAdjustmentSign,\n validateReturnAdjustmentWithinRemaining,\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_GROSS_MESSAGE,\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_NET_MESSAGE,\n quoteCreateSchema,\n quoteLineCreateSchema,\n quoteAdjustmentCreateSchema,\n orderCreateSchema,\n orderLineCreateSchema,\n orderAdjustmentCreateSchema,\n invoiceCreateSchema,\n invoiceUpdateSchema,\n creditMemoCreateSchema,\n creditMemoUpdateSchema,\n customerSnapshotSchema,\n type QuoteCreateInput,\n type QuoteLineCreateInput,\n type QuoteAdjustmentCreateInput,\n type OrderCreateInput,\n type OrderLineCreateInput,\n type OrderAdjustmentCreateInput,\n type InvoiceCreateInput,\n type CreditMemoCreateInput,\n} from \"../data/validators\";\nimport {\n ensureOrganizationScope,\n ensureTenantScope,\n extractUndoPayload,\n toNumericString,\n} from \"./shared\";\nimport {\n loadShipmentSnapshot,\n restoreShipmentSnapshot,\n type ShipmentSnapshot,\n} from \"./shipments\";\nimport {\n loadPaymentSnapshot,\n restorePaymentSnapshot,\n type PaymentSnapshot,\n} from \"./payments\";\nimport type { SalesCalculationService } from \"../services/salesCalculationService\";\nimport type { TaxCalculationService } from \"../services/taxCalculationService\";\nimport type {\n PaymentMethodContext,\n ShippingMethodContext,\n} from \"../lib/providers\";\nimport {\n type SalesLineSnapshot,\n type SalesLineUomSnapshot,\n type SalesAdjustmentDraft,\n type SalesLineCalculationResult,\n type SalesDocumentCalculationResult,\n} from \"../lib/types\";\nimport { resolveDictionaryEntryValue } from \"../lib/dictionaries\";\nimport { resolveStatusEntryIdByValue } from \"../lib/statusHelpers\";\nimport { SalesDocumentNumberGenerator } from \"../services/salesDocumentNumberGenerator\";\nimport { loadSalesSettings } from \"./settings\";\nimport { notificationTypes } from \"../notifications\";\nimport {\n REFERENCE_UNIT_CODES,\n canonicalizeUnitCode,\n toUnitLookupKey,\n} from \"@open-mercato/shared/lib/units/unitCodes\";\nimport type { AuthContext } from \"@open-mercato/shared/lib/auth/server\";\nimport type { TranslateWithFallbackFn } from \"@open-mercato/shared/lib/i18n/translate\";\n\n// CRUD events configuration for workflow triggers\nconst orderCrudEvents: CrudEventsConfig<SalesOrder> = {\n module: \"sales\",\n entity: \"order\",\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n};\n\nconst quoteCrudEvents: CrudEventsConfig<SalesQuote> = {\n module: \"sales\",\n entity: \"quote\",\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 DocumentAddressSnapshot = {\n id: string;\n organizationId: string;\n tenantId: string;\n documentId: string;\n documentKind: \"order\" | \"quote\";\n customerAddressId: string | null;\n name: string | null;\n purpose: string | null;\n companyName: string | null;\n addressLine1: string;\n addressLine2: string | null;\n city: string | null;\n region: string | null;\n postalCode: string | null;\n country: string | null;\n buildingNumber: string | null;\n flatNumber: string | null;\n latitude: number | null;\n longitude: number | null;\n};\n\ntype NoteSnapshot = {\n id: string;\n organizationId: string;\n tenantId: string;\n contextType: \"order\" | \"quote\";\n contextId: string;\n orderId: string | null;\n quoteId: string | null;\n body: string;\n authorUserId: string | null;\n appearanceIcon: string | null;\n appearanceColor: string | null;\n};\n\ntype TagAssignmentSnapshot = {\n id: string;\n tagId: string;\n organizationId: string;\n tenantId: string;\n documentId: string;\n documentKind: \"order\" | \"quote\";\n};\n\ntype QuoteGraphSnapshot = {\n quote: {\n id: string;\n organizationId: string;\n tenantId: string;\n quoteNumber: string;\n statusEntryId: string | null;\n status: string | null;\n customerEntityId: string | null;\n customerContactId: string | null;\n customerSnapshot: Record<string, unknown> | null;\n billingAddressId: string | null;\n shippingAddressId: string | null;\n billingAddressSnapshot: Record<string, unknown> | null;\n shippingAddressSnapshot: Record<string, unknown> | null;\n currencyCode: string;\n validFrom: string | null;\n validUntil: string | null;\n comments: string | null;\n taxInfo: Record<string, unknown> | null;\n shippingMethodId: string | null;\n shippingMethodCode: string | null;\n deliveryWindowId: string | null;\n deliveryWindowCode: string | null;\n paymentMethodId: string | null;\n paymentMethodCode: string | null;\n channelId: string | null;\n shippingMethodSnapshot: Record<string, unknown> | null;\n deliveryWindowSnapshot: Record<string, unknown> | null;\n paymentMethodSnapshot: Record<string, unknown> | null;\n metadata: Record<string, unknown> | null;\n customFieldSetId: string | null;\n customFields: Record<string, unknown> | null;\n subtotalNetAmount: string;\n subtotalGrossAmount: string;\n discountTotalAmount: string;\n taxTotalAmount: string;\n grandTotalNetAmount: string;\n grandTotalGrossAmount: string;\n totalsSnapshot: Record<string, unknown> | null;\n lineItemCount: number;\n };\n lines: QuoteLineSnapshot[];\n adjustments: QuoteAdjustmentSnapshot[];\n addresses: DocumentAddressSnapshot[];\n notes: NoteSnapshot[];\n tags: TagAssignmentSnapshot[];\n};\n\ntype QuoteLineSnapshot = {\n id: string;\n lineNumber: number;\n kind: string;\n statusEntryId: string | null;\n status: string | null;\n productId: string | null;\n productVariantId: string | null;\n catalogSnapshot: Record<string, unknown> | null;\n name: string | null;\n description: string | null;\n comment: string | null;\n quantity: string;\n quantityUnit: string | null;\n normalizedQuantity: string;\n normalizedUnit: string | null;\n uomSnapshot: SalesLineUomSnapshot | null;\n currencyCode: string;\n unitPriceNet: string;\n unitPriceGross: string;\n discountAmount: string;\n discountPercent: string;\n taxRate: string;\n taxAmount: string;\n totalNetAmount: string;\n totalGrossAmount: string;\n configuration: Record<string, unknown> | null;\n promotionCode: string | null;\n promotionSnapshot: Record<string, unknown> | null;\n metadata: Record<string, unknown> | null;\n customFieldSetId: string | null;\n customFields: Record<string, unknown> | null;\n};\n\ntype QuoteAdjustmentSnapshot = {\n id: string;\n scope: \"order\" | \"line\";\n kind: string;\n code: string | null;\n label: string | null;\n calculatorKey: string | null;\n promotionId: string | null;\n rate: string;\n amountNet: string;\n amountGross: string;\n currencyCode: string | null;\n metadata: Record<string, unknown> | null;\n position: number;\n quoteLineId: string | null;\n customFields: Record<string, unknown> | null;\n};\n\ntype OrderGraphSnapshot = {\n order: {\n id: string;\n organizationId: string;\n tenantId: string;\n orderNumber: string;\n statusEntryId: string | null;\n status: string | null;\n fulfillmentStatusEntryId: string | null;\n fulfillmentStatus: string | null;\n paymentStatusEntryId: string | null;\n paymentStatus: string | null;\n customerEntityId: string | null;\n customerContactId: string | null;\n customerSnapshot: Record<string, unknown> | null;\n billingAddressId: string | null;\n shippingAddressId: string | null;\n billingAddressSnapshot: Record<string, unknown> | null;\n shippingAddressSnapshot: Record<string, unknown> | null;\n currencyCode: string;\n exchangeRate: string | null;\n taxStrategyKey: string | null;\n discountStrategyKey: string | null;\n taxInfo: Record<string, unknown> | null;\n shippingMethodId: string | null;\n shippingMethodCode: string | null;\n deliveryWindowId: string | null;\n deliveryWindowCode: string | null;\n paymentMethodId: string | null;\n paymentMethodCode: string | null;\n channelId: string | null;\n placedAt: string | null;\n expectedDeliveryAt: string | null;\n dueAt: string | null;\n comments: string | null;\n internalNotes: string | null;\n shippingMethodSnapshot: Record<string, unknown> | null;\n deliveryWindowSnapshot: Record<string, unknown> | null;\n paymentMethodSnapshot: Record<string, unknown> | null;\n metadata: Record<string, unknown> | null;\n customFieldSetId: string | null;\n customFields: Record<string, unknown> | null;\n subtotalNetAmount: string;\n subtotalGrossAmount: string;\n discountTotalAmount: string;\n taxTotalAmount: string;\n shippingNetAmount: string;\n shippingGrossAmount: string;\n surchargeTotalAmount: string;\n grandTotalNetAmount: string;\n grandTotalGrossAmount: string;\n paidTotalAmount: string;\n refundedTotalAmount: string;\n outstandingAmount: string;\n totalsSnapshot: Record<string, unknown> | null;\n lineItemCount: number;\n };\n lines: OrderLineSnapshot[];\n adjustments: OrderAdjustmentSnapshot[];\n addresses: DocumentAddressSnapshot[];\n notes: NoteSnapshot[];\n tags: TagAssignmentSnapshot[];\n shipments: ShipmentSnapshot[];\n payments: PaymentSnapshot[];\n};\n\ntype OrderLineSnapshot = {\n id: string;\n lineNumber: number;\n kind: string;\n statusEntryId: string | null;\n status: string | null;\n productId: string | null;\n productVariantId: string | null;\n catalogSnapshot: Record<string, unknown> | null;\n name: string | null;\n description: string | null;\n comment: string | null;\n quantity: string;\n quantityUnit: string | null;\n normalizedQuantity: string;\n normalizedUnit: string | null;\n uomSnapshot: SalesLineUomSnapshot | null;\n reservedQuantity: string;\n fulfilledQuantity: string;\n invoicedQuantity: string;\n returnedQuantity: string;\n currencyCode: string;\n unitPriceNet: string;\n unitPriceGross: string;\n discountAmount: string;\n discountPercent: string;\n taxRate: string;\n taxAmount: string;\n totalNetAmount: string;\n totalGrossAmount: string;\n configuration: Record<string, unknown> | null;\n promotionCode: string | null;\n promotionSnapshot: Record<string, unknown> | null;\n metadata: Record<string, unknown> | null;\n customFieldSetId: string | null;\n customFields: Record<string, unknown> | null;\n};\n\ntype OrderAdjustmentSnapshot = {\n id: string;\n scope: \"order\" | \"line\";\n kind: string;\n code: string | null;\n label: string | null;\n calculatorKey: string | null;\n promotionId: string | null;\n rate: string;\n amountNet: string;\n amountGross: string;\n currencyCode: string | null;\n metadata: Record<string, unknown> | null;\n position: number;\n orderLineId: string | null;\n customFields: Record<string, unknown> | null;\n};\n\ntype OrderUndoPayload = {\n before?: OrderGraphSnapshot | null;\n after?: OrderGraphSnapshot | null;\n};\n\ntype QuoteUndoPayload = {\n before?: QuoteGraphSnapshot | null;\n after?: QuoteGraphSnapshot | null;\n};\n\ntype QuoteConvertUndoPayload = {\n quote?: QuoteGraphSnapshot | null;\n order?: OrderGraphSnapshot | null;\n};\n\ntype InvoiceGraphSnapshot = {\n invoice: {\n id: string;\n organizationId: string;\n tenantId: string;\n invoiceNumber: string;\n orderId: string | null;\n statusEntryId: string | null;\n status: string | null;\n issueDate: string | Date | null;\n dueDate: string | Date | null;\n currencyCode: string;\n subtotalNetAmount: string;\n subtotalGrossAmount: string;\n discountTotalAmount: string;\n taxTotalAmount: string;\n grandTotalNetAmount: string;\n grandTotalGrossAmount: string;\n paidTotalAmount: string;\n outstandingAmount: string;\n metadata: Record<string, unknown> | null;\n customFieldSetId: string | null;\n customFields: Record<string, unknown> | null;\n };\n lines: InvoiceLineSnapshot[];\n};\n\ntype InvoiceLineSnapshot = {\n id: string;\n orderLineId: string | null;\n lineNumber: number;\n kind: string;\n name: string | null;\n sku: string | null;\n description: string | null;\n quantity: string;\n quantityUnit: string | null;\n normalizedQuantity: string;\n normalizedUnit: string | null;\n uomSnapshot: Record<string, unknown> | null;\n currencyCode: string;\n unitPriceNet: string;\n unitPriceGross: string;\n discountAmount: string;\n discountPercent: string;\n taxRate: string;\n taxAmount: string;\n totalNetAmount: string;\n totalGrossAmount: string;\n metadata: Record<string, unknown> | null;\n};\n\ntype CreditMemoGraphSnapshot = {\n creditMemo: {\n id: string;\n organizationId: string;\n tenantId: string;\n creditMemoNumber: string;\n orderId: string | null;\n invoiceId: string | null;\n statusEntryId: string | null;\n status: string | null;\n reason: string | null;\n issueDate: string | Date | null;\n currencyCode: string;\n subtotalNetAmount: string;\n subtotalGrossAmount: string;\n taxTotalAmount: string;\n grandTotalNetAmount: string;\n grandTotalGrossAmount: string;\n metadata: Record<string, unknown> | null;\n customFieldSetId: string | null;\n customFields: Record<string, unknown> | null;\n };\n lines: CreditMemoLineSnapshot[];\n};\n\ntype CreditMemoLineSnapshot = {\n id: string;\n orderLineId: string | null;\n lineNumber: number;\n name: string | null;\n sku: string | null;\n description: string | null;\n quantity: string;\n quantityUnit: string | null;\n normalizedQuantity: string;\n normalizedUnit: string | null;\n uomSnapshot: Record<string, unknown> | null;\n currencyCode: string;\n unitPriceNet: string;\n unitPriceGross: string;\n taxRate: string;\n taxAmount: string;\n totalNetAmount: string;\n totalGrossAmount: string;\n metadata: Record<string, unknown> | null;\n};\n\ntype InvoiceUndoPayload = {\n before?: InvoiceGraphSnapshot | null;\n after?: InvoiceGraphSnapshot | null;\n};\n\ntype CreditMemoUndoPayload = {\n before?: CreditMemoGraphSnapshot | null;\n after?: CreditMemoGraphSnapshot | null;\n};\n\nconst currencyCodeSchema = z\n .string()\n .trim()\n .toUpperCase()\n .regex(/^[A-Z]{3}$/, { message: \"currency_code_invalid\" });\n\nconst dateOnlySchema = z\n .string()\n .trim()\n .regex(/^\\d{4}-\\d{2}-\\d{2}$/, { message: \"invalid_date\" })\n .refine((value) => !Number.isNaN(new Date(value).getTime()), {\n message: \"invalid_date\",\n });\n\nconst addressSnapshotSchema = z\n .record(z.string(), z.unknown())\n .nullable()\n .optional();\n\nexport const documentUpdateSchema = z\n .object({\n id: z.string().uuid(),\n customerEntityId: z.string().uuid().nullable().optional(),\n customerContactId: z.string().uuid().nullable().optional(),\n customerSnapshot: customerSnapshotSchema.nullable().optional(),\n metadata: z.record(z.string(), z.unknown()).nullable().optional(),\n customerReference: z.string().nullable().optional(),\n externalReference: z.string().nullable().optional(),\n comment: z.string().nullable().optional(),\n orderNumber: z.string().trim().min(1).max(191).optional(),\n quoteNumber: z.string().trim().min(1).max(191).optional(),\n currencyCode: currencyCodeSchema.optional(),\n channelId: z.string().uuid().nullable().optional(),\n statusEntryId: z.string().uuid().nullable().optional(),\n placedAt: z.union([dateOnlySchema, z.null()]).optional(),\n expectedDeliveryAt: z.union([dateOnlySchema, z.null()]).optional(),\n shippingAddressId: z.string().uuid().nullable().optional(),\n billingAddressId: z.string().uuid().nullable().optional(),\n shippingAddressSnapshot: addressSnapshotSchema,\n billingAddressSnapshot: addressSnapshotSchema,\n shippingMethodId: z.string().uuid().nullable().optional(),\n shippingMethodCode: z.string().nullable().optional(),\n shippingMethodSnapshot: z\n .record(z.string(), z.unknown())\n .nullable()\n .optional(),\n paymentMethodId: z.string().uuid().nullable().optional(),\n paymentMethodCode: z.string().nullable().optional(),\n paymentMethodSnapshot: z\n .record(z.string(), z.unknown())\n .nullable()\n .optional(),\n tags: z.array(z.string().uuid()).optional(),\n customFields: z.record(z.string(), z.unknown()).optional(),\n customFieldSetId: z.string().uuid().nullable().optional(),\n })\n .refine(\n (input) =>\n typeof input.currencyCode === \"string\" ||\n input.placedAt !== undefined ||\n input.expectedDeliveryAt !== undefined ||\n input.channelId !== undefined ||\n input.statusEntryId !== undefined ||\n input.shippingAddressId !== undefined ||\n input.billingAddressId !== undefined ||\n input.customerEntityId !== undefined ||\n input.customerContactId !== undefined ||\n input.customerSnapshot !== undefined ||\n input.metadata !== undefined ||\n input.customerReference !== undefined ||\n input.externalReference !== undefined ||\n input.comment !== undefined ||\n input.orderNumber !== undefined ||\n input.quoteNumber !== undefined ||\n input.shippingAddressSnapshot !== undefined ||\n input.billingAddressSnapshot !== undefined ||\n input.shippingMethodId !== undefined ||\n input.shippingMethodCode !== undefined ||\n input.shippingMethodSnapshot !== undefined ||\n input.paymentMethodId !== undefined ||\n input.paymentMethodCode !== undefined ||\n input.paymentMethodSnapshot !== undefined ||\n input.tags !== undefined ||\n input.customFields !== undefined ||\n input.customFieldSetId !== undefined,\n { message: \"update_payload_empty\" },\n );\n\nexport type DocumentUpdateInput = z.infer<typeof documentUpdateSchema>;\n\ntype DocumentLineCreateInput = QuoteLineCreateInput | OrderLineCreateInput;\ntype DocumentAdjustmentCreateInput =\n | QuoteAdjustmentCreateInput\n | OrderAdjustmentCreateInput;\n\nfunction cloneJson<T>(value: T): T {\n if (value === null || value === undefined) return value;\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\nasync function resolveCustomerSnapshot(\n em: EntityManager,\n organizationId: string,\n tenantId: string,\n customerEntityId?: string | null,\n customerContactId?: string | null,\n): Promise<Record<string, unknown> | null> {\n if (!customerEntityId) return null;\n const customer = await em.findOne(\n CustomerEntity,\n { id: customerEntityId, organizationId, tenantId },\n { populate: [\"personProfile\", \"companyProfile\"] },\n );\n if (!customer) return null;\n\n const contact = customerContactId\n ? await em.findOne(CustomerPersonProfile, {\n id: customerContactId,\n organizationId,\n tenantId,\n })\n : null;\n\n return {\n customer: {\n id: customer.id,\n kind: customer.kind,\n displayName: customer.displayName,\n primaryEmail: customer.primaryEmail ?? null,\n primaryPhone: customer.primaryPhone ?? null,\n personProfile: customer.personProfile\n ? {\n id: customer.personProfile.id,\n firstName: customer.personProfile.firstName ?? null,\n lastName: customer.personProfile.lastName ?? null,\n preferredName: customer.personProfile.preferredName ?? null,\n }\n : null,\n companyProfile: customer.companyProfile\n ? {\n id: customer.companyProfile.id,\n legalName: customer.companyProfile.legalName ?? null,\n brandName: customer.companyProfile.brandName ?? null,\n domain: customer.companyProfile.domain ?? null,\n websiteUrl: customer.companyProfile.websiteUrl ?? null,\n }\n : null,\n },\n contact: contact\n ? {\n id: contact.id,\n firstName: contact.firstName ?? null,\n lastName: contact.lastName ?? null,\n preferredName: contact.preferredName ?? null,\n jobTitle: contact.jobTitle ?? null,\n department: contact.department ?? null,\n }\n : null,\n };\n}\n\nasync function resolveAddressSnapshot(\n em: EntityManager,\n organizationId: string,\n tenantId: string,\n addressId?: string | null,\n): Promise<Record<string, unknown> | null> {\n if (!addressId) return null;\n const address = await em.findOne(CustomerAddress, {\n id: addressId,\n organizationId,\n tenantId,\n });\n if (!address) return null;\n\n return {\n id: address.id,\n name: address.name ?? null,\n purpose: address.purpose ?? null,\n companyName: address.companyName ?? null,\n addressLine1: address.addressLine1,\n addressLine2: address.addressLine2 ?? null,\n buildingNumber: address.buildingNumber ?? null,\n flatNumber: address.flatNumber ?? null,\n city: address.city ?? null,\n region: address.region ?? null,\n postalCode: address.postalCode ?? null,\n country: address.country ?? null,\n latitude: address.latitude ?? null,\n longitude: address.longitude ?? null,\n isPrimary: address.isPrimary,\n };\n}\n\nasync function resolveDocumentReferences(\n em: EntityManager,\n parsed: {\n organizationId: string;\n tenantId: string;\n customerEntityId?: string | null;\n customerContactId?: string | null;\n customerSnapshot?: Record<string, unknown> | null;\n billingAddressId?: string | null;\n shippingAddressId?: string | null;\n billingAddressSnapshot?: Record<string, unknown> | null;\n shippingAddressSnapshot?: Record<string, unknown> | null;\n shippingMethodId?: string | null;\n deliveryWindowId?: string | null;\n paymentMethodId?: string | null;\n },\n): Promise<{\n customerSnapshot: Record<string, unknown> | null;\n billingAddressSnapshot: Record<string, unknown> | null;\n shippingAddressSnapshot: Record<string, unknown> | null;\n shippingMethod: SalesShippingMethod | null;\n deliveryWindow: SalesDeliveryWindow | null;\n paymentMethod: SalesPaymentMethod | null;\n}> {\n const [\n resolvedCustomerSnapshot,\n resolvedBillingSnapshot,\n resolvedShippingSnapshot,\n shippingMethod,\n deliveryWindow,\n paymentMethod,\n ] = await Promise.all([\n parsed.customerSnapshot\n ? Promise.resolve(cloneJson(parsed.customerSnapshot))\n : resolveCustomerSnapshot(\n em,\n parsed.organizationId,\n parsed.tenantId,\n parsed.customerEntityId ?? null,\n parsed.customerContactId ?? null,\n ),\n parsed.billingAddressSnapshot\n ? Promise.resolve(cloneJson(parsed.billingAddressSnapshot))\n : resolveAddressSnapshot(\n em,\n parsed.organizationId,\n parsed.tenantId,\n parsed.billingAddressId ?? null,\n ),\n parsed.shippingAddressSnapshot\n ? Promise.resolve(cloneJson(parsed.shippingAddressSnapshot))\n : resolveAddressSnapshot(\n em,\n parsed.organizationId,\n parsed.tenantId,\n parsed.shippingAddressId ?? null,\n ),\n parsed.shippingMethodId\n ? em.findOne(SalesShippingMethod, {\n id: parsed.shippingMethodId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n })\n : Promise.resolve(null),\n parsed.deliveryWindowId\n ? em.findOne(SalesDeliveryWindow, {\n id: parsed.deliveryWindowId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n })\n : Promise.resolve(null),\n parsed.paymentMethodId\n ? em.findOne(SalesPaymentMethod, {\n id: parsed.paymentMethodId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n })\n : Promise.resolve(null),\n ]);\n\n return {\n customerSnapshot: resolvedCustomerSnapshot\n ? cloneJson(resolvedCustomerSnapshot)\n : null,\n billingAddressSnapshot: resolvedBillingSnapshot\n ? cloneJson(resolvedBillingSnapshot)\n : null,\n shippingAddressSnapshot: resolvedShippingSnapshot\n ? cloneJson(resolvedShippingSnapshot)\n : null,\n shippingMethod: shippingMethod ?? null,\n deliveryWindow: deliveryWindow ?? null,\n paymentMethod: paymentMethod ?? null,\n };\n}\n\nfunction normalizeStatusValue(raw: unknown): string | null {\n if (typeof raw !== \"string\") return null;\n const trimmed = raw.trim();\n return trimmed.length ? trimmed : null;\n}\n\nfunction resolveNoteAuthorFromAuth(auth: AuthContext | null): string | null {\n if (!auth || auth.isApiKey) return null;\n const sub = typeof auth.sub === \"string\" ? auth.sub.trim() : \"\";\n const uuidRegex =\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/;\n return uuidRegex.test(sub) ? sub : null;\n}\n\nfunction resolveStatusChangeActor(auth: AuthContext | null, translate: TranslateWithFallbackFn): string {\n const unknownLabel = translate(\n \"sales.orders.status_change.actor_unknown\",\n \"unknown user\",\n );\n if (!auth) return unknownLabel;\n if (auth.isApiKey) {\n const keyName = typeof auth.keyName === \"string\" ? auth.keyName.trim() : \"\";\n const keyId = typeof auth.keyId === \"string\" ? auth.keyId.trim() : \"\";\n const label =\n keyName || keyId || (typeof auth.sub === \"string\" ? auth.sub : \"\");\n return label\n ? translate(\n \"sales.orders.status_change.actor_api_key\",\n \"API key {name}\",\n { name: label },\n )\n : unknownLabel;\n }\n const email = typeof auth.email === \"string\" ? auth.email.trim() : \"\";\n if (email) return email;\n const sub = typeof auth.sub === \"string\" ? auth.sub.trim() : \"\";\n if (sub) return sub;\n return unknownLabel;\n}\n\nfunction formatStatusLabel(status: string | null, translate: TranslateWithFallbackFn): string {\n if (status && status.trim().length) return status.trim();\n return translate(\"sales.orders.status_change.empty\", \"unset\");\n}\n\nasync function appendOrderStatusChangeNote({\n em,\n order,\n previousStatus,\n auth,\n}: {\n em: EntityManager;\n order: SalesOrder;\n previousStatus: string | null;\n auth: AuthContext | null;\n}): Promise<SalesNote | null> {\n const nextStatus = normalizeStatusValue(order.status);\n if (previousStatus === nextStatus) return null;\n const { translate } = await resolveTranslations();\n const body = translate(\n \"sales.orders.status_change.note\",\n \"Status changed from {from} to {to} by {actor}.\",\n {\n from: formatStatusLabel(previousStatus, translate),\n to: formatStatusLabel(nextStatus, translate),\n actor: resolveStatusChangeActor(auth, translate),\n },\n );\n const note = em.create(SalesNote, {\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n contextType: \"order\",\n contextId: order.id,\n order,\n authorUserId: resolveNoteAuthorFromAuth(auth),\n appearanceIcon: null,\n appearanceColor: null,\n body,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(note);\n return note;\n}\n\nasync function applyDocumentUpdate({\n kind,\n entity,\n input,\n em,\n}: {\n kind: \"order\" | \"quote\";\n entity: SalesOrder | SalesQuote;\n input: DocumentUpdateInput;\n em: EntityManager;\n}): Promise<void> {\n const organizationId = (entity as any).organizationId as string;\n const tenantId = (entity as any).tenantId as string;\n const status =\n typeof (entity as any).status === \"string\" ? (entity as any).status : null;\n const { translate } = await resolveTranslations();\n\n const wantsCustomerChange =\n input.customerEntityId !== undefined ||\n input.customerContactId !== undefined ||\n input.customerSnapshot !== undefined ||\n input.metadata !== undefined;\n const wantsAddressChange =\n input.shippingAddressId !== undefined ||\n input.billingAddressId !== undefined ||\n input.shippingAddressSnapshot !== undefined ||\n input.billingAddressSnapshot !== undefined;\n\n let settings: SalesSettings | null = null;\n if (kind === \"order\" && (wantsCustomerChange || wantsAddressChange)) {\n settings = await loadSalesSettings(em, { organizationId, tenantId });\n }\n\n const guardStatus = (\n allowed: string[] | null | undefined,\n errorKey: string,\n fallback: string,\n ) => {\n if (!Array.isArray(allowed)) return;\n if (allowed.length === 0) {\n throw new CrudHttpError(400, { error: translate(errorKey, fallback) });\n }\n if (!status || !allowed.includes(status)) {\n throw new CrudHttpError(400, { error: translate(errorKey, fallback) });\n }\n };\n\n if (kind === \"order\" && wantsCustomerChange) {\n guardStatus(\n settings?.orderCustomerEditableStatuses ?? null,\n \"sales.orders.edit_customer_blocked\",\n \"Editing the customer is blocked for this status.\",\n );\n }\n if (kind === \"order\" && wantsAddressChange) {\n guardStatus(\n settings?.orderAddressEditableStatuses ?? null,\n \"sales.orders.edit_addresses_blocked\",\n \"Editing addresses is blocked for this status.\",\n );\n }\n\n if (kind === \"order\" && typeof input.orderNumber === \"string\") {\n (entity as SalesOrder).orderNumber = input.orderNumber;\n }\n if (kind === \"quote\" && typeof input.quoteNumber === \"string\") {\n (entity as SalesQuote).quoteNumber = input.quoteNumber;\n }\n\n if (input.customerEntityId !== undefined) {\n entity.customerEntityId = input.customerEntityId ?? null;\n entity.customerSnapshot = await resolveCustomerSnapshot(\n em,\n organizationId,\n tenantId,\n input.customerEntityId,\n input.customerContactId ?? entity.customerContactId ?? null,\n );\n entity.customerContactId = input.customerContactId ?? null;\n entity.billingAddressId = null;\n entity.shippingAddressId = null;\n entity.billingAddressSnapshot = null;\n entity.shippingAddressSnapshot = null;\n }\n if (input.customerContactId !== undefined) {\n entity.customerContactId = input.customerContactId ?? null;\n if (entity.customerEntityId) {\n entity.customerSnapshot = await resolveCustomerSnapshot(\n em,\n organizationId,\n tenantId,\n entity.customerEntityId,\n input.customerContactId,\n );\n }\n }\n if (input.customerSnapshot !== undefined) {\n entity.customerSnapshot = input.customerSnapshot ?? null;\n }\n if (input.metadata !== undefined) {\n entity.metadata = input.metadata ?? null;\n }\n if (input.externalReference !== undefined) {\n const normalized =\n typeof input.externalReference === \"string\"\n ? input.externalReference.trim()\n : \"\";\n entity.externalReference = normalized.length ? normalized : null;\n }\n if (input.customerReference !== undefined) {\n const normalized =\n typeof input.customerReference === \"string\"\n ? input.customerReference.trim()\n : \"\";\n entity.customerReference = normalized.length ? normalized : null;\n }\n if (input.comment !== undefined) {\n const normalized =\n typeof input.comment === \"string\" ? input.comment.trim() : \"\";\n entity.comments = normalized.length ? normalized : null;\n }\n if (typeof input.currencyCode === \"string\") {\n entity.currencyCode = input.currencyCode;\n }\n if (input.channelId !== undefined) {\n if (input.channelId === null) {\n entity.channelId = null;\n } else {\n const channel = await em.findOne(SalesChannel, {\n id: input.channelId,\n organizationId,\n tenantId,\n deletedAt: null,\n });\n if (!channel) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.documents.detail.channelInvalid\",\n \"Selected channel could not be found.\",\n ),\n });\n }\n entity.channelId = channel.id;\n }\n }\n if (input.statusEntryId !== undefined) {\n const statusValue = await resolveDictionaryEntryValue(\n em,\n input.statusEntryId,\n );\n if (input.statusEntryId && !statusValue) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.documents.detail.statusInvalid\",\n \"Selected status could not be found.\",\n ),\n });\n }\n (entity as any).statusEntryId = input.statusEntryId ?? null;\n (entity as any).status = statusValue;\n }\n if (input.placedAt !== undefined) {\n if (input.placedAt === null) {\n entity.placedAt = null;\n } else {\n const parsed = new Date(input.placedAt);\n entity.placedAt = Number.isNaN(parsed.getTime())\n ? entity.placedAt\n : parsed;\n }\n }\n if (\n input.expectedDeliveryAt !== undefined &&\n \"expectedDeliveryAt\" in entity\n ) {\n if (input.expectedDeliveryAt === null) {\n (entity as SalesOrder).expectedDeliveryAt = null;\n } else {\n const parsed = new Date(input.expectedDeliveryAt);\n (entity as SalesOrder).expectedDeliveryAt = Number.isNaN(parsed.getTime())\n ? (entity as SalesOrder).expectedDeliveryAt\n : parsed;\n }\n }\n if (input.shippingAddressId !== undefined) {\n entity.shippingAddressId = input.shippingAddressId ?? null;\n if (input.shippingAddressSnapshot === undefined) {\n entity.shippingAddressSnapshot = await resolveAddressSnapshot(\n em,\n organizationId,\n tenantId,\n input.shippingAddressId,\n );\n }\n }\n if (input.billingAddressId !== undefined) {\n entity.billingAddressId = input.billingAddressId ?? null;\n if (input.billingAddressSnapshot === undefined) {\n entity.billingAddressSnapshot = await resolveAddressSnapshot(\n em,\n organizationId,\n tenantId,\n input.billingAddressId,\n );\n }\n }\n if (input.shippingAddressSnapshot !== undefined) {\n entity.shippingAddressSnapshot = input.shippingAddressSnapshot ?? null;\n }\n if (input.billingAddressSnapshot !== undefined) {\n entity.billingAddressSnapshot = input.billingAddressSnapshot ?? null;\n }\n if (\n input.shippingMethodId !== undefined ||\n input.shippingMethodSnapshot !== undefined ||\n input.shippingMethodCode !== undefined\n ) {\n let shippingMethod: SalesShippingMethod | null = null;\n if (input.shippingMethodId) {\n shippingMethod = await em.findOne(SalesShippingMethod, {\n id: input.shippingMethodId,\n organizationId,\n tenantId,\n deletedAt: null,\n });\n if (!shippingMethod) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.documents.detail.shippingMethodInvalid\",\n \"Selected shipping method could not be found.\",\n ),\n });\n }\n }\n (entity as any).shippingMethodId = input.shippingMethodId ?? null;\n (entity as any).shippingMethod = shippingMethod ?? null;\n (entity as any).shippingMethodCode =\n input.shippingMethodCode ?? shippingMethod?.code ?? null;\n if (input.shippingMethodSnapshot !== undefined) {\n (entity as any).shippingMethodSnapshot =\n input.shippingMethodSnapshot ?? null;\n } else {\n (entity as any).shippingMethodSnapshot = shippingMethod\n ? {\n id: shippingMethod.id,\n code: shippingMethod.code,\n name: shippingMethod.name,\n description: shippingMethod.description ?? null,\n carrierCode: shippingMethod.carrierCode ?? null,\n providerKey: shippingMethod.providerKey ?? null,\n serviceLevel: shippingMethod.serviceLevel ?? null,\n estimatedTransitDays: shippingMethod.estimatedTransitDays ?? null,\n baseRateNet: shippingMethod.baseRateNet,\n baseRateGross: shippingMethod.baseRateGross,\n currencyCode: shippingMethod.currencyCode ?? null,\n metadata: shippingMethod.metadata\n ? cloneJson(shippingMethod.metadata)\n : null,\n providerSettings:\n shippingMethod.metadata &&\n typeof shippingMethod.metadata === \"object\"\n ? cloneJson(\n (shippingMethod.metadata as Record<string, unknown>)\n .providerSettings ?? null,\n )\n : null,\n }\n : null;\n }\n }\n if (\n input.paymentMethodId !== undefined ||\n input.paymentMethodSnapshot !== undefined ||\n input.paymentMethodCode !== undefined\n ) {\n let paymentMethod: SalesPaymentMethod | null = null;\n if (input.paymentMethodId) {\n paymentMethod = await em.findOne(SalesPaymentMethod, {\n id: input.paymentMethodId,\n organizationId,\n tenantId,\n deletedAt: null,\n });\n if (!paymentMethod) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.documents.detail.paymentMethodInvalid\",\n \"Selected payment method could not be found.\",\n ),\n });\n }\n }\n (entity as any).paymentMethodId = input.paymentMethodId ?? null;\n (entity as any).paymentMethod = paymentMethod ?? null;\n (entity as any).paymentMethodCode =\n input.paymentMethodCode ?? paymentMethod?.code ?? null;\n if (input.paymentMethodSnapshot !== undefined) {\n (entity as any).paymentMethodSnapshot =\n input.paymentMethodSnapshot ?? null;\n } else {\n (entity as any).paymentMethodSnapshot = paymentMethod\n ? {\n id: paymentMethod.id,\n code: paymentMethod.code,\n name: paymentMethod.name,\n description: paymentMethod.description ?? null,\n providerKey: paymentMethod.providerKey ?? null,\n terms: paymentMethod.terms ?? null,\n metadata: paymentMethod.metadata\n ? cloneJson(paymentMethod.metadata)\n : null,\n providerSettings:\n paymentMethod.metadata &&\n typeof paymentMethod.metadata === \"object\"\n ? cloneJson(\n (paymentMethod.metadata as Record<string, unknown>)\n .providerSettings ?? null,\n )\n : null,\n }\n : null;\n }\n }\n\n if (input.tags !== undefined) {\n await syncSalesDocumentTags(em, {\n documentId: entity.id,\n kind,\n organizationId,\n tenantId,\n tagIds: input.tags,\n });\n }\n\n if (input.customFieldSetId !== undefined) {\n (entity as any).customFieldSetId = input.customFieldSetId ?? null;\n }\n\n if (input.customFields !== undefined) {\n const values =\n input.customFields &&\n typeof input.customFields === \"object\" &&\n !Array.isArray(input.customFields)\n ? (input.customFields as Record<string, unknown>)\n : {};\n await setRecordCustomFields(em, {\n entityId: kind === \"order\" ? E.sales.sales_order : E.sales.sales_quote,\n recordId: entity.id,\n organizationId,\n tenantId,\n values,\n });\n }\n}\n\nasync function loadQuoteSnapshot(\n em: EntityManager,\n id: string,\n): Promise<QuoteGraphSnapshot | null> {\n const quote = await findOneWithDecryption(em, SalesQuote, { id, deletedAt: null });\n if (!quote) return null;\n const decryptionScope = { tenantId: quote.tenantId, organizationId: quote.organizationId };\n const lines = await findWithDecryption(\n em,\n SalesQuoteLine,\n { quote },\n { orderBy: { lineNumber: \"asc\" } },\n decryptionScope,\n );\n const adjustments = await findWithDecryption(\n em,\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n decryptionScope,\n );\n const [\n addresses,\n notes,\n tags,\n quoteCustomFields,\n lineCustomFields,\n adjustmentCustomFields,\n ] = await Promise.all([\n findWithDecryption(\n em,\n SalesDocumentAddress,\n { documentId: id, documentKind: \"quote\" },\n undefined,\n { tenantId: quote.tenantId, organizationId: quote.organizationId },\n ),\n findWithDecryption(\n em,\n SalesNote,\n { contextType: \"quote\", contextId: id },\n undefined,\n { tenantId: quote.tenantId, organizationId: quote.organizationId },\n ),\n findWithDecryption(\n em,\n SalesDocumentTagAssignment,\n { documentId: id, documentKind: \"quote\" },\n { populate: [\"tag\"] },\n { tenantId: quote.tenantId, organizationId: quote.organizationId },\n ),\n loadCustomFieldValues({\n em,\n entityId: E.sales.sales_quote,\n recordIds: [quote.id],\n tenantIdByRecord: { [quote.id]: quote.tenantId },\n organizationIdByRecord: { [quote.id]: quote.organizationId },\n }),\n lines.length\n ? loadCustomFieldValues({\n em,\n entityId: E.sales.sales_quote_line,\n recordIds: lines.map((line) => line.id),\n tenantIdByRecord: Object.fromEntries(\n lines.map((line) => [line.id, quote.tenantId]),\n ),\n organizationIdByRecord: Object.fromEntries(\n lines.map((line) => [line.id, quote.organizationId]),\n ),\n })\n : Promise.resolve({}),\n adjustments.length\n ? loadCustomFieldValues({\n em,\n entityId: E.sales.sales_quote_adjustment,\n recordIds: adjustments.map((adj) => adj.id),\n tenantIdByRecord: Object.fromEntries(\n adjustments.map((adj) => [adj.id, quote.tenantId]),\n ),\n organizationIdByRecord: Object.fromEntries(\n adjustments.map((adj) => [adj.id, quote.organizationId]),\n ),\n })\n : Promise.resolve({}),\n ]);\n const addressSnapshots: DocumentAddressSnapshot[] = addresses.map(\n (entry) => ({\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n documentId: entry.documentId,\n documentKind: \"quote\",\n customerAddressId: entry.customerAddressId ?? null,\n name: entry.name ?? null,\n purpose: entry.purpose ?? null,\n companyName: entry.companyName ?? null,\n addressLine1: entry.addressLine1,\n addressLine2: entry.addressLine2 ?? null,\n city: entry.city ?? null,\n region: entry.region ?? null,\n postalCode: entry.postalCode ?? null,\n country: entry.country ?? null,\n buildingNumber: entry.buildingNumber ?? null,\n flatNumber: entry.flatNumber ?? null,\n latitude: entry.latitude ?? null,\n longitude: entry.longitude ?? null,\n }),\n );\n const noteSnapshots: NoteSnapshot[] = notes.map((entry) => ({\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n contextType: entry.contextType as \"order\" | \"quote\",\n contextId: entry.contextId,\n orderId: entry.order\n ? typeof entry.order === \"string\"\n ? entry.order\n : entry.order.id\n : null,\n quoteId: entry.quote\n ? typeof entry.quote === \"string\"\n ? entry.quote\n : entry.quote.id\n : null,\n body: entry.body,\n authorUserId: entry.authorUserId ?? null,\n appearanceIcon: entry.appearanceIcon ?? null,\n appearanceColor: entry.appearanceColor ?? null,\n }));\n const tagSnapshots: TagAssignmentSnapshot[] = tags\n .map((assignment) => {\n const tagId =\n typeof assignment.tag === \"string\"\n ? assignment.tag\n : (assignment.tag?.id ?? (assignment as any)?.tag_id ?? null);\n if (!tagId) return null;\n return {\n id: assignment.id,\n tagId,\n organizationId: assignment.organizationId,\n tenantId: assignment.tenantId,\n documentId: assignment.documentId,\n documentKind: \"quote\",\n };\n })\n .filter((entry): entry is TagAssignmentSnapshot => !!entry);\n\n return {\n quote: {\n id: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteNumber: quote.quoteNumber,\n statusEntryId: quote.statusEntryId ?? null,\n status: quote.status ?? null,\n customerEntityId: quote.customerEntityId ?? null,\n customerContactId: quote.customerContactId ?? null,\n customerSnapshot: quote.customerSnapshot\n ? cloneJson(quote.customerSnapshot)\n : null,\n billingAddressId: quote.billingAddressId ?? null,\n shippingAddressId: quote.shippingAddressId ?? null,\n billingAddressSnapshot: quote.billingAddressSnapshot\n ? cloneJson(quote.billingAddressSnapshot)\n : null,\n shippingAddressSnapshot: quote.shippingAddressSnapshot\n ? cloneJson(quote.shippingAddressSnapshot)\n : null,\n currencyCode: quote.currencyCode,\n validFrom: quote.validFrom ? quote.validFrom.toISOString() : null,\n validUntil: quote.validUntil ? quote.validUntil.toISOString() : null,\n comments: quote.comments ?? null,\n taxInfo: quote.taxInfo ? cloneJson(quote.taxInfo) : null,\n shippingMethodId: quote.shippingMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n deliveryWindowId: quote.deliveryWindowId ?? null,\n deliveryWindowCode: quote.deliveryWindowCode ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n channelId: quote.channelId ?? null,\n shippingMethodSnapshot: quote.shippingMethodSnapshot\n ? cloneJson(quote.shippingMethodSnapshot)\n : null,\n deliveryWindowSnapshot: quote.deliveryWindowSnapshot\n ? cloneJson(quote.deliveryWindowSnapshot)\n : null,\n paymentMethodSnapshot: quote.paymentMethodSnapshot\n ? cloneJson(quote.paymentMethodSnapshot)\n : null,\n metadata: quote.metadata ? cloneJson(quote.metadata) : null,\n customFieldSetId: quote.customFieldSetId ?? null,\n customFields: quoteCustomFields[quote.id]\n ? cloneJson(quoteCustomFields[quote.id])\n : null,\n subtotalNetAmount: quote.subtotalNetAmount,\n subtotalGrossAmount: quote.subtotalGrossAmount,\n discountTotalAmount: quote.discountTotalAmount,\n taxTotalAmount: quote.taxTotalAmount,\n grandTotalNetAmount: quote.grandTotalNetAmount,\n grandTotalGrossAmount: quote.grandTotalGrossAmount,\n totalsSnapshot: quote.totalsSnapshot\n ? cloneJson(quote.totalsSnapshot)\n : null,\n lineItemCount: quote.lineItemCount,\n },\n lines: lines.map((line) => ({\n id: line.id,\n lineNumber: line.lineNumber,\n kind: line.kind,\n statusEntryId: line.statusEntryId ?? null,\n status: line.status ?? null,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: line.normalizedQuantity ?? line.quantity,\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n discountAmount: line.discountAmount,\n discountPercent: line.discountPercent,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n totalNetAmount: line.totalNetAmount,\n totalGrossAmount: line.totalGrossAmount,\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n customFields: lineCustomFields[line.id]\n ? cloneJson(lineCustomFields[line.id])\n : null,\n })),\n adjustments: adjustments.map((adj) => ({\n id: adj.id,\n scope: adj.scope,\n kind: adj.kind,\n code: adj.code ?? null,\n label: adj.label ?? null,\n calculatorKey: adj.calculatorKey ?? null,\n promotionId: adj.promotionId ?? null,\n rate: adj.rate,\n amountNet: adj.amountNet,\n amountGross: adj.amountGross,\n currencyCode: adj.currencyCode ?? null,\n metadata: adj.metadata ? cloneJson(adj.metadata) : null,\n position: adj.position,\n quoteLineId:\n typeof adj.quoteLine === \"string\"\n ? adj.quoteLine\n : (adj.quoteLine?.id ?? null),\n customFields: adjustmentCustomFields[adj.id]\n ? cloneJson(adjustmentCustomFields[adj.id])\n : null,\n })),\n addresses: addressSnapshots,\n notes: noteSnapshots,\n tags: tagSnapshots,\n };\n}\n\nasync function loadOrderSnapshot(\n em: EntityManager,\n id: string,\n): Promise<OrderGraphSnapshot | null> {\n const order = await findOneWithDecryption(em, SalesOrder, { id, deletedAt: null });\n if (!order) return null;\n const decryptionScope = { tenantId: order.tenantId, organizationId: order.organizationId };\n const lines = await findWithDecryption(\n em,\n SalesOrderLine,\n { order },\n { orderBy: { lineNumber: \"asc\" } },\n decryptionScope,\n );\n const adjustments = await findWithDecryption(\n em,\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n decryptionScope,\n );\n const [\n addresses,\n notes,\n tags,\n shipments,\n payments,\n orderCustomFields,\n lineCustomFields,\n adjustmentCustomFields,\n ] = await Promise.all([\n findWithDecryption(\n em,\n SalesDocumentAddress,\n { documentId: id, documentKind: \"order\" },\n undefined,\n { tenantId: order.tenantId, organizationId: order.organizationId },\n ),\n findWithDecryption(\n em,\n SalesNote,\n { contextType: \"order\", contextId: id },\n undefined,\n { tenantId: order.tenantId, organizationId: order.organizationId },\n ),\n findWithDecryption(\n em,\n SalesDocumentTagAssignment,\n { documentId: id, documentKind: \"order\" },\n { populate: [\"tag\"] },\n { tenantId: order.tenantId, organizationId: order.organizationId },\n ),\n em.find(SalesShipment, { order: order }),\n em.find(SalesPayment, { order: order }),\n loadCustomFieldValues({\n em,\n entityId: E.sales.sales_order,\n recordIds: [order.id],\n tenantIdByRecord: { [order.id]: order.tenantId },\n organizationIdByRecord: { [order.id]: order.organizationId },\n }),\n lines.length\n ? loadCustomFieldValues({\n em,\n entityId: E.sales.sales_order_line,\n recordIds: lines.map((line) => line.id),\n tenantIdByRecord: Object.fromEntries(\n lines.map((line) => [line.id, order.tenantId]),\n ),\n organizationIdByRecord: Object.fromEntries(\n lines.map((line) => [line.id, order.organizationId]),\n ),\n })\n : Promise.resolve({}),\n adjustments.length\n ? loadCustomFieldValues({\n em,\n entityId: E.sales.sales_order_adjustment,\n recordIds: adjustments.map((adj) => adj.id),\n tenantIdByRecord: Object.fromEntries(\n adjustments.map((adj) => [adj.id, order.tenantId]),\n ),\n organizationIdByRecord: Object.fromEntries(\n adjustments.map((adj) => [adj.id, order.organizationId]),\n ),\n })\n : Promise.resolve({}),\n ]);\n const shipmentSnapshots = (\n await Promise.all(\n shipments.map((entry) => loadShipmentSnapshot(em, entry.id)),\n )\n ).filter((entry): entry is ShipmentSnapshot => !!entry);\n const paymentSnapshots = (\n await Promise.all(\n payments.map((entry) => loadPaymentSnapshot(em, entry.id)),\n )\n ).filter((entry): entry is PaymentSnapshot => !!entry);\n const addressSnapshots: DocumentAddressSnapshot[] = addresses.map(\n (entry) => ({\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n documentId: entry.documentId,\n documentKind: \"order\",\n customerAddressId: entry.customerAddressId ?? null,\n name: entry.name ?? null,\n purpose: entry.purpose ?? null,\n companyName: entry.companyName ?? null,\n addressLine1: entry.addressLine1,\n addressLine2: entry.addressLine2 ?? null,\n city: entry.city ?? null,\n region: entry.region ?? null,\n postalCode: entry.postalCode ?? null,\n country: entry.country ?? null,\n buildingNumber: entry.buildingNumber ?? null,\n flatNumber: entry.flatNumber ?? null,\n latitude: entry.latitude ?? null,\n longitude: entry.longitude ?? null,\n }),\n );\n const noteSnapshots: NoteSnapshot[] = notes.map((entry) => ({\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n contextType: entry.contextType as \"order\" | \"quote\",\n contextId: entry.contextId,\n orderId: entry.order\n ? typeof entry.order === \"string\"\n ? entry.order\n : entry.order.id\n : null,\n quoteId: entry.quote\n ? typeof entry.quote === \"string\"\n ? entry.quote\n : entry.quote.id\n : null,\n body: entry.body,\n authorUserId: entry.authorUserId ?? null,\n appearanceIcon: entry.appearanceIcon ?? null,\n appearanceColor: entry.appearanceColor ?? null,\n }));\n const tagSnapshots: TagAssignmentSnapshot[] = tags\n .map((assignment) => {\n const tagId =\n typeof assignment.tag === \"string\"\n ? assignment.tag\n : (assignment.tag?.id ?? (assignment as any)?.tag_id ?? null);\n if (!tagId) return null;\n return {\n id: assignment.id,\n tagId,\n organizationId: assignment.organizationId,\n tenantId: assignment.tenantId,\n documentId: assignment.documentId,\n documentKind: \"order\",\n };\n })\n .filter((entry): entry is TagAssignmentSnapshot => !!entry);\n\n return {\n order: {\n id: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderNumber: order.orderNumber,\n statusEntryId: order.statusEntryId ?? null,\n status: order.status ?? null,\n fulfillmentStatusEntryId: order.fulfillmentStatusEntryId ?? null,\n fulfillmentStatus: order.fulfillmentStatus ?? null,\n paymentStatusEntryId: order.paymentStatusEntryId ?? null,\n paymentStatus: order.paymentStatus ?? null,\n customerEntityId: order.customerEntityId ?? null,\n customerContactId: order.customerContactId ?? null,\n customerSnapshot: order.customerSnapshot\n ? cloneJson(order.customerSnapshot)\n : null,\n billingAddressId: order.billingAddressId ?? null,\n shippingAddressId: order.shippingAddressId ?? null,\n billingAddressSnapshot: order.billingAddressSnapshot\n ? cloneJson(order.billingAddressSnapshot)\n : null,\n shippingAddressSnapshot: order.shippingAddressSnapshot\n ? cloneJson(order.shippingAddressSnapshot)\n : null,\n currencyCode: order.currencyCode,\n exchangeRate: order.exchangeRate ?? null,\n taxStrategyKey: order.taxStrategyKey ?? null,\n discountStrategyKey: order.discountStrategyKey ?? null,\n taxInfo: order.taxInfo ? cloneJson(order.taxInfo) : null,\n shippingMethodId: order.shippingMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n deliveryWindowId: order.deliveryWindowId ?? null,\n deliveryWindowCode: order.deliveryWindowCode ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n channelId: order.channelId ?? null,\n placedAt: order.placedAt ? order.placedAt.toISOString() : null,\n expectedDeliveryAt: order.expectedDeliveryAt\n ? order.expectedDeliveryAt.toISOString()\n : null,\n dueAt: order.dueAt ? order.dueAt.toISOString() : null,\n comments: order.comments ?? null,\n internalNotes: order.internalNotes ?? null,\n shippingMethodSnapshot: order.shippingMethodSnapshot\n ? cloneJson(order.shippingMethodSnapshot)\n : null,\n deliveryWindowSnapshot: order.deliveryWindowSnapshot\n ? cloneJson(order.deliveryWindowSnapshot)\n : null,\n paymentMethodSnapshot: order.paymentMethodSnapshot\n ? cloneJson(order.paymentMethodSnapshot)\n : null,\n metadata: order.metadata ? cloneJson(order.metadata) : null,\n customFieldSetId: order.customFieldSetId ?? null,\n customFields: orderCustomFields[order.id]\n ? cloneJson(orderCustomFields[order.id])\n : null,\n subtotalNetAmount: order.subtotalNetAmount,\n subtotalGrossAmount: order.subtotalGrossAmount,\n discountTotalAmount: order.discountTotalAmount,\n taxTotalAmount: order.taxTotalAmount,\n shippingNetAmount: order.shippingNetAmount,\n shippingGrossAmount: order.shippingGrossAmount,\n surchargeTotalAmount: order.surchargeTotalAmount,\n grandTotalNetAmount: order.grandTotalNetAmount,\n grandTotalGrossAmount: order.grandTotalGrossAmount,\n paidTotalAmount: order.paidTotalAmount,\n refundedTotalAmount: order.refundedTotalAmount,\n outstandingAmount: order.outstandingAmount,\n totalsSnapshot: order.totalsSnapshot\n ? cloneJson(order.totalsSnapshot)\n : null,\n lineItemCount: order.lineItemCount,\n },\n lines: lines.map((line) => ({\n id: line.id,\n lineNumber: line.lineNumber,\n kind: line.kind,\n statusEntryId: line.statusEntryId ?? null,\n status: line.status ?? null,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: line.normalizedQuantity ?? line.quantity,\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n reservedQuantity: line.reservedQuantity,\n fulfilledQuantity: line.fulfilledQuantity,\n invoicedQuantity: line.invoicedQuantity,\n returnedQuantity: line.returnedQuantity,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n discountAmount: line.discountAmount,\n discountPercent: line.discountPercent,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n totalNetAmount: line.totalNetAmount,\n totalGrossAmount: line.totalGrossAmount,\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n customFields: lineCustomFields[line.id]\n ? cloneJson(lineCustomFields[line.id])\n : null,\n })),\n adjustments: adjustments.map((adj) => ({\n id: adj.id,\n scope: adj.scope,\n kind: adj.kind,\n code: adj.code ?? null,\n label: adj.label ?? null,\n calculatorKey: adj.calculatorKey ?? null,\n promotionId: adj.promotionId ?? null,\n rate: adj.rate,\n amountNet: adj.amountNet,\n amountGross: adj.amountGross,\n currencyCode: adj.currencyCode ?? null,\n metadata: adj.metadata ? cloneJson(adj.metadata) : null,\n position: adj.position,\n orderLineId:\n typeof adj.orderLine === \"string\"\n ? adj.orderLine\n : (adj.orderLine?.id ?? null),\n customFields: adjustmentCustomFields[adj.id]\n ? cloneJson(adjustmentCustomFields[adj.id])\n : null,\n })),\n addresses: addressSnapshots,\n notes: noteSnapshots,\n tags: tagSnapshots,\n shipments: shipmentSnapshots,\n payments: paymentSnapshots,\n };\n}\n\nasync function loadInvoiceSnapshot(\n em: EntityManager,\n id: string,\n): Promise<InvoiceGraphSnapshot | null> {\n const invoice = await em.findOne(SalesInvoice, { id, deletedAt: null });\n if (!invoice) return null;\n const lines = await em.find(\n SalesInvoiceLine,\n { invoice: invoice },\n { orderBy: { lineNumber: \"asc\" } },\n );\n const [invoiceCustomFields] = await Promise.all([\n loadCustomFieldValues({\n em,\n entityId: E.sales.sales_invoice,\n recordIds: [invoice.id],\n tenantIdByRecord: { [invoice.id]: invoice.tenantId },\n organizationIdByRecord: { [invoice.id]: invoice.organizationId },\n }),\n ]);\n return {\n invoice: {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n invoiceNumber: invoice.invoiceNumber,\n orderId: invoice.orderId ?? null,\n statusEntryId: invoice.statusEntryId ?? null,\n status: invoice.status ?? null,\n issueDate: invoice.issueDate ?? null,\n dueDate: invoice.dueDate ?? null,\n currencyCode: invoice.currencyCode,\n subtotalNetAmount: String(invoice.subtotalNetAmount),\n subtotalGrossAmount: String(invoice.subtotalGrossAmount),\n discountTotalAmount: String(invoice.discountTotalAmount),\n taxTotalAmount: String(invoice.taxTotalAmount),\n grandTotalNetAmount: String(invoice.grandTotalNetAmount),\n grandTotalGrossAmount: String(invoice.grandTotalGrossAmount),\n paidTotalAmount: String(invoice.paidTotalAmount),\n outstandingAmount: String(invoice.outstandingAmount),\n metadata: invoice.metadata ?? null,\n customFieldSetId: invoice.customFieldSetId ?? null,\n customFields: invoiceCustomFields[invoice.id] ?? null,\n },\n lines: lines.map((line) => ({\n id: line.id,\n orderLineId: line.orderLineId ?? null,\n lineNumber: line.lineNumber,\n kind: line.kind ?? \"product\",\n name: line.name ?? null,\n sku: line.sku ?? null,\n description: line.description ?? null,\n quantity: String(line.quantity),\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: String(line.normalizedQuantity),\n normalizedUnit: line.normalizedUnit ?? null,\n uomSnapshot: line.uomSnapshot ?? null,\n currencyCode: line.currencyCode,\n unitPriceNet: String(line.unitPriceNet),\n unitPriceGross: String(line.unitPriceGross),\n discountAmount: String(line.discountAmount),\n discountPercent: String(line.discountPercent),\n taxRate: String(line.taxRate),\n taxAmount: String(line.taxAmount),\n totalNetAmount: String(line.totalNetAmount),\n totalGrossAmount: String(line.totalGrossAmount),\n metadata: line.metadata ?? null,\n })),\n };\n}\n\nasync function loadCreditMemoSnapshot(\n em: EntityManager,\n id: string,\n): Promise<CreditMemoGraphSnapshot | null> {\n const creditMemo = await em.findOne(SalesCreditMemo, { id, deletedAt: null });\n if (!creditMemo) return null;\n const lines = await em.find(\n SalesCreditMemoLine,\n { creditMemo: creditMemo },\n { orderBy: { lineNumber: \"asc\" } },\n );\n const [creditMemoCustomFields] = await Promise.all([\n loadCustomFieldValues({\n em,\n entityId: E.sales.sales_credit_memo,\n recordIds: [creditMemo.id],\n tenantIdByRecord: { [creditMemo.id]: creditMemo.tenantId },\n organizationIdByRecord: { [creditMemo.id]: creditMemo.organizationId },\n }),\n ]);\n return {\n creditMemo: {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n creditMemoNumber: creditMemo.creditMemoNumber,\n orderId: creditMemo.orderId ?? null,\n invoiceId: creditMemo.invoiceId ?? null,\n statusEntryId: creditMemo.statusEntryId ?? null,\n status: creditMemo.status ?? null,\n reason: creditMemo.reason ?? null,\n issueDate: creditMemo.issueDate ?? null,\n currencyCode: creditMemo.currencyCode,\n subtotalNetAmount: String(creditMemo.subtotalNetAmount),\n subtotalGrossAmount: String(creditMemo.subtotalGrossAmount),\n taxTotalAmount: String(creditMemo.taxTotalAmount),\n grandTotalNetAmount: String(creditMemo.grandTotalNetAmount),\n grandTotalGrossAmount: String(creditMemo.grandTotalGrossAmount),\n metadata: creditMemo.metadata ?? null,\n customFieldSetId: creditMemo.customFieldSetId ?? null,\n customFields: creditMemoCustomFields[creditMemo.id] ?? null,\n },\n lines: lines.map((line) => ({\n id: line.id,\n orderLineId: line.orderLineId ?? null,\n lineNumber: line.lineNumber,\n name: line.name ?? null,\n sku: line.sku ?? null,\n description: line.description ?? null,\n quantity: String(line.quantity),\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: String(line.normalizedQuantity),\n normalizedUnit: line.normalizedUnit ?? null,\n uomSnapshot: line.uomSnapshot ?? null,\n currencyCode: line.currencyCode,\n unitPriceNet: String(line.unitPriceNet),\n unitPriceGross: String(line.unitPriceGross),\n taxRate: String(line.taxRate),\n taxAmount: String(line.taxAmount),\n totalNetAmount: String(line.totalNetAmount),\n totalGrossAmount: String(line.totalGrossAmount),\n metadata: line.metadata ?? null,\n })),\n };\n}\n\ntype DeletableEntity = {\n id?: string;\n organizationId?: string | null;\n tenantId?: string | null;\n};\n\nasync function queueDeletionSideEffects(\n dataEngine: DataEngine,\n entities: DeletableEntity[] | DeletableEntity | null | undefined,\n entityType: string,\n): Promise<void> {\n if (!entities) return;\n const list = Array.isArray(entities) ? entities : [entities];\n const tasks: Array<Promise<void>> = [];\n for (const entity of list) {\n if (!entity) continue;\n const id = typeof entity.id === \"string\" ? entity.id : null;\n if (!id) continue;\n tasks.push(\n emitCrudSideEffects({\n dataEngine,\n action: \"deleted\",\n entity,\n identifiers: {\n id,\n organizationId: entity.organizationId ?? null,\n tenantId: entity.tenantId ?? null,\n },\n indexer: { entityType },\n }),\n );\n }\n if (tasks.length) await Promise.all(tasks);\n}\n\nfunction toNumeric(value: string | number | null | undefined): number {\n if (typeof value === \"number\") return value;\n if (typeof value === \"string\" && value.trim().length) {\n const parsed = Number(value);\n if (!Number.isNaN(parsed)) return parsed;\n }\n return 0;\n}\n\nconst UNIT_DICTIONARY_KEYS = [\"unit\", \"units\", \"measurement_units\"] as const;\nconst UOM_REFERENCE_UNITS = new Set<string>(REFERENCE_UNIT_CODES);\nconst UOM_NORMALIZED_SCALE = 6;\nconst UOM_NORMALIZED_MAX = 1_000_000_000_000;\nconst UNIT_PRICE_AUTOCONVERT_SCALE = 4;\n\ntype ProductUomState = {\n productId: string;\n baseUnitCode: string | null;\n defaultSalesUnit: string | null;\n unitPriceEnabled: boolean;\n unitPriceReferenceUnit: \"kg\" | \"l\" | \"m2\" | \"m3\" | \"pc\" | null;\n unitPriceBaseQuantity: string | null;\n conversionsByUnitKey: Map<string, CatalogProductUnitConversion>;\n};\n\ntype UomResolver = {\n dictionaryPromise: Promise<Dictionary | null> | null;\n unitExistsCache: Map<string, boolean>;\n productCache: Map<string, ProductUomState | null>;\n};\n\ntype NormalizeLineUomInput = {\n em: EntityManager;\n resolver: UomResolver;\n organizationId: string;\n tenantId: string;\n line: {\n productId?: string | null;\n productVariantId?: string | null;\n quantity?: number | string | null;\n quantityUnit?: string | null;\n unitPriceNet?: number | null;\n unitPriceGross?: number | null;\n normalizedQuantity?: number | string | null;\n normalizedUnit?: string | null;\n uomSnapshot?: Record<string, unknown> | null;\n };\n};\n\nfunction createUomResolver(): UomResolver {\n return {\n dictionaryPromise: null,\n unitExistsCache: new Map<string, boolean>(),\n productCache: new Map<string, ProductUomState | null>(),\n };\n}\n\nfunction normalizeUnitCode(value: unknown): string | null {\n return canonicalizeUnitCode(value);\n}\n\nfunction unitLookupKey(value: string | null | undefined): string | null {\n return toUnitLookupKey(value);\n}\n\nfunction roundNormalizedQuantity(value: number): number {\n const factor = 10 ** UOM_NORMALIZED_SCALE;\n if (!Number.isFinite(value)) return 0;\n return Math.round(value * factor) / factor;\n}\n\nfunction assertNormalizedPrecision(value: number) {\n if (!Number.isFinite(value) || Math.abs(value) >= UOM_NORMALIZED_MAX) {\n throw new CrudHttpError(422, { error: \"uom.precision_overflow\" });\n }\n}\n\nfunction toOptionalNumber(value: unknown): number | null {\n if (value === null || value === undefined) return null;\n if (typeof value === \"number\") return Number.isFinite(value) ? value : null;\n if (typeof value === \"string\" && value.trim().length) {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : null;\n }\n return null;\n}\n\nfunction resolveSnapshotToBaseFactor(snapshot: unknown): number {\n if (!snapshot || typeof snapshot !== \"object\") return 1;\n const payload = snapshot as Record<string, unknown>;\n const factor = toOptionalNumber(payload.toBaseFactor ?? payload.to_base_factor);\n if (!Number.isFinite(factor) || !factor || factor <= 0) return 1;\n return factor;\n}\n\nfunction roundAutoConvertedUnitPrice(value: number): number | null {\n if (!Number.isFinite(value) || value < 0) return null;\n const factor = 10 ** UNIT_PRICE_AUTOCONVERT_SCALE;\n const rounded = Math.round((value + Number.EPSILON) * factor) / factor;\n return Number.isFinite(rounded) ? rounded : null;\n}\n\nfunction convertLineUnitPricesOnUnitChange(params: {\n existingSnapshot: SalesLineSnapshot | null;\n nextQuantityUnit: string | null;\n nextUomSnapshot: SalesLineUomSnapshot | Record<string, unknown> | null;\n unitPriceNet: number | null;\n unitPriceGross: number | null;\n}): {\n unitPriceNet: number | null;\n unitPriceGross: number | null;\n didConvert: boolean;\n} {\n if (!params.existingSnapshot) {\n return {\n unitPriceNet: params.unitPriceNet,\n unitPriceGross: params.unitPriceGross,\n didConvert: false,\n };\n }\n const existingUnitPriceNet =\n typeof params.existingSnapshot.unitPriceNet === \"number\" &&\n Number.isFinite(params.existingSnapshot.unitPriceNet)\n ? params.existingSnapshot.unitPriceNet\n : null;\n const existingUnitPriceGross =\n typeof params.existingSnapshot.unitPriceGross === \"number\" &&\n Number.isFinite(params.existingSnapshot.unitPriceGross)\n ? params.existingSnapshot.unitPriceGross\n : null;\n const sameNumber = (left: number | null, right: number | null): boolean => {\n if (left === null || right === null) return left === right;\n return Math.abs(left - right) < 0.000001;\n };\n const shouldConvertNet =\n params.unitPriceNet === null ||\n sameNumber(params.unitPriceNet, existingUnitPriceNet);\n const shouldConvertGross =\n params.unitPriceGross === null ||\n sameNumber(params.unitPriceGross, existingUnitPriceGross);\n if (!shouldConvertNet && !shouldConvertGross) {\n return {\n unitPriceNet: params.unitPriceNet,\n unitPriceGross: params.unitPriceGross,\n didConvert: false,\n };\n }\n const previousUnit = normalizeUnitCode(params.existingSnapshot?.quantityUnit ?? null);\n const nextUnit = normalizeUnitCode(params.nextQuantityUnit);\n if (!previousUnit || !nextUnit || previousUnit === nextUnit) {\n return {\n unitPriceNet: params.unitPriceNet,\n unitPriceGross: params.unitPriceGross,\n didConvert: false,\n };\n }\n const previousFactor = resolveSnapshotToBaseFactor(\n params.existingSnapshot?.uomSnapshot ?? null,\n );\n const nextFactor = resolveSnapshotToBaseFactor(params.nextUomSnapshot);\n if (\n !Number.isFinite(previousFactor) ||\n previousFactor <= 0 ||\n !Number.isFinite(nextFactor) ||\n nextFactor <= 0\n ) {\n return {\n unitPriceNet: params.unitPriceNet,\n unitPriceGross: params.unitPriceGross,\n didConvert: false,\n };\n }\n const convertAmount = (\n value: number | null,\n shouldConvert: boolean,\n ): number | null => {\n if (!shouldConvert) return value;\n if (value === null || !Number.isFinite(value)) return value;\n const converted = roundAutoConvertedUnitPrice((value / previousFactor) * nextFactor);\n return converted ?? value;\n };\n const nextUnitPriceNet = convertAmount(params.unitPriceNet, shouldConvertNet);\n const nextUnitPriceGross = convertAmount(\n params.unitPriceGross,\n shouldConvertGross,\n );\n const didConvert =\n nextUnitPriceNet !== params.unitPriceNet ||\n nextUnitPriceGross !== params.unitPriceGross;\n return {\n unitPriceNet: nextUnitPriceNet,\n unitPriceGross: nextUnitPriceGross,\n didConvert,\n };\n}\n\nfunction resolveReferenceUnit(\n value: unknown,\n): \"kg\" | \"l\" | \"m2\" | \"m3\" | \"pc\" | null {\n const normalized = toUnitLookupKey(value);\n if (!normalized) return null;\n if (!UOM_REFERENCE_UNITS.has(normalized)) return null;\n return normalized as \"kg\" | \"l\" | \"m2\" | \"m3\" | \"pc\";\n}\n\nasync function resolveUnitDictionaryScoped(\n em: EntityManager,\n organizationId: string,\n tenantId: string,\n): Promise<Dictionary | null> {\n return findOneWithDecryption(\n em,\n Dictionary,\n {\n organizationId,\n tenantId,\n key: { $in: [...UNIT_DICTIONARY_KEYS] },\n deletedAt: null,\n isActive: true,\n },\n { orderBy: { createdAt: \"asc\" } },\n );\n}\n\nasync function assertUnitExists(\n em: EntityManager,\n resolver: UomResolver,\n organizationId: string,\n tenantId: string,\n unitCode: string,\n): Promise<void> {\n const normalizedCode = unitLookupKey(unitCode);\n if (!normalizedCode) return;\n const rawUnitCode = unitCode.trim();\n if (!resolver.dictionaryPromise) {\n resolver.dictionaryPromise = resolveUnitDictionaryScoped(\n em,\n organizationId,\n tenantId,\n );\n }\n const dictionary = await resolver.dictionaryPromise;\n if (!dictionary) {\n throw new CrudHttpError(400, { error: \"uom.unit_not_found\" });\n }\n const cacheKey = `${dictionary.id}:${normalizedCode}`;\n if (resolver.unitExistsCache.has(cacheKey)) {\n if (!resolver.unitExistsCache.get(cacheKey)) {\n throw new CrudHttpError(400, { error: \"uom.unit_not_found\" });\n }\n return;\n }\n const entry = await findOneWithDecryption(em, DictionaryEntry, {\n dictionary,\n organizationId: dictionary.organizationId,\n tenantId: dictionary.tenantId,\n $or: [{ normalizedValue: normalizedCode }, { value: rawUnitCode }],\n });\n const exists = !!entry;\n resolver.unitExistsCache.set(cacheKey, exists);\n if (!exists) {\n throw new CrudHttpError(400, { error: \"uom.unit_not_found\" });\n }\n}\n\nasync function resolveProductUomState(\n em: EntityManager,\n resolver: UomResolver,\n organizationId: string,\n tenantId: string,\n productId: string,\n): Promise<ProductUomState | null> {\n if (resolver.productCache.has(productId)) {\n return resolver.productCache.get(productId) ?? null;\n }\n const product = await findOneWithDecryption(em, CatalogProduct, {\n id: productId,\n organizationId,\n tenantId,\n deletedAt: null,\n });\n if (!product) {\n resolver.productCache.set(productId, null);\n return null;\n }\n const conversions = await findWithDecryption(em, CatalogProductUnitConversion, {\n product: product.id,\n organizationId,\n tenantId,\n deletedAt: null,\n isActive: true,\n });\n const conversionsByUnitKey = new Map<string, CatalogProductUnitConversion>();\n for (const conversion of conversions) {\n const key = unitLookupKey(conversion.unitCode);\n if (!key) continue;\n conversionsByUnitKey.set(key, conversion);\n }\n const state: ProductUomState = {\n productId: product.id,\n baseUnitCode: normalizeUnitCode(product.defaultUnit ?? null),\n defaultSalesUnit: normalizeUnitCode(product.defaultSalesUnit ?? null),\n unitPriceEnabled: Boolean(product.unitPriceEnabled),\n unitPriceReferenceUnit: resolveReferenceUnit(\n product.unitPriceReferenceUnit,\n ),\n unitPriceBaseQuantity: product.unitPriceBaseQuantity ?? null,\n conversionsByUnitKey,\n };\n resolver.productCache.set(productId, state);\n return state;\n}\n\nfunction buildUnitPriceReferenceSnapshot(params: {\n product: ProductUomState;\n toBaseFactor: number;\n unitPriceNet: number | null;\n unitPriceGross: number | null;\n}) {\n if (!params.product.unitPriceEnabled) return undefined;\n const baseQuantityNumber = toNumeric(params.product.unitPriceBaseQuantity);\n const output: NonNullable<SalesLineUomSnapshot[\"unitPriceReference\"]> = {\n enabled: true,\n referenceUnitCode: params.product.unitPriceReferenceUnit ?? null,\n baseQuantity: params.product.unitPriceBaseQuantity ?? null,\n };\n if (\n !params.product.unitPriceReferenceUnit ||\n params.toBaseFactor <= 0 ||\n baseQuantityNumber <= 0\n ) {\n return output;\n }\n if (\n typeof params.unitPriceGross === \"number\" &&\n Number.isFinite(params.unitPriceGross)\n ) {\n output.grossPerReference = toNumericString(\n (params.unitPriceGross / params.toBaseFactor) * baseQuantityNumber,\n );\n }\n if (\n typeof params.unitPriceNet === \"number\" &&\n Number.isFinite(params.unitPriceNet)\n ) {\n output.netPerReference = toNumericString(\n (params.unitPriceNet / params.toBaseFactor) * baseQuantityNumber,\n );\n }\n return output;\n}\n\nasync function normalizeLineUom(input: NormalizeLineUomInput): Promise<{\n quantity: number;\n quantityUnit: string | null;\n normalizedQuantity: number;\n normalizedUnit: string | null;\n uomSnapshot: SalesLineUomSnapshot | null;\n}> {\n const quantity = toNumeric(input.line.quantity);\n const existingSnapshot =\n input.line.uomSnapshot && typeof input.line.uomSnapshot === \"object\"\n ? (cloneJson(input.line.uomSnapshot) as SalesLineUomSnapshot)\n : null;\n const productId =\n typeof input.line.productId === \"string\" ? input.line.productId : null;\n const variantId =\n typeof input.line.productVariantId === \"string\"\n ? input.line.productVariantId\n : null;\n const enteredUnitInput = normalizeUnitCode(input.line.quantityUnit);\n if (!productId) {\n if (enteredUnitInput) {\n await assertUnitExists(\n input.em,\n input.resolver,\n input.organizationId,\n input.tenantId,\n enteredUnitInput,\n );\n }\n const normalizedQuantity = toNumeric(\n input.line.normalizedQuantity ?? quantity,\n );\n assertNormalizedPrecision(normalizedQuantity);\n return {\n quantity,\n quantityUnit: enteredUnitInput ?? null,\n normalizedQuantity,\n normalizedUnit:\n normalizeUnitCode(input.line.normalizedUnit) ??\n enteredUnitInput ??\n null,\n uomSnapshot: existingSnapshot ?? {\n version: 1,\n productId: null,\n productVariantId: variantId,\n baseUnitCode:\n normalizeUnitCode(input.line.normalizedUnit) ??\n enteredUnitInput ??\n null,\n enteredUnitCode: enteredUnitInput,\n enteredQuantity: toNumericString(quantity) ?? \"0\",\n toBaseFactor: \"1\",\n normalizedQuantity: toNumericString(normalizedQuantity) ?? \"0\",\n rounding: { mode: \"half_up\", scale: UOM_NORMALIZED_SCALE },\n source: { conversionId: null, resolvedAt: new Date().toISOString() },\n },\n };\n }\n\n const productState = await resolveProductUomState(\n input.em,\n input.resolver,\n input.organizationId,\n input.tenantId,\n productId,\n );\n if (!productState) {\n if (enteredUnitInput) {\n await assertUnitExists(\n input.em,\n input.resolver,\n input.organizationId,\n input.tenantId,\n enteredUnitInput,\n );\n }\n const normalizedQuantity = toNumeric(\n input.line.normalizedQuantity ?? quantity,\n );\n assertNormalizedPrecision(normalizedQuantity);\n return {\n quantity,\n quantityUnit: enteredUnitInput ?? null,\n normalizedQuantity,\n normalizedUnit:\n normalizeUnitCode(input.line.normalizedUnit) ??\n enteredUnitInput ??\n null,\n uomSnapshot: existingSnapshot,\n };\n }\n\n const baseUnitCode = productState.baseUnitCode;\n const enteredUnitCode =\n enteredUnitInput ??\n productState.defaultSalesUnit ??\n baseUnitCode ??\n normalizeUnitCode(input.line.normalizedUnit);\n if (enteredUnitCode) {\n await assertUnitExists(\n input.em,\n input.resolver,\n input.organizationId,\n input.tenantId,\n enteredUnitCode,\n );\n }\n if (baseUnitCode) {\n await assertUnitExists(\n input.em,\n input.resolver,\n input.organizationId,\n input.tenantId,\n baseUnitCode,\n );\n }\n\n if (!baseUnitCode) {\n const requiresBase =\n Boolean(enteredUnitCode) ||\n productState.conversionsByUnitKey.size > 0 ||\n Boolean(productState.defaultSalesUnit);\n if (requiresBase) {\n throw new CrudHttpError(400, { error: \"uom.default_unit_missing\" });\n }\n const normalizedQuantity = toNumeric(\n input.line.normalizedQuantity ?? quantity,\n );\n assertNormalizedPrecision(normalizedQuantity);\n return {\n quantity,\n quantityUnit: enteredUnitCode ?? null,\n normalizedQuantity,\n normalizedUnit:\n normalizeUnitCode(input.line.normalizedUnit) ?? enteredUnitCode ?? null,\n uomSnapshot: existingSnapshot,\n };\n }\n\n const resolvedEnteredUnit = enteredUnitCode ?? baseUnitCode;\n const enteredKey = unitLookupKey(resolvedEnteredUnit);\n const baseKey = unitLookupKey(baseUnitCode);\n let toBaseFactor = 1;\n let conversionId: string | null = null;\n if (enteredKey && baseKey && enteredKey !== baseKey) {\n const conversion = productState.conversionsByUnitKey.get(enteredKey);\n if (!conversion) {\n throw new CrudHttpError(400, { error: \"uom.conversion_not_found\" });\n }\n toBaseFactor = toNumeric(conversion.toBaseFactor);\n conversionId = conversion.id;\n }\n if (!Number.isFinite(toBaseFactor) || toBaseFactor <= 0) {\n throw new CrudHttpError(400, { error: \"uom.invalid_factor\" });\n }\n const normalizedQuantity = roundNormalizedQuantity(quantity * toBaseFactor);\n assertNormalizedPrecision(normalizedQuantity);\n const unitPriceReference = buildUnitPriceReferenceSnapshot({\n product: productState,\n toBaseFactor,\n unitPriceNet: toOptionalNumber(input.line.unitPriceNet),\n unitPriceGross: toOptionalNumber(input.line.unitPriceGross),\n });\n const snapshot: SalesLineUomSnapshot = {\n version: 1,\n productId,\n productVariantId: variantId,\n baseUnitCode,\n enteredUnitCode: resolvedEnteredUnit,\n enteredQuantity: toNumericString(quantity) ?? \"0\",\n toBaseFactor: toNumericString(toBaseFactor) ?? \"1\",\n normalizedQuantity: toNumericString(normalizedQuantity) ?? \"0\",\n rounding: {\n mode: \"half_up\",\n scale: UOM_NORMALIZED_SCALE,\n },\n source: {\n conversionId,\n resolvedAt: new Date().toISOString(),\n },\n ...(unitPriceReference ? { unitPriceReference } : {}),\n };\n\n return {\n quantity,\n quantityUnit: resolvedEnteredUnit,\n normalizedQuantity,\n normalizedUnit: baseUnitCode,\n uomSnapshot: snapshot,\n };\n}\n\nfunction normalizeShippingMethodContext(\n snapshot: Record<string, unknown> | null | undefined,\n id?: string | null,\n code?: string | null,\n currencyCode?: string,\n): ShippingMethodContext | null {\n if (!snapshot || typeof snapshot !== \"object\") return null;\n const metadata = (snapshot as Record<string, unknown>).metadata;\n const providerSettings =\n (snapshot as Record<string, unknown>).providerSettings ??\n (metadata && typeof metadata === \"object\"\n ? ((metadata as Record<string, unknown>).providerSettings ?? null)\n : null);\n return {\n id:\n ((snapshot as Record<string, unknown>).id as string | undefined) ??\n id ??\n null,\n code:\n typeof (snapshot as Record<string, unknown>).code === \"string\"\n ? ((snapshot as Record<string, unknown>).code as string)\n : (code ?? null),\n name:\n typeof (snapshot as Record<string, unknown>).name === \"string\"\n ? ((snapshot as Record<string, unknown>).name as string)\n : null,\n providerKey:\n typeof (snapshot as Record<string, unknown>).providerKey === \"string\"\n ? ((snapshot as Record<string, unknown>).providerKey as string)\n : null,\n currencyCode:\n typeof (snapshot as Record<string, unknown>).currencyCode === \"string\"\n ? ((snapshot as Record<string, unknown>).currencyCode as string)\n : (currencyCode ?? null),\n baseRateNet: toNumeric(\n ((snapshot as Record<string, unknown>).baseRateNet ??\n (snapshot as Record<string, unknown>).base_rate_net) as\n | string\n | number\n | null,\n ),\n baseRateGross: toNumeric(\n ((snapshot as Record<string, unknown>).baseRateGross ??\n (snapshot as Record<string, unknown>).base_rate_gross) as\n | string\n | number\n | null,\n ),\n metadata:\n metadata && typeof metadata === \"object\"\n ? cloneJson(metadata as Record<string, unknown>)\n : null,\n providerSettings:\n providerSettings && typeof providerSettings === \"object\"\n ? cloneJson(providerSettings as Record<string, unknown>)\n : null,\n };\n}\n\nfunction normalizePaymentMethodContext(\n snapshot: Record<string, unknown> | null | undefined,\n id?: string | null,\n code?: string | null,\n): PaymentMethodContext | null {\n if (!snapshot || typeof snapshot !== \"object\") return null;\n const metadata = (snapshot as Record<string, unknown>).metadata;\n const providerSettings =\n (snapshot as Record<string, unknown>).providerSettings ??\n (metadata && typeof metadata === \"object\"\n ? ((metadata as Record<string, unknown>).providerSettings ?? null)\n : null);\n return {\n id:\n ((snapshot as Record<string, unknown>).id as string | undefined) ??\n id ??\n null,\n code:\n typeof (snapshot as Record<string, unknown>).code === \"string\"\n ? ((snapshot as Record<string, unknown>).code as string)\n : (code ?? null),\n name:\n typeof (snapshot as Record<string, unknown>).name === \"string\"\n ? ((snapshot as Record<string, unknown>).name as string)\n : null,\n providerKey:\n typeof (snapshot as Record<string, unknown>).providerKey === \"string\"\n ? ((snapshot as Record<string, unknown>).providerKey as string)\n : null,\n terms:\n typeof (snapshot as Record<string, unknown>).terms === \"string\"\n ? ((snapshot as Record<string, unknown>).terms as string)\n : null,\n metadata:\n metadata && typeof metadata === \"object\"\n ? cloneJson(metadata as Record<string, unknown>)\n : null,\n providerSettings:\n providerSettings && typeof providerSettings === \"object\"\n ? cloneJson(providerSettings as Record<string, unknown>)\n : null,\n };\n}\n\nfunction buildProviderContext(params: {\n shippingSnapshot?: Record<string, unknown> | null;\n paymentSnapshot?: Record<string, unknown> | null;\n shippingMethodId?: string | null;\n paymentMethodId?: string | null;\n shippingMethodCode?: string | null;\n paymentMethodCode?: string | null;\n currencyCode: string;\n}) {\n return {\n shippingMethod: normalizeShippingMethodContext(\n params.shippingSnapshot,\n params.shippingMethodId,\n params.shippingMethodCode,\n params.currencyCode,\n ),\n paymentMethod: normalizePaymentMethodContext(\n params.paymentSnapshot,\n params.paymentMethodId,\n params.paymentMethodCode,\n ),\n };\n}\n\nfunction buildCalculationContext(params: {\n tenantId: string;\n organizationId: string;\n currencyCode: string;\n shippingSnapshot?: Record<string, unknown> | null;\n paymentSnapshot?: Record<string, unknown> | null;\n shippingMethodId?: string | null;\n paymentMethodId?: string | null;\n shippingMethodCode?: string | null;\n paymentMethodCode?: string | null;\n}) {\n return {\n tenantId: params.tenantId,\n organizationId: params.organizationId,\n currencyCode: params.currencyCode,\n metadata: buildProviderContext({\n shippingSnapshot: params.shippingSnapshot,\n paymentSnapshot: params.paymentSnapshot,\n shippingMethodId: params.shippingMethodId,\n paymentMethodId: params.paymentMethodId,\n shippingMethodCode: params.shippingMethodCode,\n paymentMethodCode: params.paymentMethodCode,\n currencyCode: params.currencyCode,\n }),\n };\n}\n\nfunction mapOrderLineEntityToSnapshot(line: SalesOrderLine): SalesLineSnapshot {\n return {\n id: line.id,\n lineNumber: line.lineNumber,\n kind: line.kind,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: toNumeric(line.quantity),\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: toNumeric(line.normalizedQuantity ?? line.quantity),\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n currencyCode: line.currencyCode,\n unitPriceNet: toNumeric(line.unitPriceNet),\n unitPriceGross: toNumeric(line.unitPriceGross),\n discountAmount: toNumeric(line.discountAmount),\n discountPercent: toNumeric(line.discountPercent),\n taxRate: toNumeric(line.taxRate),\n taxAmount: toNumeric(line.taxAmount),\n totalNetAmount: toNumeric(line.totalNetAmount),\n totalGrossAmount: toNumeric(line.totalGrossAmount),\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n };\n}\n\nfunction mapQuoteLineEntityToSnapshot(line: SalesQuoteLine): SalesLineSnapshot {\n return {\n id: line.id,\n lineNumber: line.lineNumber,\n kind: line.kind,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: toNumeric(line.quantity),\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: toNumeric(line.normalizedQuantity ?? line.quantity),\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n currencyCode: line.currencyCode,\n unitPriceNet: toNumeric(line.unitPriceNet),\n unitPriceGross: toNumeric(line.unitPriceGross),\n discountAmount: toNumeric(line.discountAmount),\n discountPercent: toNumeric(line.discountPercent),\n taxRate: toNumeric(line.taxRate),\n taxAmount: toNumeric(line.taxAmount),\n totalNetAmount: toNumeric(line.totalNetAmount),\n totalGrossAmount: toNumeric(line.totalGrossAmount),\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n };\n}\n\nfunction mapOrderAdjustmentToDraft(\n adjustment: SalesOrderAdjustment,\n): SalesAdjustmentDraft {\n return {\n id: adjustment.id,\n scope: adjustment.scope ?? \"order\",\n kind: adjustment.kind,\n code: adjustment.code ?? null,\n label: adjustment.label ?? null,\n calculatorKey: adjustment.calculatorKey ?? null,\n promotionId: adjustment.promotionId ?? null,\n rate: toNumeric(adjustment.rate),\n amountNet: toNumeric(adjustment.amountNet),\n amountGross: toNumeric(adjustment.amountGross),\n currencyCode: adjustment.currencyCode ?? null,\n metadata: adjustment.metadata ? cloneJson(adjustment.metadata) : null,\n position: adjustment.position ?? 0,\n };\n}\n\nfunction mapQuoteAdjustmentToDraft(\n adjustment: SalesQuoteAdjustment,\n): SalesAdjustmentDraft {\n return {\n id: adjustment.id,\n scope: adjustment.scope ?? \"order\",\n kind: adjustment.kind,\n code: adjustment.code ?? null,\n label: adjustment.label ?? null,\n calculatorKey: adjustment.calculatorKey ?? null,\n promotionId: adjustment.promotionId ?? null,\n rate: toNumeric(adjustment.rate),\n amountNet: toNumeric(adjustment.amountNet),\n amountGross: toNumeric(adjustment.amountGross),\n currencyCode: adjustment.currencyCode ?? null,\n metadata: adjustment.metadata ? cloneJson(adjustment.metadata) : null,\n position: adjustment.position ?? 0,\n };\n}\n\nasync function emitTotalsCalculated(\n eventBus: EventBus | null | undefined,\n payload: {\n documentKind: SalesDocumentKind;\n documentId: string;\n organizationId: string;\n tenantId: string;\n customerId?: string | null;\n totals: SalesDocumentCalculationResult[\"totals\"];\n lineCount: number;\n },\n): Promise<void> {\n if (!eventBus) return;\n await eventBus.emitEvent(\"sales.document.totals.calculated\", payload);\n}\n\nfunction createLineSnapshotFromInput(\n line: DocumentLineCreateInput,\n lineNumber: number,\n): SalesLineSnapshot {\n const quantity = Number(line.quantity ?? 0);\n const normalizedQuantity = toNumeric(\n line.normalizedQuantity ?? quantity,\n );\n return {\n lineNumber,\n kind: line.kind ?? \"product\",\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity,\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity,\n normalizedUnit:\n typeof line.normalizedUnit === \"string\"\n ? line.normalizedUnit\n : (line.quantityUnit ?? null),\n uomSnapshot:\n line.uomSnapshot && typeof line.uomSnapshot === \"object\"\n ? cloneJson(line.uomSnapshot as Record<string, unknown>)\n : null,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet ?? null,\n unitPriceGross: line.unitPriceGross ?? null,\n discountAmount: line.discountAmount ?? null,\n discountPercent: line.discountPercent ?? null,\n taxRate: line.taxRate ?? null,\n taxAmount: line.taxAmount ?? null,\n totalNetAmount: line.totalNetAmount ?? null,\n totalGrossAmount: line.totalGrossAmount ?? null,\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId:\n \"customFieldSetId\" in line\n ? ((line as any).customFieldSetId ?? null)\n : null,\n customFields:\n \"customFields\" in line && line.customFields\n ? cloneJson((line as any).customFields)\n : null,\n };\n}\n\nfunction createAdjustmentDraftFromInput(\n adjustment: DocumentAdjustmentCreateInput & { id?: string | null },\n): SalesAdjustmentDraft {\n const lineRef =\n \"quoteLineId\" in adjustment\n ? (adjustment as any).quoteLineId\n : (adjustment as any).orderLineId;\n if (adjustment.scope === \"line\" && lineRef) {\n throw new CrudHttpError(400, {\n error: \"Line-scoped adjustments are not supported yet.\",\n });\n }\n return {\n id: typeof adjustment.id === \"string\" ? adjustment.id : undefined,\n scope: adjustment.scope ?? \"order\",\n kind: adjustment.kind ?? \"custom\",\n code: adjustment.code ?? null,\n label: adjustment.label ?? null,\n calculatorKey: adjustment.calculatorKey ?? null,\n promotionId: adjustment.promotionId ?? null,\n rate: adjustment.rate ?? null,\n amountNet: adjustment.amountNet ?? null,\n amountGross: adjustment.amountGross ?? null,\n currencyCode: adjustment.currencyCode ?? null,\n metadata: adjustment.metadata ? cloneJson(adjustment.metadata) : null,\n position: adjustment.position ?? 0,\n };\n}\n\nfunction convertLineCalculationToEntityInput(\n lineResult: SalesLineCalculationResult,\n sourceLine: DocumentLineCreateInput,\n document: { organizationId: string; tenantId: string },\n index: number,\n) {\n const line = lineResult.line;\n return {\n lineNumber: line.lineNumber ?? index + 1,\n kind: line.kind ?? \"product\",\n statusEntryId: sourceLine.statusEntryId ?? null,\n productId: sourceLine.productId ?? null,\n productVariantId: sourceLine.productVariantId ?? null,\n catalogSnapshot: sourceLine.catalogSnapshot\n ? cloneJson(sourceLine.catalogSnapshot)\n : null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: toNumericString(line.quantity) ?? \"0\",\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity:\n toNumericString(line.normalizedQuantity ?? line.quantity) ?? \"0\",\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot:\n line.uomSnapshot && typeof line.uomSnapshot === \"object\"\n ? cloneJson(line.uomSnapshot as Record<string, unknown>)\n : null,\n currencyCode: line.currencyCode,\n unitPriceNet:\n toNumericString(\n line.unitPriceNet ??\n lineResult.netAmount / Math.max(line.quantity || 1, 1),\n ) ?? \"0\",\n unitPriceGross:\n toNumericString(\n line.unitPriceGross ??\n lineResult.grossAmount / Math.max(line.quantity || 1, 1),\n ) ?? \"0\",\n discountAmount: toNumericString(lineResult.discountAmount) ?? \"0\",\n discountPercent: toNumericString(line.discountPercent) ?? \"0\",\n taxRate: toNumericString(line.taxRate) ?? \"0\",\n taxAmount: toNumericString(lineResult.taxAmount) ?? \"0\",\n totalNetAmount: toNumericString(lineResult.netAmount) ?? \"0\",\n totalGrossAmount: toNumericString(lineResult.grossAmount) ?? \"0\",\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n promotionSnapshot: sourceLine.promotionSnapshot\n ? cloneJson(sourceLine.promotionSnapshot)\n : null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: sourceLine.customFieldSetId ?? null,\n organizationId: document.organizationId,\n tenantId: document.tenantId,\n };\n}\n\nfunction convertAdjustmentResultToEntityInput(\n adjustment: SalesAdjustmentDraft,\n sourceAdjustment: DocumentAdjustmentCreateInput | null,\n document: { organizationId: string; tenantId: string },\n index: number,\n) {\n const metadata = adjustment.metadata ? cloneJson(adjustment.metadata) : null;\n const resolvedPosition =\n sourceAdjustment?.position ??\n (adjustment.position !== null && adjustment.position !== undefined\n ? adjustment.position\n : index);\n return {\n scope: adjustment.scope ?? \"order\",\n kind: adjustment.kind ?? \"custom\",\n code: adjustment.code ?? null,\n label: adjustment.label ?? null,\n calculatorKey: adjustment.calculatorKey ?? null,\n promotionId: adjustment.promotionId ?? null,\n rate: toNumericString(adjustment.rate) ?? \"0\",\n amountNet: toNumericString(adjustment.amountNet) ?? \"0\",\n amountGross:\n toNumericString(adjustment.amountGross ?? adjustment.amountNet) ?? \"0\",\n currencyCode: adjustment.currencyCode ?? null,\n metadata,\n position: resolvedPosition,\n organizationId: document.organizationId,\n tenantId: document.tenantId,\n };\n}\n\nasync function applyOrderLineResults(params: {\n em: EntityManager;\n order: SalesOrder;\n calculation: SalesDocumentCalculationResult;\n sourceLines: Array<DocumentLineCreateInput & { id?: string }>;\n existingLines: SalesOrderLine[];\n}): Promise<void> {\n const { em, order, calculation, sourceLines, existingLines } = params;\n const existingMap = new Map(existingLines.map((line) => [line.id, line]));\n const persisted = new Set<string>();\n const statusCache = new Map<string, string | null>();\n const resolveStatus = async (entryId?: string | null) => {\n if (!entryId) return null;\n if (statusCache.has(entryId)) return statusCache.get(entryId) ?? null;\n const value = await resolveDictionaryEntryValue(em, entryId);\n statusCache.set(entryId, value);\n return value;\n };\n for (let index = 0; index < calculation.lines.length; index += 1) {\n const lineResult = calculation.lines[index];\n const sourceLine = sourceLines[index];\n const statusEntryId = (sourceLine as any).statusEntryId ?? null;\n const statusValue = await resolveStatus(statusEntryId ?? null);\n const payload = convertLineCalculationToEntityInput(\n lineResult,\n sourceLine,\n order,\n index,\n );\n const existing = sourceLine.id\n ? (existingMap.get(sourceLine.id) ?? null)\n : null;\n const lineEntity =\n existing ??\n em.create(SalesOrderLine, {\n order,\n id: sourceLine.id ?? undefined,\n reservedQuantity: existing?.reservedQuantity ?? \"0\",\n fulfilledQuantity: existing?.fulfilledQuantity ?? \"0\",\n invoicedQuantity: existing?.invoicedQuantity ?? \"0\",\n returnedQuantity: existing?.returnedQuantity ?? \"0\",\n createdAt: existing?.createdAt ?? new Date(),\n updatedAt: new Date(),\n });\n Object.assign(lineEntity, {\n ...payload,\n order,\n statusEntryId,\n status: statusValue,\n });\n em.persist(lineEntity);\n const rawCustomFields = (sourceLine as any).customFields;\n if (rawCustomFields !== undefined && rawCustomFields !== null) {\n const customValues =\n rawCustomFields && typeof rawCustomFields === \"object\"\n ? (rawCustomFields as Record<string, unknown>)\n : {};\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order_line,\n recordId: lineEntity.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n values: normalizeCustomFieldValues(customValues),\n });\n }\n persisted.add(lineEntity.id);\n }\n for (const [id, line] of existingMap.entries()) {\n if (!persisted.has(id)) {\n em.remove(line);\n }\n }\n}\n\nasync function applyQuoteLineResults(params: {\n em: EntityManager;\n quote: SalesQuote;\n calculation: SalesDocumentCalculationResult;\n sourceLines: Array<DocumentLineCreateInput & { id?: string }>;\n existingLines: SalesQuoteLine[];\n}): Promise<void> {\n const { em, quote, calculation, sourceLines, existingLines } = params;\n const existingMap = new Map(existingLines.map((line) => [line.id, line]));\n const persisted = new Set<string>();\n const statusCache = new Map<string, string | null>();\n const resolveStatus = async (entryId?: string | null) => {\n if (!entryId) return null;\n if (statusCache.has(entryId)) return statusCache.get(entryId) ?? null;\n const value = await resolveDictionaryEntryValue(em, entryId);\n statusCache.set(entryId, value);\n return value;\n };\n for (let index = 0; index < calculation.lines.length; index += 1) {\n const lineResult = calculation.lines[index];\n const sourceLine = sourceLines[index];\n const statusEntryId = (sourceLine as any).statusEntryId ?? null;\n const statusValue = await resolveStatus(statusEntryId ?? null);\n const payload = convertLineCalculationToEntityInput(\n lineResult,\n sourceLine,\n quote,\n index,\n );\n const existing = sourceLine.id\n ? (existingMap.get(sourceLine.id) ?? null)\n : null;\n const lineEntity =\n existing ??\n em.create(SalesQuoteLine, {\n quote,\n id: sourceLine.id ?? undefined,\n createdAt: existing?.createdAt ?? new Date(),\n updatedAt: new Date(),\n });\n Object.assign(lineEntity, {\n ...payload,\n quote,\n statusEntryId,\n status: statusValue,\n });\n em.persist(lineEntity);\n const rawCustomFields = (sourceLine as any).customFields;\n if (rawCustomFields !== undefined && rawCustomFields !== null) {\n const customValues =\n rawCustomFields && typeof rawCustomFields === \"object\"\n ? (rawCustomFields as Record<string, unknown>)\n : {};\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_quote_line,\n recordId: lineEntity.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n values: normalizeCustomFieldValues(customValues),\n });\n }\n persisted.add(lineEntity.id);\n }\n for (const [id, line] of existingMap.entries()) {\n if (!persisted.has(id)) {\n em.remove(line);\n }\n }\n}\n\nasync function replaceQuoteLines(\n em: EntityManager,\n quote: SalesQuote,\n calculation: SalesDocumentCalculationResult,\n lineInputs: QuoteLineCreateInput[],\n): Promise<void> {\n await em.nativeDelete(SalesQuoteLine, { quote: quote.id });\n const statusCache = new Map<string, string | null>();\n const resolveStatus = async (entryId?: string | null) => {\n if (!entryId) return null;\n if (statusCache.has(entryId)) return statusCache.get(entryId) ?? null;\n const value = await resolveDictionaryEntryValue(em, entryId);\n statusCache.set(entryId, value);\n return value;\n };\n for (let index = 0; index < calculation.lines.length; index += 1) {\n const lineResult = calculation.lines[index];\n const sourceLine = lineInputs[index];\n const entityInput = convertLineCalculationToEntityInput(\n lineResult,\n sourceLine,\n quote,\n index,\n );\n const statusValue = await resolveStatus(sourceLine.statusEntryId ?? null);\n const lineEntity = em.create(SalesQuoteLine, {\n quote,\n ...entityInput,\n status: statusValue,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(lineEntity);\n const rawCustomFields = (sourceLine as any).customFields;\n if (rawCustomFields !== undefined && rawCustomFields !== null) {\n const customValues =\n rawCustomFields && typeof rawCustomFields === \"object\"\n ? (rawCustomFields as Record<string, unknown>)\n : {};\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_quote_line,\n recordId: lineEntity.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n values: normalizeCustomFieldValues(customValues),\n });\n }\n }\n}\n\nasync function replaceQuoteAdjustments(\n em: EntityManager,\n quote: SalesQuote,\n calculation: SalesDocumentCalculationResult,\n adjustmentInputs: QuoteAdjustmentCreateInput[] | null,\n): Promise<void> {\n const existing = await em.find(\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n );\n const existingMap = new Map<string, SalesQuoteAdjustment>();\n existing.forEach((adj) => existingMap.set(adj.id, adj));\n const seen = new Set<string>();\n const adjustmentDrafts = calculation.adjustments;\n for (let index = 0; index < adjustmentDrafts.length; index += 1) {\n const draft = adjustmentDrafts[index];\n const sourceById =\n adjustmentInputs?.find((adj) => (adj as any).id === draft.id) ?? null;\n const source =\n sourceById ??\n (adjustmentInputs ? (adjustmentInputs[index] ?? null) : null);\n const entityInput = convertAdjustmentResultToEntityInput(\n draft,\n source,\n quote,\n index,\n );\n const adjustmentId =\n (draft as any).id ?? (source as any)?.id ?? randomUUID();\n const existingEntity = existingMap.get(adjustmentId);\n const entity =\n existingEntity ??\n em.create(SalesQuoteAdjustment, {\n id: adjustmentId,\n quote,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n createdAt: new Date(),\n });\n entity.scope = entityInput.scope;\n entity.kind = entityInput.kind;\n entity.code = entityInput.code ?? null;\n entity.label = entityInput.label ?? null;\n entity.calculatorKey = entityInput.calculatorKey ?? null;\n entity.promotionId = entityInput.promotionId ?? null;\n entity.rate = entityInput.rate ?? \"0\";\n entity.amountNet = entityInput.amountNet ?? \"0\";\n entity.amountGross =\n entityInput.amountGross ?? entityInput.amountNet ?? \"0\";\n entity.currencyCode = entityInput.currencyCode ?? quote.currencyCode;\n entity.metadata = entityInput.metadata ?? null;\n entity.position = entityInput.position ?? index;\n entity.updatedAt = new Date();\n entity.quoteLine = null;\n seen.add(adjustmentId);\n if (source?.customFields !== undefined) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_quote_adjustment,\n recordId: adjustmentId,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n values:\n source.customFields && typeof source.customFields === \"object\"\n ? (source.customFields as Record<string, unknown>)\n : {},\n });\n }\n em.persist(entity);\n }\n\n existing.forEach((adj) => {\n if (!seen.has(adj.id)) {\n em.remove(adj);\n }\n });\n}\n\nasync function replaceOrderLines(\n em: EntityManager,\n order: SalesOrder,\n calculation: SalesDocumentCalculationResult,\n lineInputs: OrderLineCreateInput[],\n): Promise<void> {\n await em.nativeDelete(SalesOrderLine, { order: order.id });\n const statusCache = new Map<string, string | null>();\n const resolveStatus = async (entryId?: string | null) => {\n if (!entryId) return null;\n if (statusCache.has(entryId)) return statusCache.get(entryId) ?? null;\n const value = await resolveDictionaryEntryValue(em, entryId);\n statusCache.set(entryId, value);\n return value;\n };\n for (let index = 0; index < calculation.lines.length; index += 1) {\n const lineResult = calculation.lines[index];\n const sourceLine = lineInputs[index];\n const entityInput = convertLineCalculationToEntityInput(\n lineResult,\n sourceLine,\n order,\n index,\n );\n const statusValue = await resolveStatus(sourceLine.statusEntryId ?? null);\n const lineEntity = em.create(SalesOrderLine, {\n order,\n ...entityInput,\n reservedQuantity: \"0\",\n fulfilledQuantity: \"0\",\n invoicedQuantity: \"0\",\n returnedQuantity: \"0\",\n status: statusValue,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(lineEntity);\n const rawCustomFields = (sourceLine as any).customFields;\n if (rawCustomFields !== undefined && rawCustomFields !== null) {\n const customValues =\n rawCustomFields && typeof rawCustomFields === \"object\"\n ? (rawCustomFields as Record<string, unknown>)\n : {};\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order_line,\n recordId: lineEntity.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n values: normalizeCustomFieldValues(customValues),\n });\n }\n }\n}\n\nasync function replaceOrderAdjustments(\n em: EntityManager,\n order: SalesOrder,\n calculation: SalesDocumentCalculationResult,\n adjustmentInputs: OrderAdjustmentCreateInput[] | null,\n): Promise<void> {\n const existing = await em.find(\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n );\n const existingMap = new Map<string, SalesOrderAdjustment>();\n existing.forEach((adj) => existingMap.set(adj.id, adj));\n const seen = new Set<string>();\n const adjustmentDrafts = calculation.adjustments;\n for (let index = 0; index < adjustmentDrafts.length; index += 1) {\n const draft = adjustmentDrafts[index];\n const sourceById =\n adjustmentInputs?.find((adj) => (adj as any).id === draft.id) ?? null;\n const source =\n sourceById ??\n (adjustmentInputs ? (adjustmentInputs[index] ?? null) : null);\n const entityInput = convertAdjustmentResultToEntityInput(\n draft,\n source,\n order,\n index,\n );\n const adjustmentId =\n (draft as any).id ?? (source as any)?.id ?? randomUUID();\n const existingEntity = existingMap.get(adjustmentId);\n const entity =\n existingEntity ??\n em.create(SalesOrderAdjustment, {\n id: adjustmentId,\n order,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n createdAt: new Date(),\n });\n entity.scope = entityInput.scope;\n entity.kind = entityInput.kind;\n entity.code = entityInput.code ?? null;\n entity.label = entityInput.label ?? null;\n entity.calculatorKey = entityInput.calculatorKey ?? null;\n entity.promotionId = entityInput.promotionId ?? null;\n entity.rate = entityInput.rate ?? \"0\";\n entity.amountNet = entityInput.amountNet ?? \"0\";\n entity.amountGross =\n entityInput.amountGross ?? entityInput.amountNet ?? \"0\";\n entity.currencyCode = entityInput.currencyCode ?? order.currencyCode;\n entity.metadata = entityInput.metadata ?? null;\n entity.position = entityInput.position ?? index;\n entity.updatedAt = new Date();\n entity.orderLine = null;\n seen.add(adjustmentId);\n if (source?.customFields !== undefined) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order_adjustment,\n recordId: adjustmentId,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n values:\n source.customFields && typeof source.customFields === \"object\"\n ? (source.customFields as Record<string, unknown>)\n : {},\n });\n }\n em.persist(entity);\n }\n\n existing.forEach((adj) => {\n if (!seen.has(adj.id)) {\n em.remove(adj);\n }\n });\n}\n\nfunction applyQuoteTotals(\n quote: SalesQuote,\n totals: SalesDocumentCalculationResult[\"totals\"],\n lineCount: number,\n): void {\n quote.subtotalNetAmount = toNumericString(totals.subtotalNetAmount) ?? \"0\";\n quote.subtotalGrossAmount =\n toNumericString(totals.subtotalGrossAmount) ?? \"0\";\n quote.discountTotalAmount =\n toNumericString(totals.discountTotalAmount) ?? \"0\";\n quote.taxTotalAmount = toNumericString(totals.taxTotalAmount) ?? \"0\";\n quote.grandTotalNetAmount =\n toNumericString(totals.grandTotalNetAmount) ?? \"0\";\n quote.grandTotalGrossAmount =\n toNumericString(totals.grandTotalGrossAmount) ?? \"0\";\n quote.totalsSnapshot = cloneJson(totals);\n quote.lineItemCount = lineCount;\n}\n\nfunction applyOrderTotals(\n order: SalesOrder,\n totals: SalesDocumentCalculationResult[\"totals\"],\n lineCount: number,\n): void {\n order.subtotalNetAmount = toNumericString(totals.subtotalNetAmount) ?? \"0\";\n order.subtotalGrossAmount =\n toNumericString(totals.subtotalGrossAmount) ?? \"0\";\n order.discountTotalAmount =\n toNumericString(totals.discountTotalAmount) ?? \"0\";\n order.taxTotalAmount = toNumericString(totals.taxTotalAmount) ?? \"0\";\n order.shippingNetAmount = toNumericString(totals.shippingNetAmount) ?? \"0\";\n order.shippingGrossAmount =\n toNumericString(totals.shippingGrossAmount) ?? \"0\";\n order.surchargeTotalAmount =\n toNumericString(totals.surchargeTotalAmount) ?? \"0\";\n order.grandTotalNetAmount =\n toNumericString(totals.grandTotalNetAmount) ?? \"0\";\n order.grandTotalGrossAmount =\n toNumericString(totals.grandTotalGrossAmount) ?? \"0\";\n order.paidTotalAmount = toNumericString(totals.paidTotalAmount) ?? \"0\";\n order.refundedTotalAmount =\n toNumericString(totals.refundedTotalAmount) ?? \"0\";\n order.outstandingAmount = toNumericString(totals.outstandingAmount) ?? \"0\";\n order.totalsSnapshot = cloneJson(totals);\n order.lineItemCount = lineCount;\n}\n\nfunction normalizePaymentTotal(value: unknown): number {\n if (typeof value === \"number\" && Number.isFinite(value))\n return Math.max(value, 0);\n if (typeof value === \"string\" && value.trim().length) {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? Math.max(parsed, 0) : 0;\n }\n return 0;\n}\n\nfunction resolveExistingPaymentTotals(order: SalesOrder) {\n return {\n paidTotalAmount: normalizePaymentTotal(order.paidTotalAmount),\n refundedTotalAmount: normalizePaymentTotal(order.refundedTotalAmount),\n };\n}\n\nfunction ensureQuoteScope(\n ctx: Parameters<typeof ensureTenantScope>[0],\n organizationId: string,\n tenantId: string,\n): void {\n ensureTenantScope(ctx, tenantId);\n ensureOrganizationScope(ctx, organizationId);\n}\n\nfunction ensureOrderScope(\n ctx: Parameters<typeof ensureTenantScope>[0],\n organizationId: string,\n tenantId: string,\n): void {\n ensureTenantScope(ctx, tenantId);\n ensureOrganizationScope(ctx, organizationId);\n}\n\nfunction normalizeTagIds(tags?: Array<string | null | undefined>): string[] {\n if (!Array.isArray(tags)) return [];\n const set = new Set<string>();\n tags.forEach((id) => {\n if (typeof id === \"string\" && id.trim().length > 0) set.add(id.trim());\n });\n return Array.from(set);\n}\n\nfunction buildTagChange(\n beforeTags: TagAssignmentSnapshot[] | undefined,\n afterTags: TagAssignmentSnapshot[] | undefined,\n): { from: string[]; to: string[] } | null {\n const beforeIds = normalizeTagIds(beforeTags?.map((tag) => tag.tagId));\n const afterIds = normalizeTagIds(afterTags?.map((tag) => tag.tagId));\n beforeIds.sort((a, b) => a.localeCompare(b));\n afterIds.sort((a, b) => a.localeCompare(b));\n if (\n beforeIds.length === afterIds.length &&\n beforeIds.every((id, index) => id === afterIds[index])\n ) {\n return null;\n }\n return { from: beforeIds, to: afterIds };\n}\n\nfunction buildDocumentUpdateChangeKeys(kind: SalesDocumentKind, input: DocumentUpdateInput): string[] {\n const keys = new Set<string>();\n if (kind === \"order\") {\n if (input.orderNumber !== undefined) keys.add(\"orderNumber\");\n } else {\n if (input.quoteNumber !== undefined) keys.add(\"quoteNumber\");\n }\n if (input.statusEntryId !== undefined) {\n keys.add(\"statusEntryId\");\n keys.add(\"status\");\n }\n if (input.customerEntityId !== undefined) {\n keys.add(\"customerEntityId\");\n keys.add(\"customerContactId\");\n keys.add(\"customerSnapshot\");\n keys.add(\"billingAddressId\");\n keys.add(\"shippingAddressId\");\n keys.add(\"billingAddressSnapshot\");\n keys.add(\"shippingAddressSnapshot\");\n }\n if (input.customerContactId !== undefined) {\n keys.add(\"customerContactId\");\n keys.add(\"customerSnapshot\");\n }\n if (input.customerSnapshot !== undefined) keys.add(\"customerSnapshot\");\n if (input.metadata !== undefined) keys.add(\"metadata\");\n if (input.comment !== undefined) keys.add(\"comments\");\n if (input.currencyCode !== undefined) keys.add(\"currencyCode\");\n if (input.channelId !== undefined) keys.add(\"channelId\");\n if (kind === \"order\") {\n if (input.placedAt !== undefined) keys.add(\"placedAt\");\n if (input.expectedDeliveryAt !== undefined) keys.add(\"expectedDeliveryAt\");\n }\n if (\n input.shippingAddressId !== undefined ||\n input.shippingAddressSnapshot !== undefined\n ) {\n keys.add(\"shippingAddressId\");\n keys.add(\"shippingAddressSnapshot\");\n }\n if (\n input.billingAddressId !== undefined ||\n input.billingAddressSnapshot !== undefined\n ) {\n keys.add(\"billingAddressId\");\n keys.add(\"billingAddressSnapshot\");\n }\n if (\n input.shippingMethodId !== undefined ||\n input.shippingMethodCode !== undefined ||\n input.shippingMethodSnapshot !== undefined\n ) {\n keys.add(\"shippingMethodId\");\n keys.add(\"shippingMethodCode\");\n keys.add(\"shippingMethodSnapshot\");\n }\n if (\n input.paymentMethodId !== undefined ||\n input.paymentMethodCode !== undefined ||\n input.paymentMethodSnapshot !== undefined\n ) {\n keys.add(\"paymentMethodId\");\n keys.add(\"paymentMethodCode\");\n keys.add(\"paymentMethodSnapshot\");\n }\n if (input.customFieldSetId !== undefined) keys.add(\"customFieldSetId\");\n if (input.customFields !== undefined) keys.add(\"customFields\");\n return Array.from(keys);\n}\n\nasync function syncSalesDocumentTags(\n em: EntityManager,\n params: {\n documentId: string;\n kind: SalesDocumentKind;\n organizationId: string;\n tenantId: string;\n tagIds?: Array<string | null | undefined> | null;\n },\n) {\n if (params.tagIds === undefined) return;\n const tagIds = normalizeTagIds(params.tagIds);\n if (tagIds.length === 0) {\n await em.nativeDelete(SalesDocumentTagAssignment, {\n documentId: params.documentId,\n documentKind: params.kind,\n });\n return;\n }\n const tagsInScope = await em.find(SalesDocumentTag, {\n id: { $in: tagIds },\n organizationId: params.organizationId,\n tenantId: params.tenantId,\n });\n if (tagsInScope.length !== tagIds.length) {\n throw new CrudHttpError(400, {\n error: \"One or more tags not found for this scope\",\n });\n }\n const byId = new Map(tagsInScope.map((tag) => [tag.id, tag]));\n await em.nativeDelete(SalesDocumentTagAssignment, {\n documentId: params.documentId,\n documentKind: params.kind,\n });\n for (const tagId of tagIds) {\n const tag = byId.get(tagId);\n if (!tag) continue;\n const assignment = em.create(SalesDocumentTagAssignment, {\n organizationId: params.organizationId,\n tenantId: params.tenantId,\n documentId: params.documentId,\n documentKind: params.kind,\n tag,\n order:\n params.kind === \"order\"\n ? em.getReference(SalesOrder, params.documentId)\n : null,\n quote:\n params.kind === \"quote\"\n ? em.getReference(SalesQuote, params.documentId)\n : null,\n });\n em.persist(assignment);\n }\n}\n\nfunction applyQuoteSnapshot(\n quote: SalesQuote,\n snapshot: QuoteGraphSnapshot[\"quote\"],\n): void {\n quote.organizationId = snapshot.organizationId;\n quote.tenantId = snapshot.tenantId;\n quote.quoteNumber = snapshot.quoteNumber;\n quote.statusEntryId = snapshot.statusEntryId ?? null;\n quote.status = snapshot.status ?? null;\n quote.customerEntityId = snapshot.customerEntityId ?? null;\n quote.customerContactId = snapshot.customerContactId ?? null;\n quote.customerSnapshot = snapshot.customerSnapshot\n ? cloneJson(snapshot.customerSnapshot)\n : null;\n quote.billingAddressId = snapshot.billingAddressId ?? null;\n quote.shippingAddressId = snapshot.shippingAddressId ?? null;\n quote.billingAddressSnapshot = snapshot.billingAddressSnapshot\n ? cloneJson(snapshot.billingAddressSnapshot)\n : null;\n quote.shippingAddressSnapshot = snapshot.shippingAddressSnapshot\n ? cloneJson(snapshot.shippingAddressSnapshot)\n : null;\n quote.currencyCode = snapshot.currencyCode;\n quote.validFrom = snapshot.validFrom ? new Date(snapshot.validFrom) : null;\n quote.validUntil = snapshot.validUntil ? new Date(snapshot.validUntil) : null;\n quote.comments = snapshot.comments ?? null;\n quote.taxInfo = snapshot.taxInfo ? cloneJson(snapshot.taxInfo) : null;\n quote.shippingMethodId = snapshot.shippingMethodId ?? null;\n quote.shippingMethodCode = snapshot.shippingMethodCode ?? null;\n quote.deliveryWindowId = snapshot.deliveryWindowId ?? null;\n quote.deliveryWindowCode = snapshot.deliveryWindowCode ?? null;\n quote.paymentMethodId = snapshot.paymentMethodId ?? null;\n quote.paymentMethodCode = snapshot.paymentMethodCode ?? null;\n quote.shippingMethodSnapshot = snapshot.shippingMethodSnapshot\n ? cloneJson(snapshot.shippingMethodSnapshot)\n : null;\n quote.deliveryWindowSnapshot = snapshot.deliveryWindowSnapshot\n ? cloneJson(snapshot.deliveryWindowSnapshot)\n : null;\n quote.paymentMethodSnapshot = snapshot.paymentMethodSnapshot\n ? cloneJson(snapshot.paymentMethodSnapshot)\n : null;\n quote.metadata = snapshot.metadata ? cloneJson(snapshot.metadata) : null;\n quote.channelId = snapshot.channelId ?? null;\n quote.customFieldSetId = snapshot.customFieldSetId ?? null;\n quote.subtotalNetAmount = snapshot.subtotalNetAmount;\n quote.subtotalGrossAmount = snapshot.subtotalGrossAmount;\n quote.discountTotalAmount = snapshot.discountTotalAmount;\n quote.taxTotalAmount = snapshot.taxTotalAmount;\n quote.grandTotalNetAmount = snapshot.grandTotalNetAmount;\n quote.grandTotalGrossAmount = snapshot.grandTotalGrossAmount;\n quote.totalsSnapshot = snapshot.totalsSnapshot\n ? cloneJson(snapshot.totalsSnapshot)\n : null;\n quote.lineItemCount = snapshot.lineItemCount;\n}\n\nfunction applyOrderSnapshot(\n order: SalesOrder,\n snapshot: OrderGraphSnapshot[\"order\"],\n): void {\n order.organizationId = snapshot.organizationId;\n order.tenantId = snapshot.tenantId;\n order.orderNumber = snapshot.orderNumber;\n order.statusEntryId = snapshot.statusEntryId ?? null;\n order.status = snapshot.status ?? null;\n order.fulfillmentStatusEntryId = snapshot.fulfillmentStatusEntryId ?? null;\n order.fulfillmentStatus = snapshot.fulfillmentStatus ?? null;\n order.paymentStatusEntryId = snapshot.paymentStatusEntryId ?? null;\n order.paymentStatus = snapshot.paymentStatus ?? null;\n order.customerEntityId = snapshot.customerEntityId ?? null;\n order.customerContactId = snapshot.customerContactId ?? null;\n order.customerSnapshot = snapshot.customerSnapshot\n ? cloneJson(snapshot.customerSnapshot)\n : null;\n order.billingAddressId = snapshot.billingAddressId ?? null;\n order.shippingAddressId = snapshot.shippingAddressId ?? null;\n order.billingAddressSnapshot = snapshot.billingAddressSnapshot\n ? cloneJson(snapshot.billingAddressSnapshot)\n : null;\n order.shippingAddressSnapshot = snapshot.shippingAddressSnapshot\n ? cloneJson(snapshot.shippingAddressSnapshot)\n : null;\n order.currencyCode = snapshot.currencyCode;\n order.exchangeRate = snapshot.exchangeRate ?? null;\n order.taxStrategyKey = snapshot.taxStrategyKey ?? null;\n order.discountStrategyKey = snapshot.discountStrategyKey ?? null;\n order.taxInfo = snapshot.taxInfo ? cloneJson(snapshot.taxInfo) : null;\n order.shippingMethodId = snapshot.shippingMethodId ?? null;\n order.shippingMethodCode = snapshot.shippingMethodCode ?? null;\n order.deliveryWindowId = snapshot.deliveryWindowId ?? null;\n order.deliveryWindowCode = snapshot.deliveryWindowCode ?? null;\n order.paymentMethodId = snapshot.paymentMethodId ?? null;\n order.paymentMethodCode = snapshot.paymentMethodCode ?? null;\n order.channelId = snapshot.channelId ?? null;\n order.placedAt = snapshot.placedAt ? new Date(snapshot.placedAt) : null;\n order.expectedDeliveryAt = snapshot.expectedDeliveryAt\n ? new Date(snapshot.expectedDeliveryAt)\n : null;\n order.dueAt = snapshot.dueAt ? new Date(snapshot.dueAt) : null;\n order.comments = snapshot.comments ?? null;\n order.internalNotes = snapshot.internalNotes ?? null;\n order.shippingMethodSnapshot = snapshot.shippingMethodSnapshot\n ? cloneJson(snapshot.shippingMethodSnapshot)\n : null;\n order.deliveryWindowSnapshot = snapshot.deliveryWindowSnapshot\n ? cloneJson(snapshot.deliveryWindowSnapshot)\n : null;\n order.paymentMethodSnapshot = snapshot.paymentMethodSnapshot\n ? cloneJson(snapshot.paymentMethodSnapshot)\n : null;\n order.metadata = snapshot.metadata ? cloneJson(snapshot.metadata) : null;\n order.customFieldSetId = snapshot.customFieldSetId ?? null;\n order.subtotalNetAmount = snapshot.subtotalNetAmount;\n order.subtotalGrossAmount = snapshot.subtotalGrossAmount;\n order.discountTotalAmount = snapshot.discountTotalAmount;\n order.taxTotalAmount = snapshot.taxTotalAmount;\n order.shippingNetAmount = snapshot.shippingNetAmount;\n order.shippingGrossAmount = snapshot.shippingGrossAmount;\n order.surchargeTotalAmount = snapshot.surchargeTotalAmount;\n order.grandTotalNetAmount = snapshot.grandTotalNetAmount;\n order.grandTotalGrossAmount = snapshot.grandTotalGrossAmount;\n order.paidTotalAmount = snapshot.paidTotalAmount;\n order.refundedTotalAmount = snapshot.refundedTotalAmount;\n order.outstandingAmount = snapshot.outstandingAmount;\n order.totalsSnapshot = snapshot.totalsSnapshot\n ? cloneJson(snapshot.totalsSnapshot)\n : null;\n order.lineItemCount = snapshot.lineItemCount;\n}\n\nasync function restoreQuoteGraph(\n em: EntityManager,\n snapshot: QuoteGraphSnapshot,\n): Promise<SalesQuote> {\n let quote = await em.findOne(SalesQuote, { id: snapshot.quote.id });\n if (!quote) {\n quote = em.create(SalesQuote, {\n id: snapshot.quote.id,\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n quoteNumber: snapshot.quote.quoteNumber,\n statusEntryId: snapshot.quote.statusEntryId ?? null,\n status: snapshot.quote.status ?? null,\n customerEntityId: snapshot.quote.customerEntityId ?? null,\n customerContactId: snapshot.quote.customerContactId ?? null,\n customerSnapshot: snapshot.quote.customerSnapshot\n ? cloneJson(snapshot.quote.customerSnapshot)\n : null,\n billingAddressId: snapshot.quote.billingAddressId ?? null,\n shippingAddressId: snapshot.quote.shippingAddressId ?? null,\n billingAddressSnapshot: snapshot.quote.billingAddressSnapshot\n ? cloneJson(snapshot.quote.billingAddressSnapshot)\n : null,\n shippingAddressSnapshot: snapshot.quote.shippingAddressSnapshot\n ? cloneJson(snapshot.quote.shippingAddressSnapshot)\n : null,\n currencyCode: snapshot.quote.currencyCode,\n validFrom: snapshot.quote.validFrom\n ? new Date(snapshot.quote.validFrom)\n : null,\n validUntil: snapshot.quote.validUntil\n ? new Date(snapshot.quote.validUntil)\n : null,\n comments: snapshot.quote.comments ?? null,\n taxInfo: snapshot.quote.taxInfo\n ? cloneJson(snapshot.quote.taxInfo)\n : null,\n shippingMethodId: snapshot.quote.shippingMethodId ?? null,\n shippingMethodCode: snapshot.quote.shippingMethodCode ?? null,\n deliveryWindowId: snapshot.quote.deliveryWindowId ?? null,\n deliveryWindowCode: snapshot.quote.deliveryWindowCode ?? null,\n paymentMethodId: snapshot.quote.paymentMethodId ?? null,\n paymentMethodCode: snapshot.quote.paymentMethodCode ?? null,\n shippingMethodSnapshot: snapshot.quote.shippingMethodSnapshot\n ? cloneJson(snapshot.quote.shippingMethodSnapshot)\n : null,\n deliveryWindowSnapshot: snapshot.quote.deliveryWindowSnapshot\n ? cloneJson(snapshot.quote.deliveryWindowSnapshot)\n : null,\n paymentMethodSnapshot: snapshot.quote.paymentMethodSnapshot\n ? cloneJson(snapshot.quote.paymentMethodSnapshot)\n : null,\n metadata: snapshot.quote.metadata\n ? cloneJson(snapshot.quote.metadata)\n : null,\n channelId: snapshot.quote.channelId ?? null,\n customFieldSetId: snapshot.quote.customFieldSetId ?? null,\n subtotalNetAmount: snapshot.quote.subtotalNetAmount,\n subtotalGrossAmount: snapshot.quote.subtotalGrossAmount,\n discountTotalAmount: snapshot.quote.discountTotalAmount,\n taxTotalAmount: snapshot.quote.taxTotalAmount,\n grandTotalNetAmount: snapshot.quote.grandTotalNetAmount,\n grandTotalGrossAmount: snapshot.quote.grandTotalGrossAmount,\n totalsSnapshot: snapshot.quote.totalsSnapshot\n ? cloneJson(snapshot.quote.totalsSnapshot)\n : null,\n lineItemCount: snapshot.quote.lineItemCount,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(quote);\n }\n applyQuoteSnapshot(quote, snapshot.quote);\n await em.flush();\n const existingLines = await em.find(\n SalesQuoteLine,\n { quote: quote.id },\n { fields: [\"id\"] },\n );\n const existingAdjustments = await em.find(\n SalesQuoteAdjustment,\n { quote: quote.id },\n { fields: [\"id\"] },\n );\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_quote,\n recordId: quote.id,\n });\n if (existingLines.length) {\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_quote_line,\n recordId: { $in: existingLines.map((line) => line.id) },\n });\n }\n if (existingAdjustments.length) {\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_quote_adjustment,\n recordId: { $in: existingAdjustments.map((adj) => adj.id) },\n });\n }\n const addressSnapshots = Array.isArray(snapshot.addresses)\n ? snapshot.addresses\n : [];\n const noteSnapshots = Array.isArray(snapshot.notes) ? snapshot.notes : [];\n const tagSnapshots = Array.isArray(snapshot.tags) ? snapshot.tags : [];\n await em.nativeDelete(SalesDocumentAddress, {\n documentId: quote.id,\n documentKind: \"quote\",\n });\n await em.nativeDelete(SalesNote, {\n contextType: \"quote\",\n contextId: quote.id,\n });\n await em.nativeDelete(SalesDocumentTagAssignment, {\n documentId: quote.id,\n documentKind: \"quote\",\n });\n await em.nativeDelete(SalesQuoteLine, { quote: quote.id });\n await em.nativeDelete(SalesQuoteAdjustment, { quote: quote.id });\n existingLines.forEach((entry) => em.getUnitOfWork().unsetIdentity(entry));\n existingAdjustments.forEach((entry) =>\n em.getUnitOfWork().unsetIdentity(entry),\n );\n\n snapshot.lines.forEach((line) => {\n const lineEntity = em.create(SalesQuoteLine, {\n id: line.id,\n quote,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n lineNumber: line.lineNumber,\n kind: line.kind as SalesLineKind,\n statusEntryId: line.statusEntryId ?? null,\n status: line.status ?? null,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: line.normalizedQuantity ?? line.quantity,\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n discountAmount: line.discountAmount,\n discountPercent: line.discountPercent,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n totalNetAmount: line.totalNetAmount,\n totalGrossAmount: line.totalGrossAmount,\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(lineEntity);\n });\n\n snapshot.adjustments.forEach((adjustment, index) => {\n const adjustmentEntity = em.create(SalesQuoteAdjustment, {\n id: adjustment.id,\n quote,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n scope: adjustment.scope,\n kind: adjustment.kind as SalesAdjustmentKind,\n code: adjustment.code ?? null,\n label: adjustment.label ?? null,\n calculatorKey: adjustment.calculatorKey ?? null,\n promotionId: adjustment.promotionId ?? null,\n rate: adjustment.rate,\n amountNet: adjustment.amountNet,\n amountGross: adjustment.amountGross,\n currencyCode: adjustment.currencyCode ?? null,\n metadata: adjustment.metadata ? cloneJson(adjustment.metadata) : null,\n position: adjustment.position ?? index,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n adjustmentEntity.quoteLine = null;\n em.persist(adjustmentEntity);\n });\n\n addressSnapshots.forEach((entry) => {\n const entity = em.create(SalesDocumentAddress, {\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n documentId: quote.id,\n documentKind: \"quote\",\n customerAddressId: entry.customerAddressId ?? null,\n name: entry.name ?? null,\n purpose: entry.purpose ?? null,\n companyName: entry.companyName ?? null,\n addressLine1: entry.addressLine1,\n addressLine2: entry.addressLine2 ?? null,\n city: entry.city ?? null,\n region: entry.region ?? null,\n postalCode: entry.postalCode ?? null,\n country: entry.country ?? null,\n buildingNumber: entry.buildingNumber ?? null,\n flatNumber: entry.flatNumber ?? null,\n latitude: entry.latitude ?? null,\n longitude: entry.longitude ?? null,\n quote,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(entity);\n });\n\n noteSnapshots.forEach((entry) => {\n const entity = em.create(SalesNote, {\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n contextType: \"quote\",\n contextId: quote.id,\n order: null,\n quote,\n body: entry.body,\n authorUserId: entry.authorUserId ?? null,\n appearanceIcon: entry.appearanceIcon ?? null,\n appearanceColor: entry.appearanceColor ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(entity);\n });\n\n tagSnapshots.forEach((entry) => {\n const tag = em.getReference(SalesDocumentTag, entry.tagId);\n const assignment = em.create(SalesDocumentTagAssignment, {\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n documentId: quote.id,\n documentKind: \"quote\",\n tag,\n quote,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(assignment);\n });\n\n if (snapshot.quote.customFields) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_quote,\n recordId: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n values: normalizeCustomFieldValues(snapshot.quote.customFields),\n });\n }\n for (const line of snapshot.lines) {\n if (!line.customFields) continue;\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_quote_line,\n recordId: line.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n values: normalizeCustomFieldValues(line.customFields),\n });\n }\n for (const adjustment of snapshot.adjustments) {\n if (!adjustment.customFields) continue;\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_quote_adjustment,\n recordId: adjustment.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n values: normalizeCustomFieldValues(adjustment.customFields),\n });\n }\n\n return quote;\n}\n\nasync function restoreOrderGraph(\n em: EntityManager,\n snapshot: OrderGraphSnapshot,\n): Promise<SalesOrder> {\n let order = await em.findOne(SalesOrder, { id: snapshot.order.id });\n if (!order) {\n order = em.create(SalesOrder, {\n id: snapshot.order.id,\n organizationId: snapshot.order.organizationId,\n tenantId: snapshot.order.tenantId,\n orderNumber: snapshot.order.orderNumber,\n statusEntryId: snapshot.order.statusEntryId ?? null,\n status: snapshot.order.status ?? null,\n fulfillmentStatusEntryId: snapshot.order.fulfillmentStatusEntryId ?? null,\n fulfillmentStatus: snapshot.order.fulfillmentStatus ?? null,\n paymentStatusEntryId: snapshot.order.paymentStatusEntryId ?? null,\n paymentStatus: snapshot.order.paymentStatus ?? null,\n customerEntityId: snapshot.order.customerEntityId ?? null,\n customerContactId: snapshot.order.customerContactId ?? null,\n customerSnapshot: snapshot.order.customerSnapshot\n ? cloneJson(snapshot.order.customerSnapshot)\n : null,\n billingAddressId: snapshot.order.billingAddressId ?? null,\n shippingAddressId: snapshot.order.shippingAddressId ?? null,\n billingAddressSnapshot: snapshot.order.billingAddressSnapshot\n ? cloneJson(snapshot.order.billingAddressSnapshot)\n : null,\n shippingAddressSnapshot: snapshot.order.shippingAddressSnapshot\n ? cloneJson(snapshot.order.shippingAddressSnapshot)\n : null,\n currencyCode: snapshot.order.currencyCode,\n exchangeRate: snapshot.order.exchangeRate ?? null,\n taxStrategyKey: snapshot.order.taxStrategyKey ?? null,\n discountStrategyKey: snapshot.order.discountStrategyKey ?? null,\n taxInfo: snapshot.order.taxInfo\n ? cloneJson(snapshot.order.taxInfo)\n : null,\n shippingMethodId: snapshot.order.shippingMethodId ?? null,\n shippingMethodCode: snapshot.order.shippingMethodCode ?? null,\n deliveryWindowId: snapshot.order.deliveryWindowId ?? null,\n deliveryWindowCode: snapshot.order.deliveryWindowCode ?? null,\n paymentMethodId: snapshot.order.paymentMethodId ?? null,\n paymentMethodCode: snapshot.order.paymentMethodCode ?? null,\n channelId: snapshot.order.channelId ?? null,\n placedAt: snapshot.order.placedAt\n ? new Date(snapshot.order.placedAt)\n : null,\n expectedDeliveryAt: snapshot.order.expectedDeliveryAt\n ? new Date(snapshot.order.expectedDeliveryAt)\n : null,\n dueAt: snapshot.order.dueAt ? new Date(snapshot.order.dueAt) : null,\n comments: snapshot.order.comments ?? null,\n internalNotes: snapshot.order.internalNotes ?? null,\n shippingMethodSnapshot: snapshot.order.shippingMethodSnapshot\n ? cloneJson(snapshot.order.shippingMethodSnapshot)\n : null,\n deliveryWindowSnapshot: snapshot.order.deliveryWindowSnapshot\n ? cloneJson(snapshot.order.deliveryWindowSnapshot)\n : null,\n paymentMethodSnapshot: snapshot.order.paymentMethodSnapshot\n ? cloneJson(snapshot.order.paymentMethodSnapshot)\n : null,\n metadata: snapshot.order.metadata\n ? cloneJson(snapshot.order.metadata)\n : null,\n customFieldSetId: snapshot.order.customFieldSetId ?? null,\n subtotalNetAmount: snapshot.order.subtotalNetAmount,\n subtotalGrossAmount: snapshot.order.subtotalGrossAmount,\n discountTotalAmount: snapshot.order.discountTotalAmount,\n taxTotalAmount: snapshot.order.taxTotalAmount,\n shippingNetAmount: snapshot.order.shippingNetAmount,\n shippingGrossAmount: snapshot.order.shippingGrossAmount,\n surchargeTotalAmount: snapshot.order.surchargeTotalAmount,\n grandTotalNetAmount: snapshot.order.grandTotalNetAmount,\n grandTotalGrossAmount: snapshot.order.grandTotalGrossAmount,\n paidTotalAmount: snapshot.order.paidTotalAmount,\n refundedTotalAmount: snapshot.order.refundedTotalAmount,\n outstandingAmount: snapshot.order.outstandingAmount,\n totalsSnapshot: snapshot.order.totalsSnapshot\n ? cloneJson(snapshot.order.totalsSnapshot)\n : null,\n lineItemCount: snapshot.order.lineItemCount,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(order);\n }\n applyOrderSnapshot(order, snapshot.order);\n await em.flush();\n const existingLines = await em.find(\n SalesOrderLine,\n { order: order.id },\n { fields: [\"id\"] },\n );\n const existingAdjustments = await em.find(\n SalesOrderAdjustment,\n { order: order.id },\n { fields: [\"id\"] },\n );\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_order,\n recordId: order.id,\n });\n if (existingLines.length) {\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_order_line,\n recordId: { $in: existingLines.map((line) => line.id) },\n });\n }\n if (existingAdjustments.length) {\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_order_adjustment,\n recordId: { $in: existingAdjustments.map((adj) => adj.id) },\n });\n }\n const addressSnapshots = Array.isArray(snapshot.addresses)\n ? snapshot.addresses\n : [];\n const noteSnapshots = Array.isArray(snapshot.notes) ? snapshot.notes : [];\n const tagSnapshots = Array.isArray(snapshot.tags) ? snapshot.tags : [];\n const shipmentSnapshots = Array.isArray(snapshot.shipments)\n ? snapshot.shipments\n : [];\n const paymentSnapshots = Array.isArray(snapshot.payments)\n ? snapshot.payments\n : [];\n const existingShipments = await em.find(SalesShipment, { order: order.id });\n const shipmentIds = existingShipments.map((entry) => entry.id);\n if (shipmentIds.length) {\n await em.nativeDelete(SalesShipmentItem, {\n shipment: { $in: shipmentIds },\n });\n await em.nativeDelete(SalesShipment, { id: { $in: shipmentIds } });\n existingShipments.forEach((entry) =>\n em.getUnitOfWork().unsetIdentity(entry),\n );\n }\n await em.nativeDelete(SalesPaymentAllocation, { order: order.id });\n await em.nativeDelete(SalesPayment, { order: order.id });\n await em.nativeDelete(SalesDocumentAddress, {\n documentId: order.id,\n documentKind: \"order\",\n });\n await em.nativeDelete(SalesNote, {\n contextType: \"order\",\n contextId: order.id,\n });\n await em.nativeDelete(SalesDocumentTagAssignment, {\n documentId: order.id,\n documentKind: \"order\",\n });\n await em.nativeDelete(SalesOrderAdjustment, { order: order.id });\n await em.nativeDelete(SalesOrderLine, { order: order.id });\n existingLines.forEach((entry) => em.getUnitOfWork().unsetIdentity(entry));\n existingAdjustments.forEach((entry) =>\n em.getUnitOfWork().unsetIdentity(entry),\n );\n\n snapshot.lines.forEach((line) => {\n const lineEntity = em.create(SalesOrderLine, {\n id: line.id,\n order,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n lineNumber: line.lineNumber,\n kind: line.kind as SalesLineKind,\n statusEntryId: line.statusEntryId ?? null,\n status: line.status ?? null,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: line.normalizedQuantity ?? line.quantity,\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n reservedQuantity: line.reservedQuantity,\n fulfilledQuantity: line.fulfilledQuantity,\n invoicedQuantity: line.invoicedQuantity,\n returnedQuantity: line.returnedQuantity,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n discountAmount: line.discountAmount,\n discountPercent: line.discountPercent,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n totalNetAmount: line.totalNetAmount,\n totalGrossAmount: line.totalGrossAmount,\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(lineEntity);\n });\n\n snapshot.adjustments.forEach((adjustment, index) => {\n const adjustmentEntity = em.create(SalesOrderAdjustment, {\n id: adjustment.id,\n order,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n scope: adjustment.scope,\n kind: adjustment.kind as SalesAdjustmentKind,\n code: adjustment.code ?? null,\n label: adjustment.label ?? null,\n calculatorKey: adjustment.calculatorKey ?? null,\n promotionId: adjustment.promotionId ?? null,\n rate: adjustment.rate,\n amountNet: adjustment.amountNet,\n amountGross: adjustment.amountGross,\n currencyCode: adjustment.currencyCode ?? null,\n metadata: adjustment.metadata ? cloneJson(adjustment.metadata) : null,\n position: adjustment.position ?? index,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n adjustmentEntity.orderLine = null;\n em.persist(adjustmentEntity);\n });\n\n addressSnapshots.forEach((entry) => {\n const entity = em.create(SalesDocumentAddress, {\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n documentId: order.id,\n documentKind: \"order\",\n customerAddressId: entry.customerAddressId ?? null,\n name: entry.name ?? null,\n purpose: entry.purpose ?? null,\n companyName: entry.companyName ?? null,\n addressLine1: entry.addressLine1,\n addressLine2: entry.addressLine2 ?? null,\n city: entry.city ?? null,\n region: entry.region ?? null,\n postalCode: entry.postalCode ?? null,\n country: entry.country ?? null,\n buildingNumber: entry.buildingNumber ?? null,\n flatNumber: entry.flatNumber ?? null,\n latitude: entry.latitude ?? null,\n longitude: entry.longitude ?? null,\n order,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(entity);\n });\n\n noteSnapshots.forEach((entry) => {\n const entity = em.create(SalesNote, {\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n contextType: \"order\",\n contextId: order.id,\n order,\n quote: null,\n body: entry.body,\n authorUserId: entry.authorUserId ?? null,\n appearanceIcon: entry.appearanceIcon ?? null,\n appearanceColor: entry.appearanceColor ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(entity);\n });\n\n tagSnapshots.forEach((entry) => {\n const tag = em.getReference(SalesDocumentTag, entry.tagId);\n const assignment = em.create(SalesDocumentTagAssignment, {\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n documentId: order.id,\n documentKind: \"order\",\n tag,\n order,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(assignment);\n });\n\n if (snapshot.order.customFields) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order,\n recordId: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n values: normalizeCustomFieldValues(snapshot.order.customFields),\n });\n }\n for (const line of snapshot.lines) {\n if (!line.customFields) continue;\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order_line,\n recordId: line.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n values: normalizeCustomFieldValues(line.customFields),\n });\n }\n for (const adjustment of snapshot.adjustments) {\n if (!adjustment.customFields) continue;\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order_adjustment,\n recordId: adjustment.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n values: normalizeCustomFieldValues(adjustment.customFields),\n });\n }\n\n for (const shipment of shipmentSnapshots) {\n await restoreShipmentSnapshot(em, shipment);\n }\n\n for (const payment of paymentSnapshots) {\n await restorePaymentSnapshot(em, payment);\n }\n\n return order;\n}\n\nconst createQuoteCommand: CommandHandler<\n QuoteCreateInput,\n { quoteId: string }\n> = {\n id: \"sales.quotes.create\",\n async execute(rawInput, ctx) {\n const generator = ctx.container.resolve(\n \"salesDocumentNumberGenerator\",\n ) as SalesDocumentNumberGenerator;\n const initial = quoteCreateSchema.parse(rawInput ?? {});\n const quoteNumber =\n typeof initial.quoteNumber === \"string\" &&\n initial.quoteNumber.trim().length\n ? initial.quoteNumber.trim()\n : (\n await generator.generate({\n kind: \"quote\",\n organizationId: initial.organizationId,\n tenantId: initial.tenantId,\n })\n ).number;\n const parsed = quoteCreateSchema.parse({ ...initial, quoteNumber });\n const ensuredQuoteNumber = parsed.quoteNumber ?? quoteNumber;\n if (!ensuredQuoteNumber) {\n throw new CrudHttpError(400, { error: \"Quote number is required.\" });\n }\n ensureQuoteScope(ctx, parsed.organizationId, parsed.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const {\n customerSnapshot: resolvedCustomerSnapshot,\n billingAddressSnapshot: resolvedBillingSnapshot,\n shippingAddressSnapshot: resolvedShippingSnapshot,\n shippingMethod,\n deliveryWindow,\n paymentMethod,\n } = await resolveDocumentReferences(em, parsed);\n const quoteStatus = await resolveDictionaryEntryValue(\n em,\n parsed.statusEntryId ?? null,\n );\n const quoteId = randomUUID();\n const quote = em.create(SalesQuote, {\n id: quoteId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n quoteNumber: ensuredQuoteNumber,\n statusEntryId: parsed.statusEntryId ?? null,\n status: quoteStatus,\n customerEntityId: parsed.customerEntityId ?? null,\n customerContactId: parsed.customerContactId ?? null,\n customerSnapshot: resolvedCustomerSnapshot\n ? cloneJson(resolvedCustomerSnapshot)\n : null,\n billingAddressId: parsed.billingAddressId ?? null,\n shippingAddressId: parsed.shippingAddressId ?? null,\n billingAddressSnapshot: resolvedBillingSnapshot\n ? cloneJson(resolvedBillingSnapshot)\n : null,\n shippingAddressSnapshot: resolvedShippingSnapshot\n ? cloneJson(resolvedShippingSnapshot)\n : null,\n currencyCode: parsed.currencyCode,\n validFrom: parsed.validFrom ?? null,\n validUntil: parsed.validUntil ?? null,\n comments: parsed.comments ?? null,\n taxInfo: parsed.taxInfo ? cloneJson(parsed.taxInfo) : null,\n shippingMethodId: parsed.shippingMethodId ?? null,\n shippingMethod: shippingMethod ?? null,\n shippingMethodCode:\n parsed.shippingMethodCode ?? shippingMethod?.code ?? null,\n deliveryWindowId: parsed.deliveryWindowId ?? null,\n deliveryWindow: deliveryWindow ?? null,\n deliveryWindowCode:\n parsed.deliveryWindowCode ?? deliveryWindow?.code ?? null,\n paymentMethodId: parsed.paymentMethodId ?? null,\n paymentMethod: paymentMethod ?? null,\n paymentMethodCode:\n parsed.paymentMethodCode ?? paymentMethod?.code ?? null,\n shippingMethodSnapshot: parsed.shippingMethodSnapshot\n ? cloneJson(parsed.shippingMethodSnapshot)\n : shippingMethod\n ? {\n id: shippingMethod.id,\n code: shippingMethod.code,\n name: shippingMethod.name,\n description: shippingMethod.description ?? null,\n carrierCode: shippingMethod.carrierCode ?? null,\n providerKey: shippingMethod.providerKey ?? null,\n serviceLevel: shippingMethod.serviceLevel ?? null,\n estimatedTransitDays: shippingMethod.estimatedTransitDays ?? null,\n baseRateNet: shippingMethod.baseRateNet,\n baseRateGross: shippingMethod.baseRateGross,\n currencyCode: shippingMethod.currencyCode ?? null,\n metadata: shippingMethod.metadata\n ? cloneJson(shippingMethod.metadata)\n : null,\n providerSettings:\n shippingMethod.metadata &&\n typeof shippingMethod.metadata === \"object\"\n ? cloneJson(\n (shippingMethod.metadata as Record<string, unknown>)\n .providerSettings ?? null,\n )\n : null,\n }\n : null,\n deliveryWindowSnapshot: parsed.deliveryWindowSnapshot\n ? cloneJson(parsed.deliveryWindowSnapshot)\n : deliveryWindow\n ? {\n id: deliveryWindow.id,\n code: deliveryWindow.code,\n name: deliveryWindow.name,\n description: deliveryWindow.description ?? null,\n leadTimeDays: deliveryWindow.leadTimeDays ?? null,\n cutoffTime: deliveryWindow.cutoffTime ?? null,\n timezone: deliveryWindow.timezone ?? null,\n }\n : null,\n paymentMethodSnapshot: parsed.paymentMethodSnapshot\n ? cloneJson(parsed.paymentMethodSnapshot)\n : paymentMethod\n ? {\n id: paymentMethod.id,\n code: paymentMethod.code,\n name: paymentMethod.name,\n description: paymentMethod.description ?? null,\n providerKey: paymentMethod.providerKey ?? null,\n terms: paymentMethod.terms ?? null,\n metadata: paymentMethod.metadata\n ? cloneJson(paymentMethod.metadata)\n : null,\n providerSettings:\n paymentMethod.metadata &&\n typeof paymentMethod.metadata === \"object\"\n ? cloneJson(\n (paymentMethod.metadata as Record<string, unknown>)\n .providerSettings ?? null,\n )\n : null,\n }\n : null,\n metadata: parsed.metadata ? cloneJson(parsed.metadata) : null,\n channelId: parsed.channelId ?? null,\n customFieldSetId: parsed.customFieldSetId ?? null,\n subtotalNetAmount: \"0\",\n subtotalGrossAmount: \"0\",\n discountTotalAmount: \"0\",\n taxTotalAmount: \"0\",\n grandTotalNetAmount: \"0\",\n grandTotalGrossAmount: \"0\",\n lineItemCount: 0,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n\n const lineInputs = (parsed.lines ?? []).map((line, index) =>\n quoteLineCreateSchema.parse({\n ...line,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n quoteId: quote.id,\n lineNumber: line.lineNumber ?? index + 1,\n }),\n );\n const uomResolver = createUomResolver();\n const normalizedLineInputs = await Promise.all(\n lineInputs.map(async (line) => {\n const normalized = await normalizeLineUom({\n em,\n resolver: uomResolver,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n line,\n });\n return {\n ...line,\n quantity: normalized.quantity,\n quantityUnit: normalized.quantityUnit,\n normalizedQuantity: normalized.normalizedQuantity,\n normalizedUnit: normalized.normalizedUnit,\n uomSnapshot: normalized.uomSnapshot,\n };\n }),\n );\n const adjustmentInputs = parsed.adjustments\n ? parsed.adjustments.map((adj) =>\n quoteAdjustmentCreateSchema.parse({\n ...adj,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n quoteId: quote.id,\n }),\n )\n : null;\n\n const lineSnapshots: SalesLineSnapshot[] = normalizedLineInputs.map(\n (line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const adjustmentDrafts: SalesAdjustmentDraft[] = adjustmentInputs\n ? adjustmentInputs.map((adj) => createAdjustmentDraftFromInput(adj))\n : [];\n\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n currencyCode: quote.currencyCode,\n shippingSnapshot: quote.shippingMethodSnapshot,\n paymentSnapshot: quote.paymentMethodSnapshot,\n shippingMethodId: quote.shippingMethodId ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: lineSnapshots,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n });\n\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n // Persist the quote header, lines, adjustments, totals and tags atomically.\n // replace*/setRecordCustomFields flush mid-build, so without a transaction a\n // later failure (e.g. tag sync) would leave a half-built quote committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n em.persist(quote);\n await replaceQuoteLines(em, quote, calculation, normalizedLineInputs);\n await replaceQuoteAdjustments(\n em,\n quote,\n calculation,\n adjustmentInputs,\n );\n applyQuoteTotals(quote, calculation.totals, calculation.lines.length);\n await emitTotalsCalculated(eventBus, {\n documentKind: \"quote\",\n documentId: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n customerId: quote.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n await syncSalesDocumentTags(em, {\n documentId: quote.id,\n kind: \"quote\",\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n tagIds: parsed.tags,\n });\n },\n ],\n { transaction: true },\n );\n\n // Create notification for users with sales.quotes.manage feature\n try {\n const notificationService = resolveNotificationService(ctx.container);\n const typeDef = notificationTypes.find(\n (type) => type.type === \"sales.quote.created\",\n );\n if (typeDef) {\n const totalAmount =\n quote.grandTotalGrossAmount && quote.currencyCode\n ? `${quote.grandTotalGrossAmount} ${quote.currencyCode}`\n : \"\";\n const totalDisplay = totalAmount ? ` (${totalAmount})` : \"\";\n const notificationInput = buildFeatureNotificationFromType(typeDef, {\n requiredFeature: \"sales.quotes.manage\",\n bodyVariables: {\n quoteNumber: quote.quoteNumber,\n total: totalDisplay,\n totalAmount,\n },\n sourceEntityType: \"sales:quote\",\n sourceEntityId: quote.id,\n linkHref: `/backend/sales/quotes/${quote.id}`,\n });\n\n await notificationService.createForFeature(notificationInput, {\n tenantId: quote.tenantId,\n organizationId: quote.organizationId ?? null,\n });\n }\n } catch (err) {\n // Notification creation is non-critical, don't fail the command\n console.error(\n \"[sales.quotes.create] Failed to create notification:\",\n err,\n );\n }\n\n // Emit CRUD side effects to trigger workflow event listeners\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"created\",\n entity: quote,\n identifiers: {\n id: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n },\n events: quoteCrudEvents,\n indexer: { entityType: E.sales.sales_quote },\n });\n\n // Invalidate cache\n const resourceKind =\n deriveResourceFromCommandId(createQuoteCommand.id) ?? \"sales.quote\";\n await invalidateCrudCache(\n ctx.container,\n resourceKind,\n {\n id: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"created\",\n );\n\n return { quoteId: quote.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadQuoteSnapshot(em, result.quoteId);\n },\n buildLog: async ({ result, snapshots }) => {\n const after = snapshots.after as QuoteGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.quotes.create\", \"Create sales quote\"),\n resourceKind: \"sales.quote\",\n resourceId: result.quoteId,\n tenantId: after.quote.tenantId,\n organizationId: after.quote.organizationId,\n snapshotAfter: after,\n payload: {\n undo: {\n after,\n } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const after = payload?.after;\n if (!after) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const quote = await em.findOne(SalesQuote, { id: after.quote.id });\n if (!quote) return;\n ensureQuoteScope(ctx, quote.organizationId, quote.tenantId);\n await em.nativeDelete(SalesQuoteAdjustment, { quote: quote.id });\n await em.nativeDelete(SalesQuoteLine, { quote: quote.id });\n em.remove(quote);\n await em.flush();\n },\n};\n\nconst deleteQuoteCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { quoteId: string }\n> = {\n id: \"sales.quotes.delete\",\n async prepare(input, ctx) {\n const id = requireId(input, \"Quote id is required\");\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadQuoteSnapshot(em, id);\n if (snapshot) {\n ensureQuoteScope(\n ctx,\n snapshot.quote.organizationId,\n snapshot.quote.tenantId,\n );\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(input, ctx) {\n const id = requireId(input, \"Quote id is required\");\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const quote = await em.findOne(SalesQuote, { id });\n if (!quote)\n throw new CrudHttpError(404, { error: \"Sales quote not found\" });\n ensureQuoteScope(ctx, quote.organizationId, quote.tenantId);\n const [addresses, notes, tags, adjustments, lines] = await Promise.all([\n findWithDecryption(\n em,\n SalesDocumentAddress,\n {\n documentId: quote.id,\n documentKind: \"quote\",\n },\n undefined,\n { tenantId: quote.tenantId, organizationId: quote.organizationId },\n ),\n findWithDecryption(\n em,\n SalesNote,\n { contextType: \"quote\", contextId: quote.id },\n undefined,\n { tenantId: quote.tenantId, organizationId: quote.organizationId },\n ),\n em.find(SalesDocumentTagAssignment, {\n documentId: quote.id,\n documentKind: \"quote\",\n }),\n em.find(SalesQuoteAdjustment, { quote: quote.id }),\n em.find(SalesQuoteLine, { quote: quote.id }),\n ]);\n // Delete the quote and its cascade atomically so a mid-cascade failure\n // cannot leave a partially-deleted quote committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n await em.nativeDelete(SalesDocumentAddress, {\n documentId: quote.id,\n documentKind: \"quote\",\n });\n await em.nativeDelete(SalesNote, {\n contextType: \"quote\",\n contextId: quote.id,\n });\n await em.nativeDelete(SalesDocumentTagAssignment, {\n documentId: quote.id,\n documentKind: \"quote\",\n });\n await em.nativeDelete(SalesQuoteAdjustment, { quote: quote.id });\n await em.nativeDelete(SalesQuoteLine, { quote: quote.id });\n em.remove(quote);\n },\n ],\n { transaction: true },\n );\n const dataEngine = ctx.container.resolve<DataEngine>(\"dataEngine\");\n await Promise.all([\n queueDeletionSideEffects(dataEngine, quote, E.sales.sales_quote),\n queueDeletionSideEffects(dataEngine, lines, E.sales.sales_quote_line),\n queueDeletionSideEffects(\n dataEngine,\n adjustments,\n E.sales.sales_quote_adjustment,\n ),\n queueDeletionSideEffects(\n dataEngine,\n addresses,\n E.sales.sales_document_address,\n ),\n queueDeletionSideEffects(dataEngine, notes, E.sales.sales_note),\n queueDeletionSideEffects(\n dataEngine,\n tags,\n E.sales.sales_document_tag_assignment,\n ),\n ]);\n return { quoteId: id };\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as QuoteGraphSnapshot | undefined;\n if (!before) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.quotes.delete\", \"Delete sales quote\"),\n resourceKind: \"sales.quote\",\n resourceId: before.quote.id,\n tenantId: before.quote.tenantId,\n organizationId: before.quote.organizationId,\n snapshotBefore: before,\n payload: {\n undo: {\n before,\n } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureQuoteScope(ctx, before.quote.organizationId, before.quote.tenantId);\n await restoreQuoteGraph(em, before);\n await em.flush();\n },\n};\n\nconst updateQuoteCommand: CommandHandler<\n DocumentUpdateInput,\n { quote: SalesQuote }\n> = {\n id: \"sales.quotes.update\",\n async prepare(input, ctx) {\n const parsed = documentUpdateSchema.parse(input ?? {});\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadQuoteSnapshot(em, parsed.id);\n if (snapshot) {\n ensureQuoteScope(\n ctx,\n snapshot.quote.organizationId,\n snapshot.quote.tenantId,\n );\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const parsed = documentUpdateSchema.parse(rawInput ?? {});\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const quote = await em.findOne(SalesQuote, {\n id: parsed.id,\n deletedAt: null,\n });\n if (!quote)\n throw new CrudHttpError(404, { error: \"Sales quote not found\" });\n ensureQuoteScope(ctx, quote.organizationId, quote.tenantId);\n const shouldInvalidateSentToken = (quote.status ?? null) === \"sent\";\n if (shouldInvalidateSentToken) {\n quote.acceptanceToken = null;\n quote.sentAt = null;\n }\n const shouldRecalculateTotals =\n parsed.shippingMethodId !== undefined ||\n parsed.shippingMethodSnapshot !== undefined ||\n parsed.shippingMethodCode !== undefined ||\n parsed.paymentMethodId !== undefined ||\n parsed.paymentMethodSnapshot !== undefined ||\n parsed.paymentMethodCode !== undefined ||\n parsed.currencyCode !== undefined;\n // Apply the scalar update, optional sent-token reset, and totals recalc\n // atomically. applyDocumentUpdate/replace*/setRecordCustomFields flush\n // mid-build, so without a transaction a later failure would leave a\n // half-updated quote committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n await applyDocumentUpdate({\n kind: \"quote\",\n entity: quote,\n input: parsed,\n em,\n });\n if (shouldInvalidateSentToken) {\n quote.status = \"draft\";\n quote.statusEntryId = await resolveStatusEntryIdByValue(em, {\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n value: \"draft\",\n });\n }\n if (shouldRecalculateTotals) {\n const [existingLines, adjustments] = await Promise.all([\n em.find(\n SalesQuoteLine,\n { quote },\n { orderBy: { lineNumber: \"asc\" } },\n ),\n em.find(\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const lineSnapshots = existingLines.map(mapQuoteLineEntityToSnapshot);\n const calcLines = lineSnapshots.map((line, index) =>\n createLineSnapshotFromInput(\n {\n ...line,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n lineNumber: line.lineNumber ?? index + 1,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n },\n line.lineNumber ?? index + 1,\n ),\n );\n const adjustmentDrafts = adjustments.map(mapQuoteAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\n \"salesCalculationService\",\n );\n const calculationContext = buildCalculationContext({\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n currencyCode: quote.currencyCode,\n shippingSnapshot: quote.shippingMethodSnapshot,\n paymentSnapshot: quote.paymentMethodSnapshot,\n shippingMethodId: quote.shippingMethodId ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n });\n const calculation =\n await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n });\n const adjustmentInputs = adjustmentDrafts.map((adj, index) => ({\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n scope: adj.scope ?? \"order\",\n kind: adj.kind ?? \"custom\",\n code: adj.code ?? undefined,\n label: adj.label ?? undefined,\n calculatorKey: adj.calculatorKey ?? undefined,\n promotionId: adj.promotionId ?? undefined,\n rate: adj.rate ?? undefined,\n amountNet: adj.amountNet ?? undefined,\n amountGross: adj.amountGross ?? undefined,\n currencyCode: adj.currencyCode ?? quote.currencyCode,\n metadata: adj.metadata ?? undefined,\n position: adj.position ?? index,\n }));\n await replaceQuoteAdjustments(\n em,\n quote,\n calculation,\n adjustmentInputs,\n );\n applyQuoteTotals(quote, calculation.totals, calculation.lines.length);\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n await emitTotalsCalculated(eventBus, {\n documentKind: \"quote\",\n documentId: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n customerId: quote.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n }\n quote.updatedAt = new Date();\n },\n ],\n { transaction: true },\n );\n const resourceKind =\n deriveResourceFromCommandId(updateQuoteCommand.id) ?? \"sales.quote\";\n await invalidateCrudCache(\n ctx.container,\n resourceKind,\n {\n id: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"updated\",\n );\n return { quote };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadQuoteSnapshot(em, result.quote.id);\n },\n buildLog: async ({ input, snapshots, result }) => {\n const parsed = documentUpdateSchema.parse(input ?? {});\n const before = snapshots.before as QuoteGraphSnapshot | undefined;\n const after = snapshots.after as QuoteGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n const changes = before\n ? buildChanges(\n before.quote as unknown as Record<string, unknown>,\n after.quote as unknown as Record<string, unknown>,\n buildDocumentUpdateChangeKeys(\"quote\", parsed),\n )\n : {};\n if (parsed.tags !== undefined) {\n const tagChange = buildTagChange(before?.tags, after.tags);\n if (tagChange) changes.tags = tagChange;\n }\n return {\n actionLabel: translate(\"sales.audit.quotes.update\", \"Update sales quote\"),\n resourceKind: \"sales.quote\",\n resourceId: result.quote.id,\n tenantId: after.quote.tenantId,\n organizationId: after.quote.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n changes: Object.keys(changes).length ? changes : null,\n payload: {\n undo: {\n before,\n after,\n } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureQuoteScope(ctx, before.quote.organizationId, before.quote.tenantId);\n await restoreQuoteGraph(em, before);\n await em.flush();\n },\n};\n\nconst updateOrderCommand: CommandHandler<\n DocumentUpdateInput,\n { order: SalesOrder }\n> = {\n id: \"sales.orders.update\",\n async prepare(input, ctx) {\n const parsed = documentUpdateSchema.parse(input ?? {});\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadOrderSnapshot(em, parsed.id);\n if (snapshot) {\n ensureOrderScope(\n ctx,\n snapshot.order.organizationId,\n snapshot.order.tenantId,\n );\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const parsed = documentUpdateSchema.parse(rawInput ?? {});\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const order = await em.findOne(SalesOrder, {\n id: parsed.id,\n deletedAt: null,\n });\n if (!order)\n throw new CrudHttpError(404, { error: \"Sales order not found\" });\n ensureOrderScope(ctx, order.organizationId, order.tenantId);\n const previousStatus = normalizeStatusValue(order.status);\n let statusChangeNote: SalesNote | null = null;\n const shouldRecalculateTotals =\n parsed.shippingMethodId !== undefined ||\n parsed.shippingMethodSnapshot !== undefined ||\n parsed.shippingMethodCode !== undefined ||\n parsed.paymentMethodId !== undefined ||\n parsed.paymentMethodSnapshot !== undefined ||\n parsed.paymentMethodCode !== undefined ||\n parsed.currencyCode !== undefined;\n // Apply the scalar update, totals recalc, and status-change note atomically.\n // applyDocumentUpdate/replace*/setRecordCustomFields flush mid-build, so\n // without a transaction a later failure would leave a half-updated order\n // committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n await applyDocumentUpdate({\n kind: \"order\",\n entity: order,\n input: parsed,\n em,\n });\n if (shouldRecalculateTotals) {\n const [existingLines, adjustments] = await Promise.all([\n em.find(\n SalesOrderLine,\n { order },\n { orderBy: { lineNumber: \"asc\" } },\n ),\n em.find(\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const lineSnapshots = existingLines.map(mapOrderLineEntityToSnapshot);\n const calcLines = lineSnapshots.map((line, index) =>\n createLineSnapshotFromInput(\n {\n ...line,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n lineNumber: line.lineNumber ?? index + 1,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n },\n line.lineNumber ?? index + 1,\n ),\n );\n const adjustmentDrafts = adjustments.map(mapOrderAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\n \"salesCalculationService\",\n );\n const calculationContext = buildCalculationContext({\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n currencyCode: order.currencyCode,\n shippingSnapshot: order.shippingMethodSnapshot,\n paymentSnapshot: order.paymentMethodSnapshot,\n shippingMethodId: order.shippingMethodId ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n });\n const calculation =\n await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n });\n const adjustmentInputs = adjustmentDrafts.map((adj, index) => ({\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n scope: adj.scope ?? \"order\",\n kind: adj.kind ?? \"custom\",\n code: adj.code ?? undefined,\n label: adj.label ?? undefined,\n calculatorKey: adj.calculatorKey ?? undefined,\n promotionId: adj.promotionId ?? undefined,\n rate: adj.rate ?? undefined,\n amountNet: adj.amountNet ?? undefined,\n amountGross: adj.amountGross ?? undefined,\n currencyCode: adj.currencyCode ?? order.currencyCode,\n metadata: adj.metadata ?? undefined,\n position: adj.position ?? index,\n }));\n await replaceOrderAdjustments(\n em,\n order,\n calculation,\n adjustmentInputs,\n );\n applyOrderTotals(order, calculation.totals, calculation.lines.length);\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n await emitTotalsCalculated(eventBus, {\n documentKind: \"order\",\n documentId: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n customerId: order.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n }\n statusChangeNote = await appendOrderStatusChangeNote({\n em,\n order,\n previousStatus,\n auth: ctx.auth ?? null,\n });\n order.updatedAt = new Date();\n },\n ],\n { transaction: true },\n );\n if (statusChangeNote) {\n const dataEngine = ctx.container.resolve(\"dataEngine\");\n await emitCrudSideEffects({\n dataEngine,\n action: \"created\",\n entity: statusChangeNote,\n identifiers: {\n id: statusChangeNote.id,\n organizationId: statusChangeNote.organizationId,\n tenantId: statusChangeNote.tenantId,\n },\n indexer: { entityType: E.sales.sales_note },\n });\n }\n const resourceKind =\n deriveResourceFromCommandId(updateOrderCommand.id) ?? \"sales.order\";\n await invalidateCrudCache(\n ctx.container,\n resourceKind,\n {\n id: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"updated\",\n );\n return { order };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadOrderSnapshot(em, result.order.id);\n },\n buildLog: async ({ input, snapshots, result }) => {\n const parsed = documentUpdateSchema.parse(input ?? {});\n const before = snapshots.before as OrderGraphSnapshot | undefined;\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n const changes = before\n ? buildChanges(\n before.order as unknown as Record<string, unknown>,\n after.order as unknown as Record<string, unknown>,\n buildDocumentUpdateChangeKeys(\"order\", parsed),\n )\n : {};\n if (parsed.tags !== undefined) {\n const tagChange = buildTagChange(before?.tags, after.tags);\n if (tagChange) changes.tags = tagChange;\n }\n return {\n actionLabel: translate(\"sales.audit.orders.update\", \"Update sales order\"),\n resourceKind: \"sales.order\",\n resourceId: result.order.id,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n changes: Object.keys(changes).length ? changes : null,\n payload: {\n undo: {\n before,\n after,\n } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureOrderScope(ctx, before.order.organizationId, before.order.tenantId);\n await restoreOrderGraph(em, before);\n await em.flush();\n },\n};\n\nconst createOrderCommand: CommandHandler<\n OrderCreateInput,\n { orderId: string }\n> = {\n id: \"sales.orders.create\",\n async execute(rawInput, ctx) {\n const generator = ctx.container.resolve(\n \"salesDocumentNumberGenerator\",\n ) as SalesDocumentNumberGenerator;\n const initial = orderCreateSchema.parse(rawInput ?? {});\n const orderNumber =\n typeof initial.orderNumber === \"string\" &&\n initial.orderNumber.trim().length\n ? initial.orderNumber.trim()\n : (\n await generator.generate({\n kind: \"order\",\n organizationId: initial.organizationId,\n tenantId: initial.tenantId,\n })\n ).number;\n const parsed = orderCreateSchema.parse({ ...initial, orderNumber });\n const ensuredOrderNumber = parsed.orderNumber ?? orderNumber;\n if (!ensuredOrderNumber) {\n throw new CrudHttpError(400, { error: \"Order number is required.\" });\n }\n ensureOrderScope(ctx, parsed.organizationId, parsed.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const [status, fulfillmentStatus, paymentStatus] = await Promise.all([\n resolveDictionaryEntryValue(em, parsed.statusEntryId ?? null),\n resolveDictionaryEntryValue(em, parsed.fulfillmentStatusEntryId ?? null),\n resolveDictionaryEntryValue(em, parsed.paymentStatusEntryId ?? null),\n ]);\n const {\n customerSnapshot: resolvedCustomerSnapshot,\n billingAddressSnapshot: resolvedBillingSnapshot,\n shippingAddressSnapshot: resolvedShippingSnapshot,\n shippingMethod,\n deliveryWindow,\n paymentMethod,\n } = await resolveDocumentReferences(em, parsed);\n\n const orderId = randomUUID()\n const order = em.create(SalesOrder, {\n id: orderId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n orderNumber: ensuredOrderNumber,\n externalReference: parsed.externalReference ?? null,\n customerReference: parsed.customerReference ?? null,\n statusEntryId: parsed.statusEntryId ?? null,\n status,\n fulfillmentStatusEntryId: parsed.fulfillmentStatusEntryId ?? null,\n fulfillmentStatus,\n paymentStatusEntryId: parsed.paymentStatusEntryId ?? null,\n paymentStatus,\n customerEntityId: parsed.customerEntityId ?? null,\n customerContactId: parsed.customerContactId ?? null,\n customerSnapshot: resolvedCustomerSnapshot\n ? cloneJson(resolvedCustomerSnapshot)\n : null,\n billingAddressId: parsed.billingAddressId ?? null,\n shippingAddressId: parsed.shippingAddressId ?? null,\n billingAddressSnapshot: resolvedBillingSnapshot\n ? cloneJson(resolvedBillingSnapshot)\n : null,\n shippingAddressSnapshot: resolvedShippingSnapshot\n ? cloneJson(resolvedShippingSnapshot)\n : null,\n currencyCode: parsed.currencyCode,\n exchangeRate:\n typeof parsed.exchangeRate === \"number\"\n ? toNumericString(parsed.exchangeRate)\n : null,\n taxStrategyKey: parsed.taxStrategyKey ?? null,\n discountStrategyKey: parsed.discountStrategyKey ?? null,\n taxInfo: parsed.taxInfo ? cloneJson(parsed.taxInfo) : null,\n shippingMethodId: parsed.shippingMethodId ?? null,\n shippingMethod: shippingMethod ?? null,\n shippingMethodCode:\n parsed.shippingMethodCode ?? shippingMethod?.code ?? null,\n deliveryWindowId: parsed.deliveryWindowId ?? null,\n deliveryWindow: deliveryWindow ?? null,\n deliveryWindowCode:\n parsed.deliveryWindowCode ?? deliveryWindow?.code ?? null,\n paymentMethodId: parsed.paymentMethodId ?? null,\n paymentMethod: paymentMethod ?? null,\n paymentMethodCode:\n parsed.paymentMethodCode ?? paymentMethod?.code ?? null,\n channelId: parsed.channelId ?? null,\n placedAt: parsed.placedAt ?? null,\n expectedDeliveryAt: parsed.expectedDeliveryAt ?? null,\n dueAt: parsed.dueAt ?? null,\n comments: parsed.comments ?? null,\n internalNotes: parsed.internalNotes ?? null,\n shippingMethodSnapshot: parsed.shippingMethodSnapshot\n ? cloneJson(parsed.shippingMethodSnapshot)\n : shippingMethod\n ? {\n id: shippingMethod.id,\n code: shippingMethod.code,\n name: shippingMethod.name,\n description: shippingMethod.description ?? null,\n carrierCode: shippingMethod.carrierCode ?? null,\n providerKey: shippingMethod.providerKey ?? null,\n serviceLevel: shippingMethod.serviceLevel ?? null,\n estimatedTransitDays: shippingMethod.estimatedTransitDays ?? null,\n baseRateNet: shippingMethod.baseRateNet,\n baseRateGross: shippingMethod.baseRateGross,\n currencyCode: shippingMethod.currencyCode ?? null,\n metadata: shippingMethod.metadata\n ? cloneJson(shippingMethod.metadata)\n : null,\n providerSettings:\n shippingMethod.metadata &&\n typeof shippingMethod.metadata === \"object\"\n ? cloneJson(\n (shippingMethod.metadata as Record<string, unknown>)\n .providerSettings ?? null,\n )\n : null,\n }\n : null,\n deliveryWindowSnapshot: parsed.deliveryWindowSnapshot\n ? cloneJson(parsed.deliveryWindowSnapshot)\n : deliveryWindow\n ? {\n id: deliveryWindow.id,\n code: deliveryWindow.code,\n name: deliveryWindow.name,\n description: deliveryWindow.description ?? null,\n leadTimeDays: deliveryWindow.leadTimeDays ?? null,\n cutoffTime: deliveryWindow.cutoffTime ?? null,\n timezone: deliveryWindow.timezone ?? null,\n }\n : null,\n paymentMethodSnapshot: parsed.paymentMethodSnapshot\n ? cloneJson(parsed.paymentMethodSnapshot)\n : paymentMethod\n ? {\n id: paymentMethod.id,\n code: paymentMethod.code,\n name: paymentMethod.name,\n description: paymentMethod.description ?? null,\n providerKey: paymentMethod.providerKey ?? null,\n terms: paymentMethod.terms ?? null,\n metadata: paymentMethod.metadata\n ? cloneJson(paymentMethod.metadata)\n : null,\n providerSettings:\n paymentMethod.metadata &&\n typeof paymentMethod.metadata === \"object\"\n ? cloneJson(\n (paymentMethod.metadata as Record<string, unknown>)\n .providerSettings ?? null,\n )\n : null,\n }\n : null,\n metadata: parsed.metadata ? cloneJson(parsed.metadata) : null,\n customFieldSetId: parsed.customFieldSetId ?? null,\n subtotalNetAmount: \"0\",\n subtotalGrossAmount: \"0\",\n discountTotalAmount: \"0\",\n taxTotalAmount: \"0\",\n shippingNetAmount: \"0\",\n shippingGrossAmount: \"0\",\n surchargeTotalAmount: \"0\",\n grandTotalNetAmount: \"0\",\n grandTotalGrossAmount: \"0\",\n paidTotalAmount: \"0\",\n refundedTotalAmount: \"0\",\n outstandingAmount: \"0\",\n lineItemCount: 0,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n const lineInputs = (parsed.lines ?? []).map((line, index) =>\n orderLineCreateSchema.parse({\n ...line,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n orderId: order.id,\n lineNumber: line.lineNumber ?? index + 1,\n }),\n );\n const uomResolver = createUomResolver();\n const normalizedLineInputs = await Promise.all(\n lineInputs.map(async (line) => {\n const normalized = await normalizeLineUom({\n em,\n resolver: uomResolver,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n line,\n });\n return {\n ...line,\n quantity: normalized.quantity,\n quantityUnit: normalized.quantityUnit,\n normalizedQuantity: normalized.normalizedQuantity,\n normalizedUnit: normalized.normalizedUnit,\n uomSnapshot: normalized.uomSnapshot,\n };\n }),\n );\n const adjustmentInputs = parsed.adjustments\n ? parsed.adjustments.map((adj) =>\n orderAdjustmentCreateSchema.parse({\n ...adj,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n orderId: order.id,\n }),\n )\n : null;\n\n const lineSnapshots: SalesLineSnapshot[] = normalizedLineInputs.map(\n (line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const adjustmentDrafts: SalesAdjustmentDraft[] = adjustmentInputs\n ? adjustmentInputs.map((adj) => createAdjustmentDraftFromInput(adj))\n : [];\n\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n currencyCode: order.currencyCode,\n shippingSnapshot: order.shippingMethodSnapshot,\n paymentSnapshot: order.paymentMethodSnapshot,\n shippingMethodId: order.shippingMethodId ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: lineSnapshots,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n });\n\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n // Persist the order header, lines, adjustments, totals and tags atomically.\n // replace*/setRecordCustomFields flush mid-build, so without a transaction a\n // later failure (e.g. tag sync) would leave a half-built order committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n em.persist(order);\n await replaceOrderLines(em, order, calculation, normalizedLineInputs);\n await replaceOrderAdjustments(\n em,\n order,\n calculation,\n adjustmentInputs,\n );\n applyOrderTotals(order, calculation.totals, calculation.lines.length);\n await emitTotalsCalculated(eventBus, {\n documentKind: \"order\",\n documentId: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n customerId: order.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n await syncSalesDocumentTags(em, {\n documentId: order.id,\n kind: \"order\",\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n tagIds: parsed.tags,\n });\n },\n ],\n { transaction: true },\n );\n\n // Create notification for users with sales.orders.manage feature\n try {\n const notificationService = resolveNotificationService(ctx.container);\n const typeDef = notificationTypes.find(\n (type) => type.type === \"sales.order.created\",\n );\n if (typeDef) {\n const totalAmount =\n order.grandTotalGrossAmount && order.currencyCode\n ? `${order.grandTotalGrossAmount} ${order.currencyCode}`\n : \"\";\n const totalDisplay = totalAmount ? ` (${totalAmount})` : \"\";\n const notificationInput = buildFeatureNotificationFromType(typeDef, {\n requiredFeature: \"sales.orders.manage\",\n bodyVariables: {\n orderNumber: order.orderNumber,\n total: totalDisplay,\n totalAmount,\n },\n sourceEntityType: \"sales:order\",\n sourceEntityId: order.id,\n linkHref: `/backend/sales/orders/${order.id}`,\n });\n\n await notificationService.createForFeature(notificationInput, {\n tenantId: order.tenantId,\n organizationId: order.organizationId ?? null,\n });\n }\n } catch (err) {\n // Notification creation is non-critical, don't fail the command\n console.error(\n \"[sales.orders.create] Failed to create notification:\",\n err,\n );\n }\n\n // Emit CRUD side effects to trigger workflow event listeners\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"created\",\n entity: order,\n identifiers: {\n id: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n },\n events: orderCrudEvents,\n indexer: { entityType: E.sales.sales_order },\n });\n\n // Invalidate cache\n const resourceKind =\n deriveResourceFromCommandId(createOrderCommand.id) ?? \"sales.order\";\n await invalidateCrudCache(\n ctx.container,\n resourceKind,\n {\n id: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"created\",\n );\n\n return { orderId: order.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadOrderSnapshot(em, result.orderId);\n },\n buildLog: async ({ result, snapshots }) => {\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.orders.create\", \"Create sales order\"),\n resourceKind: \"sales.order\",\n resourceId: result.orderId,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n snapshotAfter: after,\n payload: {\n undo: {\n after,\n } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const after = payload?.after;\n if (!after) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const order = await em.findOne(SalesOrder, { id: after.order.id });\n if (!order) return;\n ensureOrderScope(ctx, order.organizationId, order.tenantId);\n await em.nativeDelete(SalesOrderAdjustment, { order: order.id });\n await em.nativeDelete(SalesOrderLine, { order: order.id });\n em.remove(order);\n await em.flush();\n },\n};\n\nconst deleteOrderCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { orderId: string }\n> = {\n id: \"sales.orders.delete\",\n async prepare(input, ctx) {\n const id = requireId(input, \"Order id is required\");\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadOrderSnapshot(em, id);\n if (snapshot) {\n ensureOrderScope(\n ctx,\n snapshot.order.organizationId,\n snapshot.order.tenantId,\n );\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(input, ctx) {\n const id = requireId(input, \"Order id is required\");\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const order = await em.findOne(SalesOrder, { id });\n if (!order)\n throw new CrudHttpError(404, { error: \"Sales order not found\" });\n ensureOrderScope(ctx, order.organizationId, order.tenantId);\n const shipments = await em.find(SalesShipment, { order: order.id });\n const shipmentIds = shipments.map((entry) => entry.id);\n const [\n shipmentItems,\n payments,\n paymentAllocations,\n addresses,\n notes,\n tags,\n adjustments,\n lines,\n ] = await Promise.all([\n shipmentIds.length\n ? em.find(SalesShipmentItem, { shipment: { $in: shipmentIds } })\n : Promise.resolve([]),\n em.find(SalesPayment, { order: order.id }),\n em.find(SalesPaymentAllocation, { order: order.id }),\n findWithDecryption(\n em,\n SalesDocumentAddress,\n {\n documentId: order.id,\n documentKind: \"order\",\n },\n undefined,\n { tenantId: order.tenantId, organizationId: order.organizationId },\n ),\n findWithDecryption(\n em,\n SalesNote,\n { contextType: \"order\", contextId: order.id },\n undefined,\n { tenantId: order.tenantId, organizationId: order.organizationId },\n ),\n em.find(SalesDocumentTagAssignment, {\n documentId: order.id,\n documentKind: \"order\",\n }),\n em.find(SalesOrderAdjustment, { order: order.id }),\n em.find(SalesOrderLine, { order: order.id }),\n ]);\n // Delete the order and its cascade atomically so a mid-cascade failure\n // cannot leave a partially-deleted order committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n if (shipmentIds.length) {\n await em.nativeDelete(SalesShipmentItem, {\n shipment: { $in: shipmentIds },\n });\n await em.nativeDelete(SalesShipment, { id: { $in: shipmentIds } });\n }\n await em.nativeDelete(SalesPaymentAllocation, { order: order.id });\n await em.nativeDelete(SalesPayment, { order: order.id });\n await em.nativeDelete(SalesDocumentAddress, {\n documentId: order.id,\n documentKind: \"order\",\n });\n await em.nativeDelete(SalesNote, {\n contextType: \"order\",\n contextId: order.id,\n });\n await em.nativeDelete(SalesDocumentTagAssignment, {\n documentId: order.id,\n documentKind: \"order\",\n });\n await em.nativeDelete(SalesOrderAdjustment, { order: order.id });\n await em.nativeDelete(SalesOrderLine, { order: order.id });\n em.remove(order);\n },\n ],\n { transaction: true },\n );\n const dataEngine = ctx.container.resolve<DataEngine>(\"dataEngine\");\n await Promise.all([\n queueDeletionSideEffects(dataEngine, order, E.sales.sales_order),\n queueDeletionSideEffects(dataEngine, lines, E.sales.sales_order_line),\n queueDeletionSideEffects(\n dataEngine,\n adjustments,\n E.sales.sales_order_adjustment,\n ),\n queueDeletionSideEffects(dataEngine, shipments, E.sales.sales_shipment),\n queueDeletionSideEffects(\n dataEngine,\n shipmentItems,\n E.sales.sales_shipment_item,\n ),\n queueDeletionSideEffects(dataEngine, payments, E.sales.sales_payment),\n queueDeletionSideEffects(\n dataEngine,\n paymentAllocations,\n E.sales.sales_payment_allocation,\n ),\n queueDeletionSideEffects(\n dataEngine,\n addresses,\n E.sales.sales_document_address,\n ),\n queueDeletionSideEffects(dataEngine, notes, E.sales.sales_note),\n queueDeletionSideEffects(\n dataEngine,\n tags,\n E.sales.sales_document_tag_assignment,\n ),\n ]);\n return { orderId: id };\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as OrderGraphSnapshot | undefined;\n if (!before) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.orders.delete\", \"Delete sales order\"),\n resourceKind: \"sales.order\",\n resourceId: before.order.id,\n tenantId: before.order.tenantId,\n organizationId: before.order.organizationId,\n snapshotBefore: before,\n payload: {\n undo: {\n before,\n } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureOrderScope(ctx, before.order.organizationId, before.order.tenantId);\n await restoreOrderGraph(em, before);\n await em.flush();\n },\n};\n\nconst quoteConvertToOrderSchema = z.object({\n quoteId: z.string().uuid(),\n orderId: z.string().uuid().optional(),\n orderNumber: z.string().trim().max(191).optional(),\n});\n\nconst convertQuoteToOrderCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { orderId: string }\n> = {\n id: \"sales.quotes.convert_to_order\",\n async prepare(input, ctx) {\n const parsed = quoteConvertToOrderSchema.safeParse(input ?? {});\n const quoteId = parsed.success\n ? parsed.data.quoteId\n : typeof (input as any)?.quoteId === \"string\"\n ? (input as any).quoteId\n : null;\n if (!quoteId) return {};\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadQuoteSnapshot(em, quoteId);\n if (snapshot)\n ensureQuoteScope(\n ctx,\n snapshot.quote.organizationId,\n snapshot.quote.tenantId,\n );\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const payload = quoteConvertToOrderSchema.parse(rawInput ?? {});\n // When the caller supplies an existing transactional EntityManager, reuse it\n // (and its row locks) so the quote status flip and the order materialization\n // commit or roll back as one atomic unit \u2014 no out-of-band compensating write.\n const callerEm = ctx.transactionalEm;\n const rootEm =\n callerEm ?? (ctx.container.resolve(\"em\") as EntityManager).fork();\n const transactionalEm = rootEm as EntityManager & {\n transactional?: <TResult>(\n callback: (trx: EntityManager) => Promise<TResult>,\n ) => Promise<TResult>;\n };\n const runConversion = async (em: EntityManager) => {\n const quote = await findOneWithDecryption(\n em,\n SalesQuote,\n {\n id: payload.quoteId,\n deletedAt: null,\n },\n { lockMode: LockMode.PESSIMISTIC_WRITE },\n );\n const { translate } = await resolveTranslations();\n if (!quote)\n throw new CrudHttpError(404, {\n error: translate(\n \"sales.documents.detail.error\",\n \"Document not found or inaccessible.\",\n ),\n });\n ensureQuoteScope(ctx, quote.organizationId, quote.tenantId);\n const snapshot = await loadQuoteSnapshot(em, payload.quoteId);\n if (!snapshot)\n throw new CrudHttpError(404, {\n error: translate(\n \"sales.documents.detail.error\",\n \"Document not found or inaccessible.\",\n ),\n });\n const orderId = payload.orderId ?? quote.id;\n const existingOrder = await findOneWithDecryption(em, SalesOrder, {\n id: orderId,\n deletedAt: null,\n }, undefined, { tenantId: quote.tenantId, organizationId: quote.organizationId });\n if (existingOrder) {\n throw new CrudHttpError(409, {\n error: translate(\n \"sales.documents.detail.convertExists\",\n \"Order already exists for this quote.\",\n ),\n });\n }\n\n const generator = ctx.container.resolve(\n \"salesDocumentNumberGenerator\",\n ) as SalesDocumentNumberGenerator;\n const generatedNumber = (\n await generator.generate({\n kind: \"order\",\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n })\n ).number;\n const orderNumber =\n typeof payload.orderNumber === \"string\" &&\n payload.orderNumber.trim().length\n ? payload.orderNumber.trim()\n : generatedNumber;\n\n const [quoteCustomFields, quoteLineCustomFields] = await Promise.all([\n loadCustomFieldValues({\n em,\n entityId: E.sales.sales_quote,\n recordIds: [snapshot.quote.id],\n tenantIdByRecord: { [snapshot.quote.id]: snapshot.quote.tenantId },\n organizationIdByRecord: {\n [snapshot.quote.id]: snapshot.quote.organizationId,\n },\n }),\n snapshot.lines.length\n ? loadCustomFieldValues({\n em,\n entityId: E.sales.sales_quote_line,\n recordIds: snapshot.lines.map((line) => line.id),\n tenantIdByRecord: Object.fromEntries(\n snapshot.lines.map((line) => [line.id, snapshot.quote.tenantId]),\n ),\n organizationIdByRecord: Object.fromEntries(\n snapshot.lines.map((line) => [\n line.id,\n snapshot.quote.organizationId,\n ]),\n ),\n })\n : Promise.resolve({}),\n ]);\n\n const order = em.create(SalesOrder, {\n id: orderId,\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n orderNumber,\n statusEntryId: snapshot.quote.statusEntryId ?? null,\n status: snapshot.quote.status ?? null,\n fulfillmentStatusEntryId: null,\n fulfillmentStatus: null,\n paymentStatusEntryId: null,\n paymentStatus: null,\n customerEntityId: snapshot.quote.customerEntityId ?? null,\n customerContactId: snapshot.quote.customerContactId ?? null,\n customerSnapshot: snapshot.quote.customerSnapshot\n ? cloneJson(snapshot.quote.customerSnapshot)\n : null,\n billingAddressId: snapshot.quote.billingAddressId ?? null,\n shippingAddressId: snapshot.quote.shippingAddressId ?? null,\n billingAddressSnapshot: snapshot.quote.billingAddressSnapshot\n ? cloneJson(snapshot.quote.billingAddressSnapshot)\n : null,\n shippingAddressSnapshot: snapshot.quote.shippingAddressSnapshot\n ? cloneJson(snapshot.quote.shippingAddressSnapshot)\n : null,\n currencyCode: snapshot.quote.currencyCode,\n exchangeRate: null,\n taxStrategyKey: null,\n discountStrategyKey: null,\n taxInfo: snapshot.quote.taxInfo\n ? cloneJson(snapshot.quote.taxInfo)\n : null,\n shippingMethodId: snapshot.quote.shippingMethodId ?? null,\n shippingMethodCode: snapshot.quote.shippingMethodCode ?? null,\n deliveryWindowId: snapshot.quote.deliveryWindowId ?? null,\n deliveryWindowCode: snapshot.quote.deliveryWindowCode ?? null,\n paymentMethodId: snapshot.quote.paymentMethodId ?? null,\n paymentMethodCode: snapshot.quote.paymentMethodCode ?? null,\n channelId: snapshot.quote.channelId ?? null,\n placedAt: snapshot.quote.validFrom\n ? new Date(snapshot.quote.validFrom)\n : quote.createdAt,\n expectedDeliveryAt: snapshot.quote.validUntil\n ? new Date(snapshot.quote.validUntil)\n : null,\n dueAt: null,\n comments: snapshot.quote.comments ?? null,\n internalNotes: null,\n shippingMethodSnapshot: snapshot.quote.shippingMethodSnapshot\n ? cloneJson(snapshot.quote.shippingMethodSnapshot)\n : null,\n deliveryWindowSnapshot: snapshot.quote.deliveryWindowSnapshot\n ? cloneJson(snapshot.quote.deliveryWindowSnapshot)\n : null,\n paymentMethodSnapshot: snapshot.quote.paymentMethodSnapshot\n ? cloneJson(snapshot.quote.paymentMethodSnapshot)\n : null,\n metadata: snapshot.quote.metadata\n ? cloneJson(snapshot.quote.metadata)\n : null,\n customFieldSetId: snapshot.quote.customFieldSetId ?? null,\n subtotalNetAmount: snapshot.quote.subtotalNetAmount,\n subtotalGrossAmount: snapshot.quote.subtotalGrossAmount,\n discountTotalAmount: snapshot.quote.discountTotalAmount,\n taxTotalAmount: snapshot.quote.taxTotalAmount,\n shippingNetAmount: \"0\",\n shippingGrossAmount: \"0\",\n surchargeTotalAmount: \"0\",\n grandTotalNetAmount: snapshot.quote.grandTotalNetAmount,\n grandTotalGrossAmount: snapshot.quote.grandTotalGrossAmount,\n paidTotalAmount: \"0\",\n refundedTotalAmount: \"0\",\n outstandingAmount: snapshot.quote.grandTotalGrossAmount,\n totalsSnapshot: snapshot.quote.totalsSnapshot\n ? cloneJson(snapshot.quote.totalsSnapshot)\n : null,\n lineItemCount: snapshot.quote.lineItemCount,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(order);\n\n const orderLineMap = new Map<string, SalesOrderLine>();\n snapshot.lines.forEach((line, index) => {\n const orderLine = em.create(SalesOrderLine, {\n id: line.id,\n order,\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n lineNumber: line.lineNumber ?? index + 1,\n kind: line.kind as SalesLineKind,\n statusEntryId: (line as any).statusEntryId ?? null,\n status: (line as any).status ?? null,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: line.normalizedQuantity ?? line.quantity,\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n reservedQuantity: \"0\",\n fulfilledQuantity: \"0\",\n invoicedQuantity: \"0\",\n returnedQuantity: \"0\",\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n discountAmount: line.discountAmount,\n discountPercent: line.discountPercent,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n totalNetAmount: line.totalNetAmount,\n totalGrossAmount: line.totalGrossAmount,\n configuration: line.configuration\n ? cloneJson(line.configuration)\n : null,\n promotionCode: line.promotionCode ?? null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(orderLine);\n orderLineMap.set(orderLine.id, orderLine);\n });\n\n snapshot.adjustments.forEach((adj, index) => {\n const orderLineId = adj.quoteLineId ?? null;\n const orderLine = orderLineId\n ? (orderLineMap.get(orderLineId) ?? null)\n : null;\n const entity = em.create(SalesOrderAdjustment, {\n id: adj.id,\n order,\n orderLine: orderLine ?? null,\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n scope: adj.scope,\n kind: adj.kind as SalesAdjustmentKind,\n code: adj.code ?? null,\n label: adj.label ?? null,\n calculatorKey: adj.calculatorKey ?? null,\n promotionId: adj.promotionId ?? null,\n rate: adj.rate,\n amountNet: adj.amountNet,\n amountGross: adj.amountGross,\n currencyCode: adj.currencyCode ?? null,\n metadata: adj.metadata ? cloneJson(adj.metadata) : null,\n position: adj.position ?? index,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(entity);\n });\n\n const [addresses, notes, tags] = await Promise.all([\n em.find(SalesDocumentAddress, {\n documentId: snapshot.quote.id,\n documentKind: \"quote\",\n }),\n em.find(SalesNote, {\n contextType: \"quote\",\n contextId: snapshot.quote.id,\n }),\n em.find(SalesDocumentTagAssignment, {\n documentId: snapshot.quote.id,\n documentKind: \"quote\",\n }),\n ]);\n addresses.forEach((entry) => {\n entry.documentKind = \"order\";\n entry.documentId = order.id;\n entry.order = order;\n entry.quote = null;\n entry.updatedAt = new Date();\n });\n notes.forEach((note) => {\n note.contextType = \"order\";\n note.contextId = order.id;\n note.order = order;\n note.quote = null;\n note.updatedAt = new Date();\n });\n tags.forEach((assignment) => {\n assignment.documentKind = \"order\";\n assignment.documentId = order.id;\n assignment.order = order;\n assignment.quote = null;\n assignment.updatedAt = new Date();\n });\n\n const documentCustomValues = quoteCustomFields[snapshot.quote.id];\n if (documentCustomValues && Object.keys(documentCustomValues).length) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order,\n recordId: order.id,\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n values: documentCustomValues,\n });\n }\n const lineCustomEntries = quoteLineCustomFields as Record<\n string,\n Record<string, unknown>\n >;\n if (lineCustomEntries && Object.keys(lineCustomEntries).length) {\n for (const [lineId, values] of Object.entries(lineCustomEntries)) {\n if (!values || !Object.keys(values).length) continue;\n if (!orderLineMap.has(lineId)) continue;\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order_line,\n recordId: lineId,\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n values,\n });\n }\n }\n\n await em.nativeDelete(SalesQuoteAdjustment, { quote: snapshot.quote.id });\n await em.nativeDelete(SalesQuoteLine, { quote: snapshot.quote.id });\n em.remove(quote);\n await em.flush();\n\n return { orderId: order.id };\n };\n if (callerEm) {\n // Already inside the caller's transaction \u2014 run directly so the whole flow\n // stays a single transaction (no nested savepoint).\n return runConversion(callerEm);\n }\n return typeof transactionalEm.transactional === \"function\"\n ? transactionalEm.transactional((trx) => runConversion(trx))\n : runConversion(rootEm);\n },\n captureAfter: async (_input, result, ctx) => {\n // Prefer the caller's transactional EM so the just-created (still\n // uncommitted) order is visible when building the audit \"after\" snapshot.\n const em =\n ctx.transactionalEm ??\n (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadOrderSnapshot(em, result.orderId);\n },\n buildLog: async ({ snapshots, result }) => {\n const before = snapshots.before as QuoteGraphSnapshot | undefined;\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!before) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.quotes.convert\",\n \"Convert quote to order\",\n ),\n resourceKind: \"sales.order\",\n resourceId: result.orderId,\n tenantId: before.quote.tenantId,\n organizationId: before.quote.organizationId,\n snapshotBefore: before,\n snapshotAfter: after ?? null,\n payload: {\n undo: {\n quote: before,\n order: after ?? null,\n } satisfies QuoteConvertUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteConvertUndoPayload>(logEntry);\n const quoteSnapshot = payload?.quote;\n const orderSnapshot = payload?.order;\n if (!quoteSnapshot) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureQuoteScope(\n ctx,\n quoteSnapshot.quote.organizationId,\n quoteSnapshot.quote.tenantId,\n );\n if (orderSnapshot) {\n const orderId = orderSnapshot.order.id;\n const orderLineIds = orderSnapshot.lines.map((line) => line.id);\n const existingOrder = await findOneWithDecryption(em, SalesOrder, { id: orderId }, undefined, { tenantId: quoteSnapshot.quote.tenantId, organizationId: quoteSnapshot.quote.organizationId });\n if (existingOrder) {\n const shipments = await em.find(SalesShipment, { order: orderId });\n const shipmentIds = shipments.map((entry) => entry.id);\n if (shipmentIds.length) {\n await em.nativeDelete(SalesShipmentItem, {\n shipment: { $in: shipmentIds },\n });\n await em.nativeDelete(SalesShipment, { id: { $in: shipmentIds } });\n }\n await em.nativeDelete(SalesPaymentAllocation, { order: orderId });\n await em.nativeDelete(SalesPayment, { order: orderId });\n await em.nativeDelete(SalesDocumentAddress, {\n documentId: orderId,\n documentKind: \"order\",\n });\n await em.nativeDelete(SalesDocumentTagAssignment, {\n documentId: orderId,\n documentKind: \"order\",\n });\n await em.nativeDelete(SalesOrderAdjustment, { order: orderId });\n await em.nativeDelete(SalesOrderLine, { order: orderId });\n em.remove(existingOrder);\n }\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_order,\n recordId: orderId,\n });\n if (orderLineIds.length) {\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_order_line,\n recordId: { $in: orderLineIds } as any,\n });\n }\n }\n const noteIds = quoteSnapshot.notes.map((note) => note.id);\n if (noteIds.length) {\n await em.nativeDelete(SalesNote, { id: { $in: noteIds } });\n }\n await restoreQuoteGraph(em, quoteSnapshot);\n await em.flush();\n },\n};\n\nconst orderLineUpsertSchema = orderLineCreateSchema.extend({\n id: z.string().uuid().optional(),\n});\n\nconst orderLineDeleteSchema = z.object({\n id: z.string().uuid(),\n orderId: z.string().uuid(),\n});\n\nconst quoteLineUpsertSchema = quoteLineCreateSchema.extend({\n id: z.string().uuid().optional(),\n});\n\nconst quoteLineDeleteSchema = z.object({\n id: z.string().uuid(),\n quoteId: z.string().uuid(),\n});\n\nconst orderAdjustmentUpsertSchema = orderAdjustmentCreateSchema\n .extend({\n id: z.string().uuid().optional(),\n })\n .superRefine(enforceAdjustmentSign);\n\nconst orderAdjustmentDeleteSchema = z.object({\n id: z.string().uuid(),\n orderId: z.string().uuid(),\n});\n\nconst quoteAdjustmentUpsertSchema = quoteAdjustmentCreateSchema\n .extend({\n id: z.string().uuid().optional(),\n })\n .superRefine(enforceAdjustmentSign);\n\nconst quoteAdjustmentDeleteSchema = z.object({\n id: z.string().uuid(),\n quoteId: z.string().uuid(),\n});\n\nconst orderLineUpsertCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { orderId: string; lineId: string }\n> = {\n id: \"sales.orders.lines.upsert\",\n async prepare(input, ctx) {\n const raw = (input?.body as Record<string, unknown> | undefined) ?? {};\n const orderId = typeof raw.orderId === \"string\" ? raw.orderId : null;\n if (!orderId) return {};\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadOrderSnapshot(em, orderId);\n if (snapshot)\n ensureOrderScope(\n ctx,\n snapshot.order.organizationId,\n snapshot.order.tenantId,\n );\n return snapshot ? { before: snapshot } : {};\n },\n async execute(input, ctx) {\n const rawBody = (input?.body as Record<string, unknown> | undefined) ?? {};\n const parsed = orderLineUpsertSchema.parse(rawBody);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const order = await em.findOne(SalesOrder, {\n id: parsed.orderId,\n deletedAt: null,\n });\n if (!order)\n throw new CrudHttpError(404, { error: \"Sales order not found\" });\n ensureOrderScope(ctx, order.organizationId, order.tenantId);\n\n const [existingLines, adjustments] = await Promise.all([\n em.find(SalesOrderLine, { order }, { orderBy: { lineNumber: \"asc\" } }),\n em.find(\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const lineSnapshots = existingLines.map(mapOrderLineEntityToSnapshot);\n const existingSnapshot = parsed.id\n ? (lineSnapshots.find((line) => line.id === parsed.id) ?? null)\n : null;\n const priceMode =\n parsed.priceMode === \"gross\"\n ? \"gross\"\n : parsed.priceMode === \"net\"\n ? \"net\"\n : null;\n let unitPriceNet =\n parsed.unitPriceNet ?? existingSnapshot?.unitPriceNet ?? null;\n let unitPriceGross =\n parsed.unitPriceGross ?? existingSnapshot?.unitPriceGross ?? null;\n let taxRate = parsed.taxRate ?? existingSnapshot?.taxRate ?? null;\n if (priceMode && (unitPriceNet === null || unitPriceGross === null)) {\n let taxService: TaxCalculationService | null = null;\n try {\n taxService = ctx.container.resolve(\n \"taxCalculationService\",\n ) as TaxCalculationService;\n } catch {\n taxService = null;\n }\n if (taxService) {\n const taxResult = await taxService.calculateUnitAmounts({\n amount:\n priceMode === \"gross\"\n ? (unitPriceGross ?? unitPriceNet ?? 0)\n : (unitPriceNet ?? unitPriceGross ?? 0),\n mode: priceMode,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n taxRateId: parsed.taxRateId ?? undefined,\n taxRate: taxRate ?? undefined,\n });\n unitPriceNet = unitPriceNet ?? taxResult.netAmount;\n unitPriceGross = unitPriceGross ?? taxResult.grossAmount;\n taxRate = taxResult.taxRate ?? taxRate;\n }\n }\n\n const metadata =\n typeof parsed.metadata === \"object\" && parsed.metadata\n ? { ...parsed.metadata }\n : existingSnapshot?.metadata\n ? cloneJson(existingSnapshot.metadata)\n : {};\n if (parsed.priceId) metadata.priceId = parsed.priceId;\n if (priceMode) metadata.priceMode = priceMode;\n\n const statusEntryId =\n parsed.statusEntryId ?? (existingSnapshot as any)?.statusEntryId ?? null;\n const lineId = parsed.id ?? existingSnapshot?.id ?? randomUUID();\n const lineUomInput = {\n productId: parsed.productId ?? existingSnapshot?.productId ?? null,\n productVariantId:\n parsed.productVariantId ?? existingSnapshot?.productVariantId ?? null,\n quantity: parsed.quantity ?? existingSnapshot?.quantity ?? 0,\n quantityUnit: parsed.quantityUnit ?? existingSnapshot?.quantityUnit ?? null,\n normalizedQuantity: existingSnapshot?.normalizedQuantity ?? null,\n normalizedUnit: existingSnapshot?.normalizedUnit ?? null,\n uomSnapshot: existingSnapshot?.uomSnapshot ?? null,\n };\n const uomResolver = createUomResolver();\n let normalizedUom = await normalizeLineUom({\n em,\n resolver: uomResolver,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n line: {\n ...lineUomInput,\n unitPriceNet: unitPriceNet ?? 0,\n unitPriceGross: unitPriceGross ?? unitPriceNet ?? 0,\n },\n });\n const convertedPrices = convertLineUnitPricesOnUnitChange({\n existingSnapshot,\n nextQuantityUnit: normalizedUom.quantityUnit,\n nextUomSnapshot: normalizedUom.uomSnapshot,\n unitPriceNet,\n unitPriceGross,\n });\n if (convertedPrices.didConvert) {\n unitPriceNet = convertedPrices.unitPriceNet;\n unitPriceGross = convertedPrices.unitPriceGross;\n normalizedUom = await normalizeLineUom({\n em,\n resolver: uomResolver,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n line: {\n ...lineUomInput,\n unitPriceNet: unitPriceNet ?? 0,\n unitPriceGross: unitPriceGross ?? unitPriceNet ?? 0,\n },\n });\n }\n const updatedSnapshot: SalesLineSnapshot & {\n statusEntryId?: string | null;\n catalogSnapshot?: Record<string, unknown> | null;\n promotionSnapshot?: Record<string, unknown> | null;\n } = {\n id: lineId,\n lineNumber:\n parsed.lineNumber ??\n existingSnapshot?.lineNumber ??\n lineSnapshots.length + 1,\n kind: parsed.kind ?? existingSnapshot?.kind ?? \"product\",\n productId: parsed.productId ?? existingSnapshot?.productId ?? null,\n productVariantId:\n parsed.productVariantId ?? existingSnapshot?.productVariantId ?? null,\n name: parsed.name ?? existingSnapshot?.name ?? null,\n description: parsed.description ?? existingSnapshot?.description ?? null,\n comment: parsed.comment ?? existingSnapshot?.comment ?? null,\n quantity: normalizedUom.quantity,\n quantityUnit: normalizedUom.quantityUnit,\n normalizedQuantity: normalizedUom.normalizedQuantity,\n normalizedUnit: normalizedUom.normalizedUnit,\n uomSnapshot: normalizedUom.uomSnapshot\n ? cloneJson(normalizedUom.uomSnapshot)\n : null,\n currencyCode:\n parsed.currencyCode ??\n existingSnapshot?.currencyCode ??\n order.currencyCode,\n unitPriceNet: unitPriceNet ?? 0,\n unitPriceGross: unitPriceGross ?? unitPriceNet ?? 0,\n discountAmount:\n parsed.discountAmount ?? existingSnapshot?.discountAmount ?? 0,\n discountPercent:\n parsed.discountPercent ?? existingSnapshot?.discountPercent ?? 0,\n taxRate: taxRate ?? 0,\n taxAmount: parsed.taxAmount ?? existingSnapshot?.taxAmount ?? null,\n totalNetAmount:\n parsed.totalNetAmount ?? existingSnapshot?.totalNetAmount ?? null,\n totalGrossAmount:\n parsed.totalGrossAmount ?? existingSnapshot?.totalGrossAmount ?? null,\n configuration:\n parsed.configuration ?? existingSnapshot?.configuration ?? null,\n promotionCode:\n parsed.promotionCode ?? existingSnapshot?.promotionCode ?? null,\n metadata,\n customFieldSetId:\n parsed.customFieldSetId ?? existingSnapshot?.customFieldSetId ?? null,\n customFields:\n parsed.customFields && typeof parsed.customFields === \"object\"\n ? cloneJson(parsed.customFields)\n : ((existingSnapshot as any)?.customFields ?? null),\n };\n (updatedSnapshot as any).statusEntryId = statusEntryId;\n (updatedSnapshot as any).catalogSnapshot =\n parsed.catalogSnapshot ??\n (existingSnapshot as any)?.catalogSnapshot ??\n null;\n (updatedSnapshot as any).promotionSnapshot =\n parsed.promotionSnapshot ??\n (existingSnapshot as any)?.promotionSnapshot ??\n null;\n\n let nextLines = parsed.id\n ? lineSnapshots.map((line) =>\n line.id === parsed.id ? updatedSnapshot : line,\n )\n : [...lineSnapshots, updatedSnapshot];\n nextLines = nextLines\n .sort((a, b) => (a.lineNumber ?? 0) - (b.lineNumber ?? 0))\n .map((line, index) => ({ ...line, lineNumber: index + 1 }));\n\n const sourceInputs = nextLines.map((line, index) => ({\n ...line,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n lineNumber: line.lineNumber ?? index + 1,\n }));\n const calcLines: SalesLineSnapshot[] = sourceInputs.map((line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const adjustmentDrafts = adjustments.map(mapOrderAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n currencyCode: order.currencyCode,\n shippingSnapshot: order.shippingMethodSnapshot,\n paymentSnapshot: order.paymentMethodSnapshot,\n shippingMethodId: order.shippingMethodId ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n });\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n // Persist the line changes and recalculated totals atomically so a\n // mid-build failure cannot leave a half-updated order committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n await applyOrderLineResults({\n em,\n order,\n calculation,\n sourceLines: sourceInputs,\n existingLines,\n });\n applyOrderTotals(order, calculation.totals, calculation.lines.length);\n await emitTotalsCalculated(eventBus, {\n documentKind: \"order\",\n documentId: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n customerId: order.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n },\n ],\n { transaction: true },\n );\n return { orderId: order.id, lineId };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadOrderSnapshot(em, result.orderId);\n },\n buildLog: async ({ result, snapshots }) => {\n const before = snapshots.before as OrderGraphSnapshot | undefined;\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.orders.lines.upsert\",\n \"Upsert order line\",\n ),\n resourceKind: \"sales.order\",\n resourceId: result.orderId,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureOrderScope(ctx, before.order.organizationId, before.order.tenantId);\n await restoreOrderGraph(em, before);\n await em.flush();\n },\n};\n\nconst orderLineDeleteCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { orderId: string; lineId: string }\n> = {\n id: \"sales.orders.lines.delete\",\n async prepare(input, ctx) {\n const raw = (input?.body as Record<string, unknown> | undefined) ?? {};\n const orderId = typeof raw.orderId === \"string\" ? raw.orderId : null;\n if (!orderId) return {};\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadOrderSnapshot(em, orderId);\n if (snapshot)\n ensureOrderScope(\n ctx,\n snapshot.order.organizationId,\n snapshot.order.tenantId,\n );\n return snapshot ? { before: snapshot } : {};\n },\n async execute(input, ctx) {\n const { translate } = await resolveTranslations();\n const parsed = orderLineDeleteSchema.parse(\n (input?.body as Record<string, unknown> | undefined) ?? {},\n );\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const order = await em.findOne(SalesOrder, {\n id: parsed.orderId,\n deletedAt: null,\n });\n if (!order)\n throw new CrudHttpError(404, {\n error: translate(\n \"sales.documents.detail.error\",\n \"Document not found or inaccessible.\",\n ),\n });\n ensureOrderScope(ctx, order.organizationId, order.tenantId);\n const shipmentCount = await em.count(SalesShipmentItem, {\n orderLine: parsed.id,\n shipment: { deletedAt: null },\n });\n if (shipmentCount > 0) {\n throw new CrudHttpError(409, {\n error: translate(\n \"sales.documents.items.errorDeleteShipped\",\n \"Cannot delete a line that has shipped items.\",\n ),\n });\n }\n const existingLines = await em.find(\n SalesOrderLine,\n { order },\n { orderBy: { lineNumber: \"asc\" } },\n );\n const adjustments = await em.find(\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n );\n const filtered = existingLines.filter((line) => line.id !== parsed.id);\n if (filtered.length === existingLines.length) {\n throw new CrudHttpError(404, {\n error: translate(\n \"sales.documents.detail.error\",\n \"Document not found or inaccessible.\",\n ),\n });\n }\n const sourceInputs = filtered.map((line, index) => ({\n ...mapOrderLineEntityToSnapshot(line),\n statusEntryId: line.statusEntryId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n lineNumber: index + 1,\n }));\n const calcLines = sourceInputs.map((line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const adjustmentDrafts = adjustments.map(mapOrderAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n currencyCode: order.currencyCode,\n shippingSnapshot: order.shippingMethodSnapshot,\n paymentSnapshot: order.paymentMethodSnapshot,\n shippingMethodId: order.shippingMethodId ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n });\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n // Persist the line removal and recalculated totals atomically so a\n // mid-build failure cannot leave a half-updated order committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n await applyOrderLineResults({\n em,\n order,\n calculation,\n sourceLines: sourceInputs,\n existingLines,\n });\n applyOrderTotals(order, calculation.totals, calculation.lines.length);\n await emitTotalsCalculated(eventBus, {\n documentKind: \"order\",\n documentId: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n customerId: order.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n },\n ],\n { transaction: true },\n );\n return { orderId: order.id, lineId: parsed.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadOrderSnapshot(em, result.orderId);\n },\n buildLog: async ({ result, snapshots }) => {\n const before = snapshots.before as OrderGraphSnapshot | undefined;\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.orders.lines.delete\",\n \"Delete order line\",\n ),\n resourceKind: \"sales.order\",\n resourceId: result.orderId,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureOrderScope(ctx, before.order.organizationId, before.order.tenantId);\n await restoreOrderGraph(em, before);\n await em.flush();\n },\n};\n\nconst quoteLineUpsertCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { quoteId: string; lineId: string }\n> = {\n id: \"sales.quotes.lines.upsert\",\n async prepare(input, ctx) {\n const raw = (input?.body as Record<string, unknown> | undefined) ?? {};\n const quoteId = typeof raw.quoteId === \"string\" ? raw.quoteId : null;\n if (!quoteId) return {};\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadQuoteSnapshot(em, quoteId);\n if (snapshot)\n ensureQuoteScope(\n ctx,\n snapshot.quote.organizationId,\n snapshot.quote.tenantId,\n );\n return snapshot ? { before: snapshot } : {};\n },\n async execute(input, ctx) {\n const rawBody = (input?.body as Record<string, unknown> | undefined) ?? {};\n const parsed = quoteLineUpsertSchema.parse(rawBody);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const quote = await em.findOne(SalesQuote, {\n id: parsed.quoteId,\n deletedAt: null,\n });\n if (!quote)\n throw new CrudHttpError(404, { error: \"Sales quote not found\" });\n ensureQuoteScope(ctx, quote.organizationId, quote.tenantId);\n const [existingLines, adjustments] = await Promise.all([\n em.find(SalesQuoteLine, { quote }, { orderBy: { lineNumber: \"asc\" } }),\n em.find(\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const lineSnapshots = existingLines.map(mapQuoteLineEntityToSnapshot);\n const existingSnapshot = parsed.id\n ? (lineSnapshots.find((line) => line.id === parsed.id) ?? null)\n : null;\n const priceMode =\n parsed.priceMode === \"gross\"\n ? \"gross\"\n : parsed.priceMode === \"net\"\n ? \"net\"\n : null;\n let unitPriceNet =\n parsed.unitPriceNet ?? existingSnapshot?.unitPriceNet ?? null;\n let unitPriceGross =\n parsed.unitPriceGross ?? existingSnapshot?.unitPriceGross ?? null;\n let taxRate = parsed.taxRate ?? existingSnapshot?.taxRate ?? null;\n if (priceMode && (unitPriceNet === null || unitPriceGross === null)) {\n let taxService: TaxCalculationService | null = null;\n try {\n taxService = ctx.container.resolve(\n \"taxCalculationService\",\n ) as TaxCalculationService;\n } catch {\n taxService = null;\n }\n if (taxService) {\n const taxResult = await taxService.calculateUnitAmounts({\n amount:\n priceMode === \"gross\"\n ? (unitPriceGross ?? unitPriceNet ?? 0)\n : (unitPriceNet ?? unitPriceGross ?? 0),\n mode: priceMode,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n taxRateId: parsed.taxRateId ?? undefined,\n taxRate: taxRate ?? undefined,\n });\n unitPriceNet = unitPriceNet ?? taxResult.netAmount;\n unitPriceGross = unitPriceGross ?? taxResult.grossAmount;\n taxRate = taxResult.taxRate ?? taxRate;\n }\n }\n const metadata =\n typeof parsed.metadata === \"object\" && parsed.metadata\n ? { ...parsed.metadata }\n : existingSnapshot?.metadata\n ? cloneJson(existingSnapshot.metadata)\n : {};\n if (parsed.priceId) metadata.priceId = parsed.priceId;\n if (priceMode) metadata.priceMode = priceMode;\n\n const statusEntryId =\n parsed.statusEntryId ?? (existingSnapshot as any)?.statusEntryId ?? null;\n const lineId = parsed.id ?? existingSnapshot?.id ?? randomUUID();\n const lineUomInput = {\n productId: parsed.productId ?? existingSnapshot?.productId ?? null,\n productVariantId:\n parsed.productVariantId ?? existingSnapshot?.productVariantId ?? null,\n quantity: parsed.quantity ?? existingSnapshot?.quantity ?? 0,\n quantityUnit: parsed.quantityUnit ?? existingSnapshot?.quantityUnit ?? null,\n normalizedQuantity: existingSnapshot?.normalizedQuantity ?? null,\n normalizedUnit: existingSnapshot?.normalizedUnit ?? null,\n uomSnapshot: existingSnapshot?.uomSnapshot ?? null,\n };\n const uomResolver = createUomResolver();\n let normalizedUom = await normalizeLineUom({\n em,\n resolver: uomResolver,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n line: {\n ...lineUomInput,\n unitPriceNet: unitPriceNet ?? 0,\n unitPriceGross: unitPriceGross ?? unitPriceNet ?? 0,\n },\n });\n const convertedPrices = convertLineUnitPricesOnUnitChange({\n existingSnapshot,\n nextQuantityUnit: normalizedUom.quantityUnit,\n nextUomSnapshot: normalizedUom.uomSnapshot,\n unitPriceNet,\n unitPriceGross,\n });\n if (convertedPrices.didConvert) {\n unitPriceNet = convertedPrices.unitPriceNet;\n unitPriceGross = convertedPrices.unitPriceGross;\n normalizedUom = await normalizeLineUom({\n em,\n resolver: uomResolver,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n line: {\n ...lineUomInput,\n unitPriceNet: unitPriceNet ?? 0,\n unitPriceGross: unitPriceGross ?? unitPriceNet ?? 0,\n },\n });\n }\n const updatedSnapshot: SalesLineSnapshot & {\n statusEntryId?: string | null;\n catalogSnapshot?: Record<string, unknown> | null;\n promotionSnapshot?: Record<string, unknown> | null;\n } = {\n id: lineId,\n lineNumber:\n parsed.lineNumber ??\n existingSnapshot?.lineNumber ??\n lineSnapshots.length + 1,\n kind: parsed.kind ?? existingSnapshot?.kind ?? \"product\",\n productId: parsed.productId ?? existingSnapshot?.productId ?? null,\n productVariantId:\n parsed.productVariantId ?? existingSnapshot?.productVariantId ?? null,\n name: parsed.name ?? existingSnapshot?.name ?? null,\n description: parsed.description ?? existingSnapshot?.description ?? null,\n comment: parsed.comment ?? existingSnapshot?.comment ?? null,\n quantity: normalizedUom.quantity,\n quantityUnit: normalizedUom.quantityUnit,\n normalizedQuantity: normalizedUom.normalizedQuantity,\n normalizedUnit: normalizedUom.normalizedUnit,\n uomSnapshot: normalizedUom.uomSnapshot\n ? cloneJson(normalizedUom.uomSnapshot)\n : null,\n currencyCode:\n parsed.currencyCode ??\n existingSnapshot?.currencyCode ??\n quote.currencyCode,\n unitPriceNet: unitPriceNet ?? 0,\n unitPriceGross: unitPriceGross ?? unitPriceNet ?? 0,\n discountAmount:\n parsed.discountAmount ?? existingSnapshot?.discountAmount ?? 0,\n discountPercent:\n parsed.discountPercent ?? existingSnapshot?.discountPercent ?? 0,\n taxRate: taxRate ?? 0,\n taxAmount: parsed.taxAmount ?? existingSnapshot?.taxAmount ?? null,\n totalNetAmount:\n parsed.totalNetAmount ?? existingSnapshot?.totalNetAmount ?? null,\n totalGrossAmount:\n parsed.totalGrossAmount ?? existingSnapshot?.totalGrossAmount ?? null,\n configuration:\n parsed.configuration ?? existingSnapshot?.configuration ?? null,\n promotionCode:\n parsed.promotionCode ?? existingSnapshot?.promotionCode ?? null,\n metadata,\n customFieldSetId:\n parsed.customFieldSetId ?? existingSnapshot?.customFieldSetId ?? null,\n customFields:\n parsed.customFields && typeof parsed.customFields === \"object\"\n ? cloneJson(parsed.customFields)\n : ((existingSnapshot as any)?.customFields ?? null),\n };\n (updatedSnapshot as any).statusEntryId = statusEntryId;\n (updatedSnapshot as any).catalogSnapshot =\n parsed.catalogSnapshot ??\n (existingSnapshot as any)?.catalogSnapshot ??\n null;\n (updatedSnapshot as any).promotionSnapshot =\n parsed.promotionSnapshot ??\n (existingSnapshot as any)?.promotionSnapshot ??\n null;\n\n let nextLines = parsed.id\n ? lineSnapshots.map((line) =>\n line.id === parsed.id ? updatedSnapshot : line,\n )\n : [...lineSnapshots, updatedSnapshot];\n nextLines = nextLines\n .sort((a, b) => (a.lineNumber ?? 0) - (b.lineNumber ?? 0))\n .map((line, index) => ({ ...line, lineNumber: index + 1 }));\n\n const sourceInputs = nextLines.map((line, index) => ({\n ...line,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n lineNumber: line.lineNumber ?? index + 1,\n }));\n const calcLines: SalesLineSnapshot[] = sourceInputs.map((line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const adjustmentDrafts = adjustments.map(mapQuoteAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n currencyCode: quote.currencyCode,\n shippingSnapshot: quote.shippingMethodSnapshot,\n paymentSnapshot: quote.paymentMethodSnapshot,\n shippingMethodId: quote.shippingMethodId ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n });\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n // Persist the line changes and recalculated totals atomically so a\n // mid-build failure cannot leave a half-updated quote committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n await applyQuoteLineResults({\n em,\n quote,\n calculation,\n sourceLines: sourceInputs,\n existingLines,\n });\n applyQuoteTotals(quote, calculation.totals, calculation.lines.length);\n await emitTotalsCalculated(eventBus, {\n documentKind: \"quote\",\n documentId: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n customerId: quote.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n },\n ],\n { transaction: true },\n );\n return { quoteId: quote.id, lineId };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadQuoteSnapshot(em, result.quoteId);\n },\n buildLog: async ({ result, snapshots }) => {\n const before = snapshots.before as QuoteGraphSnapshot | undefined;\n const after = snapshots.after as QuoteGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.quotes.lines.upsert\",\n \"Upsert quote line\",\n ),\n resourceKind: \"sales.quote\",\n resourceId: result.quoteId,\n tenantId: after.quote.tenantId,\n organizationId: after.quote.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureQuoteScope(ctx, before.quote.organizationId, before.quote.tenantId);\n await restoreQuoteGraph(em, before);\n await em.flush();\n },\n};\n\nconst quoteLineDeleteCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { quoteId: string; lineId: string }\n> = {\n id: \"sales.quotes.lines.delete\",\n async prepare(input, ctx) {\n const raw = (input?.body as Record<string, unknown> | undefined) ?? {};\n const quoteId = typeof raw.quoteId === \"string\" ? raw.quoteId : null;\n if (!quoteId) return {};\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadQuoteSnapshot(em, quoteId);\n if (snapshot)\n ensureQuoteScope(\n ctx,\n snapshot.quote.organizationId,\n snapshot.quote.tenantId,\n );\n return snapshot ? { before: snapshot } : {};\n },\n async execute(input, ctx) {\n const parsed = quoteLineDeleteSchema.parse(\n (input?.body as Record<string, unknown> | undefined) ?? {},\n );\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const quote = await em.findOne(SalesQuote, {\n id: parsed.quoteId,\n deletedAt: null,\n });\n if (!quote)\n throw new CrudHttpError(404, { error: \"Sales quote not found\" });\n ensureQuoteScope(ctx, quote.organizationId, quote.tenantId);\n const existingLines = await em.find(\n SalesQuoteLine,\n { quote },\n { orderBy: { lineNumber: \"asc\" } },\n );\n const adjustments = await em.find(\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n );\n const filtered = existingLines.filter((line) => line.id !== parsed.id);\n if (filtered.length === existingLines.length) {\n throw new CrudHttpError(404, { error: \"Quote line not found\" });\n }\n const sourceInputs = filtered.map((line, index) => ({\n ...mapQuoteLineEntityToSnapshot(line),\n statusEntryId: line.statusEntryId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n lineNumber: index + 1,\n }));\n const calcLines = sourceInputs.map((line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const adjustmentDrafts = adjustments.map(mapQuoteAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n currencyCode: quote.currencyCode,\n shippingSnapshot: quote.shippingMethodSnapshot,\n paymentSnapshot: quote.paymentMethodSnapshot,\n shippingMethodId: quote.shippingMethodId ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n });\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n // Persist the line removal and recalculated totals atomically so a\n // mid-build failure cannot leave a half-updated quote committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n await applyQuoteLineResults({\n em,\n quote,\n calculation,\n sourceLines: sourceInputs,\n existingLines,\n });\n applyQuoteTotals(quote, calculation.totals, calculation.lines.length);\n await emitTotalsCalculated(eventBus, {\n documentKind: \"quote\",\n documentId: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n customerId: quote.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n },\n ],\n { transaction: true },\n );\n return { quoteId: quote.id, lineId: parsed.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadQuoteSnapshot(em, result.quoteId);\n },\n buildLog: async ({ result, snapshots }) => {\n const before = snapshots.before as QuoteGraphSnapshot | undefined;\n const after = snapshots.after as QuoteGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.quotes.lines.delete\",\n \"Delete quote line\",\n ),\n resourceKind: \"sales.quote\",\n resourceId: result.quoteId,\n tenantId: after.quote.tenantId,\n organizationId: after.quote.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureQuoteScope(ctx, before.quote.organizationId, before.quote.tenantId);\n await restoreQuoteGraph(em, before);\n await em.flush();\n },\n};\n\nconst orderAdjustmentUpsertCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { orderId: string; adjustmentId: string }\n> = {\n id: \"sales.orders.adjustments.upsert\",\n async prepare(input, ctx) {\n const raw = (input?.body as Record<string, unknown> | undefined) ?? {};\n const orderId = typeof raw.orderId === \"string\" ? raw.orderId : null;\n if (!orderId) return {};\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadOrderSnapshot(em, orderId);\n if (snapshot)\n ensureOrderScope(\n ctx,\n snapshot.order.organizationId,\n snapshot.order.tenantId,\n );\n return snapshot ? { before: snapshot } : {};\n },\n async execute(input, ctx) {\n const parsed = orderAdjustmentUpsertSchema.parse(\n (input?.body as Record<string, unknown> | undefined) ?? {},\n );\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const order = await em.findOne(SalesOrder, {\n id: parsed.orderId,\n deletedAt: null,\n });\n if (!order)\n throw new CrudHttpError(404, { error: \"Sales order not found\" });\n ensureOrderScope(ctx, order.organizationId, order.tenantId);\n if (parsed.scope === \"line\") {\n throw new CrudHttpError(400, {\n error: \"Line-scoped adjustments are not supported yet.\",\n });\n }\n\n const [existingLines, existingAdjustments] = await Promise.all([\n em.find(SalesOrderLine, { order }, { orderBy: { lineNumber: \"asc\" } }),\n em.find(\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const lineSnapshots = existingLines.map(mapOrderLineEntityToSnapshot);\n const adjustmentDrafts = existingAdjustments.map(mapOrderAdjustmentToDraft);\n const existingSnapshot = parsed.id\n ? (adjustmentDrafts.find((adj) => adj.id === parsed.id) ?? null)\n : null;\n const adjustmentId = parsed.id ?? existingSnapshot?.id ?? randomUUID();\n let metadata =\n typeof parsed.metadata === \"object\" && parsed.metadata\n ? cloneJson(parsed.metadata)\n : existingSnapshot?.metadata\n ? cloneJson(existingSnapshot.metadata)\n : null;\n const calculatorKey =\n parsed.calculatorKey ?? existingSnapshot?.calculatorKey ?? null;\n if (\n parsed.id &&\n calculatorKey &&\n (calculatorKey.startsWith(\"shipping-provider:\") ||\n calculatorKey.startsWith(\"payment-provider:\"))\n ) {\n metadata = { ...(metadata ?? {}), manualOverride: true };\n }\n let nextAdjustments = parsed.id\n ? adjustmentDrafts.map((adj) =>\n adj.id === parsed.id\n ? {\n ...adj,\n id: adjustmentId,\n scope: parsed.scope ?? adj.scope ?? \"order\",\n kind: parsed.kind ?? adj.kind ?? \"custom\",\n code: parsed.code ?? adj.code ?? null,\n label: parsed.label ?? adj.label ?? null,\n calculatorKey:\n parsed.calculatorKey ?? adj.calculatorKey ?? null,\n promotionId: parsed.promotionId ?? adj.promotionId ?? null,\n rate: parsed.rate ?? adj.rate ?? null,\n amountNet: parsed.amountNet ?? adj.amountNet ?? null,\n amountGross: parsed.amountGross ?? adj.amountGross ?? null,\n currencyCode:\n parsed.currencyCode ?? adj.currencyCode ?? order.currencyCode,\n metadata,\n customFields:\n parsed.customFields !== undefined\n ? parsed.customFields\n : ((adj as any).customFields ?? null),\n position:\n parsed.position ?? adj.position ?? adjustmentDrafts.length,\n }\n : adj,\n )\n : [\n ...adjustmentDrafts,\n {\n id: adjustmentId,\n scope: parsed.scope ?? \"order\",\n kind: parsed.kind ?? \"custom\",\n code: parsed.code ?? null,\n label: parsed.label ?? null,\n calculatorKey: parsed.calculatorKey ?? null,\n promotionId: parsed.promotionId ?? null,\n rate: parsed.rate ?? null,\n amountNet: parsed.amountNet ?? null,\n amountGross: parsed.amountGross ?? null,\n currencyCode: parsed.currencyCode ?? order.currencyCode,\n metadata,\n customFields: parsed.customFields ?? null,\n position: parsed.position ?? adjustmentDrafts.length,\n },\n ];\n\n nextAdjustments = nextAdjustments\n .sort((a, b) => (a.position ?? 0) - (b.position ?? 0))\n .map((adj, index) => ({ ...adj, position: adj.position ?? index }));\n\n const sourceLines = lineSnapshots.map((line, index) => ({\n ...line,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n lineNumber: line.lineNumber ?? index + 1,\n }));\n const calcLines = sourceLines.map((line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n currencyCode: order.currencyCode,\n shippingSnapshot: order.shippingMethodSnapshot,\n paymentSnapshot: order.paymentMethodSnapshot,\n shippingMethodId: order.shippingMethodId ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n });\n const effectiveAdjustment = nextAdjustments.find(\n (adj) => adj.id === adjustmentId,\n );\n if (effectiveAdjustment?.kind === \"return\") {\n const baselineAdjustments = nextAdjustments.filter(\n (adj) => adj.id !== adjustmentId,\n );\n const baselineCalculation =\n await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: calcLines,\n adjustments: baselineAdjustments,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n });\n const issues = validateReturnAdjustmentWithinRemaining({\n kind: \"return\",\n amountNet:\n effectiveAdjustment.amountNet ?? effectiveAdjustment.amountGross ?? 0,\n amountGross:\n effectiveAdjustment.amountGross ?? effectiveAdjustment.amountNet ?? 0,\n remainingNet: Number(\n baselineCalculation.totals?.grandTotalNetAmount ?? 0,\n ),\n remainingGross: Number(\n baselineCalculation.totals?.grandTotalGrossAmount ?? 0,\n ),\n });\n if (issues.length > 0) {\n const { translate } = await resolveTranslations();\n const grossIssue = issues.find((issue) => issue.path === \"amountGross\");\n const netIssue = issues.find((issue) => issue.path === \"amountNet\");\n const fieldErrors: Record<string, string> = {};\n if (grossIssue) {\n fieldErrors.amountGross = translate(\n \"sales.adjustments.error.returnExceedsRemainingGrandTotalGross\",\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_GROSS_MESSAGE,\n );\n }\n if (netIssue) {\n fieldErrors.amountNet = translate(\n \"sales.adjustments.error.returnExceedsRemainingGrandTotalNet\",\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_NET_MESSAGE,\n );\n }\n throw new CrudHttpError(400, {\n error:\n fieldErrors.amountGross ??\n fieldErrors.amountNet ??\n translate(\n \"sales.adjustments.error.returnExceedsRemainingGrandTotalGross\",\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_GROSS_MESSAGE,\n ),\n fieldErrors,\n });\n }\n }\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: calcLines,\n adjustments: nextAdjustments,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n });\n const adjustmentInputs = nextAdjustments.map((adj, index) => ({\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n scope: adj.scope ?? \"order\",\n kind: adj.kind ?? \"custom\",\n code: adj.code ?? undefined,\n label: adj.label ?? undefined,\n calculatorKey: adj.calculatorKey ?? undefined,\n promotionId: adj.promotionId ?? undefined,\n rate: adj.rate ?? undefined,\n amountNet: adj.amountNet ?? undefined,\n amountGross: adj.amountGross ?? undefined,\n currencyCode: adj.currencyCode ?? order.currencyCode,\n metadata: adj.metadata ?? undefined,\n customFields: (adj as any).customFields ?? undefined,\n position: adj.position ?? index,\n }));\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n // Persist the adjustment change and recalculated totals atomically so a\n // mid-build failure cannot leave a half-updated order committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n await replaceOrderAdjustments(em, order, calculation, adjustmentInputs);\n applyOrderTotals(order, calculation.totals, calculation.lines.length);\n order.updatedAt = new Date();\n await emitTotalsCalculated(eventBus, {\n documentKind: \"order\",\n documentId: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n customerId: order.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n },\n ],\n { transaction: true },\n );\n return { orderId: order.id, adjustmentId };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadOrderSnapshot(em, result.orderId);\n },\n buildLog: async ({ snapshots, result }) => {\n const before = snapshots.before as OrderGraphSnapshot | undefined;\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.orders.adjustments.upsert\",\n \"Upsert order adjustment\",\n ),\n resourceKind: \"sales.order\",\n resourceId: result.orderId,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureOrderScope(ctx, before.order.organizationId, before.order.tenantId);\n await restoreOrderGraph(em, before);\n await em.flush();\n },\n};\n\nconst orderAdjustmentDeleteCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { orderId: string; adjustmentId: string }\n> = {\n id: \"sales.orders.adjustments.delete\",\n async prepare(input, ctx) {\n const raw = (input?.body as Record<string, unknown> | undefined) ?? {};\n const orderId = typeof raw.orderId === \"string\" ? raw.orderId : null;\n if (!orderId) return {};\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadOrderSnapshot(em, orderId);\n if (snapshot)\n ensureOrderScope(\n ctx,\n snapshot.order.organizationId,\n snapshot.order.tenantId,\n );\n return snapshot ? { before: snapshot } : {};\n },\n async execute(input, ctx) {\n const parsed = orderAdjustmentDeleteSchema.parse(\n (input?.body as Record<string, unknown> | undefined) ?? {},\n );\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const order = await em.findOne(SalesOrder, {\n id: parsed.orderId,\n deletedAt: null,\n });\n if (!order)\n throw new CrudHttpError(404, { error: \"Sales order not found\" });\n ensureOrderScope(ctx, order.organizationId, order.tenantId);\n\n const [existingLines, adjustments] = await Promise.all([\n em.find(SalesOrderLine, { order }, { orderBy: { lineNumber: \"asc\" } }),\n em.find(\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const filtered = adjustments.filter((adj) => adj.id !== parsed.id);\n if (filtered.length === adjustments.length) {\n throw new CrudHttpError(404, { error: \"Adjustment not found\" });\n }\n const lineSnapshots = existingLines.map(mapOrderLineEntityToSnapshot);\n const calcLines = lineSnapshots.map((line, index) =>\n createLineSnapshotFromInput(\n {\n ...line,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n lineNumber: line.lineNumber ?? index + 1,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n },\n line.lineNumber ?? index + 1,\n ),\n );\n const adjustmentDrafts = filtered.map(mapOrderAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n currencyCode: order.currencyCode,\n shippingSnapshot: order.shippingMethodSnapshot,\n paymentSnapshot: order.paymentMethodSnapshot,\n shippingMethodId: order.shippingMethodId ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n });\n const adjustmentInputs = adjustmentDrafts.map((adj, index) => ({\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n scope: adj.scope ?? \"order\",\n kind: adj.kind ?? \"custom\",\n code: adj.code ?? undefined,\n label: adj.label ?? undefined,\n calculatorKey: adj.calculatorKey ?? undefined,\n promotionId: adj.promotionId ?? undefined,\n rate: adj.rate ?? undefined,\n amountNet: adj.amountNet ?? undefined,\n amountGross: adj.amountGross ?? undefined,\n currencyCode: adj.currencyCode ?? order.currencyCode,\n metadata: adj.metadata ?? undefined,\n position: adj.position ?? index,\n }));\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n // Persist the adjustment removal and recalculated totals atomically so a\n // mid-build failure cannot leave a half-updated order committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n await replaceOrderAdjustments(em, order, calculation, adjustmentInputs);\n applyOrderTotals(order, calculation.totals, calculation.lines.length);\n order.updatedAt = new Date();\n await emitTotalsCalculated(eventBus, {\n documentKind: \"order\",\n documentId: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n customerId: order.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n },\n ],\n { transaction: true },\n );\n return { orderId: order.id, adjustmentId: parsed.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadOrderSnapshot(em, result.orderId);\n },\n buildLog: async ({ snapshots, result }) => {\n const before = snapshots.before as OrderGraphSnapshot | undefined;\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.orders.adjustments.delete\",\n \"Delete order adjustment\",\n ),\n resourceKind: \"sales.order\",\n resourceId: result.orderId,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureOrderScope(ctx, before.order.organizationId, before.order.tenantId);\n await restoreOrderGraph(em, before);\n await em.flush();\n },\n};\n\nconst quoteAdjustmentUpsertCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { quoteId: string; adjustmentId: string }\n> = {\n id: \"sales.quotes.adjustments.upsert\",\n async prepare(input, ctx) {\n const raw = (input?.body as Record<string, unknown> | undefined) ?? {};\n const quoteId = typeof raw.quoteId === \"string\" ? raw.quoteId : null;\n if (!quoteId) return {};\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadQuoteSnapshot(em, quoteId);\n if (snapshot)\n ensureQuoteScope(\n ctx,\n snapshot.quote.organizationId,\n snapshot.quote.tenantId,\n );\n return snapshot ? { before: snapshot } : {};\n },\n async execute(input, ctx) {\n const parsed = quoteAdjustmentUpsertSchema.parse(\n (input?.body as Record<string, unknown> | undefined) ?? {},\n );\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const quote = await em.findOne(SalesQuote, {\n id: parsed.quoteId,\n deletedAt: null,\n });\n if (!quote)\n throw new CrudHttpError(404, { error: \"Sales quote not found\" });\n ensureQuoteScope(ctx, quote.organizationId, quote.tenantId);\n if (parsed.scope === \"line\") {\n throw new CrudHttpError(400, {\n error: \"Line-scoped adjustments are not supported yet.\",\n });\n }\n\n const [existingLines, existingAdjustments] = await Promise.all([\n em.find(SalesQuoteLine, { quote }, { orderBy: { lineNumber: \"asc\" } }),\n em.find(\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const lineSnapshots = existingLines.map(mapQuoteLineEntityToSnapshot);\n const adjustmentDrafts = existingAdjustments.map(mapQuoteAdjustmentToDraft);\n const existingSnapshot = parsed.id\n ? (adjustmentDrafts.find((adj) => adj.id === parsed.id) ?? null)\n : null;\n const adjustmentId = parsed.id ?? existingSnapshot?.id ?? randomUUID();\n let metadata =\n typeof parsed.metadata === \"object\" && parsed.metadata\n ? cloneJson(parsed.metadata)\n : existingSnapshot?.metadata\n ? cloneJson(existingSnapshot.metadata)\n : null;\n const calculatorKey =\n parsed.calculatorKey ?? existingSnapshot?.calculatorKey ?? null;\n if (\n parsed.id &&\n calculatorKey &&\n (calculatorKey.startsWith(\"shipping-provider:\") ||\n calculatorKey.startsWith(\"payment-provider:\"))\n ) {\n metadata = { ...(metadata ?? {}), manualOverride: true };\n }\n let nextAdjustments = parsed.id\n ? adjustmentDrafts.map((adj) =>\n adj.id === parsed.id\n ? {\n ...adj,\n id: adjustmentId,\n scope: parsed.scope ?? adj.scope ?? \"order\",\n kind: parsed.kind ?? adj.kind ?? \"custom\",\n code: parsed.code ?? adj.code ?? null,\n label: parsed.label ?? adj.label ?? null,\n calculatorKey:\n parsed.calculatorKey ?? adj.calculatorKey ?? null,\n promotionId: parsed.promotionId ?? adj.promotionId ?? null,\n rate: parsed.rate ?? adj.rate ?? null,\n amountNet: parsed.amountNet ?? adj.amountNet ?? null,\n amountGross: parsed.amountGross ?? adj.amountGross ?? null,\n currencyCode:\n parsed.currencyCode ?? adj.currencyCode ?? quote.currencyCode,\n metadata,\n customFields:\n parsed.customFields !== undefined\n ? parsed.customFields\n : ((adj as any).customFields ?? null),\n position:\n parsed.position ?? adj.position ?? adjustmentDrafts.length,\n }\n : adj,\n )\n : [\n ...adjustmentDrafts,\n {\n id: adjustmentId,\n scope: parsed.scope ?? \"order\",\n kind: parsed.kind ?? \"custom\",\n code: parsed.code ?? null,\n label: parsed.label ?? null,\n calculatorKey: parsed.calculatorKey ?? null,\n promotionId: parsed.promotionId ?? null,\n rate: parsed.rate ?? null,\n amountNet: parsed.amountNet ?? null,\n amountGross: parsed.amountGross ?? null,\n currencyCode: parsed.currencyCode ?? quote.currencyCode,\n metadata,\n customFields: parsed.customFields ?? null,\n position: parsed.position ?? adjustmentDrafts.length,\n },\n ];\n\n nextAdjustments = nextAdjustments\n .sort((a, b) => (a.position ?? 0) - (b.position ?? 0))\n .map((adj, index) => ({ ...adj, position: adj.position ?? index }));\n\n const sourceLines = lineSnapshots.map((line, index) => ({\n ...line,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n lineNumber: line.lineNumber ?? index + 1,\n }));\n const calcLines = sourceLines.map((line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n currencyCode: quote.currencyCode,\n shippingSnapshot: quote.shippingMethodSnapshot,\n paymentSnapshot: quote.paymentMethodSnapshot,\n shippingMethodId: quote.shippingMethodId ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n });\n const effectiveAdjustment = nextAdjustments.find(\n (adj) => adj.id === adjustmentId,\n );\n if (effectiveAdjustment?.kind === \"return\") {\n const baselineAdjustments = nextAdjustments.filter(\n (adj) => adj.id !== adjustmentId,\n );\n const baselineCalculation =\n await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: calcLines,\n adjustments: baselineAdjustments,\n context: calculationContext,\n });\n const issues = validateReturnAdjustmentWithinRemaining({\n kind: \"return\",\n amountNet:\n effectiveAdjustment.amountNet ?? effectiveAdjustment.amountGross ?? 0,\n amountGross:\n effectiveAdjustment.amountGross ?? effectiveAdjustment.amountNet ?? 0,\n remainingNet: Number(\n baselineCalculation.totals?.grandTotalNetAmount ?? 0,\n ),\n remainingGross: Number(\n baselineCalculation.totals?.grandTotalGrossAmount ?? 0,\n ),\n });\n if (issues.length > 0) {\n const { translate } = await resolveTranslations();\n const grossIssue = issues.find((issue) => issue.path === \"amountGross\");\n const netIssue = issues.find((issue) => issue.path === \"amountNet\");\n const fieldErrors: Record<string, string> = {};\n if (grossIssue) {\n fieldErrors.amountGross = translate(\n \"sales.adjustments.error.returnExceedsRemainingGrandTotalGross\",\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_GROSS_MESSAGE,\n );\n }\n if (netIssue) {\n fieldErrors.amountNet = translate(\n \"sales.adjustments.error.returnExceedsRemainingGrandTotalNet\",\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_NET_MESSAGE,\n );\n }\n throw new CrudHttpError(400, {\n error:\n fieldErrors.amountGross ??\n fieldErrors.amountNet ??\n translate(\n \"sales.adjustments.error.returnExceedsRemainingGrandTotalGross\",\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_GROSS_MESSAGE,\n ),\n fieldErrors,\n });\n }\n }\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: calcLines,\n adjustments: nextAdjustments,\n context: calculationContext,\n });\n const adjustmentInputs = nextAdjustments.map((adj, index) => ({\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n scope: adj.scope ?? \"order\",\n kind: adj.kind ?? \"custom\",\n code: adj.code ?? undefined,\n label: adj.label ?? undefined,\n calculatorKey: adj.calculatorKey ?? undefined,\n promotionId: adj.promotionId ?? undefined,\n rate: adj.rate ?? undefined,\n amountNet: adj.amountNet ?? undefined,\n amountGross: adj.amountGross ?? undefined,\n currencyCode: adj.currencyCode ?? quote.currencyCode,\n metadata: adj.metadata ?? undefined,\n customFields: (adj as any).customFields ?? undefined,\n position: adj.position ?? index,\n }));\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n // Persist the adjustment change and recalculated totals atomically so a\n // mid-build failure cannot leave a half-updated quote committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n await replaceQuoteAdjustments(em, quote, calculation, adjustmentInputs);\n applyQuoteTotals(quote, calculation.totals, calculation.lines.length);\n quote.updatedAt = new Date();\n await emitTotalsCalculated(eventBus, {\n documentKind: \"quote\",\n documentId: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n customerId: quote.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n },\n ],\n { transaction: true },\n );\n return { quoteId: quote.id, adjustmentId };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadQuoteSnapshot(em, result.quoteId);\n },\n buildLog: async ({ snapshots, result }) => {\n const before = snapshots.before as QuoteGraphSnapshot | undefined;\n const after = snapshots.after as QuoteGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.quotes.adjustments.upsert\",\n \"Upsert quote adjustment\",\n ),\n resourceKind: \"sales.quote\",\n resourceId: result.quoteId,\n tenantId: after.quote.tenantId,\n organizationId: after.quote.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureQuoteScope(ctx, before.quote.organizationId, before.quote.tenantId);\n await restoreQuoteGraph(em, before);\n await em.flush();\n },\n};\n\nconst quoteAdjustmentDeleteCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { quoteId: string; adjustmentId: string }\n> = {\n id: \"sales.quotes.adjustments.delete\",\n async prepare(input, ctx) {\n const raw = (input?.body as Record<string, unknown> | undefined) ?? {};\n const quoteId = typeof raw.quoteId === \"string\" ? raw.quoteId : null;\n if (!quoteId) return {};\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadQuoteSnapshot(em, quoteId);\n if (snapshot)\n ensureQuoteScope(\n ctx,\n snapshot.quote.organizationId,\n snapshot.quote.tenantId,\n );\n return snapshot ? { before: snapshot } : {};\n },\n async execute(input, ctx) {\n const parsed = quoteAdjustmentDeleteSchema.parse(\n (input?.body as Record<string, unknown> | undefined) ?? {},\n );\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const quote = await em.findOne(SalesQuote, {\n id: parsed.quoteId,\n deletedAt: null,\n });\n if (!quote)\n throw new CrudHttpError(404, { error: \"Sales quote not found\" });\n ensureQuoteScope(ctx, quote.organizationId, quote.tenantId);\n\n const [existingLines, adjustments] = await Promise.all([\n em.find(SalesQuoteLine, { quote }, { orderBy: { lineNumber: \"asc\" } }),\n em.find(\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const filtered = adjustments.filter((adj) => adj.id !== parsed.id);\n if (filtered.length === adjustments.length) {\n throw new CrudHttpError(404, { error: \"Adjustment not found\" });\n }\n const lineSnapshots = existingLines.map(mapQuoteLineEntityToSnapshot);\n const calcLines = lineSnapshots.map((line, index) =>\n createLineSnapshotFromInput(\n {\n ...line,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n lineNumber: line.lineNumber ?? index + 1,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n },\n line.lineNumber ?? index + 1,\n ),\n );\n const adjustmentDrafts = filtered.map(mapQuoteAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n currencyCode: quote.currencyCode,\n shippingSnapshot: quote.shippingMethodSnapshot,\n paymentSnapshot: quote.paymentMethodSnapshot,\n shippingMethodId: quote.shippingMethodId ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n });\n const adjustmentInputs = adjustmentDrafts.map((adj, index) => ({\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n scope: adj.scope ?? \"order\",\n kind: adj.kind ?? \"custom\",\n code: adj.code ?? undefined,\n label: adj.label ?? undefined,\n calculatorKey: adj.calculatorKey ?? undefined,\n promotionId: adj.promotionId ?? undefined,\n rate: adj.rate ?? undefined,\n amountNet: adj.amountNet ?? undefined,\n amountGross: adj.amountGross ?? undefined,\n currencyCode: adj.currencyCode ?? quote.currencyCode,\n metadata: adj.metadata ?? undefined,\n position: adj.position ?? index,\n }));\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n // Persist the adjustment removal and recalculated totals atomically so a\n // mid-build failure cannot leave a half-updated quote committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n await replaceQuoteAdjustments(em, quote, calculation, adjustmentInputs);\n applyQuoteTotals(quote, calculation.totals, calculation.lines.length);\n quote.updatedAt = new Date();\n await emitTotalsCalculated(eventBus, {\n documentKind: \"quote\",\n documentId: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n customerId: quote.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n },\n ],\n { transaction: true },\n );\n return { quoteId: quote.id, adjustmentId: parsed.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadQuoteSnapshot(em, result.quoteId);\n },\n buildLog: async ({ snapshots, result }) => {\n const before = snapshots.before as QuoteGraphSnapshot | undefined;\n const after = snapshots.after as QuoteGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.quotes.adjustments.delete\",\n \"Delete quote adjustment\",\n ),\n resourceKind: \"sales.quote\",\n resourceId: result.quoteId,\n tenantId: after.quote.tenantId,\n organizationId: after.quote.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureQuoteScope(ctx, before.quote.organizationId, before.quote.tenantId);\n await restoreQuoteGraph(em, before);\n await em.flush();\n },\n};\n\n// ---------------------------------------------------------------------------\n// Invoice CRUD commands\n// ---------------------------------------------------------------------------\n\nconst invoiceCrudEvents: CrudEventsConfig<SalesInvoice> = {\n module: \"sales\",\n entity: \"invoice\",\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n};\n\nconst createInvoiceCommand: CommandHandler<\n InvoiceCreateInput,\n { invoiceId: string }\n> = {\n id: \"sales.invoices.create\",\n async execute(rawInput, ctx) {\n const generator = ctx.container.resolve(\n \"salesDocumentNumberGenerator\",\n ) as SalesDocumentNumberGenerator;\n const initial = invoiceCreateSchema.parse(rawInput ?? {});\n const invoiceNumber =\n typeof initial.invoiceNumber === \"string\" &&\n initial.invoiceNumber.trim().length\n ? initial.invoiceNumber.trim()\n : (\n await generator.generate({\n kind: \"invoice\",\n organizationId: initial.organizationId,\n tenantId: initial.tenantId,\n })\n ).number;\n const parsed = invoiceCreateSchema.parse({ ...initial, invoiceNumber });\n const ensuredInvoiceNumber = parsed.invoiceNumber ?? invoiceNumber;\n if (!ensuredInvoiceNumber) {\n throw new CrudHttpError(400, { error: \"Invoice number is required.\" });\n }\n ensureOrganizationScope(ctx, parsed.organizationId);\n ensureTenantScope(ctx, parsed.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const status = await resolveDictionaryEntryValue(\n em,\n parsed.statusEntryId ?? null,\n );\n\n // Validate orderId belongs to same org/tenant\n if (parsed.orderId) {\n const orderExists = await em.findOne(SalesOrder, {\n id: parsed.orderId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n deletedAt: null,\n });\n if (!orderExists) {\n throw new CrudHttpError(400, { error: \"Referenced order not found in current scope.\" });\n }\n }\n\n const invoiceId = randomUUID();\n const invoice = em.create(SalesInvoice, {\n id: invoiceId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n invoiceNumber: ensuredInvoiceNumber,\n orderId: parsed.orderId ?? null,\n statusEntryId: parsed.statusEntryId ?? null,\n status,\n issueDate: parsed.issueDate ?? new Date(),\n dueDate: parsed.dueDate ?? null,\n currencyCode: parsed.currencyCode,\n subtotalNetAmount: toNumericString(parsed.subtotalNetAmount ?? 0),\n subtotalGrossAmount: toNumericString(parsed.subtotalGrossAmount ?? 0),\n discountTotalAmount: toNumericString(parsed.discountTotalAmount ?? 0),\n taxTotalAmount: toNumericString(parsed.taxTotalAmount ?? 0),\n grandTotalNetAmount: toNumericString(parsed.grandTotalNetAmount ?? 0),\n grandTotalGrossAmount: toNumericString(parsed.grandTotalGrossAmount ?? 0),\n paidTotalAmount: toNumericString(parsed.paidTotalAmount ?? 0),\n outstandingAmount: toNumericString(parsed.outstandingAmount ?? 0),\n metadata: parsed.metadata ?? null,\n customFieldSetId: parsed.customFieldSetId ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n\n // Header + lines + custom-field writes must commit atomically.\n // setRecordCustomFields flushes mid-build, so without a transaction a\n // partial write could persist the header without its lines/custom fields.\n await withAtomicFlush(\n em,\n [\n async () => {\n em.persist(invoice);\n\n if (parsed.lines?.length) {\n for (let i = 0; i < parsed.lines.length; i++) {\n const line = parsed.lines[i];\n em.persist(\n em.create(SalesInvoiceLine, {\n id: randomUUID(),\n invoice,\n orderLineId: line.orderLineId ?? null,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n lineNumber: line.lineNumber ?? i + 1,\n kind: line.kind ?? \"product\",\n name: line.name ?? null,\n sku: line.sku ?? null,\n description: line.description ?? null,\n quantity: toNumericString(line.quantity ?? 0),\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: toNumericString(line.normalizedQuantity ?? 0),\n normalizedUnit: line.normalizedUnit ?? null,\n uomSnapshot: line.uomSnapshot ?? null,\n currencyCode: line.currencyCode ?? parsed.currencyCode,\n unitPriceNet: toNumericString(line.unitPriceNet ?? 0),\n unitPriceGross: toNumericString(line.unitPriceGross ?? 0),\n discountAmount: toNumericString(line.discountAmount ?? 0),\n discountPercent: toNumericString(line.discountPercent ?? 0),\n taxRate: toNumericString(line.taxRate ?? 0),\n taxAmount: toNumericString(line.taxAmount ?? 0),\n totalNetAmount: toNumericString(line.totalNetAmount ?? 0),\n totalGrossAmount: toNumericString(line.totalGrossAmount ?? 0),\n metadata: line.metadata ?? null,\n }),\n );\n }\n }\n\n if (parsed.customFieldSetId) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_invoice,\n recordId: invoiceId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n values: normalizeCustomFieldValues(\n ((parsed as Record<string, unknown>).customFields as Record<string, unknown>) ?? {},\n ),\n });\n }\n },\n ],\n { transaction: true },\n );\n\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"created\",\n entity: invoice,\n identifiers: {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n },\n events: invoiceCrudEvents,\n indexer: { entityType: E.sales.sales_invoice },\n });\n\n await invalidateCrudCache(\n ctx.container,\n \"sales.invoice\",\n {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"created\",\n );\n\n return { invoiceId: invoice.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadInvoiceSnapshot(em, result.invoiceId);\n },\n buildLog: async ({ result, snapshots }) => {\n const after = snapshots.after as InvoiceGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.invoices.create\", \"Create invoice\"),\n resourceKind: \"sales.invoice\",\n resourceId: result.invoiceId,\n tenantId: after.invoice.tenantId,\n organizationId: after.invoice.organizationId,\n snapshotAfter: after,\n payload: {\n undo: { after } satisfies InvoiceUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<InvoiceUndoPayload>(logEntry);\n const after = payload?.after;\n if (!after) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const invoice = await em.findOne(SalesInvoice, { id: after.invoice.id });\n if (!invoice) return;\n ensureOrganizationScope(ctx, invoice.organizationId);\n ensureTenantScope(ctx, invoice.tenantId);\n await em.nativeDelete(SalesInvoiceLine, { invoice: invoice.id });\n em.remove(invoice);\n await em.flush();\n },\n};\n\nconst updateInvoiceCommand: CommandHandler<\n z.infer<typeof invoiceUpdateSchema>,\n { invoiceId: string }\n> = {\n id: \"sales.invoices.update\",\n async prepare(input, ctx) {\n const id = requireId(input);\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadInvoiceSnapshot(em, id);\n if (snapshot) {\n ensureOrganizationScope(ctx, snapshot.invoice.organizationId);\n ensureTenantScope(ctx, snapshot.invoice.tenantId);\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const parsed = invoiceUpdateSchema.parse(rawInput ?? {});\n const id = requireId(parsed);\n ensureOrganizationScope(ctx, parsed.organizationId);\n ensureTenantScope(ctx, parsed.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const invoice = await em.findOneOrFail(SalesInvoice, {\n id,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n deletedAt: null,\n });\n\n const changes = buildChanges(invoice, parsed, [\n \"invoiceNumber\",\n \"statusEntryId\",\n \"status\",\n \"issueDate\",\n \"dueDate\",\n \"currencyCode\",\n \"subtotalNetAmount\",\n \"subtotalGrossAmount\",\n \"discountTotalAmount\",\n \"taxTotalAmount\",\n \"grandTotalNetAmount\",\n \"grandTotalGrossAmount\",\n \"paidTotalAmount\",\n \"outstandingAmount\",\n \"metadata\",\n ]);\n\n if (parsed.statusEntryId !== undefined) {\n invoice.status = await resolveDictionaryEntryValue(em, parsed.statusEntryId ?? null);\n }\n\n Object.assign(invoice, changes);\n invoice.updatedAt = new Date();\n await em.flush();\n\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"updated\",\n entity: invoice,\n identifiers: {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n },\n events: invoiceCrudEvents,\n indexer: { entityType: E.sales.sales_invoice },\n });\n\n await invalidateCrudCache(\n ctx.container,\n \"sales.invoice\",\n {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"updated\",\n );\n\n return { invoiceId: invoice.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadInvoiceSnapshot(em, result.invoiceId);\n },\n buildLog: async ({ result, snapshots }) => {\n const before = snapshots.before as InvoiceGraphSnapshot | undefined;\n const after = snapshots.after as InvoiceGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.invoices.update\", \"Update invoice\"),\n resourceKind: \"sales.invoice\",\n resourceId: result.invoiceId,\n tenantId: after.invoice.tenantId,\n organizationId: after.invoice.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies InvoiceUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<InvoiceUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const invoice = await em.findOne(SalesInvoice, { id: before.invoice.id });\n if (!invoice) return;\n ensureOrganizationScope(ctx, invoice.organizationId);\n ensureTenantScope(ctx, invoice.tenantId);\n invoice.invoiceNumber = before.invoice.invoiceNumber;\n invoice.orderId = before.invoice.orderId;\n invoice.statusEntryId = before.invoice.statusEntryId;\n invoice.status = before.invoice.status;\n invoice.issueDate = before.invoice.issueDate ? new Date(before.invoice.issueDate as string) : null;\n invoice.dueDate = before.invoice.dueDate ? new Date(before.invoice.dueDate as string) : null;\n invoice.currencyCode = before.invoice.currencyCode;\n invoice.subtotalNetAmount = before.invoice.subtotalNetAmount;\n invoice.subtotalGrossAmount = before.invoice.subtotalGrossAmount;\n invoice.discountTotalAmount = before.invoice.discountTotalAmount;\n invoice.taxTotalAmount = before.invoice.taxTotalAmount;\n invoice.grandTotalNetAmount = before.invoice.grandTotalNetAmount;\n invoice.grandTotalGrossAmount = before.invoice.grandTotalGrossAmount;\n invoice.paidTotalAmount = before.invoice.paidTotalAmount;\n invoice.outstandingAmount = before.invoice.outstandingAmount;\n invoice.metadata = before.invoice.metadata;\n invoice.updatedAt = new Date();\n await em.flush();\n },\n};\n\nconst deleteInvoiceCommand: CommandHandler<\n { id: string; organizationId: string; tenantId: string },\n { invoiceId: string }\n> = {\n id: \"sales.invoices.delete\",\n async prepare(input, ctx) {\n const id = requireId(input);\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadInvoiceSnapshot(em, id);\n if (snapshot) {\n ensureOrganizationScope(ctx, snapshot.invoice.organizationId);\n ensureTenantScope(ctx, snapshot.invoice.tenantId);\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const id = requireId(rawInput);\n ensureOrganizationScope(ctx, rawInput.organizationId);\n ensureTenantScope(ctx, rawInput.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const invoice = await em.findOneOrFail(SalesInvoice, {\n id,\n organizationId: rawInput.organizationId,\n tenantId: rawInput.tenantId,\n deletedAt: null,\n });\n invoice.deletedAt = new Date();\n invoice.updatedAt = new Date();\n await em.flush();\n\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"deleted\",\n entity: invoice,\n identifiers: {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n },\n events: invoiceCrudEvents,\n indexer: { entityType: E.sales.sales_invoice },\n });\n\n await invalidateCrudCache(\n ctx.container,\n \"sales.invoice\",\n {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"deleted\",\n );\n\n return { invoiceId: invoice.id };\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as InvoiceGraphSnapshot | undefined;\n if (!before) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.invoices.delete\", \"Delete invoice\"),\n resourceKind: \"sales.invoice\",\n resourceId: before.invoice.id,\n tenantId: before.invoice.tenantId,\n organizationId: before.invoice.organizationId,\n snapshotBefore: before,\n payload: {\n undo: { before } satisfies InvoiceUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<InvoiceUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureOrganizationScope(ctx, before.invoice.organizationId);\n ensureTenantScope(ctx, before.invoice.tenantId);\n const restored = em.create(SalesInvoice, {\n id: before.invoice.id,\n organizationId: before.invoice.organizationId,\n tenantId: before.invoice.tenantId,\n invoiceNumber: before.invoice.invoiceNumber,\n orderId: before.invoice.orderId,\n statusEntryId: before.invoice.statusEntryId,\n status: before.invoice.status,\n issueDate: before.invoice.issueDate ? new Date(before.invoice.issueDate as string) : new Date(),\n dueDate: before.invoice.dueDate ? new Date(before.invoice.dueDate as string) : null,\n currencyCode: before.invoice.currencyCode,\n subtotalNetAmount: before.invoice.subtotalNetAmount,\n subtotalGrossAmount: before.invoice.subtotalGrossAmount,\n discountTotalAmount: before.invoice.discountTotalAmount,\n taxTotalAmount: before.invoice.taxTotalAmount,\n grandTotalNetAmount: before.invoice.grandTotalNetAmount,\n grandTotalGrossAmount: before.invoice.grandTotalGrossAmount,\n paidTotalAmount: before.invoice.paidTotalAmount,\n outstandingAmount: before.invoice.outstandingAmount,\n metadata: before.invoice.metadata,\n customFieldSetId: before.invoice.customFieldSetId,\n deletedAt: null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(restored);\n for (const line of before.lines) {\n em.persist(em.create(SalesInvoiceLine, {\n id: line.id,\n invoice: restored,\n orderLineId: line.orderLineId,\n organizationId: before.invoice.organizationId,\n tenantId: before.invoice.tenantId,\n lineNumber: line.lineNumber,\n kind: line.kind,\n name: line.name,\n sku: line.sku,\n description: line.description,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit,\n normalizedQuantity: line.normalizedQuantity,\n normalizedUnit: line.normalizedUnit,\n uomSnapshot: line.uomSnapshot,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n discountAmount: line.discountAmount,\n discountPercent: line.discountPercent,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n totalNetAmount: line.totalNetAmount,\n totalGrossAmount: line.totalGrossAmount,\n metadata: line.metadata,\n }));\n }\n await em.flush();\n },\n};\n\n// ---------------------------------------------------------------------------\n// Credit Memo CRUD commands\n// ---------------------------------------------------------------------------\n\nconst creditMemoCrudEvents: CrudEventsConfig<SalesCreditMemo> = {\n module: \"sales\",\n entity: \"credit_memo\",\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n};\n\nconst createCreditMemoCommand: CommandHandler<\n CreditMemoCreateInput,\n { creditMemoId: string }\n> = {\n id: \"sales.credit_memos.create\",\n async execute(rawInput, ctx) {\n const generator = ctx.container.resolve(\n \"salesDocumentNumberGenerator\",\n ) as SalesDocumentNumberGenerator;\n const initial = creditMemoCreateSchema.parse(rawInput ?? {});\n const creditMemoNumber =\n typeof initial.creditMemoNumber === \"string\" &&\n initial.creditMemoNumber.trim().length\n ? initial.creditMemoNumber.trim()\n : (\n await generator.generate({\n kind: \"credit_memo\",\n organizationId: initial.organizationId,\n tenantId: initial.tenantId,\n })\n ).number;\n const parsed = creditMemoCreateSchema.parse({ ...initial, creditMemoNumber });\n const ensuredCreditMemoNumber = parsed.creditMemoNumber ?? creditMemoNumber;\n if (!ensuredCreditMemoNumber) {\n throw new CrudHttpError(400, { error: \"Credit memo number is required.\" });\n }\n ensureOrganizationScope(ctx, parsed.organizationId);\n ensureTenantScope(ctx, parsed.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const status = await resolveDictionaryEntryValue(\n em,\n parsed.statusEntryId ?? null,\n );\n\n // Validate orderId belongs to same org/tenant\n if (parsed.orderId) {\n const orderExists = await em.findOne(SalesOrder, {\n id: parsed.orderId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n deletedAt: null,\n });\n if (!orderExists) {\n throw new CrudHttpError(400, { error: \"Referenced order not found in current scope.\" });\n }\n }\n\n // Validate invoiceId belongs to same org/tenant\n if (parsed.invoiceId) {\n const invoiceExists = await em.findOne(SalesInvoice, {\n id: parsed.invoiceId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n deletedAt: null,\n });\n if (!invoiceExists) {\n throw new CrudHttpError(400, { error: \"Referenced invoice not found in current scope.\" });\n }\n }\n\n const creditMemoId = randomUUID();\n const creditMemo = em.create(SalesCreditMemo, {\n id: creditMemoId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n creditMemoNumber: ensuredCreditMemoNumber,\n orderId: parsed.orderId ?? null,\n invoiceId: parsed.invoiceId ?? null,\n statusEntryId: parsed.statusEntryId ?? null,\n status,\n reason: parsed.reason ?? null,\n issueDate: parsed.issueDate ?? new Date(),\n currencyCode: parsed.currencyCode,\n subtotalNetAmount: toNumericString(parsed.subtotalNetAmount ?? 0),\n subtotalGrossAmount: toNumericString(parsed.subtotalGrossAmount ?? 0),\n taxTotalAmount: toNumericString(parsed.taxTotalAmount ?? 0),\n grandTotalNetAmount: toNumericString(parsed.grandTotalNetAmount ?? 0),\n grandTotalGrossAmount: toNumericString(parsed.grandTotalGrossAmount ?? 0),\n metadata: parsed.metadata ?? null,\n customFieldSetId: parsed.customFieldSetId ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n\n // Header + lines + custom-field writes must commit atomically.\n // setRecordCustomFields flushes mid-build, so without a transaction a\n // partial write could persist the header without its lines/custom fields.\n await withAtomicFlush(\n em,\n [\n async () => {\n em.persist(creditMemo);\n\n if (parsed.lines?.length) {\n for (let i = 0; i < parsed.lines.length; i++) {\n const line = parsed.lines[i];\n em.persist(\n em.create(SalesCreditMemoLine, {\n id: randomUUID(),\n creditMemo,\n orderLineId: line.orderLineId ?? null,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n lineNumber: line.lineNumber ?? i + 1,\n name: line.name ?? null,\n sku: line.sku ?? null,\n description: line.description ?? null,\n quantity: toNumericString(line.quantity ?? 0),\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: toNumericString(line.normalizedQuantity ?? 0),\n normalizedUnit: line.normalizedUnit ?? null,\n uomSnapshot: line.uomSnapshot ?? null,\n currencyCode: line.currencyCode ?? parsed.currencyCode,\n unitPriceNet: toNumericString(line.unitPriceNet ?? 0),\n unitPriceGross: toNumericString(line.unitPriceGross ?? 0),\n taxRate: toNumericString(line.taxRate ?? 0),\n taxAmount: toNumericString(line.taxAmount ?? 0),\n totalNetAmount: toNumericString(line.totalNetAmount ?? 0),\n totalGrossAmount: toNumericString(line.totalGrossAmount ?? 0),\n metadata: line.metadata ?? null,\n }),\n );\n }\n }\n\n if (parsed.customFieldSetId) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_credit_memo,\n recordId: creditMemoId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n values: normalizeCustomFieldValues(\n ((parsed as Record<string, unknown>).customFields as Record<string, unknown>) ?? {},\n ),\n });\n }\n },\n ],\n { transaction: true },\n );\n\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"created\",\n entity: creditMemo,\n identifiers: {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n },\n events: creditMemoCrudEvents,\n indexer: { entityType: E.sales.sales_credit_memo },\n });\n\n await invalidateCrudCache(\n ctx.container,\n \"sales.credit_memo\",\n {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"created\",\n );\n\n return { creditMemoId: creditMemo.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadCreditMemoSnapshot(em, result.creditMemoId);\n },\n buildLog: async ({ result, snapshots }) => {\n const after = snapshots.after as CreditMemoGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.credit_memos.create\", \"Create credit memo\"),\n resourceKind: \"sales.credit_memo\",\n resourceId: result.creditMemoId,\n tenantId: after.creditMemo.tenantId,\n organizationId: after.creditMemo.organizationId,\n snapshotAfter: after,\n payload: {\n undo: { after } satisfies CreditMemoUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CreditMemoUndoPayload>(logEntry);\n const after = payload?.after;\n if (!after) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const creditMemo = await em.findOne(SalesCreditMemo, { id: after.creditMemo.id });\n if (!creditMemo) return;\n ensureOrganizationScope(ctx, creditMemo.organizationId);\n ensureTenantScope(ctx, creditMemo.tenantId);\n await em.nativeDelete(SalesCreditMemoLine, { creditMemo: creditMemo.id });\n em.remove(creditMemo);\n await em.flush();\n },\n};\n\nconst updateCreditMemoCommand: CommandHandler<\n z.infer<typeof creditMemoUpdateSchema>,\n { creditMemoId: string }\n> = {\n id: \"sales.credit_memos.update\",\n async prepare(input, ctx) {\n const id = requireId(input);\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadCreditMemoSnapshot(em, id);\n if (snapshot) {\n ensureOrganizationScope(ctx, snapshot.creditMemo.organizationId);\n ensureTenantScope(ctx, snapshot.creditMemo.tenantId);\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const parsed = creditMemoUpdateSchema.parse(rawInput ?? {});\n const id = requireId(parsed);\n ensureOrganizationScope(ctx, parsed.organizationId);\n ensureTenantScope(ctx, parsed.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const creditMemo = await em.findOneOrFail(SalesCreditMemo, {\n id,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n deletedAt: null,\n });\n\n const changes = buildChanges(creditMemo, parsed, [\n \"creditMemoNumber\",\n \"statusEntryId\",\n \"status\",\n \"reason\",\n \"issueDate\",\n \"currencyCode\",\n \"subtotalNetAmount\",\n \"subtotalGrossAmount\",\n \"taxTotalAmount\",\n \"grandTotalNetAmount\",\n \"grandTotalGrossAmount\",\n \"metadata\",\n ]);\n\n if (parsed.statusEntryId !== undefined) {\n creditMemo.status = await resolveDictionaryEntryValue(em, parsed.statusEntryId ?? null);\n }\n\n Object.assign(creditMemo, changes);\n creditMemo.updatedAt = new Date();\n await em.flush();\n\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"updated\",\n entity: creditMemo,\n identifiers: {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n },\n events: creditMemoCrudEvents,\n indexer: { entityType: E.sales.sales_credit_memo },\n });\n\n await invalidateCrudCache(\n ctx.container,\n \"sales.credit_memo\",\n {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"updated\",\n );\n\n return { creditMemoId: creditMemo.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadCreditMemoSnapshot(em, result.creditMemoId);\n },\n buildLog: async ({ result, snapshots }) => {\n const before = snapshots.before as CreditMemoGraphSnapshot | undefined;\n const after = snapshots.after as CreditMemoGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.credit_memos.update\", \"Update credit memo\"),\n resourceKind: \"sales.credit_memo\",\n resourceId: result.creditMemoId,\n tenantId: after.creditMemo.tenantId,\n organizationId: after.creditMemo.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies CreditMemoUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CreditMemoUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const creditMemo = await em.findOne(SalesCreditMemo, { id: before.creditMemo.id });\n if (!creditMemo) return;\n ensureOrganizationScope(ctx, creditMemo.organizationId);\n ensureTenantScope(ctx, creditMemo.tenantId);\n creditMemo.creditMemoNumber = before.creditMemo.creditMemoNumber;\n creditMemo.orderId = before.creditMemo.orderId;\n creditMemo.invoiceId = before.creditMemo.invoiceId;\n creditMemo.statusEntryId = before.creditMemo.statusEntryId;\n creditMemo.status = before.creditMemo.status;\n creditMemo.reason = before.creditMemo.reason;\n creditMemo.issueDate = before.creditMemo.issueDate ? new Date(before.creditMemo.issueDate as string) : null;\n creditMemo.currencyCode = before.creditMemo.currencyCode;\n creditMemo.subtotalNetAmount = before.creditMemo.subtotalNetAmount;\n creditMemo.subtotalGrossAmount = before.creditMemo.subtotalGrossAmount;\n creditMemo.taxTotalAmount = before.creditMemo.taxTotalAmount;\n creditMemo.grandTotalNetAmount = before.creditMemo.grandTotalNetAmount;\n creditMemo.grandTotalGrossAmount = before.creditMemo.grandTotalGrossAmount;\n creditMemo.metadata = before.creditMemo.metadata;\n creditMemo.updatedAt = new Date();\n await em.flush();\n },\n};\n\nconst deleteCreditMemoCommand: CommandHandler<\n { id: string; organizationId: string; tenantId: string },\n { creditMemoId: string }\n> = {\n id: \"sales.credit_memos.delete\",\n async prepare(input, ctx) {\n const id = requireId(input);\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadCreditMemoSnapshot(em, id);\n if (snapshot) {\n ensureOrganizationScope(ctx, snapshot.creditMemo.organizationId);\n ensureTenantScope(ctx, snapshot.creditMemo.tenantId);\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const id = requireId(rawInput);\n ensureOrganizationScope(ctx, rawInput.organizationId);\n ensureTenantScope(ctx, rawInput.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const creditMemo = await em.findOneOrFail(SalesCreditMemo, {\n id,\n organizationId: rawInput.organizationId,\n tenantId: rawInput.tenantId,\n deletedAt: null,\n });\n creditMemo.deletedAt = new Date();\n creditMemo.updatedAt = new Date();\n await em.flush();\n\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"deleted\",\n entity: creditMemo,\n identifiers: {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n },\n events: creditMemoCrudEvents,\n indexer: { entityType: E.sales.sales_credit_memo },\n });\n\n await invalidateCrudCache(\n ctx.container,\n \"sales.credit_memo\",\n {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"deleted\",\n );\n\n return { creditMemoId: creditMemo.id };\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as CreditMemoGraphSnapshot | undefined;\n if (!before) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.credit_memos.delete\", \"Delete credit memo\"),\n resourceKind: \"sales.credit_memo\",\n resourceId: before.creditMemo.id,\n tenantId: before.creditMemo.tenantId,\n organizationId: before.creditMemo.organizationId,\n snapshotBefore: before,\n payload: {\n undo: { before } satisfies CreditMemoUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CreditMemoUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureOrganizationScope(ctx, before.creditMemo.organizationId);\n ensureTenantScope(ctx, before.creditMemo.tenantId);\n const restored = em.create(SalesCreditMemo, {\n id: before.creditMemo.id,\n organizationId: before.creditMemo.organizationId,\n tenantId: before.creditMemo.tenantId,\n creditMemoNumber: before.creditMemo.creditMemoNumber,\n orderId: before.creditMemo.orderId,\n invoiceId: before.creditMemo.invoiceId,\n statusEntryId: before.creditMemo.statusEntryId,\n status: before.creditMemo.status,\n reason: before.creditMemo.reason,\n issueDate: before.creditMemo.issueDate ? new Date(before.creditMemo.issueDate as string) : new Date(),\n currencyCode: before.creditMemo.currencyCode,\n subtotalNetAmount: before.creditMemo.subtotalNetAmount,\n subtotalGrossAmount: before.creditMemo.subtotalGrossAmount,\n taxTotalAmount: before.creditMemo.taxTotalAmount,\n grandTotalNetAmount: before.creditMemo.grandTotalNetAmount,\n grandTotalGrossAmount: before.creditMemo.grandTotalGrossAmount,\n metadata: before.creditMemo.metadata,\n customFieldSetId: before.creditMemo.customFieldSetId,\n deletedAt: null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(restored);\n for (const line of before.lines) {\n em.persist(em.create(SalesCreditMemoLine, {\n id: line.id,\n creditMemo: restored,\n orderLineId: line.orderLineId,\n organizationId: before.creditMemo.organizationId,\n tenantId: before.creditMemo.tenantId,\n lineNumber: line.lineNumber,\n name: line.name,\n sku: line.sku,\n description: line.description,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit,\n normalizedQuantity: line.normalizedQuantity,\n normalizedUnit: line.normalizedUnit,\n uomSnapshot: line.uomSnapshot,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n totalNetAmount: line.totalNetAmount,\n totalGrossAmount: line.totalGrossAmount,\n metadata: line.metadata,\n }));\n }\n await em.flush();\n },\n};\n\nregisterCommand(updateQuoteCommand);\nregisterCommand(createQuoteCommand);\nregisterCommand(deleteQuoteCommand);\nregisterCommand(convertQuoteToOrderCommand);\nregisterCommand(updateOrderCommand);\nregisterCommand(createOrderCommand);\nregisterCommand(deleteOrderCommand);\nregisterCommand(orderLineUpsertCommand);\nregisterCommand(orderLineDeleteCommand);\nregisterCommand(quoteLineUpsertCommand);\nregisterCommand(quoteLineDeleteCommand);\nregisterCommand(orderAdjustmentUpsertCommand);\nregisterCommand(orderAdjustmentDeleteCommand);\nregisterCommand(quoteAdjustmentUpsertCommand);\nregisterCommand(quoteAdjustmentDeleteCommand);\nregisterCommand(createInvoiceCommand);\nregisterCommand(updateInvoiceCommand);\nregisterCommand(deleteInvoiceCommand);\nregisterCommand(createCreditMemoCommand);\nregisterCommand(updateCreditMemoCommand);\nregisterCommand(deleteCreditMemoCommand);\n"],
5
- "mappings": "AAEA,SAAS,kBAAkB;AAC3B,SAAS,SAAS;AAClB,SAAS,uBAAuB;AAEhC,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,gBAAgB;AAIzB,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,kCAAkC;AAC3C,SAAS,wCAAwC;AACjD,SAAS,6BAA6B;AACtC,SAAS,6BAA6B;AACtC,SAAS,kCAAkC;AAC3C,SAAS,SAAS;AAClB,SAAS,oBAAoB,6BAA6B;AAC1D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,YAAY,uBAAuB;AAC5C,SAAS,wBAAwB;AACjC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;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kBAAkB;AAClC,gBAAgB,0BAA0B;AAC1C,gBAAgB,kBAAkB;AAClC,gBAAgB,kBAAkB;AAClC,gBAAgB,kBAAkB;AAClC,gBAAgB,sBAAsB;AACtC,gBAAgB,sBAAsB;AACtC,gBAAgB,sBAAsB;AACtC,gBAAgB,sBAAsB;AACtC,gBAAgB,4BAA4B;AAC5C,gBAAgB,4BAA4B;AAC5C,gBAAgB,4BAA4B;AAC5C,gBAAgB,4BAA4B;AAC5C,gBAAgB,oBAAoB;AACpC,gBAAgB,oBAAoB;AACpC,gBAAgB,oBAAoB;AACpC,gBAAgB,uBAAuB;AACvC,gBAAgB,uBAAuB;AACvC,gBAAgB,uBAAuB;",
4
+ "sourcesContent": ["// @ts-nocheck\n\nimport { randomUUID } from \"crypto\";\nimport { z } from \"zod\";\nimport { registerCommand } from \"@open-mercato/shared/lib/commands\";\nimport type { CommandHandler } from \"@open-mercato/shared/lib/commands\";\nimport { withAtomicFlush } from \"@open-mercato/shared/lib/commands/flush\";\nimport {\n buildChanges,\n emitCrudSideEffects,\n requireId,\n type CrudEventsConfig,\n} from \"@open-mercato/shared/lib/commands/helpers\";\nimport { LockMode } from \"@mikro-orm/core\";\nimport type { EntityManager } from \"@mikro-orm/postgresql\";\nimport type { EventBus } from \"@open-mercato/events\";\nimport type { DataEngine } from \"@open-mercato/shared/lib/data/engine\";\nimport { CrudHttpError } from \"@open-mercato/shared/lib/crud/errors\";\nimport {\n deriveResourceFromCommandId,\n invalidateCrudCache,\n} from \"@open-mercato/shared/lib/crud/cache\";\nimport { resolveTranslations } from \"@open-mercato/shared/lib/i18n/server\";\nimport { resolveNotificationService } from \"../../notifications/lib/notificationService\";\nimport { buildFeatureNotificationFromType } from \"../../notifications/lib/notificationBuilder\";\nimport { setRecordCustomFields } from \"@open-mercato/core/modules/entities/lib/helpers\";\nimport { loadCustomFieldValues } from \"@open-mercato/shared/lib/crud/custom-fields\";\nimport { normalizeCustomFieldValues } from \"@open-mercato/shared/lib/custom-fields/normalize\";\nimport { E } from \"#generated/entities.ids.generated\";\nimport { findWithDecryption, findOneWithDecryption } from \"@open-mercato/shared/lib/encryption/find\";\nimport {\n SalesQuote,\n SalesQuoteLine,\n SalesQuoteAdjustment,\n SalesOrder,\n SalesOrderLine,\n SalesOrderAdjustment,\n SalesShipment,\n SalesShipmentItem,\n SalesPayment,\n SalesPaymentAllocation,\n SalesInvoice,\n SalesInvoiceLine,\n SalesCreditMemo,\n SalesCreditMemoLine,\n SalesDocumentAddress,\n SalesNote,\n SalesChannel,\n SalesShippingMethod,\n SalesDeliveryWindow,\n SalesPaymentMethod,\n SalesDocumentTag,\n SalesDocumentTagAssignment,\n type SalesLineKind,\n type SalesAdjustmentKind,\n type SalesSettings,\n} from \"../data/entities\";\nimport {\n CatalogProduct,\n CatalogProductUnitConversion,\n} from \"../../catalog/data/entities\";\nimport { Dictionary, DictionaryEntry } from \"../../dictionaries/data/entities\";\nimport { CustomFieldValue } from \"@open-mercato/core/modules/entities/data/entities\";\nimport {\n CustomerAddress,\n CustomerEntity,\n CustomerPersonProfile,\n} from \"../../customers/data/entities\";\nimport {\n enforceAdjustmentSign,\n validateReturnAdjustmentWithinRemaining,\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_GROSS_MESSAGE,\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_NET_MESSAGE,\n quoteCreateSchema,\n quoteLineCreateSchema,\n quoteAdjustmentCreateSchema,\n orderCreateSchema,\n orderLineCreateSchema,\n orderAdjustmentCreateSchema,\n invoiceCreateSchema,\n invoiceUpdateSchema,\n creditMemoCreateSchema,\n creditMemoUpdateSchema,\n customerSnapshotSchema,\n type QuoteCreateInput,\n type QuoteLineCreateInput,\n type QuoteAdjustmentCreateInput,\n type OrderCreateInput,\n type OrderLineCreateInput,\n type OrderAdjustmentCreateInput,\n type InvoiceCreateInput,\n type CreditMemoCreateInput,\n} from \"../data/validators\";\nimport {\n ensureOrganizationScope,\n ensureTenantScope,\n extractUndoPayload,\n toNumericString,\n enforceSalesDocumentOptimisticLock,\n SALES_RESOURCE_KIND_ORDER,\n SALES_RESOURCE_KIND_QUOTE,\n} from \"./shared\";\nimport {\n loadShipmentSnapshot,\n restoreShipmentSnapshot,\n type ShipmentSnapshot,\n} from \"./shipments\";\nimport {\n loadPaymentSnapshot,\n restorePaymentSnapshot,\n type PaymentSnapshot,\n} from \"./payments\";\nimport type { SalesCalculationService } from \"../services/salesCalculationService\";\nimport type { TaxCalculationService } from \"../services/taxCalculationService\";\nimport type {\n PaymentMethodContext,\n ShippingMethodContext,\n} from \"../lib/providers\";\nimport {\n type SalesLineSnapshot,\n type SalesLineUomSnapshot,\n type SalesAdjustmentDraft,\n type SalesLineCalculationResult,\n type SalesDocumentCalculationResult,\n} from \"../lib/types\";\nimport { resolveDictionaryEntryValue } from \"../lib/dictionaries\";\nimport { resolveStatusEntryIdByValue } from \"../lib/statusHelpers\";\nimport { SalesDocumentNumberGenerator } from \"../services/salesDocumentNumberGenerator\";\nimport { loadSalesSettings } from \"./settings\";\nimport { notificationTypes } from \"../notifications\";\nimport {\n REFERENCE_UNIT_CODES,\n canonicalizeUnitCode,\n toUnitLookupKey,\n} from \"@open-mercato/shared/lib/units/unitCodes\";\nimport type { AuthContext } from \"@open-mercato/shared/lib/auth/server\";\nimport type { TranslateWithFallbackFn } from \"@open-mercato/shared/lib/i18n/translate\";\n\n// CRUD events configuration for workflow triggers\nconst orderCrudEvents: CrudEventsConfig<SalesOrder> = {\n module: \"sales\",\n entity: \"order\",\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n};\n\nconst quoteCrudEvents: CrudEventsConfig<SalesQuote> = {\n module: \"sales\",\n entity: \"quote\",\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 DocumentAddressSnapshot = {\n id: string;\n organizationId: string;\n tenantId: string;\n documentId: string;\n documentKind: \"order\" | \"quote\";\n customerAddressId: string | null;\n name: string | null;\n purpose: string | null;\n companyName: string | null;\n addressLine1: string;\n addressLine2: string | null;\n city: string | null;\n region: string | null;\n postalCode: string | null;\n country: string | null;\n buildingNumber: string | null;\n flatNumber: string | null;\n latitude: number | null;\n longitude: number | null;\n};\n\ntype NoteSnapshot = {\n id: string;\n organizationId: string;\n tenantId: string;\n contextType: \"order\" | \"quote\";\n contextId: string;\n orderId: string | null;\n quoteId: string | null;\n body: string;\n authorUserId: string | null;\n appearanceIcon: string | null;\n appearanceColor: string | null;\n};\n\ntype TagAssignmentSnapshot = {\n id: string;\n tagId: string;\n organizationId: string;\n tenantId: string;\n documentId: string;\n documentKind: \"order\" | \"quote\";\n};\n\ntype QuoteGraphSnapshot = {\n quote: {\n id: string;\n organizationId: string;\n tenantId: string;\n quoteNumber: string;\n statusEntryId: string | null;\n status: string | null;\n customerEntityId: string | null;\n customerContactId: string | null;\n customerSnapshot: Record<string, unknown> | null;\n billingAddressId: string | null;\n shippingAddressId: string | null;\n billingAddressSnapshot: Record<string, unknown> | null;\n shippingAddressSnapshot: Record<string, unknown> | null;\n currencyCode: string;\n validFrom: string | null;\n validUntil: string | null;\n comments: string | null;\n taxInfo: Record<string, unknown> | null;\n shippingMethodId: string | null;\n shippingMethodCode: string | null;\n deliveryWindowId: string | null;\n deliveryWindowCode: string | null;\n paymentMethodId: string | null;\n paymentMethodCode: string | null;\n channelId: string | null;\n shippingMethodSnapshot: Record<string, unknown> | null;\n deliveryWindowSnapshot: Record<string, unknown> | null;\n paymentMethodSnapshot: Record<string, unknown> | null;\n metadata: Record<string, unknown> | null;\n customFieldSetId: string | null;\n customFields: Record<string, unknown> | null;\n subtotalNetAmount: string;\n subtotalGrossAmount: string;\n discountTotalAmount: string;\n taxTotalAmount: string;\n grandTotalNetAmount: string;\n grandTotalGrossAmount: string;\n totalsSnapshot: Record<string, unknown> | null;\n lineItemCount: number;\n };\n lines: QuoteLineSnapshot[];\n adjustments: QuoteAdjustmentSnapshot[];\n addresses: DocumentAddressSnapshot[];\n notes: NoteSnapshot[];\n tags: TagAssignmentSnapshot[];\n};\n\ntype QuoteLineSnapshot = {\n id: string;\n lineNumber: number;\n kind: string;\n statusEntryId: string | null;\n status: string | null;\n productId: string | null;\n productVariantId: string | null;\n catalogSnapshot: Record<string, unknown> | null;\n name: string | null;\n description: string | null;\n comment: string | null;\n quantity: string;\n quantityUnit: string | null;\n normalizedQuantity: string;\n normalizedUnit: string | null;\n uomSnapshot: SalesLineUomSnapshot | null;\n currencyCode: string;\n unitPriceNet: string;\n unitPriceGross: string;\n discountAmount: string;\n discountPercent: string;\n taxRate: string;\n taxAmount: string;\n totalNetAmount: string;\n totalGrossAmount: string;\n configuration: Record<string, unknown> | null;\n promotionCode: string | null;\n promotionSnapshot: Record<string, unknown> | null;\n metadata: Record<string, unknown> | null;\n customFieldSetId: string | null;\n customFields: Record<string, unknown> | null;\n};\n\ntype QuoteAdjustmentSnapshot = {\n id: string;\n scope: \"order\" | \"line\";\n kind: string;\n code: string | null;\n label: string | null;\n calculatorKey: string | null;\n promotionId: string | null;\n rate: string;\n amountNet: string;\n amountGross: string;\n currencyCode: string | null;\n metadata: Record<string, unknown> | null;\n position: number;\n quoteLineId: string | null;\n customFields: Record<string, unknown> | null;\n};\n\ntype OrderGraphSnapshot = {\n order: {\n id: string;\n organizationId: string;\n tenantId: string;\n orderNumber: string;\n statusEntryId: string | null;\n status: string | null;\n fulfillmentStatusEntryId: string | null;\n fulfillmentStatus: string | null;\n paymentStatusEntryId: string | null;\n paymentStatus: string | null;\n customerEntityId: string | null;\n customerContactId: string | null;\n customerSnapshot: Record<string, unknown> | null;\n billingAddressId: string | null;\n shippingAddressId: string | null;\n billingAddressSnapshot: Record<string, unknown> | null;\n shippingAddressSnapshot: Record<string, unknown> | null;\n currencyCode: string;\n exchangeRate: string | null;\n taxStrategyKey: string | null;\n discountStrategyKey: string | null;\n taxInfo: Record<string, unknown> | null;\n shippingMethodId: string | null;\n shippingMethodCode: string | null;\n deliveryWindowId: string | null;\n deliveryWindowCode: string | null;\n paymentMethodId: string | null;\n paymentMethodCode: string | null;\n channelId: string | null;\n placedAt: string | null;\n expectedDeliveryAt: string | null;\n dueAt: string | null;\n comments: string | null;\n internalNotes: string | null;\n shippingMethodSnapshot: Record<string, unknown> | null;\n deliveryWindowSnapshot: Record<string, unknown> | null;\n paymentMethodSnapshot: Record<string, unknown> | null;\n metadata: Record<string, unknown> | null;\n customFieldSetId: string | null;\n customFields: Record<string, unknown> | null;\n subtotalNetAmount: string;\n subtotalGrossAmount: string;\n discountTotalAmount: string;\n taxTotalAmount: string;\n shippingNetAmount: string;\n shippingGrossAmount: string;\n surchargeTotalAmount: string;\n grandTotalNetAmount: string;\n grandTotalGrossAmount: string;\n paidTotalAmount: string;\n refundedTotalAmount: string;\n outstandingAmount: string;\n totalsSnapshot: Record<string, unknown> | null;\n lineItemCount: number;\n };\n lines: OrderLineSnapshot[];\n adjustments: OrderAdjustmentSnapshot[];\n addresses: DocumentAddressSnapshot[];\n notes: NoteSnapshot[];\n tags: TagAssignmentSnapshot[];\n shipments: ShipmentSnapshot[];\n payments: PaymentSnapshot[];\n};\n\ntype OrderLineSnapshot = {\n id: string;\n lineNumber: number;\n kind: string;\n statusEntryId: string | null;\n status: string | null;\n productId: string | null;\n productVariantId: string | null;\n catalogSnapshot: Record<string, unknown> | null;\n name: string | null;\n description: string | null;\n comment: string | null;\n quantity: string;\n quantityUnit: string | null;\n normalizedQuantity: string;\n normalizedUnit: string | null;\n uomSnapshot: SalesLineUomSnapshot | null;\n reservedQuantity: string;\n fulfilledQuantity: string;\n invoicedQuantity: string;\n returnedQuantity: string;\n currencyCode: string;\n unitPriceNet: string;\n unitPriceGross: string;\n discountAmount: string;\n discountPercent: string;\n taxRate: string;\n taxAmount: string;\n totalNetAmount: string;\n totalGrossAmount: string;\n configuration: Record<string, unknown> | null;\n promotionCode: string | null;\n promotionSnapshot: Record<string, unknown> | null;\n metadata: Record<string, unknown> | null;\n customFieldSetId: string | null;\n customFields: Record<string, unknown> | null;\n};\n\ntype OrderAdjustmentSnapshot = {\n id: string;\n scope: \"order\" | \"line\";\n kind: string;\n code: string | null;\n label: string | null;\n calculatorKey: string | null;\n promotionId: string | null;\n rate: string;\n amountNet: string;\n amountGross: string;\n currencyCode: string | null;\n metadata: Record<string, unknown> | null;\n position: number;\n orderLineId: string | null;\n customFields: Record<string, unknown> | null;\n};\n\ntype OrderUndoPayload = {\n before?: OrderGraphSnapshot | null;\n after?: OrderGraphSnapshot | null;\n};\n\ntype QuoteUndoPayload = {\n before?: QuoteGraphSnapshot | null;\n after?: QuoteGraphSnapshot | null;\n};\n\ntype QuoteConvertUndoPayload = {\n quote?: QuoteGraphSnapshot | null;\n order?: OrderGraphSnapshot | null;\n};\n\ntype InvoiceGraphSnapshot = {\n invoice: {\n id: string;\n organizationId: string;\n tenantId: string;\n invoiceNumber: string;\n orderId: string | null;\n statusEntryId: string | null;\n status: string | null;\n issueDate: string | Date | null;\n dueDate: string | Date | null;\n currencyCode: string;\n subtotalNetAmount: string;\n subtotalGrossAmount: string;\n discountTotalAmount: string;\n taxTotalAmount: string;\n grandTotalNetAmount: string;\n grandTotalGrossAmount: string;\n paidTotalAmount: string;\n outstandingAmount: string;\n metadata: Record<string, unknown> | null;\n customFieldSetId: string | null;\n customFields: Record<string, unknown> | null;\n };\n lines: InvoiceLineSnapshot[];\n};\n\ntype InvoiceLineSnapshot = {\n id: string;\n orderLineId: string | null;\n lineNumber: number;\n kind: string;\n name: string | null;\n sku: string | null;\n description: string | null;\n quantity: string;\n quantityUnit: string | null;\n normalizedQuantity: string;\n normalizedUnit: string | null;\n uomSnapshot: Record<string, unknown> | null;\n currencyCode: string;\n unitPriceNet: string;\n unitPriceGross: string;\n discountAmount: string;\n discountPercent: string;\n taxRate: string;\n taxAmount: string;\n totalNetAmount: string;\n totalGrossAmount: string;\n metadata: Record<string, unknown> | null;\n};\n\ntype CreditMemoGraphSnapshot = {\n creditMemo: {\n id: string;\n organizationId: string;\n tenantId: string;\n creditMemoNumber: string;\n orderId: string | null;\n invoiceId: string | null;\n statusEntryId: string | null;\n status: string | null;\n reason: string | null;\n issueDate: string | Date | null;\n currencyCode: string;\n subtotalNetAmount: string;\n subtotalGrossAmount: string;\n taxTotalAmount: string;\n grandTotalNetAmount: string;\n grandTotalGrossAmount: string;\n metadata: Record<string, unknown> | null;\n customFieldSetId: string | null;\n customFields: Record<string, unknown> | null;\n };\n lines: CreditMemoLineSnapshot[];\n};\n\ntype CreditMemoLineSnapshot = {\n id: string;\n orderLineId: string | null;\n lineNumber: number;\n name: string | null;\n sku: string | null;\n description: string | null;\n quantity: string;\n quantityUnit: string | null;\n normalizedQuantity: string;\n normalizedUnit: string | null;\n uomSnapshot: Record<string, unknown> | null;\n currencyCode: string;\n unitPriceNet: string;\n unitPriceGross: string;\n taxRate: string;\n taxAmount: string;\n totalNetAmount: string;\n totalGrossAmount: string;\n metadata: Record<string, unknown> | null;\n};\n\ntype InvoiceUndoPayload = {\n before?: InvoiceGraphSnapshot | null;\n after?: InvoiceGraphSnapshot | null;\n};\n\ntype CreditMemoUndoPayload = {\n before?: CreditMemoGraphSnapshot | null;\n after?: CreditMemoGraphSnapshot | null;\n};\n\nconst currencyCodeSchema = z\n .string()\n .trim()\n .toUpperCase()\n .regex(/^[A-Z]{3}$/, { message: \"currency_code_invalid\" });\n\nconst dateOnlySchema = z\n .string()\n .trim()\n .regex(/^\\d{4}-\\d{2}-\\d{2}$/, { message: \"invalid_date\" })\n .refine((value) => !Number.isNaN(new Date(value).getTime()), {\n message: \"invalid_date\",\n });\n\nconst addressSnapshotSchema = z\n .record(z.string(), z.unknown())\n .nullable()\n .optional();\n\nexport const documentUpdateSchema = z\n .object({\n id: z.string().uuid(),\n customerEntityId: z.string().uuid().nullable().optional(),\n customerContactId: z.string().uuid().nullable().optional(),\n customerSnapshot: customerSnapshotSchema.nullable().optional(),\n metadata: z.record(z.string(), z.unknown()).nullable().optional(),\n customerReference: z.string().nullable().optional(),\n externalReference: z.string().nullable().optional(),\n comment: z.string().nullable().optional(),\n orderNumber: z.string().trim().min(1).max(191).optional(),\n quoteNumber: z.string().trim().min(1).max(191).optional(),\n currencyCode: currencyCodeSchema.optional(),\n channelId: z.string().uuid().nullable().optional(),\n statusEntryId: z.string().uuid().nullable().optional(),\n placedAt: z.union([dateOnlySchema, z.null()]).optional(),\n expectedDeliveryAt: z.union([dateOnlySchema, z.null()]).optional(),\n shippingAddressId: z.string().uuid().nullable().optional(),\n billingAddressId: z.string().uuid().nullable().optional(),\n shippingAddressSnapshot: addressSnapshotSchema,\n billingAddressSnapshot: addressSnapshotSchema,\n shippingMethodId: z.string().uuid().nullable().optional(),\n shippingMethodCode: z.string().nullable().optional(),\n shippingMethodSnapshot: z\n .record(z.string(), z.unknown())\n .nullable()\n .optional(),\n paymentMethodId: z.string().uuid().nullable().optional(),\n paymentMethodCode: z.string().nullable().optional(),\n paymentMethodSnapshot: z\n .record(z.string(), z.unknown())\n .nullable()\n .optional(),\n tags: z.array(z.string().uuid()).optional(),\n customFields: z.record(z.string(), z.unknown()).optional(),\n customFieldSetId: z.string().uuid().nullable().optional(),\n })\n .refine(\n (input) =>\n typeof input.currencyCode === \"string\" ||\n input.placedAt !== undefined ||\n input.expectedDeliveryAt !== undefined ||\n input.channelId !== undefined ||\n input.statusEntryId !== undefined ||\n input.shippingAddressId !== undefined ||\n input.billingAddressId !== undefined ||\n input.customerEntityId !== undefined ||\n input.customerContactId !== undefined ||\n input.customerSnapshot !== undefined ||\n input.metadata !== undefined ||\n input.customerReference !== undefined ||\n input.externalReference !== undefined ||\n input.comment !== undefined ||\n input.orderNumber !== undefined ||\n input.quoteNumber !== undefined ||\n input.shippingAddressSnapshot !== undefined ||\n input.billingAddressSnapshot !== undefined ||\n input.shippingMethodId !== undefined ||\n input.shippingMethodCode !== undefined ||\n input.shippingMethodSnapshot !== undefined ||\n input.paymentMethodId !== undefined ||\n input.paymentMethodCode !== undefined ||\n input.paymentMethodSnapshot !== undefined ||\n input.tags !== undefined ||\n input.customFields !== undefined ||\n input.customFieldSetId !== undefined,\n { message: \"update_payload_empty\" },\n );\n\nexport type DocumentUpdateInput = z.infer<typeof documentUpdateSchema>;\n\ntype DocumentLineCreateInput = QuoteLineCreateInput | OrderLineCreateInput;\ntype DocumentAdjustmentCreateInput =\n | QuoteAdjustmentCreateInput\n | OrderAdjustmentCreateInput;\n\nfunction cloneJson<T>(value: T): T {\n if (value === null || value === undefined) return value;\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\nasync function resolveCustomerSnapshot(\n em: EntityManager,\n organizationId: string,\n tenantId: string,\n customerEntityId?: string | null,\n customerContactId?: string | null,\n): Promise<Record<string, unknown> | null> {\n if (!customerEntityId) return null;\n const customer = await em.findOne(\n CustomerEntity,\n { id: customerEntityId, organizationId, tenantId },\n { populate: [\"personProfile\", \"companyProfile\"] },\n );\n if (!customer) return null;\n\n const contact = customerContactId\n ? await em.findOne(CustomerPersonProfile, {\n id: customerContactId,\n organizationId,\n tenantId,\n })\n : null;\n\n return {\n customer: {\n id: customer.id,\n kind: customer.kind,\n displayName: customer.displayName,\n primaryEmail: customer.primaryEmail ?? null,\n primaryPhone: customer.primaryPhone ?? null,\n personProfile: customer.personProfile\n ? {\n id: customer.personProfile.id,\n firstName: customer.personProfile.firstName ?? null,\n lastName: customer.personProfile.lastName ?? null,\n preferredName: customer.personProfile.preferredName ?? null,\n }\n : null,\n companyProfile: customer.companyProfile\n ? {\n id: customer.companyProfile.id,\n legalName: customer.companyProfile.legalName ?? null,\n brandName: customer.companyProfile.brandName ?? null,\n domain: customer.companyProfile.domain ?? null,\n websiteUrl: customer.companyProfile.websiteUrl ?? null,\n }\n : null,\n },\n contact: contact\n ? {\n id: contact.id,\n firstName: contact.firstName ?? null,\n lastName: contact.lastName ?? null,\n preferredName: contact.preferredName ?? null,\n jobTitle: contact.jobTitle ?? null,\n department: contact.department ?? null,\n }\n : null,\n };\n}\n\nasync function resolveAddressSnapshot(\n em: EntityManager,\n organizationId: string,\n tenantId: string,\n addressId?: string | null,\n): Promise<Record<string, unknown> | null> {\n if (!addressId) return null;\n const address = await em.findOne(CustomerAddress, {\n id: addressId,\n organizationId,\n tenantId,\n });\n if (!address) return null;\n\n return {\n id: address.id,\n name: address.name ?? null,\n purpose: address.purpose ?? null,\n companyName: address.companyName ?? null,\n addressLine1: address.addressLine1,\n addressLine2: address.addressLine2 ?? null,\n buildingNumber: address.buildingNumber ?? null,\n flatNumber: address.flatNumber ?? null,\n city: address.city ?? null,\n region: address.region ?? null,\n postalCode: address.postalCode ?? null,\n country: address.country ?? null,\n latitude: address.latitude ?? null,\n longitude: address.longitude ?? null,\n isPrimary: address.isPrimary,\n };\n}\n\nasync function resolveDocumentReferences(\n em: EntityManager,\n parsed: {\n organizationId: string;\n tenantId: string;\n customerEntityId?: string | null;\n customerContactId?: string | null;\n customerSnapshot?: Record<string, unknown> | null;\n billingAddressId?: string | null;\n shippingAddressId?: string | null;\n billingAddressSnapshot?: Record<string, unknown> | null;\n shippingAddressSnapshot?: Record<string, unknown> | null;\n shippingMethodId?: string | null;\n deliveryWindowId?: string | null;\n paymentMethodId?: string | null;\n },\n): Promise<{\n customerSnapshot: Record<string, unknown> | null;\n billingAddressSnapshot: Record<string, unknown> | null;\n shippingAddressSnapshot: Record<string, unknown> | null;\n shippingMethod: SalesShippingMethod | null;\n deliveryWindow: SalesDeliveryWindow | null;\n paymentMethod: SalesPaymentMethod | null;\n}> {\n const [\n resolvedCustomerSnapshot,\n resolvedBillingSnapshot,\n resolvedShippingSnapshot,\n shippingMethod,\n deliveryWindow,\n paymentMethod,\n ] = await Promise.all([\n parsed.customerSnapshot\n ? Promise.resolve(cloneJson(parsed.customerSnapshot))\n : resolveCustomerSnapshot(\n em,\n parsed.organizationId,\n parsed.tenantId,\n parsed.customerEntityId ?? null,\n parsed.customerContactId ?? null,\n ),\n parsed.billingAddressSnapshot\n ? Promise.resolve(cloneJson(parsed.billingAddressSnapshot))\n : resolveAddressSnapshot(\n em,\n parsed.organizationId,\n parsed.tenantId,\n parsed.billingAddressId ?? null,\n ),\n parsed.shippingAddressSnapshot\n ? Promise.resolve(cloneJson(parsed.shippingAddressSnapshot))\n : resolveAddressSnapshot(\n em,\n parsed.organizationId,\n parsed.tenantId,\n parsed.shippingAddressId ?? null,\n ),\n parsed.shippingMethodId\n ? em.findOne(SalesShippingMethod, {\n id: parsed.shippingMethodId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n })\n : Promise.resolve(null),\n parsed.deliveryWindowId\n ? em.findOne(SalesDeliveryWindow, {\n id: parsed.deliveryWindowId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n })\n : Promise.resolve(null),\n parsed.paymentMethodId\n ? em.findOne(SalesPaymentMethod, {\n id: parsed.paymentMethodId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n })\n : Promise.resolve(null),\n ]);\n\n return {\n customerSnapshot: resolvedCustomerSnapshot\n ? cloneJson(resolvedCustomerSnapshot)\n : null,\n billingAddressSnapshot: resolvedBillingSnapshot\n ? cloneJson(resolvedBillingSnapshot)\n : null,\n shippingAddressSnapshot: resolvedShippingSnapshot\n ? cloneJson(resolvedShippingSnapshot)\n : null,\n shippingMethod: shippingMethod ?? null,\n deliveryWindow: deliveryWindow ?? null,\n paymentMethod: paymentMethod ?? null,\n };\n}\n\nfunction normalizeStatusValue(raw: unknown): string | null {\n if (typeof raw !== \"string\") return null;\n const trimmed = raw.trim();\n return trimmed.length ? trimmed : null;\n}\n\nfunction resolveNoteAuthorFromAuth(auth: AuthContext | null): string | null {\n if (!auth || auth.isApiKey) return null;\n const sub = typeof auth.sub === \"string\" ? auth.sub.trim() : \"\";\n const uuidRegex =\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/;\n return uuidRegex.test(sub) ? sub : null;\n}\n\nfunction resolveStatusChangeActor(auth: AuthContext | null, translate: TranslateWithFallbackFn): string {\n const unknownLabel = translate(\n \"sales.orders.status_change.actor_unknown\",\n \"unknown user\",\n );\n if (!auth) return unknownLabel;\n if (auth.isApiKey) {\n const keyName = typeof auth.keyName === \"string\" ? auth.keyName.trim() : \"\";\n const keyId = typeof auth.keyId === \"string\" ? auth.keyId.trim() : \"\";\n const label =\n keyName || keyId || (typeof auth.sub === \"string\" ? auth.sub : \"\");\n return label\n ? translate(\n \"sales.orders.status_change.actor_api_key\",\n \"API key {name}\",\n { name: label },\n )\n : unknownLabel;\n }\n const email = typeof auth.email === \"string\" ? auth.email.trim() : \"\";\n if (email) return email;\n const sub = typeof auth.sub === \"string\" ? auth.sub.trim() : \"\";\n if (sub) return sub;\n return unknownLabel;\n}\n\nfunction formatStatusLabel(status: string | null, translate: TranslateWithFallbackFn): string {\n if (status && status.trim().length) return status.trim();\n return translate(\"sales.orders.status_change.empty\", \"unset\");\n}\n\nasync function appendOrderStatusChangeNote({\n em,\n order,\n previousStatus,\n auth,\n}: {\n em: EntityManager;\n order: SalesOrder;\n previousStatus: string | null;\n auth: AuthContext | null;\n}): Promise<SalesNote | null> {\n const nextStatus = normalizeStatusValue(order.status);\n if (previousStatus === nextStatus) return null;\n const { translate } = await resolveTranslations();\n const body = translate(\n \"sales.orders.status_change.note\",\n \"Status changed from {from} to {to} by {actor}.\",\n {\n from: formatStatusLabel(previousStatus, translate),\n to: formatStatusLabel(nextStatus, translate),\n actor: resolveStatusChangeActor(auth, translate),\n },\n );\n const note = em.create(SalesNote, {\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n contextType: \"order\",\n contextId: order.id,\n order,\n authorUserId: resolveNoteAuthorFromAuth(auth),\n appearanceIcon: null,\n appearanceColor: null,\n body,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(note);\n return note;\n}\n\nasync function applyDocumentUpdate({\n kind,\n entity,\n input,\n em,\n}: {\n kind: \"order\" | \"quote\";\n entity: SalesOrder | SalesQuote;\n input: DocumentUpdateInput;\n em: EntityManager;\n}): Promise<void> {\n const organizationId = (entity as any).organizationId as string;\n const tenantId = (entity as any).tenantId as string;\n const status =\n typeof (entity as any).status === \"string\" ? (entity as any).status : null;\n const { translate } = await resolveTranslations();\n\n const wantsCustomerChange =\n input.customerEntityId !== undefined ||\n input.customerContactId !== undefined ||\n input.customerSnapshot !== undefined ||\n input.metadata !== undefined;\n const wantsAddressChange =\n input.shippingAddressId !== undefined ||\n input.billingAddressId !== undefined ||\n input.shippingAddressSnapshot !== undefined ||\n input.billingAddressSnapshot !== undefined;\n\n let settings: SalesSettings | null = null;\n if (kind === \"order\" && (wantsCustomerChange || wantsAddressChange)) {\n settings = await loadSalesSettings(em, { organizationId, tenantId });\n }\n\n const guardStatus = (\n allowed: string[] | null | undefined,\n errorKey: string,\n fallback: string,\n ) => {\n if (!Array.isArray(allowed)) return;\n if (allowed.length === 0) {\n throw new CrudHttpError(400, { error: translate(errorKey, fallback) });\n }\n if (!status || !allowed.includes(status)) {\n throw new CrudHttpError(400, { error: translate(errorKey, fallback) });\n }\n };\n\n if (kind === \"order\" && wantsCustomerChange) {\n guardStatus(\n settings?.orderCustomerEditableStatuses ?? null,\n \"sales.orders.edit_customer_blocked\",\n \"Editing the customer is blocked for this status.\",\n );\n }\n if (kind === \"order\" && wantsAddressChange) {\n guardStatus(\n settings?.orderAddressEditableStatuses ?? null,\n \"sales.orders.edit_addresses_blocked\",\n \"Editing addresses is blocked for this status.\",\n );\n }\n\n if (kind === \"order\" && typeof input.orderNumber === \"string\") {\n (entity as SalesOrder).orderNumber = input.orderNumber;\n }\n if (kind === \"quote\" && typeof input.quoteNumber === \"string\") {\n (entity as SalesQuote).quoteNumber = input.quoteNumber;\n }\n\n if (input.customerEntityId !== undefined) {\n entity.customerEntityId = input.customerEntityId ?? null;\n entity.customerSnapshot = await resolveCustomerSnapshot(\n em,\n organizationId,\n tenantId,\n input.customerEntityId,\n input.customerContactId ?? entity.customerContactId ?? null,\n );\n entity.customerContactId = input.customerContactId ?? null;\n entity.billingAddressId = null;\n entity.shippingAddressId = null;\n entity.billingAddressSnapshot = null;\n entity.shippingAddressSnapshot = null;\n }\n if (input.customerContactId !== undefined) {\n entity.customerContactId = input.customerContactId ?? null;\n if (entity.customerEntityId) {\n entity.customerSnapshot = await resolveCustomerSnapshot(\n em,\n organizationId,\n tenantId,\n entity.customerEntityId,\n input.customerContactId,\n );\n }\n }\n if (input.customerSnapshot !== undefined) {\n entity.customerSnapshot = input.customerSnapshot ?? null;\n }\n if (input.metadata !== undefined) {\n entity.metadata = input.metadata ?? null;\n }\n if (input.externalReference !== undefined) {\n const normalized =\n typeof input.externalReference === \"string\"\n ? input.externalReference.trim()\n : \"\";\n entity.externalReference = normalized.length ? normalized : null;\n }\n if (input.customerReference !== undefined) {\n const normalized =\n typeof input.customerReference === \"string\"\n ? input.customerReference.trim()\n : \"\";\n entity.customerReference = normalized.length ? normalized : null;\n }\n if (input.comment !== undefined) {\n const normalized =\n typeof input.comment === \"string\" ? input.comment.trim() : \"\";\n entity.comments = normalized.length ? normalized : null;\n }\n if (typeof input.currencyCode === \"string\") {\n entity.currencyCode = input.currencyCode;\n }\n if (input.channelId !== undefined) {\n if (input.channelId === null) {\n entity.channelId = null;\n } else {\n const channel = await em.findOne(SalesChannel, {\n id: input.channelId,\n organizationId,\n tenantId,\n deletedAt: null,\n });\n if (!channel) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.documents.detail.channelInvalid\",\n \"Selected channel could not be found.\",\n ),\n });\n }\n entity.channelId = channel.id;\n }\n }\n if (input.statusEntryId !== undefined) {\n const statusValue = await resolveDictionaryEntryValue(\n em,\n input.statusEntryId,\n { tenantId },\n );\n if (input.statusEntryId && !statusValue) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.documents.detail.statusInvalid\",\n \"Selected status could not be found.\",\n ),\n });\n }\n (entity as any).statusEntryId = input.statusEntryId ?? null;\n (entity as any).status = statusValue;\n }\n if (input.placedAt !== undefined) {\n if (input.placedAt === null) {\n entity.placedAt = null;\n } else {\n const parsed = new Date(input.placedAt);\n entity.placedAt = Number.isNaN(parsed.getTime())\n ? entity.placedAt\n : parsed;\n }\n }\n if (\n input.expectedDeliveryAt !== undefined &&\n \"expectedDeliveryAt\" in entity\n ) {\n if (input.expectedDeliveryAt === null) {\n (entity as SalesOrder).expectedDeliveryAt = null;\n } else {\n const parsed = new Date(input.expectedDeliveryAt);\n (entity as SalesOrder).expectedDeliveryAt = Number.isNaN(parsed.getTime())\n ? (entity as SalesOrder).expectedDeliveryAt\n : parsed;\n }\n }\n if (input.shippingAddressId !== undefined) {\n entity.shippingAddressId = input.shippingAddressId ?? null;\n if (input.shippingAddressSnapshot === undefined) {\n entity.shippingAddressSnapshot = await resolveAddressSnapshot(\n em,\n organizationId,\n tenantId,\n input.shippingAddressId,\n );\n }\n }\n if (input.billingAddressId !== undefined) {\n entity.billingAddressId = input.billingAddressId ?? null;\n if (input.billingAddressSnapshot === undefined) {\n entity.billingAddressSnapshot = await resolveAddressSnapshot(\n em,\n organizationId,\n tenantId,\n input.billingAddressId,\n );\n }\n }\n if (input.shippingAddressSnapshot !== undefined) {\n entity.shippingAddressSnapshot = input.shippingAddressSnapshot ?? null;\n }\n if (input.billingAddressSnapshot !== undefined) {\n entity.billingAddressSnapshot = input.billingAddressSnapshot ?? null;\n }\n if (\n input.shippingMethodId !== undefined ||\n input.shippingMethodSnapshot !== undefined ||\n input.shippingMethodCode !== undefined\n ) {\n let shippingMethod: SalesShippingMethod | null = null;\n if (input.shippingMethodId) {\n shippingMethod = await em.findOne(SalesShippingMethod, {\n id: input.shippingMethodId,\n organizationId,\n tenantId,\n deletedAt: null,\n });\n if (!shippingMethod) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.documents.detail.shippingMethodInvalid\",\n \"Selected shipping method could not be found.\",\n ),\n });\n }\n }\n (entity as any).shippingMethodId = input.shippingMethodId ?? null;\n (entity as any).shippingMethod = shippingMethod ?? null;\n (entity as any).shippingMethodCode =\n input.shippingMethodCode ?? shippingMethod?.code ?? null;\n if (input.shippingMethodSnapshot !== undefined) {\n (entity as any).shippingMethodSnapshot =\n input.shippingMethodSnapshot ?? null;\n } else {\n (entity as any).shippingMethodSnapshot = shippingMethod\n ? {\n id: shippingMethod.id,\n code: shippingMethod.code,\n name: shippingMethod.name,\n description: shippingMethod.description ?? null,\n carrierCode: shippingMethod.carrierCode ?? null,\n providerKey: shippingMethod.providerKey ?? null,\n serviceLevel: shippingMethod.serviceLevel ?? null,\n estimatedTransitDays: shippingMethod.estimatedTransitDays ?? null,\n baseRateNet: shippingMethod.baseRateNet,\n baseRateGross: shippingMethod.baseRateGross,\n currencyCode: shippingMethod.currencyCode ?? null,\n metadata: shippingMethod.metadata\n ? cloneJson(shippingMethod.metadata)\n : null,\n providerSettings:\n shippingMethod.metadata &&\n typeof shippingMethod.metadata === \"object\"\n ? cloneJson(\n (shippingMethod.metadata as Record<string, unknown>)\n .providerSettings ?? null,\n )\n : null,\n }\n : null;\n }\n }\n if (\n input.paymentMethodId !== undefined ||\n input.paymentMethodSnapshot !== undefined ||\n input.paymentMethodCode !== undefined\n ) {\n let paymentMethod: SalesPaymentMethod | null = null;\n if (input.paymentMethodId) {\n paymentMethod = await em.findOne(SalesPaymentMethod, {\n id: input.paymentMethodId,\n organizationId,\n tenantId,\n deletedAt: null,\n });\n if (!paymentMethod) {\n throw new CrudHttpError(400, {\n error: translate(\n \"sales.documents.detail.paymentMethodInvalid\",\n \"Selected payment method could not be found.\",\n ),\n });\n }\n }\n (entity as any).paymentMethodId = input.paymentMethodId ?? null;\n (entity as any).paymentMethod = paymentMethod ?? null;\n (entity as any).paymentMethodCode =\n input.paymentMethodCode ?? paymentMethod?.code ?? null;\n if (input.paymentMethodSnapshot !== undefined) {\n (entity as any).paymentMethodSnapshot =\n input.paymentMethodSnapshot ?? null;\n } else {\n (entity as any).paymentMethodSnapshot = paymentMethod\n ? {\n id: paymentMethod.id,\n code: paymentMethod.code,\n name: paymentMethod.name,\n description: paymentMethod.description ?? null,\n providerKey: paymentMethod.providerKey ?? null,\n terms: paymentMethod.terms ?? null,\n metadata: paymentMethod.metadata\n ? cloneJson(paymentMethod.metadata)\n : null,\n providerSettings:\n paymentMethod.metadata &&\n typeof paymentMethod.metadata === \"object\"\n ? cloneJson(\n (paymentMethod.metadata as Record<string, unknown>)\n .providerSettings ?? null,\n )\n : null,\n }\n : null;\n }\n }\n\n if (input.tags !== undefined) {\n await syncSalesDocumentTags(em, {\n documentId: entity.id,\n kind,\n organizationId,\n tenantId,\n tagIds: input.tags,\n });\n }\n\n if (input.customFieldSetId !== undefined) {\n (entity as any).customFieldSetId = input.customFieldSetId ?? null;\n }\n\n if (input.customFields !== undefined) {\n const values =\n input.customFields &&\n typeof input.customFields === \"object\" &&\n !Array.isArray(input.customFields)\n ? (input.customFields as Record<string, unknown>)\n : {};\n await setRecordCustomFields(em, {\n entityId: kind === \"order\" ? E.sales.sales_order : E.sales.sales_quote,\n recordId: entity.id,\n organizationId,\n tenantId,\n values,\n });\n }\n}\n\nasync function loadQuoteSnapshot(\n em: EntityManager,\n id: string,\n): Promise<QuoteGraphSnapshot | null> {\n const quote = await findOneWithDecryption(em, SalesQuote, { id, deletedAt: null });\n if (!quote) return null;\n const decryptionScope = { tenantId: quote.tenantId, organizationId: quote.organizationId };\n const lines = await findWithDecryption(\n em,\n SalesQuoteLine,\n { quote },\n { orderBy: { lineNumber: \"asc\" } },\n decryptionScope,\n );\n const adjustments = await findWithDecryption(\n em,\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n decryptionScope,\n );\n const [\n addresses,\n notes,\n tags,\n quoteCustomFields,\n lineCustomFields,\n adjustmentCustomFields,\n ] = await Promise.all([\n findWithDecryption(\n em,\n SalesDocumentAddress,\n { documentId: id, documentKind: \"quote\" },\n undefined,\n { tenantId: quote.tenantId, organizationId: quote.organizationId },\n ),\n findWithDecryption(\n em,\n SalesNote,\n { contextType: \"quote\", contextId: id },\n undefined,\n { tenantId: quote.tenantId, organizationId: quote.organizationId },\n ),\n findWithDecryption(\n em,\n SalesDocumentTagAssignment,\n { documentId: id, documentKind: \"quote\" },\n { populate: [\"tag\"] },\n { tenantId: quote.tenantId, organizationId: quote.organizationId },\n ),\n loadCustomFieldValues({\n em,\n entityId: E.sales.sales_quote,\n recordIds: [quote.id],\n tenantIdByRecord: { [quote.id]: quote.tenantId },\n organizationIdByRecord: { [quote.id]: quote.organizationId },\n }),\n lines.length\n ? loadCustomFieldValues({\n em,\n entityId: E.sales.sales_quote_line,\n recordIds: lines.map((line) => line.id),\n tenantIdByRecord: Object.fromEntries(\n lines.map((line) => [line.id, quote.tenantId]),\n ),\n organizationIdByRecord: Object.fromEntries(\n lines.map((line) => [line.id, quote.organizationId]),\n ),\n })\n : Promise.resolve({}),\n adjustments.length\n ? loadCustomFieldValues({\n em,\n entityId: E.sales.sales_quote_adjustment,\n recordIds: adjustments.map((adj) => adj.id),\n tenantIdByRecord: Object.fromEntries(\n adjustments.map((adj) => [adj.id, quote.tenantId]),\n ),\n organizationIdByRecord: Object.fromEntries(\n adjustments.map((adj) => [adj.id, quote.organizationId]),\n ),\n })\n : Promise.resolve({}),\n ]);\n const addressSnapshots: DocumentAddressSnapshot[] = addresses.map(\n (entry) => ({\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n documentId: entry.documentId,\n documentKind: \"quote\",\n customerAddressId: entry.customerAddressId ?? null,\n name: entry.name ?? null,\n purpose: entry.purpose ?? null,\n companyName: entry.companyName ?? null,\n addressLine1: entry.addressLine1,\n addressLine2: entry.addressLine2 ?? null,\n city: entry.city ?? null,\n region: entry.region ?? null,\n postalCode: entry.postalCode ?? null,\n country: entry.country ?? null,\n buildingNumber: entry.buildingNumber ?? null,\n flatNumber: entry.flatNumber ?? null,\n latitude: entry.latitude ?? null,\n longitude: entry.longitude ?? null,\n }),\n );\n const noteSnapshots: NoteSnapshot[] = notes.map((entry) => ({\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n contextType: entry.contextType as \"order\" | \"quote\",\n contextId: entry.contextId,\n orderId: entry.order\n ? typeof entry.order === \"string\"\n ? entry.order\n : entry.order.id\n : null,\n quoteId: entry.quote\n ? typeof entry.quote === \"string\"\n ? entry.quote\n : entry.quote.id\n : null,\n body: entry.body,\n authorUserId: entry.authorUserId ?? null,\n appearanceIcon: entry.appearanceIcon ?? null,\n appearanceColor: entry.appearanceColor ?? null,\n }));\n const tagSnapshots: TagAssignmentSnapshot[] = tags\n .map((assignment) => {\n const tagId =\n typeof assignment.tag === \"string\"\n ? assignment.tag\n : (assignment.tag?.id ?? (assignment as any)?.tag_id ?? null);\n if (!tagId) return null;\n return {\n id: assignment.id,\n tagId,\n organizationId: assignment.organizationId,\n tenantId: assignment.tenantId,\n documentId: assignment.documentId,\n documentKind: \"quote\",\n };\n })\n .filter((entry): entry is TagAssignmentSnapshot => !!entry);\n\n return {\n quote: {\n id: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteNumber: quote.quoteNumber,\n statusEntryId: quote.statusEntryId ?? null,\n status: quote.status ?? null,\n customerEntityId: quote.customerEntityId ?? null,\n customerContactId: quote.customerContactId ?? null,\n customerSnapshot: quote.customerSnapshot\n ? cloneJson(quote.customerSnapshot)\n : null,\n billingAddressId: quote.billingAddressId ?? null,\n shippingAddressId: quote.shippingAddressId ?? null,\n billingAddressSnapshot: quote.billingAddressSnapshot\n ? cloneJson(quote.billingAddressSnapshot)\n : null,\n shippingAddressSnapshot: quote.shippingAddressSnapshot\n ? cloneJson(quote.shippingAddressSnapshot)\n : null,\n currencyCode: quote.currencyCode,\n validFrom: quote.validFrom ? quote.validFrom.toISOString() : null,\n validUntil: quote.validUntil ? quote.validUntil.toISOString() : null,\n comments: quote.comments ?? null,\n taxInfo: quote.taxInfo ? cloneJson(quote.taxInfo) : null,\n shippingMethodId: quote.shippingMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n deliveryWindowId: quote.deliveryWindowId ?? null,\n deliveryWindowCode: quote.deliveryWindowCode ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n channelId: quote.channelId ?? null,\n shippingMethodSnapshot: quote.shippingMethodSnapshot\n ? cloneJson(quote.shippingMethodSnapshot)\n : null,\n deliveryWindowSnapshot: quote.deliveryWindowSnapshot\n ? cloneJson(quote.deliveryWindowSnapshot)\n : null,\n paymentMethodSnapshot: quote.paymentMethodSnapshot\n ? cloneJson(quote.paymentMethodSnapshot)\n : null,\n metadata: quote.metadata ? cloneJson(quote.metadata) : null,\n customFieldSetId: quote.customFieldSetId ?? null,\n customFields: quoteCustomFields[quote.id]\n ? cloneJson(quoteCustomFields[quote.id])\n : null,\n subtotalNetAmount: quote.subtotalNetAmount,\n subtotalGrossAmount: quote.subtotalGrossAmount,\n discountTotalAmount: quote.discountTotalAmount,\n taxTotalAmount: quote.taxTotalAmount,\n grandTotalNetAmount: quote.grandTotalNetAmount,\n grandTotalGrossAmount: quote.grandTotalGrossAmount,\n totalsSnapshot: quote.totalsSnapshot\n ? cloneJson(quote.totalsSnapshot)\n : null,\n lineItemCount: quote.lineItemCount,\n },\n lines: lines.map((line) => ({\n id: line.id,\n lineNumber: line.lineNumber,\n kind: line.kind,\n statusEntryId: line.statusEntryId ?? null,\n status: line.status ?? null,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: line.normalizedQuantity ?? line.quantity,\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n discountAmount: line.discountAmount,\n discountPercent: line.discountPercent,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n totalNetAmount: line.totalNetAmount,\n totalGrossAmount: line.totalGrossAmount,\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n customFields: lineCustomFields[line.id]\n ? cloneJson(lineCustomFields[line.id])\n : null,\n })),\n adjustments: adjustments.map((adj) => ({\n id: adj.id,\n scope: adj.scope,\n kind: adj.kind,\n code: adj.code ?? null,\n label: adj.label ?? null,\n calculatorKey: adj.calculatorKey ?? null,\n promotionId: adj.promotionId ?? null,\n rate: adj.rate,\n amountNet: adj.amountNet,\n amountGross: adj.amountGross,\n currencyCode: adj.currencyCode ?? null,\n metadata: adj.metadata ? cloneJson(adj.metadata) : null,\n position: adj.position,\n quoteLineId:\n typeof adj.quoteLine === \"string\"\n ? adj.quoteLine\n : (adj.quoteLine?.id ?? null),\n customFields: adjustmentCustomFields[adj.id]\n ? cloneJson(adjustmentCustomFields[adj.id])\n : null,\n })),\n addresses: addressSnapshots,\n notes: noteSnapshots,\n tags: tagSnapshots,\n };\n}\n\nasync function loadOrderSnapshot(\n em: EntityManager,\n id: string,\n): Promise<OrderGraphSnapshot | null> {\n const order = await findOneWithDecryption(em, SalesOrder, { id, deletedAt: null });\n if (!order) return null;\n const decryptionScope = { tenantId: order.tenantId, organizationId: order.organizationId };\n const lines = await findWithDecryption(\n em,\n SalesOrderLine,\n { order },\n { orderBy: { lineNumber: \"asc\" } },\n decryptionScope,\n );\n const adjustments = await findWithDecryption(\n em,\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n decryptionScope,\n );\n const [\n addresses,\n notes,\n tags,\n shipments,\n payments,\n orderCustomFields,\n lineCustomFields,\n adjustmentCustomFields,\n ] = await Promise.all([\n findWithDecryption(\n em,\n SalesDocumentAddress,\n { documentId: id, documentKind: \"order\" },\n undefined,\n { tenantId: order.tenantId, organizationId: order.organizationId },\n ),\n findWithDecryption(\n em,\n SalesNote,\n { contextType: \"order\", contextId: id },\n undefined,\n { tenantId: order.tenantId, organizationId: order.organizationId },\n ),\n findWithDecryption(\n em,\n SalesDocumentTagAssignment,\n { documentId: id, documentKind: \"order\" },\n { populate: [\"tag\"] },\n { tenantId: order.tenantId, organizationId: order.organizationId },\n ),\n em.find(SalesShipment, { order: order }),\n em.find(SalesPayment, { order: order }),\n loadCustomFieldValues({\n em,\n entityId: E.sales.sales_order,\n recordIds: [order.id],\n tenantIdByRecord: { [order.id]: order.tenantId },\n organizationIdByRecord: { [order.id]: order.organizationId },\n }),\n lines.length\n ? loadCustomFieldValues({\n em,\n entityId: E.sales.sales_order_line,\n recordIds: lines.map((line) => line.id),\n tenantIdByRecord: Object.fromEntries(\n lines.map((line) => [line.id, order.tenantId]),\n ),\n organizationIdByRecord: Object.fromEntries(\n lines.map((line) => [line.id, order.organizationId]),\n ),\n })\n : Promise.resolve({}),\n adjustments.length\n ? loadCustomFieldValues({\n em,\n entityId: E.sales.sales_order_adjustment,\n recordIds: adjustments.map((adj) => adj.id),\n tenantIdByRecord: Object.fromEntries(\n adjustments.map((adj) => [adj.id, order.tenantId]),\n ),\n organizationIdByRecord: Object.fromEntries(\n adjustments.map((adj) => [adj.id, order.organizationId]),\n ),\n })\n : Promise.resolve({}),\n ]);\n const shipmentSnapshots = (\n await Promise.all(\n shipments.map((entry) => loadShipmentSnapshot(em, entry.id)),\n )\n ).filter((entry): entry is ShipmentSnapshot => !!entry);\n const paymentSnapshots = (\n await Promise.all(\n payments.map((entry) => loadPaymentSnapshot(em, entry.id)),\n )\n ).filter((entry): entry is PaymentSnapshot => !!entry);\n const addressSnapshots: DocumentAddressSnapshot[] = addresses.map(\n (entry) => ({\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n documentId: entry.documentId,\n documentKind: \"order\",\n customerAddressId: entry.customerAddressId ?? null,\n name: entry.name ?? null,\n purpose: entry.purpose ?? null,\n companyName: entry.companyName ?? null,\n addressLine1: entry.addressLine1,\n addressLine2: entry.addressLine2 ?? null,\n city: entry.city ?? null,\n region: entry.region ?? null,\n postalCode: entry.postalCode ?? null,\n country: entry.country ?? null,\n buildingNumber: entry.buildingNumber ?? null,\n flatNumber: entry.flatNumber ?? null,\n latitude: entry.latitude ?? null,\n longitude: entry.longitude ?? null,\n }),\n );\n const noteSnapshots: NoteSnapshot[] = notes.map((entry) => ({\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n contextType: entry.contextType as \"order\" | \"quote\",\n contextId: entry.contextId,\n orderId: entry.order\n ? typeof entry.order === \"string\"\n ? entry.order\n : entry.order.id\n : null,\n quoteId: entry.quote\n ? typeof entry.quote === \"string\"\n ? entry.quote\n : entry.quote.id\n : null,\n body: entry.body,\n authorUserId: entry.authorUserId ?? null,\n appearanceIcon: entry.appearanceIcon ?? null,\n appearanceColor: entry.appearanceColor ?? null,\n }));\n const tagSnapshots: TagAssignmentSnapshot[] = tags\n .map((assignment) => {\n const tagId =\n typeof assignment.tag === \"string\"\n ? assignment.tag\n : (assignment.tag?.id ?? (assignment as any)?.tag_id ?? null);\n if (!tagId) return null;\n return {\n id: assignment.id,\n tagId,\n organizationId: assignment.organizationId,\n tenantId: assignment.tenantId,\n documentId: assignment.documentId,\n documentKind: \"order\",\n };\n })\n .filter((entry): entry is TagAssignmentSnapshot => !!entry);\n\n return {\n order: {\n id: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderNumber: order.orderNumber,\n statusEntryId: order.statusEntryId ?? null,\n status: order.status ?? null,\n fulfillmentStatusEntryId: order.fulfillmentStatusEntryId ?? null,\n fulfillmentStatus: order.fulfillmentStatus ?? null,\n paymentStatusEntryId: order.paymentStatusEntryId ?? null,\n paymentStatus: order.paymentStatus ?? null,\n customerEntityId: order.customerEntityId ?? null,\n customerContactId: order.customerContactId ?? null,\n customerSnapshot: order.customerSnapshot\n ? cloneJson(order.customerSnapshot)\n : null,\n billingAddressId: order.billingAddressId ?? null,\n shippingAddressId: order.shippingAddressId ?? null,\n billingAddressSnapshot: order.billingAddressSnapshot\n ? cloneJson(order.billingAddressSnapshot)\n : null,\n shippingAddressSnapshot: order.shippingAddressSnapshot\n ? cloneJson(order.shippingAddressSnapshot)\n : null,\n currencyCode: order.currencyCode,\n exchangeRate: order.exchangeRate ?? null,\n taxStrategyKey: order.taxStrategyKey ?? null,\n discountStrategyKey: order.discountStrategyKey ?? null,\n taxInfo: order.taxInfo ? cloneJson(order.taxInfo) : null,\n shippingMethodId: order.shippingMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n deliveryWindowId: order.deliveryWindowId ?? null,\n deliveryWindowCode: order.deliveryWindowCode ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n channelId: order.channelId ?? null,\n placedAt: order.placedAt ? order.placedAt.toISOString() : null,\n expectedDeliveryAt: order.expectedDeliveryAt\n ? order.expectedDeliveryAt.toISOString()\n : null,\n dueAt: order.dueAt ? order.dueAt.toISOString() : null,\n comments: order.comments ?? null,\n internalNotes: order.internalNotes ?? null,\n shippingMethodSnapshot: order.shippingMethodSnapshot\n ? cloneJson(order.shippingMethodSnapshot)\n : null,\n deliveryWindowSnapshot: order.deliveryWindowSnapshot\n ? cloneJson(order.deliveryWindowSnapshot)\n : null,\n paymentMethodSnapshot: order.paymentMethodSnapshot\n ? cloneJson(order.paymentMethodSnapshot)\n : null,\n metadata: order.metadata ? cloneJson(order.metadata) : null,\n customFieldSetId: order.customFieldSetId ?? null,\n customFields: orderCustomFields[order.id]\n ? cloneJson(orderCustomFields[order.id])\n : null,\n subtotalNetAmount: order.subtotalNetAmount,\n subtotalGrossAmount: order.subtotalGrossAmount,\n discountTotalAmount: order.discountTotalAmount,\n taxTotalAmount: order.taxTotalAmount,\n shippingNetAmount: order.shippingNetAmount,\n shippingGrossAmount: order.shippingGrossAmount,\n surchargeTotalAmount: order.surchargeTotalAmount,\n grandTotalNetAmount: order.grandTotalNetAmount,\n grandTotalGrossAmount: order.grandTotalGrossAmount,\n paidTotalAmount: order.paidTotalAmount,\n refundedTotalAmount: order.refundedTotalAmount,\n outstandingAmount: order.outstandingAmount,\n totalsSnapshot: order.totalsSnapshot\n ? cloneJson(order.totalsSnapshot)\n : null,\n lineItemCount: order.lineItemCount,\n },\n lines: lines.map((line) => ({\n id: line.id,\n lineNumber: line.lineNumber,\n kind: line.kind,\n statusEntryId: line.statusEntryId ?? null,\n status: line.status ?? null,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: line.normalizedQuantity ?? line.quantity,\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n reservedQuantity: line.reservedQuantity,\n fulfilledQuantity: line.fulfilledQuantity,\n invoicedQuantity: line.invoicedQuantity,\n returnedQuantity: line.returnedQuantity,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n discountAmount: line.discountAmount,\n discountPercent: line.discountPercent,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n totalNetAmount: line.totalNetAmount,\n totalGrossAmount: line.totalGrossAmount,\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n customFields: lineCustomFields[line.id]\n ? cloneJson(lineCustomFields[line.id])\n : null,\n })),\n adjustments: adjustments.map((adj) => ({\n id: adj.id,\n scope: adj.scope,\n kind: adj.kind,\n code: adj.code ?? null,\n label: adj.label ?? null,\n calculatorKey: adj.calculatorKey ?? null,\n promotionId: adj.promotionId ?? null,\n rate: adj.rate,\n amountNet: adj.amountNet,\n amountGross: adj.amountGross,\n currencyCode: adj.currencyCode ?? null,\n metadata: adj.metadata ? cloneJson(adj.metadata) : null,\n position: adj.position,\n orderLineId:\n typeof adj.orderLine === \"string\"\n ? adj.orderLine\n : (adj.orderLine?.id ?? null),\n customFields: adjustmentCustomFields[adj.id]\n ? cloneJson(adjustmentCustomFields[adj.id])\n : null,\n })),\n addresses: addressSnapshots,\n notes: noteSnapshots,\n tags: tagSnapshots,\n shipments: shipmentSnapshots,\n payments: paymentSnapshots,\n };\n}\n\nasync function loadInvoiceSnapshot(\n em: EntityManager,\n id: string,\n): Promise<InvoiceGraphSnapshot | null> {\n const invoice = await em.findOne(SalesInvoice, { id, deletedAt: null });\n if (!invoice) return null;\n const lines = await em.find(\n SalesInvoiceLine,\n { invoice: invoice },\n { orderBy: { lineNumber: \"asc\" } },\n );\n const [invoiceCustomFields] = await Promise.all([\n loadCustomFieldValues({\n em,\n entityId: E.sales.sales_invoice,\n recordIds: [invoice.id],\n tenantIdByRecord: { [invoice.id]: invoice.tenantId },\n organizationIdByRecord: { [invoice.id]: invoice.organizationId },\n }),\n ]);\n return {\n invoice: {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n invoiceNumber: invoice.invoiceNumber,\n orderId: invoice.orderId ?? null,\n statusEntryId: invoice.statusEntryId ?? null,\n status: invoice.status ?? null,\n issueDate: invoice.issueDate ?? null,\n dueDate: invoice.dueDate ?? null,\n currencyCode: invoice.currencyCode,\n subtotalNetAmount: String(invoice.subtotalNetAmount),\n subtotalGrossAmount: String(invoice.subtotalGrossAmount),\n discountTotalAmount: String(invoice.discountTotalAmount),\n taxTotalAmount: String(invoice.taxTotalAmount),\n grandTotalNetAmount: String(invoice.grandTotalNetAmount),\n grandTotalGrossAmount: String(invoice.grandTotalGrossAmount),\n paidTotalAmount: String(invoice.paidTotalAmount),\n outstandingAmount: String(invoice.outstandingAmount),\n metadata: invoice.metadata ?? null,\n customFieldSetId: invoice.customFieldSetId ?? null,\n customFields: invoiceCustomFields[invoice.id] ?? null,\n },\n lines: lines.map((line) => ({\n id: line.id,\n orderLineId: line.orderLineId ?? null,\n lineNumber: line.lineNumber,\n kind: line.kind ?? \"product\",\n name: line.name ?? null,\n sku: line.sku ?? null,\n description: line.description ?? null,\n quantity: String(line.quantity),\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: String(line.normalizedQuantity),\n normalizedUnit: line.normalizedUnit ?? null,\n uomSnapshot: line.uomSnapshot ?? null,\n currencyCode: line.currencyCode,\n unitPriceNet: String(line.unitPriceNet),\n unitPriceGross: String(line.unitPriceGross),\n discountAmount: String(line.discountAmount),\n discountPercent: String(line.discountPercent),\n taxRate: String(line.taxRate),\n taxAmount: String(line.taxAmount),\n totalNetAmount: String(line.totalNetAmount),\n totalGrossAmount: String(line.totalGrossAmount),\n metadata: line.metadata ?? null,\n })),\n };\n}\n\nasync function loadCreditMemoSnapshot(\n em: EntityManager,\n id: string,\n): Promise<CreditMemoGraphSnapshot | null> {\n const creditMemo = await em.findOne(SalesCreditMemo, { id, deletedAt: null });\n if (!creditMemo) return null;\n const lines = await em.find(\n SalesCreditMemoLine,\n { creditMemo: creditMemo },\n { orderBy: { lineNumber: \"asc\" } },\n );\n const [creditMemoCustomFields] = await Promise.all([\n loadCustomFieldValues({\n em,\n entityId: E.sales.sales_credit_memo,\n recordIds: [creditMemo.id],\n tenantIdByRecord: { [creditMemo.id]: creditMemo.tenantId },\n organizationIdByRecord: { [creditMemo.id]: creditMemo.organizationId },\n }),\n ]);\n return {\n creditMemo: {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n creditMemoNumber: creditMemo.creditMemoNumber,\n orderId: creditMemo.orderId ?? null,\n invoiceId: creditMemo.invoiceId ?? null,\n statusEntryId: creditMemo.statusEntryId ?? null,\n status: creditMemo.status ?? null,\n reason: creditMemo.reason ?? null,\n issueDate: creditMemo.issueDate ?? null,\n currencyCode: creditMemo.currencyCode,\n subtotalNetAmount: String(creditMemo.subtotalNetAmount),\n subtotalGrossAmount: String(creditMemo.subtotalGrossAmount),\n taxTotalAmount: String(creditMemo.taxTotalAmount),\n grandTotalNetAmount: String(creditMemo.grandTotalNetAmount),\n grandTotalGrossAmount: String(creditMemo.grandTotalGrossAmount),\n metadata: creditMemo.metadata ?? null,\n customFieldSetId: creditMemo.customFieldSetId ?? null,\n customFields: creditMemoCustomFields[creditMemo.id] ?? null,\n },\n lines: lines.map((line) => ({\n id: line.id,\n orderLineId: line.orderLineId ?? null,\n lineNumber: line.lineNumber,\n name: line.name ?? null,\n sku: line.sku ?? null,\n description: line.description ?? null,\n quantity: String(line.quantity),\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: String(line.normalizedQuantity),\n normalizedUnit: line.normalizedUnit ?? null,\n uomSnapshot: line.uomSnapshot ?? null,\n currencyCode: line.currencyCode,\n unitPriceNet: String(line.unitPriceNet),\n unitPriceGross: String(line.unitPriceGross),\n taxRate: String(line.taxRate),\n taxAmount: String(line.taxAmount),\n totalNetAmount: String(line.totalNetAmount),\n totalGrossAmount: String(line.totalGrossAmount),\n metadata: line.metadata ?? null,\n })),\n };\n}\n\ntype DeletableEntity = {\n id?: string;\n organizationId?: string | null;\n tenantId?: string | null;\n};\n\nasync function queueDeletionSideEffects(\n dataEngine: DataEngine,\n entities: DeletableEntity[] | DeletableEntity | null | undefined,\n entityType: string,\n): Promise<void> {\n if (!entities) return;\n const list = Array.isArray(entities) ? entities : [entities];\n const tasks: Array<Promise<void>> = [];\n for (const entity of list) {\n if (!entity) continue;\n const id = typeof entity.id === \"string\" ? entity.id : null;\n if (!id) continue;\n tasks.push(\n emitCrudSideEffects({\n dataEngine,\n action: \"deleted\",\n entity,\n identifiers: {\n id,\n organizationId: entity.organizationId ?? null,\n tenantId: entity.tenantId ?? null,\n },\n indexer: { entityType },\n }),\n );\n }\n if (tasks.length) await Promise.all(tasks);\n}\n\nfunction toNumeric(value: string | number | null | undefined): number {\n if (typeof value === \"number\") return value;\n if (typeof value === \"string\" && value.trim().length) {\n const parsed = Number(value);\n if (!Number.isNaN(parsed)) return parsed;\n }\n return 0;\n}\n\nconst UNIT_DICTIONARY_KEYS = [\"unit\", \"units\", \"measurement_units\"] as const;\nconst UOM_REFERENCE_UNITS = new Set<string>(REFERENCE_UNIT_CODES);\nconst UOM_NORMALIZED_SCALE = 6;\nconst UOM_NORMALIZED_MAX = 1_000_000_000_000;\nconst UNIT_PRICE_AUTOCONVERT_SCALE = 4;\n\ntype ProductUomState = {\n productId: string;\n baseUnitCode: string | null;\n defaultSalesUnit: string | null;\n unitPriceEnabled: boolean;\n unitPriceReferenceUnit: \"kg\" | \"l\" | \"m2\" | \"m3\" | \"pc\" | null;\n unitPriceBaseQuantity: string | null;\n conversionsByUnitKey: Map<string, CatalogProductUnitConversion>;\n};\n\ntype UomResolver = {\n dictionaryPromise: Promise<Dictionary | null> | null;\n unitExistsCache: Map<string, boolean>;\n productCache: Map<string, ProductUomState | null>;\n};\n\ntype NormalizeLineUomInput = {\n em: EntityManager;\n resolver: UomResolver;\n organizationId: string;\n tenantId: string;\n line: {\n productId?: string | null;\n productVariantId?: string | null;\n quantity?: number | string | null;\n quantityUnit?: string | null;\n unitPriceNet?: number | null;\n unitPriceGross?: number | null;\n normalizedQuantity?: number | string | null;\n normalizedUnit?: string | null;\n uomSnapshot?: Record<string, unknown> | null;\n };\n};\n\nfunction createUomResolver(): UomResolver {\n return {\n dictionaryPromise: null,\n unitExistsCache: new Map<string, boolean>(),\n productCache: new Map<string, ProductUomState | null>(),\n };\n}\n\nfunction normalizeUnitCode(value: unknown): string | null {\n return canonicalizeUnitCode(value);\n}\n\nfunction unitLookupKey(value: string | null | undefined): string | null {\n return toUnitLookupKey(value);\n}\n\nfunction roundNormalizedQuantity(value: number): number {\n const factor = 10 ** UOM_NORMALIZED_SCALE;\n if (!Number.isFinite(value)) return 0;\n return Math.round(value * factor) / factor;\n}\n\nfunction assertNormalizedPrecision(value: number) {\n if (!Number.isFinite(value) || Math.abs(value) >= UOM_NORMALIZED_MAX) {\n throw new CrudHttpError(422, { error: \"uom.precision_overflow\" });\n }\n}\n\nfunction toOptionalNumber(value: unknown): number | null {\n if (value === null || value === undefined) return null;\n if (typeof value === \"number\") return Number.isFinite(value) ? value : null;\n if (typeof value === \"string\" && value.trim().length) {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : null;\n }\n return null;\n}\n\nfunction resolveSnapshotToBaseFactor(snapshot: unknown): number {\n if (!snapshot || typeof snapshot !== \"object\") return 1;\n const payload = snapshot as Record<string, unknown>;\n const factor = toOptionalNumber(payload.toBaseFactor ?? payload.to_base_factor);\n if (!Number.isFinite(factor) || !factor || factor <= 0) return 1;\n return factor;\n}\n\nfunction roundAutoConvertedUnitPrice(value: number): number | null {\n if (!Number.isFinite(value) || value < 0) return null;\n const factor = 10 ** UNIT_PRICE_AUTOCONVERT_SCALE;\n const rounded = Math.round((value + Number.EPSILON) * factor) / factor;\n return Number.isFinite(rounded) ? rounded : null;\n}\n\nfunction convertLineUnitPricesOnUnitChange(params: {\n existingSnapshot: SalesLineSnapshot | null;\n nextQuantityUnit: string | null;\n nextUomSnapshot: SalesLineUomSnapshot | Record<string, unknown> | null;\n unitPriceNet: number | null;\n unitPriceGross: number | null;\n}): {\n unitPriceNet: number | null;\n unitPriceGross: number | null;\n didConvert: boolean;\n} {\n if (!params.existingSnapshot) {\n return {\n unitPriceNet: params.unitPriceNet,\n unitPriceGross: params.unitPriceGross,\n didConvert: false,\n };\n }\n const existingUnitPriceNet =\n typeof params.existingSnapshot.unitPriceNet === \"number\" &&\n Number.isFinite(params.existingSnapshot.unitPriceNet)\n ? params.existingSnapshot.unitPriceNet\n : null;\n const existingUnitPriceGross =\n typeof params.existingSnapshot.unitPriceGross === \"number\" &&\n Number.isFinite(params.existingSnapshot.unitPriceGross)\n ? params.existingSnapshot.unitPriceGross\n : null;\n const sameNumber = (left: number | null, right: number | null): boolean => {\n if (left === null || right === null) return left === right;\n return Math.abs(left - right) < 0.000001;\n };\n const shouldConvertNet =\n params.unitPriceNet === null ||\n sameNumber(params.unitPriceNet, existingUnitPriceNet);\n const shouldConvertGross =\n params.unitPriceGross === null ||\n sameNumber(params.unitPriceGross, existingUnitPriceGross);\n if (!shouldConvertNet && !shouldConvertGross) {\n return {\n unitPriceNet: params.unitPriceNet,\n unitPriceGross: params.unitPriceGross,\n didConvert: false,\n };\n }\n const previousUnit = normalizeUnitCode(params.existingSnapshot?.quantityUnit ?? null);\n const nextUnit = normalizeUnitCode(params.nextQuantityUnit);\n if (!previousUnit || !nextUnit || previousUnit === nextUnit) {\n return {\n unitPriceNet: params.unitPriceNet,\n unitPriceGross: params.unitPriceGross,\n didConvert: false,\n };\n }\n const previousFactor = resolveSnapshotToBaseFactor(\n params.existingSnapshot?.uomSnapshot ?? null,\n );\n const nextFactor = resolveSnapshotToBaseFactor(params.nextUomSnapshot);\n if (\n !Number.isFinite(previousFactor) ||\n previousFactor <= 0 ||\n !Number.isFinite(nextFactor) ||\n nextFactor <= 0\n ) {\n return {\n unitPriceNet: params.unitPriceNet,\n unitPriceGross: params.unitPriceGross,\n didConvert: false,\n };\n }\n const convertAmount = (\n value: number | null,\n shouldConvert: boolean,\n ): number | null => {\n if (!shouldConvert) return value;\n if (value === null || !Number.isFinite(value)) return value;\n const converted = roundAutoConvertedUnitPrice((value / previousFactor) * nextFactor);\n return converted ?? value;\n };\n const nextUnitPriceNet = convertAmount(params.unitPriceNet, shouldConvertNet);\n const nextUnitPriceGross = convertAmount(\n params.unitPriceGross,\n shouldConvertGross,\n );\n const didConvert =\n nextUnitPriceNet !== params.unitPriceNet ||\n nextUnitPriceGross !== params.unitPriceGross;\n return {\n unitPriceNet: nextUnitPriceNet,\n unitPriceGross: nextUnitPriceGross,\n didConvert,\n };\n}\n\nfunction resolveReferenceUnit(\n value: unknown,\n): \"kg\" | \"l\" | \"m2\" | \"m3\" | \"pc\" | null {\n const normalized = toUnitLookupKey(value);\n if (!normalized) return null;\n if (!UOM_REFERENCE_UNITS.has(normalized)) return null;\n return normalized as \"kg\" | \"l\" | \"m2\" | \"m3\" | \"pc\";\n}\n\nasync function resolveUnitDictionaryScoped(\n em: EntityManager,\n organizationId: string,\n tenantId: string,\n): Promise<Dictionary | null> {\n return findOneWithDecryption(\n em,\n Dictionary,\n {\n organizationId,\n tenantId,\n key: { $in: [...UNIT_DICTIONARY_KEYS] },\n deletedAt: null,\n isActive: true,\n },\n { orderBy: { createdAt: \"asc\" } },\n );\n}\n\nasync function assertUnitExists(\n em: EntityManager,\n resolver: UomResolver,\n organizationId: string,\n tenantId: string,\n unitCode: string,\n): Promise<void> {\n const normalizedCode = unitLookupKey(unitCode);\n if (!normalizedCode) return;\n const rawUnitCode = unitCode.trim();\n if (!resolver.dictionaryPromise) {\n resolver.dictionaryPromise = resolveUnitDictionaryScoped(\n em,\n organizationId,\n tenantId,\n );\n }\n const dictionary = await resolver.dictionaryPromise;\n if (!dictionary) {\n throw new CrudHttpError(400, { error: \"uom.unit_not_found\" });\n }\n const cacheKey = `${dictionary.id}:${normalizedCode}`;\n if (resolver.unitExistsCache.has(cacheKey)) {\n if (!resolver.unitExistsCache.get(cacheKey)) {\n throw new CrudHttpError(400, { error: \"uom.unit_not_found\" });\n }\n return;\n }\n const entry = await findOneWithDecryption(em, DictionaryEntry, {\n dictionary,\n organizationId: dictionary.organizationId,\n tenantId: dictionary.tenantId,\n $or: [{ normalizedValue: normalizedCode }, { value: rawUnitCode }],\n });\n const exists = !!entry;\n resolver.unitExistsCache.set(cacheKey, exists);\n if (!exists) {\n throw new CrudHttpError(400, { error: \"uom.unit_not_found\" });\n }\n}\n\nasync function resolveProductUomState(\n em: EntityManager,\n resolver: UomResolver,\n organizationId: string,\n tenantId: string,\n productId: string,\n): Promise<ProductUomState | null> {\n if (resolver.productCache.has(productId)) {\n return resolver.productCache.get(productId) ?? null;\n }\n const product = await findOneWithDecryption(em, CatalogProduct, {\n id: productId,\n organizationId,\n tenantId,\n deletedAt: null,\n });\n if (!product) {\n resolver.productCache.set(productId, null);\n return null;\n }\n const conversions = await findWithDecryption(em, CatalogProductUnitConversion, {\n product: product.id,\n organizationId,\n tenantId,\n deletedAt: null,\n isActive: true,\n });\n const conversionsByUnitKey = new Map<string, CatalogProductUnitConversion>();\n for (const conversion of conversions) {\n const key = unitLookupKey(conversion.unitCode);\n if (!key) continue;\n conversionsByUnitKey.set(key, conversion);\n }\n const state: ProductUomState = {\n productId: product.id,\n baseUnitCode: normalizeUnitCode(product.defaultUnit ?? null),\n defaultSalesUnit: normalizeUnitCode(product.defaultSalesUnit ?? null),\n unitPriceEnabled: Boolean(product.unitPriceEnabled),\n unitPriceReferenceUnit: resolveReferenceUnit(\n product.unitPriceReferenceUnit,\n ),\n unitPriceBaseQuantity: product.unitPriceBaseQuantity ?? null,\n conversionsByUnitKey,\n };\n resolver.productCache.set(productId, state);\n return state;\n}\n\nfunction buildUnitPriceReferenceSnapshot(params: {\n product: ProductUomState;\n toBaseFactor: number;\n unitPriceNet: number | null;\n unitPriceGross: number | null;\n}) {\n if (!params.product.unitPriceEnabled) return undefined;\n const baseQuantityNumber = toNumeric(params.product.unitPriceBaseQuantity);\n const output: NonNullable<SalesLineUomSnapshot[\"unitPriceReference\"]> = {\n enabled: true,\n referenceUnitCode: params.product.unitPriceReferenceUnit ?? null,\n baseQuantity: params.product.unitPriceBaseQuantity ?? null,\n };\n if (\n !params.product.unitPriceReferenceUnit ||\n params.toBaseFactor <= 0 ||\n baseQuantityNumber <= 0\n ) {\n return output;\n }\n if (\n typeof params.unitPriceGross === \"number\" &&\n Number.isFinite(params.unitPriceGross)\n ) {\n output.grossPerReference = toNumericString(\n (params.unitPriceGross / params.toBaseFactor) * baseQuantityNumber,\n );\n }\n if (\n typeof params.unitPriceNet === \"number\" &&\n Number.isFinite(params.unitPriceNet)\n ) {\n output.netPerReference = toNumericString(\n (params.unitPriceNet / params.toBaseFactor) * baseQuantityNumber,\n );\n }\n return output;\n}\n\nasync function normalizeLineUom(input: NormalizeLineUomInput): Promise<{\n quantity: number;\n quantityUnit: string | null;\n normalizedQuantity: number;\n normalizedUnit: string | null;\n uomSnapshot: SalesLineUomSnapshot | null;\n}> {\n const quantity = toNumeric(input.line.quantity);\n const existingSnapshot =\n input.line.uomSnapshot && typeof input.line.uomSnapshot === \"object\"\n ? (cloneJson(input.line.uomSnapshot) as SalesLineUomSnapshot)\n : null;\n const productId =\n typeof input.line.productId === \"string\" ? input.line.productId : null;\n const variantId =\n typeof input.line.productVariantId === \"string\"\n ? input.line.productVariantId\n : null;\n const enteredUnitInput = normalizeUnitCode(input.line.quantityUnit);\n if (!productId) {\n if (enteredUnitInput) {\n await assertUnitExists(\n input.em,\n input.resolver,\n input.organizationId,\n input.tenantId,\n enteredUnitInput,\n );\n }\n const normalizedQuantity = toNumeric(\n input.line.normalizedQuantity ?? quantity,\n );\n assertNormalizedPrecision(normalizedQuantity);\n return {\n quantity,\n quantityUnit: enteredUnitInput ?? null,\n normalizedQuantity,\n normalizedUnit:\n normalizeUnitCode(input.line.normalizedUnit) ??\n enteredUnitInput ??\n null,\n uomSnapshot: existingSnapshot ?? {\n version: 1,\n productId: null,\n productVariantId: variantId,\n baseUnitCode:\n normalizeUnitCode(input.line.normalizedUnit) ??\n enteredUnitInput ??\n null,\n enteredUnitCode: enteredUnitInput,\n enteredQuantity: toNumericString(quantity) ?? \"0\",\n toBaseFactor: \"1\",\n normalizedQuantity: toNumericString(normalizedQuantity) ?? \"0\",\n rounding: { mode: \"half_up\", scale: UOM_NORMALIZED_SCALE },\n source: { conversionId: null, resolvedAt: new Date().toISOString() },\n },\n };\n }\n\n const productState = await resolveProductUomState(\n input.em,\n input.resolver,\n input.organizationId,\n input.tenantId,\n productId,\n );\n if (!productState) {\n if (enteredUnitInput) {\n await assertUnitExists(\n input.em,\n input.resolver,\n input.organizationId,\n input.tenantId,\n enteredUnitInput,\n );\n }\n const normalizedQuantity = toNumeric(\n input.line.normalizedQuantity ?? quantity,\n );\n assertNormalizedPrecision(normalizedQuantity);\n return {\n quantity,\n quantityUnit: enteredUnitInput ?? null,\n normalizedQuantity,\n normalizedUnit:\n normalizeUnitCode(input.line.normalizedUnit) ??\n enteredUnitInput ??\n null,\n uomSnapshot: existingSnapshot,\n };\n }\n\n const baseUnitCode = productState.baseUnitCode;\n const enteredUnitCode =\n enteredUnitInput ??\n productState.defaultSalesUnit ??\n baseUnitCode ??\n normalizeUnitCode(input.line.normalizedUnit);\n if (enteredUnitCode) {\n await assertUnitExists(\n input.em,\n input.resolver,\n input.organizationId,\n input.tenantId,\n enteredUnitCode,\n );\n }\n if (baseUnitCode) {\n await assertUnitExists(\n input.em,\n input.resolver,\n input.organizationId,\n input.tenantId,\n baseUnitCode,\n );\n }\n\n if (!baseUnitCode) {\n const requiresBase =\n Boolean(enteredUnitCode) ||\n productState.conversionsByUnitKey.size > 0 ||\n Boolean(productState.defaultSalesUnit);\n if (requiresBase) {\n throw new CrudHttpError(400, { error: \"uom.default_unit_missing\" });\n }\n const normalizedQuantity = toNumeric(\n input.line.normalizedQuantity ?? quantity,\n );\n assertNormalizedPrecision(normalizedQuantity);\n return {\n quantity,\n quantityUnit: enteredUnitCode ?? null,\n normalizedQuantity,\n normalizedUnit:\n normalizeUnitCode(input.line.normalizedUnit) ?? enteredUnitCode ?? null,\n uomSnapshot: existingSnapshot,\n };\n }\n\n const resolvedEnteredUnit = enteredUnitCode ?? baseUnitCode;\n const enteredKey = unitLookupKey(resolvedEnteredUnit);\n const baseKey = unitLookupKey(baseUnitCode);\n let toBaseFactor = 1;\n let conversionId: string | null = null;\n if (enteredKey && baseKey && enteredKey !== baseKey) {\n const conversion = productState.conversionsByUnitKey.get(enteredKey);\n if (!conversion) {\n throw new CrudHttpError(400, { error: \"uom.conversion_not_found\" });\n }\n toBaseFactor = toNumeric(conversion.toBaseFactor);\n conversionId = conversion.id;\n }\n if (!Number.isFinite(toBaseFactor) || toBaseFactor <= 0) {\n throw new CrudHttpError(400, { error: \"uom.invalid_factor\" });\n }\n const normalizedQuantity = roundNormalizedQuantity(quantity * toBaseFactor);\n assertNormalizedPrecision(normalizedQuantity);\n const unitPriceReference = buildUnitPriceReferenceSnapshot({\n product: productState,\n toBaseFactor,\n unitPriceNet: toOptionalNumber(input.line.unitPriceNet),\n unitPriceGross: toOptionalNumber(input.line.unitPriceGross),\n });\n const snapshot: SalesLineUomSnapshot = {\n version: 1,\n productId,\n productVariantId: variantId,\n baseUnitCode,\n enteredUnitCode: resolvedEnteredUnit,\n enteredQuantity: toNumericString(quantity) ?? \"0\",\n toBaseFactor: toNumericString(toBaseFactor) ?? \"1\",\n normalizedQuantity: toNumericString(normalizedQuantity) ?? \"0\",\n rounding: {\n mode: \"half_up\",\n scale: UOM_NORMALIZED_SCALE,\n },\n source: {\n conversionId,\n resolvedAt: new Date().toISOString(),\n },\n ...(unitPriceReference ? { unitPriceReference } : {}),\n };\n\n return {\n quantity,\n quantityUnit: resolvedEnteredUnit,\n normalizedQuantity,\n normalizedUnit: baseUnitCode,\n uomSnapshot: snapshot,\n };\n}\n\nfunction normalizeShippingMethodContext(\n snapshot: Record<string, unknown> | null | undefined,\n id?: string | null,\n code?: string | null,\n currencyCode?: string,\n): ShippingMethodContext | null {\n if (!snapshot || typeof snapshot !== \"object\") return null;\n const metadata = (snapshot as Record<string, unknown>).metadata;\n const providerSettings =\n (snapshot as Record<string, unknown>).providerSettings ??\n (metadata && typeof metadata === \"object\"\n ? ((metadata as Record<string, unknown>).providerSettings ?? null)\n : null);\n return {\n id:\n ((snapshot as Record<string, unknown>).id as string | undefined) ??\n id ??\n null,\n code:\n typeof (snapshot as Record<string, unknown>).code === \"string\"\n ? ((snapshot as Record<string, unknown>).code as string)\n : (code ?? null),\n name:\n typeof (snapshot as Record<string, unknown>).name === \"string\"\n ? ((snapshot as Record<string, unknown>).name as string)\n : null,\n providerKey:\n typeof (snapshot as Record<string, unknown>).providerKey === \"string\"\n ? ((snapshot as Record<string, unknown>).providerKey as string)\n : null,\n currencyCode:\n typeof (snapshot as Record<string, unknown>).currencyCode === \"string\"\n ? ((snapshot as Record<string, unknown>).currencyCode as string)\n : (currencyCode ?? null),\n baseRateNet: toNumeric(\n ((snapshot as Record<string, unknown>).baseRateNet ??\n (snapshot as Record<string, unknown>).base_rate_net) as\n | string\n | number\n | null,\n ),\n baseRateGross: toNumeric(\n ((snapshot as Record<string, unknown>).baseRateGross ??\n (snapshot as Record<string, unknown>).base_rate_gross) as\n | string\n | number\n | null,\n ),\n metadata:\n metadata && typeof metadata === \"object\"\n ? cloneJson(metadata as Record<string, unknown>)\n : null,\n providerSettings:\n providerSettings && typeof providerSettings === \"object\"\n ? cloneJson(providerSettings as Record<string, unknown>)\n : null,\n };\n}\n\nfunction normalizePaymentMethodContext(\n snapshot: Record<string, unknown> | null | undefined,\n id?: string | null,\n code?: string | null,\n): PaymentMethodContext | null {\n if (!snapshot || typeof snapshot !== \"object\") return null;\n const metadata = (snapshot as Record<string, unknown>).metadata;\n const providerSettings =\n (snapshot as Record<string, unknown>).providerSettings ??\n (metadata && typeof metadata === \"object\"\n ? ((metadata as Record<string, unknown>).providerSettings ?? null)\n : null);\n return {\n id:\n ((snapshot as Record<string, unknown>).id as string | undefined) ??\n id ??\n null,\n code:\n typeof (snapshot as Record<string, unknown>).code === \"string\"\n ? ((snapshot as Record<string, unknown>).code as string)\n : (code ?? null),\n name:\n typeof (snapshot as Record<string, unknown>).name === \"string\"\n ? ((snapshot as Record<string, unknown>).name as string)\n : null,\n providerKey:\n typeof (snapshot as Record<string, unknown>).providerKey === \"string\"\n ? ((snapshot as Record<string, unknown>).providerKey as string)\n : null,\n terms:\n typeof (snapshot as Record<string, unknown>).terms === \"string\"\n ? ((snapshot as Record<string, unknown>).terms as string)\n : null,\n metadata:\n metadata && typeof metadata === \"object\"\n ? cloneJson(metadata as Record<string, unknown>)\n : null,\n providerSettings:\n providerSettings && typeof providerSettings === \"object\"\n ? cloneJson(providerSettings as Record<string, unknown>)\n : null,\n };\n}\n\nfunction buildProviderContext(params: {\n shippingSnapshot?: Record<string, unknown> | null;\n paymentSnapshot?: Record<string, unknown> | null;\n shippingMethodId?: string | null;\n paymentMethodId?: string | null;\n shippingMethodCode?: string | null;\n paymentMethodCode?: string | null;\n currencyCode: string;\n}) {\n return {\n shippingMethod: normalizeShippingMethodContext(\n params.shippingSnapshot,\n params.shippingMethodId,\n params.shippingMethodCode,\n params.currencyCode,\n ),\n paymentMethod: normalizePaymentMethodContext(\n params.paymentSnapshot,\n params.paymentMethodId,\n params.paymentMethodCode,\n ),\n };\n}\n\nfunction buildCalculationContext(params: {\n tenantId: string;\n organizationId: string;\n currencyCode: string;\n shippingSnapshot?: Record<string, unknown> | null;\n paymentSnapshot?: Record<string, unknown> | null;\n shippingMethodId?: string | null;\n paymentMethodId?: string | null;\n shippingMethodCode?: string | null;\n paymentMethodCode?: string | null;\n}) {\n return {\n tenantId: params.tenantId,\n organizationId: params.organizationId,\n currencyCode: params.currencyCode,\n metadata: buildProviderContext({\n shippingSnapshot: params.shippingSnapshot,\n paymentSnapshot: params.paymentSnapshot,\n shippingMethodId: params.shippingMethodId,\n paymentMethodId: params.paymentMethodId,\n shippingMethodCode: params.shippingMethodCode,\n paymentMethodCode: params.paymentMethodCode,\n currencyCode: params.currencyCode,\n }),\n };\n}\n\nfunction mapOrderLineEntityToSnapshot(line: SalesOrderLine): SalesLineSnapshot {\n return {\n id: line.id,\n lineNumber: line.lineNumber,\n kind: line.kind,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: toNumeric(line.quantity),\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: toNumeric(line.normalizedQuantity ?? line.quantity),\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n currencyCode: line.currencyCode,\n unitPriceNet: toNumeric(line.unitPriceNet),\n unitPriceGross: toNumeric(line.unitPriceGross),\n discountAmount: toNumeric(line.discountAmount),\n discountPercent: toNumeric(line.discountPercent),\n taxRate: toNumeric(line.taxRate),\n taxAmount: toNumeric(line.taxAmount),\n totalNetAmount: toNumeric(line.totalNetAmount),\n totalGrossAmount: toNumeric(line.totalGrossAmount),\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n };\n}\n\nfunction mapQuoteLineEntityToSnapshot(line: SalesQuoteLine): SalesLineSnapshot {\n return {\n id: line.id,\n lineNumber: line.lineNumber,\n kind: line.kind,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: toNumeric(line.quantity),\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: toNumeric(line.normalizedQuantity ?? line.quantity),\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n currencyCode: line.currencyCode,\n unitPriceNet: toNumeric(line.unitPriceNet),\n unitPriceGross: toNumeric(line.unitPriceGross),\n discountAmount: toNumeric(line.discountAmount),\n discountPercent: toNumeric(line.discountPercent),\n taxRate: toNumeric(line.taxRate),\n taxAmount: toNumeric(line.taxAmount),\n totalNetAmount: toNumeric(line.totalNetAmount),\n totalGrossAmount: toNumeric(line.totalGrossAmount),\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n };\n}\n\nfunction mapOrderAdjustmentToDraft(\n adjustment: SalesOrderAdjustment,\n): SalesAdjustmentDraft {\n return {\n id: adjustment.id,\n scope: adjustment.scope ?? \"order\",\n kind: adjustment.kind,\n code: adjustment.code ?? null,\n label: adjustment.label ?? null,\n calculatorKey: adjustment.calculatorKey ?? null,\n promotionId: adjustment.promotionId ?? null,\n rate: toNumeric(adjustment.rate),\n amountNet: toNumeric(adjustment.amountNet),\n amountGross: toNumeric(adjustment.amountGross),\n currencyCode: adjustment.currencyCode ?? null,\n metadata: adjustment.metadata ? cloneJson(adjustment.metadata) : null,\n position: adjustment.position ?? 0,\n };\n}\n\nfunction mapQuoteAdjustmentToDraft(\n adjustment: SalesQuoteAdjustment,\n): SalesAdjustmentDraft {\n return {\n id: adjustment.id,\n scope: adjustment.scope ?? \"order\",\n kind: adjustment.kind,\n code: adjustment.code ?? null,\n label: adjustment.label ?? null,\n calculatorKey: adjustment.calculatorKey ?? null,\n promotionId: adjustment.promotionId ?? null,\n rate: toNumeric(adjustment.rate),\n amountNet: toNumeric(adjustment.amountNet),\n amountGross: toNumeric(adjustment.amountGross),\n currencyCode: adjustment.currencyCode ?? null,\n metadata: adjustment.metadata ? cloneJson(adjustment.metadata) : null,\n position: adjustment.position ?? 0,\n };\n}\n\nasync function emitTotalsCalculated(\n eventBus: EventBus | null | undefined,\n payload: {\n documentKind: SalesDocumentKind;\n documentId: string;\n organizationId: string;\n tenantId: string;\n customerId?: string | null;\n totals: SalesDocumentCalculationResult[\"totals\"];\n lineCount: number;\n },\n): Promise<void> {\n if (!eventBus) return;\n await eventBus.emitEvent(\"sales.document.totals.calculated\", payload);\n}\n\nfunction createLineSnapshotFromInput(\n line: DocumentLineCreateInput,\n lineNumber: number,\n): SalesLineSnapshot {\n const quantity = Number(line.quantity ?? 0);\n const normalizedQuantity = toNumeric(\n line.normalizedQuantity ?? quantity,\n );\n return {\n lineNumber,\n kind: line.kind ?? \"product\",\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity,\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity,\n normalizedUnit:\n typeof line.normalizedUnit === \"string\"\n ? line.normalizedUnit\n : (line.quantityUnit ?? null),\n uomSnapshot:\n line.uomSnapshot && typeof line.uomSnapshot === \"object\"\n ? cloneJson(line.uomSnapshot as Record<string, unknown>)\n : null,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet ?? null,\n unitPriceGross: line.unitPriceGross ?? null,\n discountAmount: line.discountAmount ?? null,\n discountPercent: line.discountPercent ?? null,\n taxRate: line.taxRate ?? null,\n taxAmount: line.taxAmount ?? null,\n totalNetAmount: line.totalNetAmount ?? null,\n totalGrossAmount: line.totalGrossAmount ?? null,\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId:\n \"customFieldSetId\" in line\n ? ((line as any).customFieldSetId ?? null)\n : null,\n customFields:\n \"customFields\" in line && line.customFields\n ? cloneJson((line as any).customFields)\n : null,\n };\n}\n\nfunction createAdjustmentDraftFromInput(\n adjustment: DocumentAdjustmentCreateInput & { id?: string | null },\n): SalesAdjustmentDraft {\n const lineRef =\n \"quoteLineId\" in adjustment\n ? (adjustment as any).quoteLineId\n : (adjustment as any).orderLineId;\n if (adjustment.scope === \"line\" && lineRef) {\n throw new CrudHttpError(400, {\n error: \"Line-scoped adjustments are not supported yet.\",\n });\n }\n return {\n id: typeof adjustment.id === \"string\" ? adjustment.id : undefined,\n scope: adjustment.scope ?? \"order\",\n kind: adjustment.kind ?? \"custom\",\n code: adjustment.code ?? null,\n label: adjustment.label ?? null,\n calculatorKey: adjustment.calculatorKey ?? null,\n promotionId: adjustment.promotionId ?? null,\n rate: adjustment.rate ?? null,\n amountNet: adjustment.amountNet ?? null,\n amountGross: adjustment.amountGross ?? null,\n currencyCode: adjustment.currencyCode ?? null,\n metadata: adjustment.metadata ? cloneJson(adjustment.metadata) : null,\n position: adjustment.position ?? 0,\n };\n}\n\nfunction convertLineCalculationToEntityInput(\n lineResult: SalesLineCalculationResult,\n sourceLine: DocumentLineCreateInput,\n document: { organizationId: string; tenantId: string },\n index: number,\n) {\n const line = lineResult.line;\n return {\n lineNumber: line.lineNumber ?? index + 1,\n kind: line.kind ?? \"product\",\n statusEntryId: sourceLine.statusEntryId ?? null,\n productId: sourceLine.productId ?? null,\n productVariantId: sourceLine.productVariantId ?? null,\n catalogSnapshot: sourceLine.catalogSnapshot\n ? cloneJson(sourceLine.catalogSnapshot)\n : null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: toNumericString(line.quantity) ?? \"0\",\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity:\n toNumericString(line.normalizedQuantity ?? line.quantity) ?? \"0\",\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot:\n line.uomSnapshot && typeof line.uomSnapshot === \"object\"\n ? cloneJson(line.uomSnapshot as Record<string, unknown>)\n : null,\n currencyCode: line.currencyCode,\n unitPriceNet:\n toNumericString(\n line.unitPriceNet ??\n lineResult.netAmount / Math.max(line.quantity || 1, 1),\n ) ?? \"0\",\n unitPriceGross:\n toNumericString(\n line.unitPriceGross ??\n lineResult.grossAmount / Math.max(line.quantity || 1, 1),\n ) ?? \"0\",\n discountAmount: toNumericString(lineResult.discountAmount) ?? \"0\",\n discountPercent: toNumericString(line.discountPercent) ?? \"0\",\n taxRate: toNumericString(line.taxRate) ?? \"0\",\n taxAmount: toNumericString(lineResult.taxAmount) ?? \"0\",\n totalNetAmount: toNumericString(lineResult.netAmount) ?? \"0\",\n totalGrossAmount: toNumericString(lineResult.grossAmount) ?? \"0\",\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n promotionSnapshot: sourceLine.promotionSnapshot\n ? cloneJson(sourceLine.promotionSnapshot)\n : null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: sourceLine.customFieldSetId ?? null,\n organizationId: document.organizationId,\n tenantId: document.tenantId,\n };\n}\n\nfunction convertAdjustmentResultToEntityInput(\n adjustment: SalesAdjustmentDraft,\n sourceAdjustment: DocumentAdjustmentCreateInput | null,\n document: { organizationId: string; tenantId: string },\n index: number,\n) {\n const metadata = adjustment.metadata ? cloneJson(adjustment.metadata) : null;\n const resolvedPosition =\n sourceAdjustment?.position ??\n (adjustment.position !== null && adjustment.position !== undefined\n ? adjustment.position\n : index);\n return {\n scope: adjustment.scope ?? \"order\",\n kind: adjustment.kind ?? \"custom\",\n code: adjustment.code ?? null,\n label: adjustment.label ?? null,\n calculatorKey: adjustment.calculatorKey ?? null,\n promotionId: adjustment.promotionId ?? null,\n rate: toNumericString(adjustment.rate) ?? \"0\",\n amountNet: toNumericString(adjustment.amountNet) ?? \"0\",\n amountGross:\n toNumericString(adjustment.amountGross ?? adjustment.amountNet) ?? \"0\",\n currencyCode: adjustment.currencyCode ?? null,\n metadata,\n position: resolvedPosition,\n organizationId: document.organizationId,\n tenantId: document.tenantId,\n };\n}\n\nasync function applyOrderLineResults(params: {\n em: EntityManager;\n order: SalesOrder;\n calculation: SalesDocumentCalculationResult;\n sourceLines: Array<DocumentLineCreateInput & { id?: string }>;\n existingLines: SalesOrderLine[];\n}): Promise<void> {\n const { em, order, calculation, sourceLines, existingLines } = params;\n const existingMap = new Map(existingLines.map((line) => [line.id, line]));\n const persisted = new Set<string>();\n const statusCache = new Map<string, string | null>();\n const resolveStatus = async (entryId?: string | null) => {\n if (!entryId) return null;\n if (statusCache.has(entryId)) return statusCache.get(entryId) ?? null;\n const value = await resolveDictionaryEntryValue(em, entryId, { tenantId: order.tenantId });\n statusCache.set(entryId, value);\n return value;\n };\n for (let index = 0; index < calculation.lines.length; index += 1) {\n const lineResult = calculation.lines[index];\n const sourceLine = sourceLines[index];\n const statusEntryId = (sourceLine as any).statusEntryId ?? null;\n const statusValue = await resolveStatus(statusEntryId ?? null);\n const payload = convertLineCalculationToEntityInput(\n lineResult,\n sourceLine,\n order,\n index,\n );\n const existing = sourceLine.id\n ? (existingMap.get(sourceLine.id) ?? null)\n : null;\n const lineEntity =\n existing ??\n em.create(SalesOrderLine, {\n order,\n id: sourceLine.id ?? undefined,\n reservedQuantity: existing?.reservedQuantity ?? \"0\",\n fulfilledQuantity: existing?.fulfilledQuantity ?? \"0\",\n invoicedQuantity: existing?.invoicedQuantity ?? \"0\",\n returnedQuantity: existing?.returnedQuantity ?? \"0\",\n createdAt: existing?.createdAt ?? new Date(),\n updatedAt: new Date(),\n });\n Object.assign(lineEntity, {\n ...payload,\n order,\n statusEntryId,\n status: statusValue,\n });\n em.persist(lineEntity);\n const rawCustomFields = (sourceLine as any).customFields;\n if (rawCustomFields !== undefined && rawCustomFields !== null) {\n const customValues =\n rawCustomFields && typeof rawCustomFields === \"object\"\n ? (rawCustomFields as Record<string, unknown>)\n : {};\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order_line,\n recordId: lineEntity.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n values: normalizeCustomFieldValues(customValues),\n });\n }\n persisted.add(lineEntity.id);\n }\n for (const [id, line] of existingMap.entries()) {\n if (!persisted.has(id)) {\n em.remove(line);\n }\n }\n}\n\nasync function applyQuoteLineResults(params: {\n em: EntityManager;\n quote: SalesQuote;\n calculation: SalesDocumentCalculationResult;\n sourceLines: Array<DocumentLineCreateInput & { id?: string }>;\n existingLines: SalesQuoteLine[];\n}): Promise<void> {\n const { em, quote, calculation, sourceLines, existingLines } = params;\n const existingMap = new Map(existingLines.map((line) => [line.id, line]));\n const persisted = new Set<string>();\n const statusCache = new Map<string, string | null>();\n const resolveStatus = async (entryId?: string | null) => {\n if (!entryId) return null;\n if (statusCache.has(entryId)) return statusCache.get(entryId) ?? null;\n const value = await resolveDictionaryEntryValue(em, entryId, { tenantId: quote.tenantId });\n statusCache.set(entryId, value);\n return value;\n };\n for (let index = 0; index < calculation.lines.length; index += 1) {\n const lineResult = calculation.lines[index];\n const sourceLine = sourceLines[index];\n const statusEntryId = (sourceLine as any).statusEntryId ?? null;\n const statusValue = await resolveStatus(statusEntryId ?? null);\n const payload = convertLineCalculationToEntityInput(\n lineResult,\n sourceLine,\n quote,\n index,\n );\n const existing = sourceLine.id\n ? (existingMap.get(sourceLine.id) ?? null)\n : null;\n const lineEntity =\n existing ??\n em.create(SalesQuoteLine, {\n quote,\n id: sourceLine.id ?? undefined,\n createdAt: existing?.createdAt ?? new Date(),\n updatedAt: new Date(),\n });\n Object.assign(lineEntity, {\n ...payload,\n quote,\n statusEntryId,\n status: statusValue,\n });\n em.persist(lineEntity);\n const rawCustomFields = (sourceLine as any).customFields;\n if (rawCustomFields !== undefined && rawCustomFields !== null) {\n const customValues =\n rawCustomFields && typeof rawCustomFields === \"object\"\n ? (rawCustomFields as Record<string, unknown>)\n : {};\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_quote_line,\n recordId: lineEntity.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n values: normalizeCustomFieldValues(customValues),\n });\n }\n persisted.add(lineEntity.id);\n }\n for (const [id, line] of existingMap.entries()) {\n if (!persisted.has(id)) {\n em.remove(line);\n }\n }\n}\n\nasync function replaceQuoteLines(\n em: EntityManager,\n quote: SalesQuote,\n calculation: SalesDocumentCalculationResult,\n lineInputs: QuoteLineCreateInput[],\n): Promise<void> {\n await em.nativeDelete(SalesQuoteLine, { quote: quote.id });\n const statusCache = new Map<string, string | null>();\n const resolveStatus = async (entryId?: string | null) => {\n if (!entryId) return null;\n if (statusCache.has(entryId)) return statusCache.get(entryId) ?? null;\n const value = await resolveDictionaryEntryValue(em, entryId, { tenantId: quote.tenantId });\n statusCache.set(entryId, value);\n return value;\n };\n for (let index = 0; index < calculation.lines.length; index += 1) {\n const lineResult = calculation.lines[index];\n const sourceLine = lineInputs[index];\n const entityInput = convertLineCalculationToEntityInput(\n lineResult,\n sourceLine,\n quote,\n index,\n );\n const statusValue = await resolveStatus(sourceLine.statusEntryId ?? null);\n const lineEntity = em.create(SalesQuoteLine, {\n quote,\n ...entityInput,\n status: statusValue,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(lineEntity);\n const rawCustomFields = (sourceLine as any).customFields;\n if (rawCustomFields !== undefined && rawCustomFields !== null) {\n const customValues =\n rawCustomFields && typeof rawCustomFields === \"object\"\n ? (rawCustomFields as Record<string, unknown>)\n : {};\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_quote_line,\n recordId: lineEntity.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n values: normalizeCustomFieldValues(customValues),\n });\n }\n }\n}\n\nasync function replaceQuoteAdjustments(\n em: EntityManager,\n quote: SalesQuote,\n calculation: SalesDocumentCalculationResult,\n adjustmentInputs: QuoteAdjustmentCreateInput[] | null,\n): Promise<void> {\n const existing = await em.find(\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n );\n const existingMap = new Map<string, SalesQuoteAdjustment>();\n existing.forEach((adj) => existingMap.set(adj.id, adj));\n const seen = new Set<string>();\n const adjustmentDrafts = calculation.adjustments;\n for (let index = 0; index < adjustmentDrafts.length; index += 1) {\n const draft = adjustmentDrafts[index];\n const sourceById =\n adjustmentInputs?.find((adj) => (adj as any).id === draft.id) ?? null;\n const source =\n sourceById ??\n (adjustmentInputs ? (adjustmentInputs[index] ?? null) : null);\n const entityInput = convertAdjustmentResultToEntityInput(\n draft,\n source,\n quote,\n index,\n );\n const adjustmentId =\n (draft as any).id ?? (source as any)?.id ?? randomUUID();\n const existingEntity = existingMap.get(adjustmentId);\n const entity =\n existingEntity ??\n em.create(SalesQuoteAdjustment, {\n id: adjustmentId,\n quote,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n createdAt: new Date(),\n });\n entity.scope = entityInput.scope;\n entity.kind = entityInput.kind;\n entity.code = entityInput.code ?? null;\n entity.label = entityInput.label ?? null;\n entity.calculatorKey = entityInput.calculatorKey ?? null;\n entity.promotionId = entityInput.promotionId ?? null;\n entity.rate = entityInput.rate ?? \"0\";\n entity.amountNet = entityInput.amountNet ?? \"0\";\n entity.amountGross =\n entityInput.amountGross ?? entityInput.amountNet ?? \"0\";\n entity.currencyCode = entityInput.currencyCode ?? quote.currencyCode;\n entity.metadata = entityInput.metadata ?? null;\n entity.position = entityInput.position ?? index;\n entity.updatedAt = new Date();\n entity.quoteLine = null;\n seen.add(adjustmentId);\n if (source?.customFields !== undefined) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_quote_adjustment,\n recordId: adjustmentId,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n values:\n source.customFields && typeof source.customFields === \"object\"\n ? (source.customFields as Record<string, unknown>)\n : {},\n });\n }\n em.persist(entity);\n }\n\n existing.forEach((adj) => {\n if (!seen.has(adj.id)) {\n em.remove(adj);\n }\n });\n}\n\nasync function replaceOrderLines(\n em: EntityManager,\n order: SalesOrder,\n calculation: SalesDocumentCalculationResult,\n lineInputs: OrderLineCreateInput[],\n): Promise<void> {\n await em.nativeDelete(SalesOrderLine, { order: order.id });\n const statusCache = new Map<string, string | null>();\n const resolveStatus = async (entryId?: string | null) => {\n if (!entryId) return null;\n if (statusCache.has(entryId)) return statusCache.get(entryId) ?? null;\n const value = await resolveDictionaryEntryValue(em, entryId, { tenantId: order.tenantId });\n statusCache.set(entryId, value);\n return value;\n };\n for (let index = 0; index < calculation.lines.length; index += 1) {\n const lineResult = calculation.lines[index];\n const sourceLine = lineInputs[index];\n const entityInput = convertLineCalculationToEntityInput(\n lineResult,\n sourceLine,\n order,\n index,\n );\n const statusValue = await resolveStatus(sourceLine.statusEntryId ?? null);\n const lineEntity = em.create(SalesOrderLine, {\n order,\n ...entityInput,\n reservedQuantity: \"0\",\n fulfilledQuantity: \"0\",\n invoicedQuantity: \"0\",\n returnedQuantity: \"0\",\n status: statusValue,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(lineEntity);\n const rawCustomFields = (sourceLine as any).customFields;\n if (rawCustomFields !== undefined && rawCustomFields !== null) {\n const customValues =\n rawCustomFields && typeof rawCustomFields === \"object\"\n ? (rawCustomFields as Record<string, unknown>)\n : {};\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order_line,\n recordId: lineEntity.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n values: normalizeCustomFieldValues(customValues),\n });\n }\n }\n}\n\nasync function replaceOrderAdjustments(\n em: EntityManager,\n order: SalesOrder,\n calculation: SalesDocumentCalculationResult,\n adjustmentInputs: OrderAdjustmentCreateInput[] | null,\n): Promise<void> {\n const existing = await em.find(\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n );\n const existingMap = new Map<string, SalesOrderAdjustment>();\n existing.forEach((adj) => existingMap.set(adj.id, adj));\n const seen = new Set<string>();\n const adjustmentDrafts = calculation.adjustments;\n for (let index = 0; index < adjustmentDrafts.length; index += 1) {\n const draft = adjustmentDrafts[index];\n const sourceById =\n adjustmentInputs?.find((adj) => (adj as any).id === draft.id) ?? null;\n const source =\n sourceById ??\n (adjustmentInputs ? (adjustmentInputs[index] ?? null) : null);\n const entityInput = convertAdjustmentResultToEntityInput(\n draft,\n source,\n order,\n index,\n );\n const adjustmentId =\n (draft as any).id ?? (source as any)?.id ?? randomUUID();\n const existingEntity = existingMap.get(adjustmentId);\n const entity =\n existingEntity ??\n em.create(SalesOrderAdjustment, {\n id: adjustmentId,\n order,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n createdAt: new Date(),\n });\n entity.scope = entityInput.scope;\n entity.kind = entityInput.kind;\n entity.code = entityInput.code ?? null;\n entity.label = entityInput.label ?? null;\n entity.calculatorKey = entityInput.calculatorKey ?? null;\n entity.promotionId = entityInput.promotionId ?? null;\n entity.rate = entityInput.rate ?? \"0\";\n entity.amountNet = entityInput.amountNet ?? \"0\";\n entity.amountGross =\n entityInput.amountGross ?? entityInput.amountNet ?? \"0\";\n entity.currencyCode = entityInput.currencyCode ?? order.currencyCode;\n entity.metadata = entityInput.metadata ?? null;\n entity.position = entityInput.position ?? index;\n entity.updatedAt = new Date();\n entity.orderLine = null;\n seen.add(adjustmentId);\n if (source?.customFields !== undefined) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order_adjustment,\n recordId: adjustmentId,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n values:\n source.customFields && typeof source.customFields === \"object\"\n ? (source.customFields as Record<string, unknown>)\n : {},\n });\n }\n em.persist(entity);\n }\n\n existing.forEach((adj) => {\n if (!seen.has(adj.id)) {\n em.remove(adj);\n }\n });\n}\n\nfunction applyQuoteTotals(\n quote: SalesQuote,\n totals: SalesDocumentCalculationResult[\"totals\"],\n lineCount: number,\n): void {\n quote.subtotalNetAmount = toNumericString(totals.subtotalNetAmount) ?? \"0\";\n quote.subtotalGrossAmount =\n toNumericString(totals.subtotalGrossAmount) ?? \"0\";\n quote.discountTotalAmount =\n toNumericString(totals.discountTotalAmount) ?? \"0\";\n quote.taxTotalAmount = toNumericString(totals.taxTotalAmount) ?? \"0\";\n quote.grandTotalNetAmount =\n toNumericString(totals.grandTotalNetAmount) ?? \"0\";\n quote.grandTotalGrossAmount =\n toNumericString(totals.grandTotalGrossAmount) ?? \"0\";\n quote.totalsSnapshot = cloneJson(totals);\n quote.lineItemCount = lineCount;\n}\n\nfunction applyOrderTotals(\n order: SalesOrder,\n totals: SalesDocumentCalculationResult[\"totals\"],\n lineCount: number,\n): void {\n order.subtotalNetAmount = toNumericString(totals.subtotalNetAmount) ?? \"0\";\n order.subtotalGrossAmount =\n toNumericString(totals.subtotalGrossAmount) ?? \"0\";\n order.discountTotalAmount =\n toNumericString(totals.discountTotalAmount) ?? \"0\";\n order.taxTotalAmount = toNumericString(totals.taxTotalAmount) ?? \"0\";\n order.shippingNetAmount = toNumericString(totals.shippingNetAmount) ?? \"0\";\n order.shippingGrossAmount =\n toNumericString(totals.shippingGrossAmount) ?? \"0\";\n order.surchargeTotalAmount =\n toNumericString(totals.surchargeTotalAmount) ?? \"0\";\n order.grandTotalNetAmount =\n toNumericString(totals.grandTotalNetAmount) ?? \"0\";\n order.grandTotalGrossAmount =\n toNumericString(totals.grandTotalGrossAmount) ?? \"0\";\n order.paidTotalAmount = toNumericString(totals.paidTotalAmount) ?? \"0\";\n order.refundedTotalAmount =\n toNumericString(totals.refundedTotalAmount) ?? \"0\";\n order.outstandingAmount = toNumericString(totals.outstandingAmount) ?? \"0\";\n order.totalsSnapshot = cloneJson(totals);\n order.lineItemCount = lineCount;\n}\n\nfunction normalizePaymentTotal(value: unknown): number {\n if (typeof value === \"number\" && Number.isFinite(value))\n return Math.max(value, 0);\n if (typeof value === \"string\" && value.trim().length) {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? Math.max(parsed, 0) : 0;\n }\n return 0;\n}\n\nfunction resolveExistingPaymentTotals(order: SalesOrder) {\n return {\n paidTotalAmount: normalizePaymentTotal(order.paidTotalAmount),\n refundedTotalAmount: normalizePaymentTotal(order.refundedTotalAmount),\n };\n}\n\nfunction ensureQuoteScope(\n ctx: Parameters<typeof ensureTenantScope>[0],\n organizationId: string,\n tenantId: string,\n): void {\n ensureTenantScope(ctx, tenantId);\n ensureOrganizationScope(ctx, organizationId);\n}\n\nfunction ensureOrderScope(\n ctx: Parameters<typeof ensureTenantScope>[0],\n organizationId: string,\n tenantId: string,\n): void {\n ensureTenantScope(ctx, tenantId);\n ensureOrganizationScope(ctx, organizationId);\n}\n\nfunction normalizeTagIds(tags?: Array<string | null | undefined>): string[] {\n if (!Array.isArray(tags)) return [];\n const set = new Set<string>();\n tags.forEach((id) => {\n if (typeof id === \"string\" && id.trim().length > 0) set.add(id.trim());\n });\n return Array.from(set);\n}\n\nfunction buildTagChange(\n beforeTags: TagAssignmentSnapshot[] | undefined,\n afterTags: TagAssignmentSnapshot[] | undefined,\n): { from: string[]; to: string[] } | null {\n const beforeIds = normalizeTagIds(beforeTags?.map((tag) => tag.tagId));\n const afterIds = normalizeTagIds(afterTags?.map((tag) => tag.tagId));\n beforeIds.sort((a, b) => a.localeCompare(b));\n afterIds.sort((a, b) => a.localeCompare(b));\n if (\n beforeIds.length === afterIds.length &&\n beforeIds.every((id, index) => id === afterIds[index])\n ) {\n return null;\n }\n return { from: beforeIds, to: afterIds };\n}\n\nfunction buildDocumentUpdateChangeKeys(kind: SalesDocumentKind, input: DocumentUpdateInput): string[] {\n const keys = new Set<string>();\n if (kind === \"order\") {\n if (input.orderNumber !== undefined) keys.add(\"orderNumber\");\n } else {\n if (input.quoteNumber !== undefined) keys.add(\"quoteNumber\");\n }\n if (input.statusEntryId !== undefined) {\n keys.add(\"statusEntryId\");\n keys.add(\"status\");\n }\n if (input.customerEntityId !== undefined) {\n keys.add(\"customerEntityId\");\n keys.add(\"customerContactId\");\n keys.add(\"customerSnapshot\");\n keys.add(\"billingAddressId\");\n keys.add(\"shippingAddressId\");\n keys.add(\"billingAddressSnapshot\");\n keys.add(\"shippingAddressSnapshot\");\n }\n if (input.customerContactId !== undefined) {\n keys.add(\"customerContactId\");\n keys.add(\"customerSnapshot\");\n }\n if (input.customerSnapshot !== undefined) keys.add(\"customerSnapshot\");\n if (input.metadata !== undefined) keys.add(\"metadata\");\n if (input.comment !== undefined) keys.add(\"comments\");\n if (input.currencyCode !== undefined) keys.add(\"currencyCode\");\n if (input.channelId !== undefined) keys.add(\"channelId\");\n if (kind === \"order\") {\n if (input.placedAt !== undefined) keys.add(\"placedAt\");\n if (input.expectedDeliveryAt !== undefined) keys.add(\"expectedDeliveryAt\");\n }\n if (\n input.shippingAddressId !== undefined ||\n input.shippingAddressSnapshot !== undefined\n ) {\n keys.add(\"shippingAddressId\");\n keys.add(\"shippingAddressSnapshot\");\n }\n if (\n input.billingAddressId !== undefined ||\n input.billingAddressSnapshot !== undefined\n ) {\n keys.add(\"billingAddressId\");\n keys.add(\"billingAddressSnapshot\");\n }\n if (\n input.shippingMethodId !== undefined ||\n input.shippingMethodCode !== undefined ||\n input.shippingMethodSnapshot !== undefined\n ) {\n keys.add(\"shippingMethodId\");\n keys.add(\"shippingMethodCode\");\n keys.add(\"shippingMethodSnapshot\");\n }\n if (\n input.paymentMethodId !== undefined ||\n input.paymentMethodCode !== undefined ||\n input.paymentMethodSnapshot !== undefined\n ) {\n keys.add(\"paymentMethodId\");\n keys.add(\"paymentMethodCode\");\n keys.add(\"paymentMethodSnapshot\");\n }\n if (input.customFieldSetId !== undefined) keys.add(\"customFieldSetId\");\n if (input.customFields !== undefined) keys.add(\"customFields\");\n return Array.from(keys);\n}\n\nasync function syncSalesDocumentTags(\n em: EntityManager,\n params: {\n documentId: string;\n kind: SalesDocumentKind;\n organizationId: string;\n tenantId: string;\n tagIds?: Array<string | null | undefined> | null;\n },\n) {\n if (params.tagIds === undefined) return;\n const tagIds = normalizeTagIds(params.tagIds);\n if (tagIds.length === 0) {\n await em.nativeDelete(SalesDocumentTagAssignment, {\n documentId: params.documentId,\n documentKind: params.kind,\n });\n return;\n }\n const tagsInScope = await em.find(SalesDocumentTag, {\n id: { $in: tagIds },\n organizationId: params.organizationId,\n tenantId: params.tenantId,\n });\n if (tagsInScope.length !== tagIds.length) {\n throw new CrudHttpError(400, {\n error: \"One or more tags not found for this scope\",\n });\n }\n const byId = new Map(tagsInScope.map((tag) => [tag.id, tag]));\n await em.nativeDelete(SalesDocumentTagAssignment, {\n documentId: params.documentId,\n documentKind: params.kind,\n });\n for (const tagId of tagIds) {\n const tag = byId.get(tagId);\n if (!tag) continue;\n const assignment = em.create(SalesDocumentTagAssignment, {\n organizationId: params.organizationId,\n tenantId: params.tenantId,\n documentId: params.documentId,\n documentKind: params.kind,\n tag,\n order:\n params.kind === \"order\"\n ? em.getReference(SalesOrder, params.documentId)\n : null,\n quote:\n params.kind === \"quote\"\n ? em.getReference(SalesQuote, params.documentId)\n : null,\n });\n em.persist(assignment);\n }\n}\n\nfunction applyQuoteSnapshot(\n quote: SalesQuote,\n snapshot: QuoteGraphSnapshot[\"quote\"],\n): void {\n quote.organizationId = snapshot.organizationId;\n quote.tenantId = snapshot.tenantId;\n quote.quoteNumber = snapshot.quoteNumber;\n quote.statusEntryId = snapshot.statusEntryId ?? null;\n quote.status = snapshot.status ?? null;\n quote.customerEntityId = snapshot.customerEntityId ?? null;\n quote.customerContactId = snapshot.customerContactId ?? null;\n quote.customerSnapshot = snapshot.customerSnapshot\n ? cloneJson(snapshot.customerSnapshot)\n : null;\n quote.billingAddressId = snapshot.billingAddressId ?? null;\n quote.shippingAddressId = snapshot.shippingAddressId ?? null;\n quote.billingAddressSnapshot = snapshot.billingAddressSnapshot\n ? cloneJson(snapshot.billingAddressSnapshot)\n : null;\n quote.shippingAddressSnapshot = snapshot.shippingAddressSnapshot\n ? cloneJson(snapshot.shippingAddressSnapshot)\n : null;\n quote.currencyCode = snapshot.currencyCode;\n quote.validFrom = snapshot.validFrom ? new Date(snapshot.validFrom) : null;\n quote.validUntil = snapshot.validUntil ? new Date(snapshot.validUntil) : null;\n quote.comments = snapshot.comments ?? null;\n quote.taxInfo = snapshot.taxInfo ? cloneJson(snapshot.taxInfo) : null;\n quote.shippingMethodId = snapshot.shippingMethodId ?? null;\n quote.shippingMethodCode = snapshot.shippingMethodCode ?? null;\n quote.deliveryWindowId = snapshot.deliveryWindowId ?? null;\n quote.deliveryWindowCode = snapshot.deliveryWindowCode ?? null;\n quote.paymentMethodId = snapshot.paymentMethodId ?? null;\n quote.paymentMethodCode = snapshot.paymentMethodCode ?? null;\n quote.shippingMethodSnapshot = snapshot.shippingMethodSnapshot\n ? cloneJson(snapshot.shippingMethodSnapshot)\n : null;\n quote.deliveryWindowSnapshot = snapshot.deliveryWindowSnapshot\n ? cloneJson(snapshot.deliveryWindowSnapshot)\n : null;\n quote.paymentMethodSnapshot = snapshot.paymentMethodSnapshot\n ? cloneJson(snapshot.paymentMethodSnapshot)\n : null;\n quote.metadata = snapshot.metadata ? cloneJson(snapshot.metadata) : null;\n quote.channelId = snapshot.channelId ?? null;\n quote.customFieldSetId = snapshot.customFieldSetId ?? null;\n quote.subtotalNetAmount = snapshot.subtotalNetAmount;\n quote.subtotalGrossAmount = snapshot.subtotalGrossAmount;\n quote.discountTotalAmount = snapshot.discountTotalAmount;\n quote.taxTotalAmount = snapshot.taxTotalAmount;\n quote.grandTotalNetAmount = snapshot.grandTotalNetAmount;\n quote.grandTotalGrossAmount = snapshot.grandTotalGrossAmount;\n quote.totalsSnapshot = snapshot.totalsSnapshot\n ? cloneJson(snapshot.totalsSnapshot)\n : null;\n quote.lineItemCount = snapshot.lineItemCount;\n}\n\nfunction applyOrderSnapshot(\n order: SalesOrder,\n snapshot: OrderGraphSnapshot[\"order\"],\n): void {\n order.organizationId = snapshot.organizationId;\n order.tenantId = snapshot.tenantId;\n order.orderNumber = snapshot.orderNumber;\n order.statusEntryId = snapshot.statusEntryId ?? null;\n order.status = snapshot.status ?? null;\n order.fulfillmentStatusEntryId = snapshot.fulfillmentStatusEntryId ?? null;\n order.fulfillmentStatus = snapshot.fulfillmentStatus ?? null;\n order.paymentStatusEntryId = snapshot.paymentStatusEntryId ?? null;\n order.paymentStatus = snapshot.paymentStatus ?? null;\n order.customerEntityId = snapshot.customerEntityId ?? null;\n order.customerContactId = snapshot.customerContactId ?? null;\n order.customerSnapshot = snapshot.customerSnapshot\n ? cloneJson(snapshot.customerSnapshot)\n : null;\n order.billingAddressId = snapshot.billingAddressId ?? null;\n order.shippingAddressId = snapshot.shippingAddressId ?? null;\n order.billingAddressSnapshot = snapshot.billingAddressSnapshot\n ? cloneJson(snapshot.billingAddressSnapshot)\n : null;\n order.shippingAddressSnapshot = snapshot.shippingAddressSnapshot\n ? cloneJson(snapshot.shippingAddressSnapshot)\n : null;\n order.currencyCode = snapshot.currencyCode;\n order.exchangeRate = snapshot.exchangeRate ?? null;\n order.taxStrategyKey = snapshot.taxStrategyKey ?? null;\n order.discountStrategyKey = snapshot.discountStrategyKey ?? null;\n order.taxInfo = snapshot.taxInfo ? cloneJson(snapshot.taxInfo) : null;\n order.shippingMethodId = snapshot.shippingMethodId ?? null;\n order.shippingMethodCode = snapshot.shippingMethodCode ?? null;\n order.deliveryWindowId = snapshot.deliveryWindowId ?? null;\n order.deliveryWindowCode = snapshot.deliveryWindowCode ?? null;\n order.paymentMethodId = snapshot.paymentMethodId ?? null;\n order.paymentMethodCode = snapshot.paymentMethodCode ?? null;\n order.channelId = snapshot.channelId ?? null;\n order.placedAt = snapshot.placedAt ? new Date(snapshot.placedAt) : null;\n order.expectedDeliveryAt = snapshot.expectedDeliveryAt\n ? new Date(snapshot.expectedDeliveryAt)\n : null;\n order.dueAt = snapshot.dueAt ? new Date(snapshot.dueAt) : null;\n order.comments = snapshot.comments ?? null;\n order.internalNotes = snapshot.internalNotes ?? null;\n order.shippingMethodSnapshot = snapshot.shippingMethodSnapshot\n ? cloneJson(snapshot.shippingMethodSnapshot)\n : null;\n order.deliveryWindowSnapshot = snapshot.deliveryWindowSnapshot\n ? cloneJson(snapshot.deliveryWindowSnapshot)\n : null;\n order.paymentMethodSnapshot = snapshot.paymentMethodSnapshot\n ? cloneJson(snapshot.paymentMethodSnapshot)\n : null;\n order.metadata = snapshot.metadata ? cloneJson(snapshot.metadata) : null;\n order.customFieldSetId = snapshot.customFieldSetId ?? null;\n order.subtotalNetAmount = snapshot.subtotalNetAmount;\n order.subtotalGrossAmount = snapshot.subtotalGrossAmount;\n order.discountTotalAmount = snapshot.discountTotalAmount;\n order.taxTotalAmount = snapshot.taxTotalAmount;\n order.shippingNetAmount = snapshot.shippingNetAmount;\n order.shippingGrossAmount = snapshot.shippingGrossAmount;\n order.surchargeTotalAmount = snapshot.surchargeTotalAmount;\n order.grandTotalNetAmount = snapshot.grandTotalNetAmount;\n order.grandTotalGrossAmount = snapshot.grandTotalGrossAmount;\n order.paidTotalAmount = snapshot.paidTotalAmount;\n order.refundedTotalAmount = snapshot.refundedTotalAmount;\n order.outstandingAmount = snapshot.outstandingAmount;\n order.totalsSnapshot = snapshot.totalsSnapshot\n ? cloneJson(snapshot.totalsSnapshot)\n : null;\n order.lineItemCount = snapshot.lineItemCount;\n}\n\nasync function restoreQuoteGraph(\n em: EntityManager,\n snapshot: QuoteGraphSnapshot,\n): Promise<SalesQuote> {\n let quote = await em.findOne(SalesQuote, { id: snapshot.quote.id });\n if (!quote) {\n quote = em.create(SalesQuote, {\n id: snapshot.quote.id,\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n quoteNumber: snapshot.quote.quoteNumber,\n statusEntryId: snapshot.quote.statusEntryId ?? null,\n status: snapshot.quote.status ?? null,\n customerEntityId: snapshot.quote.customerEntityId ?? null,\n customerContactId: snapshot.quote.customerContactId ?? null,\n customerSnapshot: snapshot.quote.customerSnapshot\n ? cloneJson(snapshot.quote.customerSnapshot)\n : null,\n billingAddressId: snapshot.quote.billingAddressId ?? null,\n shippingAddressId: snapshot.quote.shippingAddressId ?? null,\n billingAddressSnapshot: snapshot.quote.billingAddressSnapshot\n ? cloneJson(snapshot.quote.billingAddressSnapshot)\n : null,\n shippingAddressSnapshot: snapshot.quote.shippingAddressSnapshot\n ? cloneJson(snapshot.quote.shippingAddressSnapshot)\n : null,\n currencyCode: snapshot.quote.currencyCode,\n validFrom: snapshot.quote.validFrom\n ? new Date(snapshot.quote.validFrom)\n : null,\n validUntil: snapshot.quote.validUntil\n ? new Date(snapshot.quote.validUntil)\n : null,\n comments: snapshot.quote.comments ?? null,\n taxInfo: snapshot.quote.taxInfo\n ? cloneJson(snapshot.quote.taxInfo)\n : null,\n shippingMethodId: snapshot.quote.shippingMethodId ?? null,\n shippingMethodCode: snapshot.quote.shippingMethodCode ?? null,\n deliveryWindowId: snapshot.quote.deliveryWindowId ?? null,\n deliveryWindowCode: snapshot.quote.deliveryWindowCode ?? null,\n paymentMethodId: snapshot.quote.paymentMethodId ?? null,\n paymentMethodCode: snapshot.quote.paymentMethodCode ?? null,\n shippingMethodSnapshot: snapshot.quote.shippingMethodSnapshot\n ? cloneJson(snapshot.quote.shippingMethodSnapshot)\n : null,\n deliveryWindowSnapshot: snapshot.quote.deliveryWindowSnapshot\n ? cloneJson(snapshot.quote.deliveryWindowSnapshot)\n : null,\n paymentMethodSnapshot: snapshot.quote.paymentMethodSnapshot\n ? cloneJson(snapshot.quote.paymentMethodSnapshot)\n : null,\n metadata: snapshot.quote.metadata\n ? cloneJson(snapshot.quote.metadata)\n : null,\n channelId: snapshot.quote.channelId ?? null,\n customFieldSetId: snapshot.quote.customFieldSetId ?? null,\n subtotalNetAmount: snapshot.quote.subtotalNetAmount,\n subtotalGrossAmount: snapshot.quote.subtotalGrossAmount,\n discountTotalAmount: snapshot.quote.discountTotalAmount,\n taxTotalAmount: snapshot.quote.taxTotalAmount,\n grandTotalNetAmount: snapshot.quote.grandTotalNetAmount,\n grandTotalGrossAmount: snapshot.quote.grandTotalGrossAmount,\n totalsSnapshot: snapshot.quote.totalsSnapshot\n ? cloneJson(snapshot.quote.totalsSnapshot)\n : null,\n lineItemCount: snapshot.quote.lineItemCount,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(quote);\n }\n applyQuoteSnapshot(quote, snapshot.quote);\n await em.flush();\n const existingLines = await em.find(\n SalesQuoteLine,\n { quote: quote.id },\n { fields: [\"id\"] },\n );\n const existingAdjustments = await em.find(\n SalesQuoteAdjustment,\n { quote: quote.id },\n { fields: [\"id\"] },\n );\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_quote,\n recordId: quote.id,\n });\n if (existingLines.length) {\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_quote_line,\n recordId: { $in: existingLines.map((line) => line.id) },\n });\n }\n if (existingAdjustments.length) {\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_quote_adjustment,\n recordId: { $in: existingAdjustments.map((adj) => adj.id) },\n });\n }\n const addressSnapshots = Array.isArray(snapshot.addresses)\n ? snapshot.addresses\n : [];\n const noteSnapshots = Array.isArray(snapshot.notes) ? snapshot.notes : [];\n const tagSnapshots = Array.isArray(snapshot.tags) ? snapshot.tags : [];\n await em.nativeDelete(SalesDocumentAddress, {\n documentId: quote.id,\n documentKind: \"quote\",\n });\n await em.nativeDelete(SalesNote, {\n contextType: \"quote\",\n contextId: quote.id,\n });\n await em.nativeDelete(SalesDocumentTagAssignment, {\n documentId: quote.id,\n documentKind: \"quote\",\n });\n await em.nativeDelete(SalesQuoteLine, { quote: quote.id });\n await em.nativeDelete(SalesQuoteAdjustment, { quote: quote.id });\n existingLines.forEach((entry) => em.getUnitOfWork().unsetIdentity(entry));\n existingAdjustments.forEach((entry) =>\n em.getUnitOfWork().unsetIdentity(entry),\n );\n\n snapshot.lines.forEach((line) => {\n const lineEntity = em.create(SalesQuoteLine, {\n id: line.id,\n quote,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n lineNumber: line.lineNumber,\n kind: line.kind as SalesLineKind,\n statusEntryId: line.statusEntryId ?? null,\n status: line.status ?? null,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: line.normalizedQuantity ?? line.quantity,\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n discountAmount: line.discountAmount,\n discountPercent: line.discountPercent,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n totalNetAmount: line.totalNetAmount,\n totalGrossAmount: line.totalGrossAmount,\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(lineEntity);\n });\n\n snapshot.adjustments.forEach((adjustment, index) => {\n const adjustmentEntity = em.create(SalesQuoteAdjustment, {\n id: adjustment.id,\n quote,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n scope: adjustment.scope,\n kind: adjustment.kind as SalesAdjustmentKind,\n code: adjustment.code ?? null,\n label: adjustment.label ?? null,\n calculatorKey: adjustment.calculatorKey ?? null,\n promotionId: adjustment.promotionId ?? null,\n rate: adjustment.rate,\n amountNet: adjustment.amountNet,\n amountGross: adjustment.amountGross,\n currencyCode: adjustment.currencyCode ?? null,\n metadata: adjustment.metadata ? cloneJson(adjustment.metadata) : null,\n position: adjustment.position ?? index,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n adjustmentEntity.quoteLine = null;\n em.persist(adjustmentEntity);\n });\n\n addressSnapshots.forEach((entry) => {\n const entity = em.create(SalesDocumentAddress, {\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n documentId: quote.id,\n documentKind: \"quote\",\n customerAddressId: entry.customerAddressId ?? null,\n name: entry.name ?? null,\n purpose: entry.purpose ?? null,\n companyName: entry.companyName ?? null,\n addressLine1: entry.addressLine1,\n addressLine2: entry.addressLine2 ?? null,\n city: entry.city ?? null,\n region: entry.region ?? null,\n postalCode: entry.postalCode ?? null,\n country: entry.country ?? null,\n buildingNumber: entry.buildingNumber ?? null,\n flatNumber: entry.flatNumber ?? null,\n latitude: entry.latitude ?? null,\n longitude: entry.longitude ?? null,\n quote,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(entity);\n });\n\n noteSnapshots.forEach((entry) => {\n const entity = em.create(SalesNote, {\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n contextType: \"quote\",\n contextId: quote.id,\n order: null,\n quote,\n body: entry.body,\n authorUserId: entry.authorUserId ?? null,\n appearanceIcon: entry.appearanceIcon ?? null,\n appearanceColor: entry.appearanceColor ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(entity);\n });\n\n tagSnapshots.forEach((entry) => {\n const tag = em.getReference(SalesDocumentTag, entry.tagId);\n const assignment = em.create(SalesDocumentTagAssignment, {\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n documentId: quote.id,\n documentKind: \"quote\",\n tag,\n quote,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(assignment);\n });\n\n if (snapshot.quote.customFields) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_quote,\n recordId: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n values: normalizeCustomFieldValues(snapshot.quote.customFields),\n });\n }\n for (const line of snapshot.lines) {\n if (!line.customFields) continue;\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_quote_line,\n recordId: line.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n values: normalizeCustomFieldValues(line.customFields),\n });\n }\n for (const adjustment of snapshot.adjustments) {\n if (!adjustment.customFields) continue;\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_quote_adjustment,\n recordId: adjustment.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n values: normalizeCustomFieldValues(adjustment.customFields),\n });\n }\n\n return quote;\n}\n\nasync function restoreOrderGraph(\n em: EntityManager,\n snapshot: OrderGraphSnapshot,\n): Promise<SalesOrder> {\n let order = await em.findOne(SalesOrder, { id: snapshot.order.id });\n if (!order) {\n order = em.create(SalesOrder, {\n id: snapshot.order.id,\n organizationId: snapshot.order.organizationId,\n tenantId: snapshot.order.tenantId,\n orderNumber: snapshot.order.orderNumber,\n statusEntryId: snapshot.order.statusEntryId ?? null,\n status: snapshot.order.status ?? null,\n fulfillmentStatusEntryId: snapshot.order.fulfillmentStatusEntryId ?? null,\n fulfillmentStatus: snapshot.order.fulfillmentStatus ?? null,\n paymentStatusEntryId: snapshot.order.paymentStatusEntryId ?? null,\n paymentStatus: snapshot.order.paymentStatus ?? null,\n customerEntityId: snapshot.order.customerEntityId ?? null,\n customerContactId: snapshot.order.customerContactId ?? null,\n customerSnapshot: snapshot.order.customerSnapshot\n ? cloneJson(snapshot.order.customerSnapshot)\n : null,\n billingAddressId: snapshot.order.billingAddressId ?? null,\n shippingAddressId: snapshot.order.shippingAddressId ?? null,\n billingAddressSnapshot: snapshot.order.billingAddressSnapshot\n ? cloneJson(snapshot.order.billingAddressSnapshot)\n : null,\n shippingAddressSnapshot: snapshot.order.shippingAddressSnapshot\n ? cloneJson(snapshot.order.shippingAddressSnapshot)\n : null,\n currencyCode: snapshot.order.currencyCode,\n exchangeRate: snapshot.order.exchangeRate ?? null,\n taxStrategyKey: snapshot.order.taxStrategyKey ?? null,\n discountStrategyKey: snapshot.order.discountStrategyKey ?? null,\n taxInfo: snapshot.order.taxInfo\n ? cloneJson(snapshot.order.taxInfo)\n : null,\n shippingMethodId: snapshot.order.shippingMethodId ?? null,\n shippingMethodCode: snapshot.order.shippingMethodCode ?? null,\n deliveryWindowId: snapshot.order.deliveryWindowId ?? null,\n deliveryWindowCode: snapshot.order.deliveryWindowCode ?? null,\n paymentMethodId: snapshot.order.paymentMethodId ?? null,\n paymentMethodCode: snapshot.order.paymentMethodCode ?? null,\n channelId: snapshot.order.channelId ?? null,\n placedAt: snapshot.order.placedAt\n ? new Date(snapshot.order.placedAt)\n : null,\n expectedDeliveryAt: snapshot.order.expectedDeliveryAt\n ? new Date(snapshot.order.expectedDeliveryAt)\n : null,\n dueAt: snapshot.order.dueAt ? new Date(snapshot.order.dueAt) : null,\n comments: snapshot.order.comments ?? null,\n internalNotes: snapshot.order.internalNotes ?? null,\n shippingMethodSnapshot: snapshot.order.shippingMethodSnapshot\n ? cloneJson(snapshot.order.shippingMethodSnapshot)\n : null,\n deliveryWindowSnapshot: snapshot.order.deliveryWindowSnapshot\n ? cloneJson(snapshot.order.deliveryWindowSnapshot)\n : null,\n paymentMethodSnapshot: snapshot.order.paymentMethodSnapshot\n ? cloneJson(snapshot.order.paymentMethodSnapshot)\n : null,\n metadata: snapshot.order.metadata\n ? cloneJson(snapshot.order.metadata)\n : null,\n customFieldSetId: snapshot.order.customFieldSetId ?? null,\n subtotalNetAmount: snapshot.order.subtotalNetAmount,\n subtotalGrossAmount: snapshot.order.subtotalGrossAmount,\n discountTotalAmount: snapshot.order.discountTotalAmount,\n taxTotalAmount: snapshot.order.taxTotalAmount,\n shippingNetAmount: snapshot.order.shippingNetAmount,\n shippingGrossAmount: snapshot.order.shippingGrossAmount,\n surchargeTotalAmount: snapshot.order.surchargeTotalAmount,\n grandTotalNetAmount: snapshot.order.grandTotalNetAmount,\n grandTotalGrossAmount: snapshot.order.grandTotalGrossAmount,\n paidTotalAmount: snapshot.order.paidTotalAmount,\n refundedTotalAmount: snapshot.order.refundedTotalAmount,\n outstandingAmount: snapshot.order.outstandingAmount,\n totalsSnapshot: snapshot.order.totalsSnapshot\n ? cloneJson(snapshot.order.totalsSnapshot)\n : null,\n lineItemCount: snapshot.order.lineItemCount,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(order);\n }\n applyOrderSnapshot(order, snapshot.order);\n await em.flush();\n const existingLines = await em.find(\n SalesOrderLine,\n { order: order.id },\n { fields: [\"id\"] },\n );\n const existingAdjustments = await em.find(\n SalesOrderAdjustment,\n { order: order.id },\n { fields: [\"id\"] },\n );\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_order,\n recordId: order.id,\n });\n if (existingLines.length) {\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_order_line,\n recordId: { $in: existingLines.map((line) => line.id) },\n });\n }\n if (existingAdjustments.length) {\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_order_adjustment,\n recordId: { $in: existingAdjustments.map((adj) => adj.id) },\n });\n }\n const addressSnapshots = Array.isArray(snapshot.addresses)\n ? snapshot.addresses\n : [];\n const noteSnapshots = Array.isArray(snapshot.notes) ? snapshot.notes : [];\n const tagSnapshots = Array.isArray(snapshot.tags) ? snapshot.tags : [];\n const shipmentSnapshots = Array.isArray(snapshot.shipments)\n ? snapshot.shipments\n : [];\n const paymentSnapshots = Array.isArray(snapshot.payments)\n ? snapshot.payments\n : [];\n const existingShipments = await em.find(SalesShipment, { order: order.id });\n const shipmentIds = existingShipments.map((entry) => entry.id);\n if (shipmentIds.length) {\n await em.nativeDelete(SalesShipmentItem, {\n shipment: { $in: shipmentIds },\n });\n await em.nativeDelete(SalesShipment, { id: { $in: shipmentIds } });\n existingShipments.forEach((entry) =>\n em.getUnitOfWork().unsetIdentity(entry),\n );\n }\n await em.nativeDelete(SalesPaymentAllocation, { order: order.id });\n await em.nativeDelete(SalesPayment, { order: order.id });\n await em.nativeDelete(SalesDocumentAddress, {\n documentId: order.id,\n documentKind: \"order\",\n });\n await em.nativeDelete(SalesNote, {\n contextType: \"order\",\n contextId: order.id,\n });\n await em.nativeDelete(SalesDocumentTagAssignment, {\n documentId: order.id,\n documentKind: \"order\",\n });\n await em.nativeDelete(SalesOrderAdjustment, { order: order.id });\n await em.nativeDelete(SalesOrderLine, { order: order.id });\n existingLines.forEach((entry) => em.getUnitOfWork().unsetIdentity(entry));\n existingAdjustments.forEach((entry) =>\n em.getUnitOfWork().unsetIdentity(entry),\n );\n\n snapshot.lines.forEach((line) => {\n const lineEntity = em.create(SalesOrderLine, {\n id: line.id,\n order,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n lineNumber: line.lineNumber,\n kind: line.kind as SalesLineKind,\n statusEntryId: line.statusEntryId ?? null,\n status: line.status ?? null,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: line.normalizedQuantity ?? line.quantity,\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n reservedQuantity: line.reservedQuantity,\n fulfilledQuantity: line.fulfilledQuantity,\n invoicedQuantity: line.invoicedQuantity,\n returnedQuantity: line.returnedQuantity,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n discountAmount: line.discountAmount,\n discountPercent: line.discountPercent,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n totalNetAmount: line.totalNetAmount,\n totalGrossAmount: line.totalGrossAmount,\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(lineEntity);\n });\n\n snapshot.adjustments.forEach((adjustment, index) => {\n const adjustmentEntity = em.create(SalesOrderAdjustment, {\n id: adjustment.id,\n order,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n scope: adjustment.scope,\n kind: adjustment.kind as SalesAdjustmentKind,\n code: adjustment.code ?? null,\n label: adjustment.label ?? null,\n calculatorKey: adjustment.calculatorKey ?? null,\n promotionId: adjustment.promotionId ?? null,\n rate: adjustment.rate,\n amountNet: adjustment.amountNet,\n amountGross: adjustment.amountGross,\n currencyCode: adjustment.currencyCode ?? null,\n metadata: adjustment.metadata ? cloneJson(adjustment.metadata) : null,\n position: adjustment.position ?? index,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n adjustmentEntity.orderLine = null;\n em.persist(adjustmentEntity);\n });\n\n addressSnapshots.forEach((entry) => {\n const entity = em.create(SalesDocumentAddress, {\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n documentId: order.id,\n documentKind: \"order\",\n customerAddressId: entry.customerAddressId ?? null,\n name: entry.name ?? null,\n purpose: entry.purpose ?? null,\n companyName: entry.companyName ?? null,\n addressLine1: entry.addressLine1,\n addressLine2: entry.addressLine2 ?? null,\n city: entry.city ?? null,\n region: entry.region ?? null,\n postalCode: entry.postalCode ?? null,\n country: entry.country ?? null,\n buildingNumber: entry.buildingNumber ?? null,\n flatNumber: entry.flatNumber ?? null,\n latitude: entry.latitude ?? null,\n longitude: entry.longitude ?? null,\n order,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(entity);\n });\n\n noteSnapshots.forEach((entry) => {\n const entity = em.create(SalesNote, {\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n contextType: \"order\",\n contextId: order.id,\n order,\n quote: null,\n body: entry.body,\n authorUserId: entry.authorUserId ?? null,\n appearanceIcon: entry.appearanceIcon ?? null,\n appearanceColor: entry.appearanceColor ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(entity);\n });\n\n tagSnapshots.forEach((entry) => {\n const tag = em.getReference(SalesDocumentTag, entry.tagId);\n const assignment = em.create(SalesDocumentTagAssignment, {\n id: entry.id,\n organizationId: entry.organizationId,\n tenantId: entry.tenantId,\n documentId: order.id,\n documentKind: \"order\",\n tag,\n order,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(assignment);\n });\n\n if (snapshot.order.customFields) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order,\n recordId: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n values: normalizeCustomFieldValues(snapshot.order.customFields),\n });\n }\n for (const line of snapshot.lines) {\n if (!line.customFields) continue;\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order_line,\n recordId: line.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n values: normalizeCustomFieldValues(line.customFields),\n });\n }\n for (const adjustment of snapshot.adjustments) {\n if (!adjustment.customFields) continue;\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order_adjustment,\n recordId: adjustment.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n values: normalizeCustomFieldValues(adjustment.customFields),\n });\n }\n\n for (const shipment of shipmentSnapshots) {\n await restoreShipmentSnapshot(em, shipment);\n }\n\n for (const payment of paymentSnapshots) {\n await restorePaymentSnapshot(em, payment);\n }\n\n return order;\n}\n\nconst createQuoteCommand: CommandHandler<\n QuoteCreateInput,\n { quoteId: string }\n> = {\n id: \"sales.quotes.create\",\n async execute(rawInput, ctx) {\n const generator = ctx.container.resolve(\n \"salesDocumentNumberGenerator\",\n ) as SalesDocumentNumberGenerator;\n const initial = quoteCreateSchema.parse(rawInput ?? {});\n const quoteNumber =\n typeof initial.quoteNumber === \"string\" &&\n initial.quoteNumber.trim().length\n ? initial.quoteNumber.trim()\n : (\n await generator.generate({\n kind: \"quote\",\n organizationId: initial.organizationId,\n tenantId: initial.tenantId,\n })\n ).number;\n const parsed = quoteCreateSchema.parse({ ...initial, quoteNumber });\n const ensuredQuoteNumber = parsed.quoteNumber ?? quoteNumber;\n if (!ensuredQuoteNumber) {\n throw new CrudHttpError(400, { error: \"Quote number is required.\" });\n }\n ensureQuoteScope(ctx, parsed.organizationId, parsed.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const {\n customerSnapshot: resolvedCustomerSnapshot,\n billingAddressSnapshot: resolvedBillingSnapshot,\n shippingAddressSnapshot: resolvedShippingSnapshot,\n shippingMethod,\n deliveryWindow,\n paymentMethod,\n } = await resolveDocumentReferences(em, parsed);\n const quoteStatus = await resolveDictionaryEntryValue(\n em,\n parsed.statusEntryId ?? null,\n { tenantId: parsed.tenantId },\n );\n const quoteId = randomUUID();\n const quote = em.create(SalesQuote, {\n id: quoteId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n quoteNumber: ensuredQuoteNumber,\n statusEntryId: parsed.statusEntryId ?? null,\n status: quoteStatus,\n customerEntityId: parsed.customerEntityId ?? null,\n customerContactId: parsed.customerContactId ?? null,\n customerSnapshot: resolvedCustomerSnapshot\n ? cloneJson(resolvedCustomerSnapshot)\n : null,\n billingAddressId: parsed.billingAddressId ?? null,\n shippingAddressId: parsed.shippingAddressId ?? null,\n billingAddressSnapshot: resolvedBillingSnapshot\n ? cloneJson(resolvedBillingSnapshot)\n : null,\n shippingAddressSnapshot: resolvedShippingSnapshot\n ? cloneJson(resolvedShippingSnapshot)\n : null,\n currencyCode: parsed.currencyCode,\n validFrom: parsed.validFrom ?? null,\n validUntil: parsed.validUntil ?? null,\n comments: parsed.comments ?? null,\n taxInfo: parsed.taxInfo ? cloneJson(parsed.taxInfo) : null,\n shippingMethodId: parsed.shippingMethodId ?? null,\n shippingMethod: shippingMethod ?? null,\n shippingMethodCode:\n parsed.shippingMethodCode ?? shippingMethod?.code ?? null,\n deliveryWindowId: parsed.deliveryWindowId ?? null,\n deliveryWindow: deliveryWindow ?? null,\n deliveryWindowCode:\n parsed.deliveryWindowCode ?? deliveryWindow?.code ?? null,\n paymentMethodId: parsed.paymentMethodId ?? null,\n paymentMethod: paymentMethod ?? null,\n paymentMethodCode:\n parsed.paymentMethodCode ?? paymentMethod?.code ?? null,\n shippingMethodSnapshot: parsed.shippingMethodSnapshot\n ? cloneJson(parsed.shippingMethodSnapshot)\n : shippingMethod\n ? {\n id: shippingMethod.id,\n code: shippingMethod.code,\n name: shippingMethod.name,\n description: shippingMethod.description ?? null,\n carrierCode: shippingMethod.carrierCode ?? null,\n providerKey: shippingMethod.providerKey ?? null,\n serviceLevel: shippingMethod.serviceLevel ?? null,\n estimatedTransitDays: shippingMethod.estimatedTransitDays ?? null,\n baseRateNet: shippingMethod.baseRateNet,\n baseRateGross: shippingMethod.baseRateGross,\n currencyCode: shippingMethod.currencyCode ?? null,\n metadata: shippingMethod.metadata\n ? cloneJson(shippingMethod.metadata)\n : null,\n providerSettings:\n shippingMethod.metadata &&\n typeof shippingMethod.metadata === \"object\"\n ? cloneJson(\n (shippingMethod.metadata as Record<string, unknown>)\n .providerSettings ?? null,\n )\n : null,\n }\n : null,\n deliveryWindowSnapshot: parsed.deliveryWindowSnapshot\n ? cloneJson(parsed.deliveryWindowSnapshot)\n : deliveryWindow\n ? {\n id: deliveryWindow.id,\n code: deliveryWindow.code,\n name: deliveryWindow.name,\n description: deliveryWindow.description ?? null,\n leadTimeDays: deliveryWindow.leadTimeDays ?? null,\n cutoffTime: deliveryWindow.cutoffTime ?? null,\n timezone: deliveryWindow.timezone ?? null,\n }\n : null,\n paymentMethodSnapshot: parsed.paymentMethodSnapshot\n ? cloneJson(parsed.paymentMethodSnapshot)\n : paymentMethod\n ? {\n id: paymentMethod.id,\n code: paymentMethod.code,\n name: paymentMethod.name,\n description: paymentMethod.description ?? null,\n providerKey: paymentMethod.providerKey ?? null,\n terms: paymentMethod.terms ?? null,\n metadata: paymentMethod.metadata\n ? cloneJson(paymentMethod.metadata)\n : null,\n providerSettings:\n paymentMethod.metadata &&\n typeof paymentMethod.metadata === \"object\"\n ? cloneJson(\n (paymentMethod.metadata as Record<string, unknown>)\n .providerSettings ?? null,\n )\n : null,\n }\n : null,\n metadata: parsed.metadata ? cloneJson(parsed.metadata) : null,\n channelId: parsed.channelId ?? null,\n customFieldSetId: parsed.customFieldSetId ?? null,\n subtotalNetAmount: \"0\",\n subtotalGrossAmount: \"0\",\n discountTotalAmount: \"0\",\n taxTotalAmount: \"0\",\n grandTotalNetAmount: \"0\",\n grandTotalGrossAmount: \"0\",\n lineItemCount: 0,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n\n const lineInputs = (parsed.lines ?? []).map((line, index) =>\n quoteLineCreateSchema.parse({\n ...line,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n quoteId: quote.id,\n lineNumber: line.lineNumber ?? index + 1,\n }),\n );\n const uomResolver = createUomResolver();\n const normalizedLineInputs = await Promise.all(\n lineInputs.map(async (line) => {\n const normalized = await normalizeLineUom({\n em,\n resolver: uomResolver,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n line,\n });\n return {\n ...line,\n quantity: normalized.quantity,\n quantityUnit: normalized.quantityUnit,\n normalizedQuantity: normalized.normalizedQuantity,\n normalizedUnit: normalized.normalizedUnit,\n uomSnapshot: normalized.uomSnapshot,\n };\n }),\n );\n const adjustmentInputs = parsed.adjustments\n ? parsed.adjustments.map((adj) =>\n quoteAdjustmentCreateSchema.parse({\n ...adj,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n quoteId: quote.id,\n }),\n )\n : null;\n\n const lineSnapshots: SalesLineSnapshot[] = normalizedLineInputs.map(\n (line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const adjustmentDrafts: SalesAdjustmentDraft[] = adjustmentInputs\n ? adjustmentInputs.map((adj) => createAdjustmentDraftFromInput(adj))\n : [];\n\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n currencyCode: quote.currencyCode,\n shippingSnapshot: quote.shippingMethodSnapshot,\n paymentSnapshot: quote.paymentMethodSnapshot,\n shippingMethodId: quote.shippingMethodId ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: lineSnapshots,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n });\n\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n // Persist the quote header, lines, adjustments, totals and tags atomically.\n // replace*/setRecordCustomFields flush mid-build, so without a transaction a\n // later failure (e.g. tag sync) would leave a half-built quote committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n em.persist(quote);\n await replaceQuoteLines(em, quote, calculation, normalizedLineInputs);\n await replaceQuoteAdjustments(\n em,\n quote,\n calculation,\n adjustmentInputs,\n );\n applyQuoteTotals(quote, calculation.totals, calculation.lines.length);\n await emitTotalsCalculated(eventBus, {\n documentKind: \"quote\",\n documentId: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n customerId: quote.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n await syncSalesDocumentTags(em, {\n documentId: quote.id,\n kind: \"quote\",\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n tagIds: parsed.tags,\n });\n },\n ],\n { transaction: true },\n );\n\n // Create notification for users with sales.quotes.manage feature\n try {\n const notificationService = resolveNotificationService(ctx.container);\n const typeDef = notificationTypes.find(\n (type) => type.type === \"sales.quote.created\",\n );\n if (typeDef) {\n const totalAmount =\n quote.grandTotalGrossAmount && quote.currencyCode\n ? `${quote.grandTotalGrossAmount} ${quote.currencyCode}`\n : \"\";\n const totalDisplay = totalAmount ? ` (${totalAmount})` : \"\";\n const notificationInput = buildFeatureNotificationFromType(typeDef, {\n requiredFeature: \"sales.quotes.manage\",\n bodyVariables: {\n quoteNumber: quote.quoteNumber,\n total: totalDisplay,\n totalAmount,\n },\n sourceEntityType: \"sales:quote\",\n sourceEntityId: quote.id,\n linkHref: `/backend/sales/quotes/${quote.id}`,\n });\n\n await notificationService.createForFeature(notificationInput, {\n tenantId: quote.tenantId,\n organizationId: quote.organizationId ?? null,\n });\n }\n } catch (err) {\n // Notification creation is non-critical, don't fail the command\n console.error(\n \"[sales.quotes.create] Failed to create notification:\",\n err,\n );\n }\n\n // Emit CRUD side effects to trigger workflow event listeners\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"created\",\n entity: quote,\n identifiers: {\n id: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n },\n events: quoteCrudEvents,\n indexer: { entityType: E.sales.sales_quote },\n });\n\n // Invalidate cache\n const resourceKind =\n deriveResourceFromCommandId(createQuoteCommand.id) ?? \"sales.quote\";\n await invalidateCrudCache(\n ctx.container,\n resourceKind,\n {\n id: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"created\",\n );\n\n return { quoteId: quote.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadQuoteSnapshot(em, result.quoteId);\n },\n buildLog: async ({ result, snapshots }) => {\n const after = snapshots.after as QuoteGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.quotes.create\", \"Create sales quote\"),\n resourceKind: \"sales.quote\",\n resourceId: result.quoteId,\n tenantId: after.quote.tenantId,\n organizationId: after.quote.organizationId,\n snapshotAfter: after,\n payload: {\n undo: {\n after,\n } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const after = payload?.after;\n if (!after) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const quote = await em.findOne(SalesQuote, { id: after.quote.id });\n if (!quote) return;\n ensureQuoteScope(ctx, quote.organizationId, quote.tenantId);\n await em.nativeDelete(SalesQuoteAdjustment, { quote: quote.id });\n await em.nativeDelete(SalesQuoteLine, { quote: quote.id });\n em.remove(quote);\n await em.flush();\n },\n};\n\nconst deleteQuoteCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { quoteId: string }\n> = {\n id: \"sales.quotes.delete\",\n async prepare(input, ctx) {\n const id = requireId(input, \"Quote id is required\");\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadQuoteSnapshot(em, id);\n if (snapshot) {\n ensureQuoteScope(\n ctx,\n snapshot.quote.organizationId,\n snapshot.quote.tenantId,\n );\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(input, ctx) {\n const id = requireId(input, \"Quote id is required\");\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const quote = await em.findOne(SalesQuote, { id });\n if (!quote)\n throw new CrudHttpError(404, { error: \"Sales quote not found\" });\n ensureQuoteScope(ctx, quote.organizationId, quote.tenantId);\n const [addresses, notes, tags, adjustments, lines] = await Promise.all([\n findWithDecryption(\n em,\n SalesDocumentAddress,\n {\n documentId: quote.id,\n documentKind: \"quote\",\n },\n undefined,\n { tenantId: quote.tenantId, organizationId: quote.organizationId },\n ),\n findWithDecryption(\n em,\n SalesNote,\n { contextType: \"quote\", contextId: quote.id },\n undefined,\n { tenantId: quote.tenantId, organizationId: quote.organizationId },\n ),\n em.find(SalesDocumentTagAssignment, {\n documentId: quote.id,\n documentKind: \"quote\",\n }),\n em.find(SalesQuoteAdjustment, { quote: quote.id }),\n em.find(SalesQuoteLine, { quote: quote.id }),\n ]);\n // Delete the quote and its cascade atomically so a mid-cascade failure\n // cannot leave a partially-deleted quote committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n await em.nativeDelete(SalesDocumentAddress, {\n documentId: quote.id,\n documentKind: \"quote\",\n });\n await em.nativeDelete(SalesNote, {\n contextType: \"quote\",\n contextId: quote.id,\n });\n await em.nativeDelete(SalesDocumentTagAssignment, {\n documentId: quote.id,\n documentKind: \"quote\",\n });\n await em.nativeDelete(SalesQuoteAdjustment, { quote: quote.id });\n await em.nativeDelete(SalesQuoteLine, { quote: quote.id });\n em.remove(quote);\n },\n ],\n { transaction: true },\n );\n const dataEngine = ctx.container.resolve<DataEngine>(\"dataEngine\");\n await Promise.all([\n queueDeletionSideEffects(dataEngine, quote, E.sales.sales_quote),\n queueDeletionSideEffects(dataEngine, lines, E.sales.sales_quote_line),\n queueDeletionSideEffects(\n dataEngine,\n adjustments,\n E.sales.sales_quote_adjustment,\n ),\n queueDeletionSideEffects(\n dataEngine,\n addresses,\n E.sales.sales_document_address,\n ),\n queueDeletionSideEffects(dataEngine, notes, E.sales.sales_note),\n queueDeletionSideEffects(\n dataEngine,\n tags,\n E.sales.sales_document_tag_assignment,\n ),\n ]);\n return { quoteId: id };\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as QuoteGraphSnapshot | undefined;\n if (!before) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.quotes.delete\", \"Delete sales quote\"),\n resourceKind: \"sales.quote\",\n resourceId: before.quote.id,\n tenantId: before.quote.tenantId,\n organizationId: before.quote.organizationId,\n snapshotBefore: before,\n payload: {\n undo: {\n before,\n } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureQuoteScope(ctx, before.quote.organizationId, before.quote.tenantId);\n await restoreQuoteGraph(em, before);\n await em.flush();\n },\n};\n\nconst updateQuoteCommand: CommandHandler<\n DocumentUpdateInput,\n { quote: SalesQuote }\n> = {\n id: \"sales.quotes.update\",\n async prepare(input, ctx) {\n const parsed = documentUpdateSchema.parse(input ?? {});\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadQuoteSnapshot(em, parsed.id);\n if (snapshot) {\n ensureQuoteScope(\n ctx,\n snapshot.quote.organizationId,\n snapshot.quote.tenantId,\n );\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const parsed = documentUpdateSchema.parse(rawInput ?? {});\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const quote = await em.findOne(SalesQuote, {\n id: parsed.id,\n deletedAt: null,\n });\n if (!quote)\n throw new CrudHttpError(404, { error: \"Sales quote not found\" });\n ensureQuoteScope(ctx, quote.organizationId, quote.tenantId);\n enforceSalesDocumentOptimisticLock(ctx, quote, SALES_RESOURCE_KIND_QUOTE);\n const shouldInvalidateSentToken = (quote.status ?? null) === \"sent\";\n if (shouldInvalidateSentToken) {\n quote.acceptanceToken = null;\n quote.sentAt = null;\n }\n const shouldRecalculateTotals =\n parsed.shippingMethodId !== undefined ||\n parsed.shippingMethodSnapshot !== undefined ||\n parsed.shippingMethodCode !== undefined ||\n parsed.paymentMethodId !== undefined ||\n parsed.paymentMethodSnapshot !== undefined ||\n parsed.paymentMethodCode !== undefined ||\n parsed.currencyCode !== undefined;\n // Apply the scalar update, optional sent-token reset, and totals recalc\n // atomically. applyDocumentUpdate/replace*/setRecordCustomFields flush\n // mid-build, so without a transaction a later failure would leave a\n // half-updated quote committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n await applyDocumentUpdate({\n kind: \"quote\",\n entity: quote,\n input: parsed,\n em,\n });\n if (shouldInvalidateSentToken) {\n quote.status = \"draft\";\n quote.statusEntryId = await resolveStatusEntryIdByValue(em, {\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n value: \"draft\",\n });\n }\n },\n // Scalar mutations above are persisted by withAtomicFlush's per-phase\n // flush boundary before the recalc reads below run any query on the same\n // EntityManager. MikroORM v7 would otherwise silently discard pending\n // scalar changes on `quote` when the `em.find` line/adjustment lookups\n // reset the changeset (see SPEC-018).\n async () => {\n if (shouldRecalculateTotals) {\n const [existingLines, adjustments] = await Promise.all([\n em.find(\n SalesQuoteLine,\n { quote },\n { orderBy: { lineNumber: \"asc\" } },\n ),\n em.find(\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const lineSnapshots = existingLines.map(mapQuoteLineEntityToSnapshot);\n const calcLines = lineSnapshots.map((line, index) =>\n createLineSnapshotFromInput(\n {\n ...line,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n lineNumber: line.lineNumber ?? index + 1,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n },\n line.lineNumber ?? index + 1,\n ),\n );\n const adjustmentDrafts = adjustments.map(mapQuoteAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\n \"salesCalculationService\",\n );\n const calculationContext = buildCalculationContext({\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n currencyCode: quote.currencyCode,\n shippingSnapshot: quote.shippingMethodSnapshot,\n paymentSnapshot: quote.paymentMethodSnapshot,\n shippingMethodId: quote.shippingMethodId ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n });\n const calculation =\n await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n });\n const adjustmentInputs = adjustmentDrafts.map((adj, index) => ({\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n scope: adj.scope ?? \"order\",\n kind: adj.kind ?? \"custom\",\n code: adj.code ?? undefined,\n label: adj.label ?? undefined,\n calculatorKey: adj.calculatorKey ?? undefined,\n promotionId: adj.promotionId ?? undefined,\n rate: adj.rate ?? undefined,\n amountNet: adj.amountNet ?? undefined,\n amountGross: adj.amountGross ?? undefined,\n currencyCode: adj.currencyCode ?? quote.currencyCode,\n metadata: adj.metadata ?? undefined,\n position: adj.position ?? index,\n }));\n await replaceQuoteAdjustments(\n em,\n quote,\n calculation,\n adjustmentInputs,\n );\n applyQuoteTotals(quote, calculation.totals, calculation.lines.length);\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n await emitTotalsCalculated(eventBus, {\n documentKind: \"quote\",\n documentId: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n customerId: quote.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n }\n quote.updatedAt = new Date();\n },\n ],\n { transaction: true },\n );\n const resourceKind =\n deriveResourceFromCommandId(updateQuoteCommand.id) ?? \"sales.quote\";\n await invalidateCrudCache(\n ctx.container,\n resourceKind,\n {\n id: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"updated\",\n );\n return { quote };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadQuoteSnapshot(em, result.quote.id);\n },\n buildLog: async ({ input, snapshots, result }) => {\n const parsed = documentUpdateSchema.parse(input ?? {});\n const before = snapshots.before as QuoteGraphSnapshot | undefined;\n const after = snapshots.after as QuoteGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n const changes = before\n ? buildChanges(\n before.quote as unknown as Record<string, unknown>,\n after.quote as unknown as Record<string, unknown>,\n buildDocumentUpdateChangeKeys(\"quote\", parsed),\n )\n : {};\n if (parsed.tags !== undefined) {\n const tagChange = buildTagChange(before?.tags, after.tags);\n if (tagChange) changes.tags = tagChange;\n }\n return {\n actionLabel: translate(\"sales.audit.quotes.update\", \"Update sales quote\"),\n resourceKind: \"sales.quote\",\n resourceId: result.quote.id,\n tenantId: after.quote.tenantId,\n organizationId: after.quote.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n changes: Object.keys(changes).length ? changes : null,\n payload: {\n undo: {\n before,\n after,\n } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureQuoteScope(ctx, before.quote.organizationId, before.quote.tenantId);\n await restoreQuoteGraph(em, before);\n await em.flush();\n },\n};\n\nconst updateOrderCommand: CommandHandler<\n DocumentUpdateInput,\n { order: SalesOrder }\n> = {\n id: \"sales.orders.update\",\n async prepare(input, ctx) {\n const parsed = documentUpdateSchema.parse(input ?? {});\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadOrderSnapshot(em, parsed.id);\n if (snapshot) {\n ensureOrderScope(\n ctx,\n snapshot.order.organizationId,\n snapshot.order.tenantId,\n );\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const parsed = documentUpdateSchema.parse(rawInput ?? {});\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const order = await em.findOne(SalesOrder, {\n id: parsed.id,\n deletedAt: null,\n });\n if (!order)\n throw new CrudHttpError(404, { error: \"Sales order not found\" });\n ensureOrderScope(ctx, order.organizationId, order.tenantId);\n const previousStatus = normalizeStatusValue(order.status);\n let statusChangeNote: SalesNote | null = null;\n const shouldRecalculateTotals =\n parsed.shippingMethodId !== undefined ||\n parsed.shippingMethodSnapshot !== undefined ||\n parsed.shippingMethodCode !== undefined ||\n parsed.paymentMethodId !== undefined ||\n parsed.paymentMethodSnapshot !== undefined ||\n parsed.paymentMethodCode !== undefined ||\n parsed.currencyCode !== undefined;\n // Apply the scalar update, totals recalc, and status-change note atomically.\n // applyDocumentUpdate/replace*/setRecordCustomFields flush mid-build, so\n // without a transaction a later failure would leave a half-updated order\n // committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n await applyDocumentUpdate({\n kind: \"order\",\n entity: order,\n input: parsed,\n em,\n });\n },\n // Scalar mutations above are persisted by withAtomicFlush's per-phase\n // flush boundary before the recalc reads and the status-change-note\n // lookup below run any query on the same EntityManager. MikroORM v7 would\n // otherwise silently discard pending scalar changes on `order` when the\n // `em.find` lines/adjustments or appendOrderStatusChangeNote queries\n // reset the changeset (see SPEC-018).\n async () => {\n if (shouldRecalculateTotals) {\n const [existingLines, adjustments] = await Promise.all([\n em.find(\n SalesOrderLine,\n { order },\n { orderBy: { lineNumber: \"asc\" } },\n ),\n em.find(\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const lineSnapshots = existingLines.map(mapOrderLineEntityToSnapshot);\n const calcLines = lineSnapshots.map((line, index) =>\n createLineSnapshotFromInput(\n {\n ...line,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n lineNumber: line.lineNumber ?? index + 1,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n },\n line.lineNumber ?? index + 1,\n ),\n );\n const adjustmentDrafts = adjustments.map(mapOrderAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\n \"salesCalculationService\",\n );\n const calculationContext = buildCalculationContext({\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n currencyCode: order.currencyCode,\n shippingSnapshot: order.shippingMethodSnapshot,\n paymentSnapshot: order.paymentMethodSnapshot,\n shippingMethodId: order.shippingMethodId ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n });\n const calculation =\n await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n });\n const adjustmentInputs = adjustmentDrafts.map((adj, index) => ({\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n scope: adj.scope ?? \"order\",\n kind: adj.kind ?? \"custom\",\n code: adj.code ?? undefined,\n label: adj.label ?? undefined,\n calculatorKey: adj.calculatorKey ?? undefined,\n promotionId: adj.promotionId ?? undefined,\n rate: adj.rate ?? undefined,\n amountNet: adj.amountNet ?? undefined,\n amountGross: adj.amountGross ?? undefined,\n currencyCode: adj.currencyCode ?? order.currencyCode,\n metadata: adj.metadata ?? undefined,\n position: adj.position ?? index,\n }));\n await replaceOrderAdjustments(\n em,\n order,\n calculation,\n adjustmentInputs,\n );\n applyOrderTotals(order, calculation.totals, calculation.lines.length);\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n await emitTotalsCalculated(eventBus, {\n documentKind: \"order\",\n documentId: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n customerId: order.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n }\n statusChangeNote = await appendOrderStatusChangeNote({\n em,\n order,\n previousStatus,\n auth: ctx.auth ?? null,\n });\n order.updatedAt = new Date();\n },\n ],\n { transaction: true },\n );\n if (statusChangeNote) {\n const dataEngine = ctx.container.resolve(\"dataEngine\");\n await emitCrudSideEffects({\n dataEngine,\n action: \"created\",\n entity: statusChangeNote,\n identifiers: {\n id: statusChangeNote.id,\n organizationId: statusChangeNote.organizationId,\n tenantId: statusChangeNote.tenantId,\n },\n indexer: { entityType: E.sales.sales_note },\n });\n }\n const resourceKind =\n deriveResourceFromCommandId(updateOrderCommand.id) ?? \"sales.order\";\n await invalidateCrudCache(\n ctx.container,\n resourceKind,\n {\n id: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"updated\",\n );\n return { order };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadOrderSnapshot(em, result.order.id);\n },\n buildLog: async ({ input, snapshots, result }) => {\n const parsed = documentUpdateSchema.parse(input ?? {});\n const before = snapshots.before as OrderGraphSnapshot | undefined;\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n const changes = before\n ? buildChanges(\n before.order as unknown as Record<string, unknown>,\n after.order as unknown as Record<string, unknown>,\n buildDocumentUpdateChangeKeys(\"order\", parsed),\n )\n : {};\n if (parsed.tags !== undefined) {\n const tagChange = buildTagChange(before?.tags, after.tags);\n if (tagChange) changes.tags = tagChange;\n }\n return {\n actionLabel: translate(\"sales.audit.orders.update\", \"Update sales order\"),\n resourceKind: \"sales.order\",\n resourceId: result.order.id,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n changes: Object.keys(changes).length ? changes : null,\n payload: {\n undo: {\n before,\n after,\n } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureOrderScope(ctx, before.order.organizationId, before.order.tenantId);\n await restoreOrderGraph(em, before);\n await em.flush();\n },\n};\n\nconst createOrderCommand: CommandHandler<\n OrderCreateInput,\n { orderId: string }\n> = {\n id: \"sales.orders.create\",\n async execute(rawInput, ctx) {\n const generator = ctx.container.resolve(\n \"salesDocumentNumberGenerator\",\n ) as SalesDocumentNumberGenerator;\n const initial = orderCreateSchema.parse(rawInput ?? {});\n const orderNumber =\n typeof initial.orderNumber === \"string\" &&\n initial.orderNumber.trim().length\n ? initial.orderNumber.trim()\n : (\n await generator.generate({\n kind: \"order\",\n organizationId: initial.organizationId,\n tenantId: initial.tenantId,\n })\n ).number;\n const parsed = orderCreateSchema.parse({ ...initial, orderNumber });\n const ensuredOrderNumber = parsed.orderNumber ?? orderNumber;\n if (!ensuredOrderNumber) {\n throw new CrudHttpError(400, { error: \"Order number is required.\" });\n }\n ensureOrderScope(ctx, parsed.organizationId, parsed.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const [status, fulfillmentStatus, paymentStatus] = await Promise.all([\n resolveDictionaryEntryValue(em, parsed.statusEntryId ?? null, { tenantId: parsed.tenantId }),\n resolveDictionaryEntryValue(em, parsed.fulfillmentStatusEntryId ?? null, { tenantId: parsed.tenantId }),\n resolveDictionaryEntryValue(em, parsed.paymentStatusEntryId ?? null, { tenantId: parsed.tenantId }),\n ]);\n const {\n customerSnapshot: resolvedCustomerSnapshot,\n billingAddressSnapshot: resolvedBillingSnapshot,\n shippingAddressSnapshot: resolvedShippingSnapshot,\n shippingMethod,\n deliveryWindow,\n paymentMethod,\n } = await resolveDocumentReferences(em, parsed);\n\n const orderId = randomUUID()\n const order = em.create(SalesOrder, {\n id: orderId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n orderNumber: ensuredOrderNumber,\n externalReference: parsed.externalReference ?? null,\n customerReference: parsed.customerReference ?? null,\n statusEntryId: parsed.statusEntryId ?? null,\n status,\n fulfillmentStatusEntryId: parsed.fulfillmentStatusEntryId ?? null,\n fulfillmentStatus,\n paymentStatusEntryId: parsed.paymentStatusEntryId ?? null,\n paymentStatus,\n customerEntityId: parsed.customerEntityId ?? null,\n customerContactId: parsed.customerContactId ?? null,\n customerSnapshot: resolvedCustomerSnapshot\n ? cloneJson(resolvedCustomerSnapshot)\n : null,\n billingAddressId: parsed.billingAddressId ?? null,\n shippingAddressId: parsed.shippingAddressId ?? null,\n billingAddressSnapshot: resolvedBillingSnapshot\n ? cloneJson(resolvedBillingSnapshot)\n : null,\n shippingAddressSnapshot: resolvedShippingSnapshot\n ? cloneJson(resolvedShippingSnapshot)\n : null,\n currencyCode: parsed.currencyCode,\n exchangeRate:\n typeof parsed.exchangeRate === \"number\"\n ? toNumericString(parsed.exchangeRate)\n : null,\n taxStrategyKey: parsed.taxStrategyKey ?? null,\n discountStrategyKey: parsed.discountStrategyKey ?? null,\n taxInfo: parsed.taxInfo ? cloneJson(parsed.taxInfo) : null,\n shippingMethodId: parsed.shippingMethodId ?? null,\n shippingMethod: shippingMethod ?? null,\n shippingMethodCode:\n parsed.shippingMethodCode ?? shippingMethod?.code ?? null,\n deliveryWindowId: parsed.deliveryWindowId ?? null,\n deliveryWindow: deliveryWindow ?? null,\n deliveryWindowCode:\n parsed.deliveryWindowCode ?? deliveryWindow?.code ?? null,\n paymentMethodId: parsed.paymentMethodId ?? null,\n paymentMethod: paymentMethod ?? null,\n paymentMethodCode:\n parsed.paymentMethodCode ?? paymentMethod?.code ?? null,\n channelId: parsed.channelId ?? null,\n placedAt: parsed.placedAt ?? null,\n expectedDeliveryAt: parsed.expectedDeliveryAt ?? null,\n dueAt: parsed.dueAt ?? null,\n comments: parsed.comments ?? null,\n internalNotes: parsed.internalNotes ?? null,\n shippingMethodSnapshot: parsed.shippingMethodSnapshot\n ? cloneJson(parsed.shippingMethodSnapshot)\n : shippingMethod\n ? {\n id: shippingMethod.id,\n code: shippingMethod.code,\n name: shippingMethod.name,\n description: shippingMethod.description ?? null,\n carrierCode: shippingMethod.carrierCode ?? null,\n providerKey: shippingMethod.providerKey ?? null,\n serviceLevel: shippingMethod.serviceLevel ?? null,\n estimatedTransitDays: shippingMethod.estimatedTransitDays ?? null,\n baseRateNet: shippingMethod.baseRateNet,\n baseRateGross: shippingMethod.baseRateGross,\n currencyCode: shippingMethod.currencyCode ?? null,\n metadata: shippingMethod.metadata\n ? cloneJson(shippingMethod.metadata)\n : null,\n providerSettings:\n shippingMethod.metadata &&\n typeof shippingMethod.metadata === \"object\"\n ? cloneJson(\n (shippingMethod.metadata as Record<string, unknown>)\n .providerSettings ?? null,\n )\n : null,\n }\n : null,\n deliveryWindowSnapshot: parsed.deliveryWindowSnapshot\n ? cloneJson(parsed.deliveryWindowSnapshot)\n : deliveryWindow\n ? {\n id: deliveryWindow.id,\n code: deliveryWindow.code,\n name: deliveryWindow.name,\n description: deliveryWindow.description ?? null,\n leadTimeDays: deliveryWindow.leadTimeDays ?? null,\n cutoffTime: deliveryWindow.cutoffTime ?? null,\n timezone: deliveryWindow.timezone ?? null,\n }\n : null,\n paymentMethodSnapshot: parsed.paymentMethodSnapshot\n ? cloneJson(parsed.paymentMethodSnapshot)\n : paymentMethod\n ? {\n id: paymentMethod.id,\n code: paymentMethod.code,\n name: paymentMethod.name,\n description: paymentMethod.description ?? null,\n providerKey: paymentMethod.providerKey ?? null,\n terms: paymentMethod.terms ?? null,\n metadata: paymentMethod.metadata\n ? cloneJson(paymentMethod.metadata)\n : null,\n providerSettings:\n paymentMethod.metadata &&\n typeof paymentMethod.metadata === \"object\"\n ? cloneJson(\n (paymentMethod.metadata as Record<string, unknown>)\n .providerSettings ?? null,\n )\n : null,\n }\n : null,\n metadata: parsed.metadata ? cloneJson(parsed.metadata) : null,\n customFieldSetId: parsed.customFieldSetId ?? null,\n subtotalNetAmount: \"0\",\n subtotalGrossAmount: \"0\",\n discountTotalAmount: \"0\",\n taxTotalAmount: \"0\",\n shippingNetAmount: \"0\",\n shippingGrossAmount: \"0\",\n surchargeTotalAmount: \"0\",\n grandTotalNetAmount: \"0\",\n grandTotalGrossAmount: \"0\",\n paidTotalAmount: \"0\",\n refundedTotalAmount: \"0\",\n outstandingAmount: \"0\",\n lineItemCount: 0,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n const lineInputs = (parsed.lines ?? []).map((line, index) =>\n orderLineCreateSchema.parse({\n ...line,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n orderId: order.id,\n lineNumber: line.lineNumber ?? index + 1,\n }),\n );\n const uomResolver = createUomResolver();\n const normalizedLineInputs = await Promise.all(\n lineInputs.map(async (line) => {\n const normalized = await normalizeLineUom({\n em,\n resolver: uomResolver,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n line,\n });\n return {\n ...line,\n quantity: normalized.quantity,\n quantityUnit: normalized.quantityUnit,\n normalizedQuantity: normalized.normalizedQuantity,\n normalizedUnit: normalized.normalizedUnit,\n uomSnapshot: normalized.uomSnapshot,\n };\n }),\n );\n const adjustmentInputs = parsed.adjustments\n ? parsed.adjustments.map((adj) =>\n orderAdjustmentCreateSchema.parse({\n ...adj,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n orderId: order.id,\n }),\n )\n : null;\n\n const lineSnapshots: SalesLineSnapshot[] = normalizedLineInputs.map(\n (line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const adjustmentDrafts: SalesAdjustmentDraft[] = adjustmentInputs\n ? adjustmentInputs.map((adj) => createAdjustmentDraftFromInput(adj))\n : [];\n\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n currencyCode: order.currencyCode,\n shippingSnapshot: order.shippingMethodSnapshot,\n paymentSnapshot: order.paymentMethodSnapshot,\n shippingMethodId: order.shippingMethodId ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: lineSnapshots,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n });\n\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n // Persist the order header, lines, adjustments, totals and tags atomically.\n // replace*/setRecordCustomFields flush mid-build, so without a transaction a\n // later failure (e.g. tag sync) would leave a half-built order committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n em.persist(order);\n await replaceOrderLines(em, order, calculation, normalizedLineInputs);\n await replaceOrderAdjustments(\n em,\n order,\n calculation,\n adjustmentInputs,\n );\n applyOrderTotals(order, calculation.totals, calculation.lines.length);\n await emitTotalsCalculated(eventBus, {\n documentKind: \"order\",\n documentId: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n customerId: order.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n await syncSalesDocumentTags(em, {\n documentId: order.id,\n kind: \"order\",\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n tagIds: parsed.tags,\n });\n },\n ],\n { transaction: true },\n );\n\n // Create notification for users with sales.orders.manage feature\n try {\n const notificationService = resolveNotificationService(ctx.container);\n const typeDef = notificationTypes.find(\n (type) => type.type === \"sales.order.created\",\n );\n if (typeDef) {\n const totalAmount =\n order.grandTotalGrossAmount && order.currencyCode\n ? `${order.grandTotalGrossAmount} ${order.currencyCode}`\n : \"\";\n const totalDisplay = totalAmount ? ` (${totalAmount})` : \"\";\n const notificationInput = buildFeatureNotificationFromType(typeDef, {\n requiredFeature: \"sales.orders.manage\",\n bodyVariables: {\n orderNumber: order.orderNumber,\n total: totalDisplay,\n totalAmount,\n },\n sourceEntityType: \"sales:order\",\n sourceEntityId: order.id,\n linkHref: `/backend/sales/orders/${order.id}`,\n });\n\n await notificationService.createForFeature(notificationInput, {\n tenantId: order.tenantId,\n organizationId: order.organizationId ?? null,\n });\n }\n } catch (err) {\n // Notification creation is non-critical, don't fail the command\n console.error(\n \"[sales.orders.create] Failed to create notification:\",\n err,\n );\n }\n\n // Emit CRUD side effects to trigger workflow event listeners\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"created\",\n entity: order,\n identifiers: {\n id: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n },\n events: orderCrudEvents,\n indexer: { entityType: E.sales.sales_order },\n });\n\n // Invalidate cache\n const resourceKind =\n deriveResourceFromCommandId(createOrderCommand.id) ?? \"sales.order\";\n await invalidateCrudCache(\n ctx.container,\n resourceKind,\n {\n id: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"created\",\n );\n\n return { orderId: order.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadOrderSnapshot(em, result.orderId);\n },\n buildLog: async ({ result, snapshots }) => {\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.orders.create\", \"Create sales order\"),\n resourceKind: \"sales.order\",\n resourceId: result.orderId,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n snapshotAfter: after,\n payload: {\n undo: {\n after,\n } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const after = payload?.after;\n if (!after) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const order = await em.findOne(SalesOrder, { id: after.order.id });\n if (!order) return;\n ensureOrderScope(ctx, order.organizationId, order.tenantId);\n await em.nativeDelete(SalesOrderAdjustment, { order: order.id });\n await em.nativeDelete(SalesOrderLine, { order: order.id });\n em.remove(order);\n await em.flush();\n },\n};\n\nconst deleteOrderCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { orderId: string }\n> = {\n id: \"sales.orders.delete\",\n async prepare(input, ctx) {\n const id = requireId(input, \"Order id is required\");\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadOrderSnapshot(em, id);\n if (snapshot) {\n ensureOrderScope(\n ctx,\n snapshot.order.organizationId,\n snapshot.order.tenantId,\n );\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(input, ctx) {\n const id = requireId(input, \"Order id is required\");\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const order = await em.findOne(SalesOrder, { id });\n if (!order)\n throw new CrudHttpError(404, { error: \"Sales order not found\" });\n ensureOrderScope(ctx, order.organizationId, order.tenantId);\n const shipments = await em.find(SalesShipment, { order: order.id });\n const shipmentIds = shipments.map((entry) => entry.id);\n const [\n shipmentItems,\n payments,\n paymentAllocations,\n addresses,\n notes,\n tags,\n adjustments,\n lines,\n ] = await Promise.all([\n shipmentIds.length\n ? em.find(SalesShipmentItem, { shipment: { $in: shipmentIds } })\n : Promise.resolve([]),\n em.find(SalesPayment, { order: order.id }),\n em.find(SalesPaymentAllocation, { order: order.id }),\n findWithDecryption(\n em,\n SalesDocumentAddress,\n {\n documentId: order.id,\n documentKind: \"order\",\n },\n undefined,\n { tenantId: order.tenantId, organizationId: order.organizationId },\n ),\n findWithDecryption(\n em,\n SalesNote,\n { contextType: \"order\", contextId: order.id },\n undefined,\n { tenantId: order.tenantId, organizationId: order.organizationId },\n ),\n em.find(SalesDocumentTagAssignment, {\n documentId: order.id,\n documentKind: \"order\",\n }),\n em.find(SalesOrderAdjustment, { order: order.id }),\n em.find(SalesOrderLine, { order: order.id }),\n ]);\n // Delete the order and its cascade atomically so a mid-cascade failure\n // cannot leave a partially-deleted order committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n if (shipmentIds.length) {\n await em.nativeDelete(SalesShipmentItem, {\n shipment: { $in: shipmentIds },\n });\n await em.nativeDelete(SalesShipment, { id: { $in: shipmentIds } });\n }\n await em.nativeDelete(SalesPaymentAllocation, { order: order.id });\n await em.nativeDelete(SalesPayment, { order: order.id });\n await em.nativeDelete(SalesDocumentAddress, {\n documentId: order.id,\n documentKind: \"order\",\n });\n await em.nativeDelete(SalesNote, {\n contextType: \"order\",\n contextId: order.id,\n });\n await em.nativeDelete(SalesDocumentTagAssignment, {\n documentId: order.id,\n documentKind: \"order\",\n });\n await em.nativeDelete(SalesOrderAdjustment, { order: order.id });\n await em.nativeDelete(SalesOrderLine, { order: order.id });\n em.remove(order);\n },\n ],\n { transaction: true },\n );\n const dataEngine = ctx.container.resolve<DataEngine>(\"dataEngine\");\n await Promise.all([\n queueDeletionSideEffects(dataEngine, order, E.sales.sales_order),\n queueDeletionSideEffects(dataEngine, lines, E.sales.sales_order_line),\n queueDeletionSideEffects(\n dataEngine,\n adjustments,\n E.sales.sales_order_adjustment,\n ),\n queueDeletionSideEffects(dataEngine, shipments, E.sales.sales_shipment),\n queueDeletionSideEffects(\n dataEngine,\n shipmentItems,\n E.sales.sales_shipment_item,\n ),\n queueDeletionSideEffects(dataEngine, payments, E.sales.sales_payment),\n queueDeletionSideEffects(\n dataEngine,\n paymentAllocations,\n E.sales.sales_payment_allocation,\n ),\n queueDeletionSideEffects(\n dataEngine,\n addresses,\n E.sales.sales_document_address,\n ),\n queueDeletionSideEffects(dataEngine, notes, E.sales.sales_note),\n queueDeletionSideEffects(\n dataEngine,\n tags,\n E.sales.sales_document_tag_assignment,\n ),\n ]);\n return { orderId: id };\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as OrderGraphSnapshot | undefined;\n if (!before) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.orders.delete\", \"Delete sales order\"),\n resourceKind: \"sales.order\",\n resourceId: before.order.id,\n tenantId: before.order.tenantId,\n organizationId: before.order.organizationId,\n snapshotBefore: before,\n payload: {\n undo: {\n before,\n } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureOrderScope(ctx, before.order.organizationId, before.order.tenantId);\n await restoreOrderGraph(em, before);\n await em.flush();\n },\n};\n\nconst quoteConvertToOrderSchema = z.object({\n quoteId: z.string().uuid(),\n orderId: z.string().uuid().optional(),\n orderNumber: z.string().trim().max(191).optional(),\n});\n\nconst convertQuoteToOrderCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { orderId: string }\n> = {\n id: \"sales.quotes.convert_to_order\",\n async prepare(input, ctx) {\n const parsed = quoteConvertToOrderSchema.safeParse(input ?? {});\n const quoteId = parsed.success\n ? parsed.data.quoteId\n : typeof (input as any)?.quoteId === \"string\"\n ? (input as any).quoteId\n : null;\n if (!quoteId) return {};\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadQuoteSnapshot(em, quoteId);\n if (snapshot)\n ensureQuoteScope(\n ctx,\n snapshot.quote.organizationId,\n snapshot.quote.tenantId,\n );\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const payload = quoteConvertToOrderSchema.parse(rawInput ?? {});\n // When the caller supplies an existing transactional EntityManager, reuse it\n // (and its row locks) so the quote status flip and the order materialization\n // commit or roll back as one atomic unit \u2014 no out-of-band compensating write.\n const callerEm = ctx.transactionalEm;\n const rootEm =\n callerEm ?? (ctx.container.resolve(\"em\") as EntityManager).fork();\n const transactionalEm = rootEm as EntityManager & {\n transactional?: <TResult>(\n callback: (trx: EntityManager) => Promise<TResult>,\n ) => Promise<TResult>;\n };\n const runConversion = async (em: EntityManager) => {\n const quote = await findOneWithDecryption(\n em,\n SalesQuote,\n {\n id: payload.quoteId,\n deletedAt: null,\n },\n { lockMode: LockMode.PESSIMISTIC_WRITE },\n );\n const { translate } = await resolveTranslations();\n if (!quote)\n throw new CrudHttpError(404, {\n error: translate(\n \"sales.documents.detail.error\",\n \"Document not found or inaccessible.\",\n ),\n });\n ensureQuoteScope(ctx, quote.organizationId, quote.tenantId);\n enforceSalesDocumentOptimisticLock(ctx, quote, SALES_RESOURCE_KIND_QUOTE);\n const snapshot = await loadQuoteSnapshot(em, payload.quoteId);\n if (!snapshot)\n throw new CrudHttpError(404, {\n error: translate(\n \"sales.documents.detail.error\",\n \"Document not found or inaccessible.\",\n ),\n });\n const orderId = payload.orderId ?? quote.id;\n const existingOrder = await findOneWithDecryption(em, SalesOrder, {\n id: orderId,\n deletedAt: null,\n }, undefined, { tenantId: quote.tenantId, organizationId: quote.organizationId });\n if (existingOrder) {\n throw new CrudHttpError(409, {\n error: translate(\n \"sales.documents.detail.convertExists\",\n \"Order already exists for this quote.\",\n ),\n });\n }\n\n const generator = ctx.container.resolve(\n \"salesDocumentNumberGenerator\",\n ) as SalesDocumentNumberGenerator;\n const generatedNumber = (\n await generator.generate({\n kind: \"order\",\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n })\n ).number;\n const orderNumber =\n typeof payload.orderNumber === \"string\" &&\n payload.orderNumber.trim().length\n ? payload.orderNumber.trim()\n : generatedNumber;\n\n const [quoteCustomFields, quoteLineCustomFields] = await Promise.all([\n loadCustomFieldValues({\n em,\n entityId: E.sales.sales_quote,\n recordIds: [snapshot.quote.id],\n tenantIdByRecord: { [snapshot.quote.id]: snapshot.quote.tenantId },\n organizationIdByRecord: {\n [snapshot.quote.id]: snapshot.quote.organizationId,\n },\n }),\n snapshot.lines.length\n ? loadCustomFieldValues({\n em,\n entityId: E.sales.sales_quote_line,\n recordIds: snapshot.lines.map((line) => line.id),\n tenantIdByRecord: Object.fromEntries(\n snapshot.lines.map((line) => [line.id, snapshot.quote.tenantId]),\n ),\n organizationIdByRecord: Object.fromEntries(\n snapshot.lines.map((line) => [\n line.id,\n snapshot.quote.organizationId,\n ]),\n ),\n })\n : Promise.resolve({}),\n ]);\n\n const order = em.create(SalesOrder, {\n id: orderId,\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n orderNumber,\n statusEntryId: snapshot.quote.statusEntryId ?? null,\n status: snapshot.quote.status ?? null,\n fulfillmentStatusEntryId: null,\n fulfillmentStatus: null,\n paymentStatusEntryId: null,\n paymentStatus: null,\n customerEntityId: snapshot.quote.customerEntityId ?? null,\n customerContactId: snapshot.quote.customerContactId ?? null,\n customerSnapshot: snapshot.quote.customerSnapshot\n ? cloneJson(snapshot.quote.customerSnapshot)\n : null,\n billingAddressId: snapshot.quote.billingAddressId ?? null,\n shippingAddressId: snapshot.quote.shippingAddressId ?? null,\n billingAddressSnapshot: snapshot.quote.billingAddressSnapshot\n ? cloneJson(snapshot.quote.billingAddressSnapshot)\n : null,\n shippingAddressSnapshot: snapshot.quote.shippingAddressSnapshot\n ? cloneJson(snapshot.quote.shippingAddressSnapshot)\n : null,\n currencyCode: snapshot.quote.currencyCode,\n exchangeRate: null,\n taxStrategyKey: null,\n discountStrategyKey: null,\n taxInfo: snapshot.quote.taxInfo\n ? cloneJson(snapshot.quote.taxInfo)\n : null,\n shippingMethodId: snapshot.quote.shippingMethodId ?? null,\n shippingMethodCode: snapshot.quote.shippingMethodCode ?? null,\n deliveryWindowId: snapshot.quote.deliveryWindowId ?? null,\n deliveryWindowCode: snapshot.quote.deliveryWindowCode ?? null,\n paymentMethodId: snapshot.quote.paymentMethodId ?? null,\n paymentMethodCode: snapshot.quote.paymentMethodCode ?? null,\n channelId: snapshot.quote.channelId ?? null,\n placedAt: snapshot.quote.validFrom\n ? new Date(snapshot.quote.validFrom)\n : quote.createdAt,\n expectedDeliveryAt: snapshot.quote.validUntil\n ? new Date(snapshot.quote.validUntil)\n : null,\n dueAt: null,\n comments: snapshot.quote.comments ?? null,\n internalNotes: null,\n shippingMethodSnapshot: snapshot.quote.shippingMethodSnapshot\n ? cloneJson(snapshot.quote.shippingMethodSnapshot)\n : null,\n deliveryWindowSnapshot: snapshot.quote.deliveryWindowSnapshot\n ? cloneJson(snapshot.quote.deliveryWindowSnapshot)\n : null,\n paymentMethodSnapshot: snapshot.quote.paymentMethodSnapshot\n ? cloneJson(snapshot.quote.paymentMethodSnapshot)\n : null,\n metadata: snapshot.quote.metadata\n ? cloneJson(snapshot.quote.metadata)\n : null,\n customFieldSetId: snapshot.quote.customFieldSetId ?? null,\n subtotalNetAmount: snapshot.quote.subtotalNetAmount,\n subtotalGrossAmount: snapshot.quote.subtotalGrossAmount,\n discountTotalAmount: snapshot.quote.discountTotalAmount,\n taxTotalAmount: snapshot.quote.taxTotalAmount,\n shippingNetAmount: \"0\",\n shippingGrossAmount: \"0\",\n surchargeTotalAmount: \"0\",\n grandTotalNetAmount: snapshot.quote.grandTotalNetAmount,\n grandTotalGrossAmount: snapshot.quote.grandTotalGrossAmount,\n paidTotalAmount: \"0\",\n refundedTotalAmount: \"0\",\n outstandingAmount: snapshot.quote.grandTotalGrossAmount,\n totalsSnapshot: snapshot.quote.totalsSnapshot\n ? cloneJson(snapshot.quote.totalsSnapshot)\n : null,\n lineItemCount: snapshot.quote.lineItemCount,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(order);\n\n const orderLineMap = new Map<string, SalesOrderLine>();\n snapshot.lines.forEach((line, index) => {\n const orderLine = em.create(SalesOrderLine, {\n id: line.id,\n order,\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n lineNumber: line.lineNumber ?? index + 1,\n kind: line.kind as SalesLineKind,\n statusEntryId: (line as any).statusEntryId ?? null,\n status: (line as any).status ?? null,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: line.normalizedQuantity ?? line.quantity,\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n reservedQuantity: \"0\",\n fulfilledQuantity: \"0\",\n invoicedQuantity: \"0\",\n returnedQuantity: \"0\",\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n discountAmount: line.discountAmount,\n discountPercent: line.discountPercent,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n totalNetAmount: line.totalNetAmount,\n totalGrossAmount: line.totalGrossAmount,\n configuration: line.configuration\n ? cloneJson(line.configuration)\n : null,\n promotionCode: line.promotionCode ?? null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(orderLine);\n orderLineMap.set(orderLine.id, orderLine);\n });\n\n snapshot.adjustments.forEach((adj, index) => {\n const orderLineId = adj.quoteLineId ?? null;\n const orderLine = orderLineId\n ? (orderLineMap.get(orderLineId) ?? null)\n : null;\n const entity = em.create(SalesOrderAdjustment, {\n id: adj.id,\n order,\n orderLine: orderLine ?? null,\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n scope: adj.scope,\n kind: adj.kind as SalesAdjustmentKind,\n code: adj.code ?? null,\n label: adj.label ?? null,\n calculatorKey: adj.calculatorKey ?? null,\n promotionId: adj.promotionId ?? null,\n rate: adj.rate,\n amountNet: adj.amountNet,\n amountGross: adj.amountGross,\n currencyCode: adj.currencyCode ?? null,\n metadata: adj.metadata ? cloneJson(adj.metadata) : null,\n position: adj.position ?? index,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(entity);\n });\n\n const [addresses, notes, tags] = await Promise.all([\n em.find(SalesDocumentAddress, {\n documentId: snapshot.quote.id,\n documentKind: \"quote\",\n }),\n em.find(SalesNote, {\n contextType: \"quote\",\n contextId: snapshot.quote.id,\n }),\n em.find(SalesDocumentTagAssignment, {\n documentId: snapshot.quote.id,\n documentKind: \"quote\",\n }),\n ]);\n addresses.forEach((entry) => {\n entry.documentKind = \"order\";\n entry.documentId = order.id;\n entry.order = order;\n entry.quote = null;\n entry.updatedAt = new Date();\n });\n notes.forEach((note) => {\n note.contextType = \"order\";\n note.contextId = order.id;\n note.order = order;\n note.quote = null;\n note.updatedAt = new Date();\n });\n tags.forEach((assignment) => {\n assignment.documentKind = \"order\";\n assignment.documentId = order.id;\n assignment.order = order;\n assignment.quote = null;\n assignment.updatedAt = new Date();\n });\n\n const documentCustomValues = quoteCustomFields[snapshot.quote.id];\n if (documentCustomValues && Object.keys(documentCustomValues).length) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order,\n recordId: order.id,\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n values: documentCustomValues,\n });\n }\n const lineCustomEntries = quoteLineCustomFields as Record<\n string,\n Record<string, unknown>\n >;\n if (lineCustomEntries && Object.keys(lineCustomEntries).length) {\n for (const [lineId, values] of Object.entries(lineCustomEntries)) {\n if (!values || !Object.keys(values).length) continue;\n if (!orderLineMap.has(lineId)) continue;\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_order_line,\n recordId: lineId,\n organizationId: snapshot.quote.organizationId,\n tenantId: snapshot.quote.tenantId,\n values,\n });\n }\n }\n\n await em.nativeDelete(SalesQuoteAdjustment, { quote: snapshot.quote.id });\n await em.nativeDelete(SalesQuoteLine, { quote: snapshot.quote.id });\n em.remove(quote);\n await em.flush();\n\n return { orderId: order.id };\n };\n if (callerEm) {\n // Already inside the caller's transaction \u2014 run directly so the whole flow\n // stays a single transaction (no nested savepoint).\n return runConversion(callerEm);\n }\n return typeof transactionalEm.transactional === \"function\"\n ? transactionalEm.transactional((trx) => runConversion(trx))\n : runConversion(rootEm);\n },\n captureAfter: async (_input, result, ctx) => {\n // Prefer the caller's transactional EM so the just-created (still\n // uncommitted) order is visible when building the audit \"after\" snapshot.\n const em =\n ctx.transactionalEm ??\n (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadOrderSnapshot(em, result.orderId);\n },\n buildLog: async ({ snapshots, result }) => {\n const before = snapshots.before as QuoteGraphSnapshot | undefined;\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!before) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.quotes.convert\",\n \"Convert quote to order\",\n ),\n resourceKind: \"sales.order\",\n resourceId: result.orderId,\n tenantId: before.quote.tenantId,\n organizationId: before.quote.organizationId,\n snapshotBefore: before,\n snapshotAfter: after ?? null,\n payload: {\n undo: {\n quote: before,\n order: after ?? null,\n } satisfies QuoteConvertUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteConvertUndoPayload>(logEntry);\n const quoteSnapshot = payload?.quote;\n const orderSnapshot = payload?.order;\n if (!quoteSnapshot) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureQuoteScope(\n ctx,\n quoteSnapshot.quote.organizationId,\n quoteSnapshot.quote.tenantId,\n );\n if (orderSnapshot) {\n const orderId = orderSnapshot.order.id;\n const orderLineIds = orderSnapshot.lines.map((line) => line.id);\n const existingOrder = await findOneWithDecryption(em, SalesOrder, { id: orderId }, undefined, { tenantId: quoteSnapshot.quote.tenantId, organizationId: quoteSnapshot.quote.organizationId });\n if (existingOrder) {\n const shipments = await em.find(SalesShipment, { order: orderId });\n const shipmentIds = shipments.map((entry) => entry.id);\n if (shipmentIds.length) {\n await em.nativeDelete(SalesShipmentItem, {\n shipment: { $in: shipmentIds },\n });\n await em.nativeDelete(SalesShipment, { id: { $in: shipmentIds } });\n }\n await em.nativeDelete(SalesPaymentAllocation, { order: orderId });\n await em.nativeDelete(SalesPayment, { order: orderId });\n await em.nativeDelete(SalesDocumentAddress, {\n documentId: orderId,\n documentKind: \"order\",\n });\n await em.nativeDelete(SalesDocumentTagAssignment, {\n documentId: orderId,\n documentKind: \"order\",\n });\n await em.nativeDelete(SalesOrderAdjustment, { order: orderId });\n await em.nativeDelete(SalesOrderLine, { order: orderId });\n em.remove(existingOrder);\n }\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_order,\n recordId: orderId,\n });\n if (orderLineIds.length) {\n await em.nativeDelete(CustomFieldValue, {\n entityId: E.sales.sales_order_line,\n recordId: { $in: orderLineIds } as any,\n });\n }\n }\n const noteIds = quoteSnapshot.notes.map((note) => note.id);\n if (noteIds.length) {\n await em.nativeDelete(SalesNote, { id: { $in: noteIds } });\n }\n await restoreQuoteGraph(em, quoteSnapshot);\n await em.flush();\n },\n};\n\nconst orderLineUpsertSchema = orderLineCreateSchema.extend({\n id: z.string().uuid().optional(),\n});\n\nconst orderLineDeleteSchema = z.object({\n id: z.string().uuid(),\n orderId: z.string().uuid(),\n});\n\nconst quoteLineUpsertSchema = quoteLineCreateSchema.extend({\n id: z.string().uuid().optional(),\n});\n\nconst quoteLineDeleteSchema = z.object({\n id: z.string().uuid(),\n quoteId: z.string().uuid(),\n});\n\nconst orderAdjustmentUpsertSchema = orderAdjustmentCreateSchema\n .extend({\n id: z.string().uuid().optional(),\n })\n .superRefine(enforceAdjustmentSign);\n\nconst orderAdjustmentDeleteSchema = z.object({\n id: z.string().uuid(),\n orderId: z.string().uuid(),\n});\n\nconst quoteAdjustmentUpsertSchema = quoteAdjustmentCreateSchema\n .extend({\n id: z.string().uuid().optional(),\n })\n .superRefine(enforceAdjustmentSign);\n\nconst quoteAdjustmentDeleteSchema = z.object({\n id: z.string().uuid(),\n quoteId: z.string().uuid(),\n});\n\nconst orderLineUpsertCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { orderId: string; lineId: string }\n> = {\n id: \"sales.orders.lines.upsert\",\n async prepare(input, ctx) {\n const raw = (input?.body as Record<string, unknown> | undefined) ?? {};\n const orderId = typeof raw.orderId === \"string\" ? raw.orderId : null;\n if (!orderId) return {};\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadOrderSnapshot(em, orderId);\n if (snapshot)\n ensureOrderScope(\n ctx,\n snapshot.order.organizationId,\n snapshot.order.tenantId,\n );\n return snapshot ? { before: snapshot } : {};\n },\n async execute(input, ctx) {\n const rawBody = (input?.body as Record<string, unknown> | undefined) ?? {};\n const parsed = orderLineUpsertSchema.parse(rawBody);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const order = await em.findOne(SalesOrder, {\n id: parsed.orderId,\n deletedAt: null,\n });\n if (!order)\n throw new CrudHttpError(404, { error: \"Sales order not found\" });\n ensureOrderScope(ctx, order.organizationId, order.tenantId);\n enforceSalesDocumentOptimisticLock(ctx, order, SALES_RESOURCE_KIND_ORDER);\n\n const [existingLines, adjustments] = await Promise.all([\n em.find(SalesOrderLine, { order }, { orderBy: { lineNumber: \"asc\" } }),\n em.find(\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const lineSnapshots = existingLines.map(mapOrderLineEntityToSnapshot);\n const existingSnapshot = parsed.id\n ? (lineSnapshots.find((line) => line.id === parsed.id) ?? null)\n : null;\n const priceMode =\n parsed.priceMode === \"gross\"\n ? \"gross\"\n : parsed.priceMode === \"net\"\n ? \"net\"\n : null;\n let unitPriceNet =\n parsed.unitPriceNet ?? existingSnapshot?.unitPriceNet ?? null;\n let unitPriceGross =\n parsed.unitPriceGross ?? existingSnapshot?.unitPriceGross ?? null;\n let taxRate = parsed.taxRate ?? existingSnapshot?.taxRate ?? null;\n if (priceMode && (unitPriceNet === null || unitPriceGross === null)) {\n let taxService: TaxCalculationService | null = null;\n try {\n taxService = ctx.container.resolve(\n \"taxCalculationService\",\n ) as TaxCalculationService;\n } catch {\n taxService = null;\n }\n if (taxService) {\n const taxResult = await taxService.calculateUnitAmounts({\n amount:\n priceMode === \"gross\"\n ? (unitPriceGross ?? unitPriceNet ?? 0)\n : (unitPriceNet ?? unitPriceGross ?? 0),\n mode: priceMode,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n taxRateId: parsed.taxRateId ?? undefined,\n taxRate: taxRate ?? undefined,\n });\n unitPriceNet = unitPriceNet ?? taxResult.netAmount;\n unitPriceGross = unitPriceGross ?? taxResult.grossAmount;\n taxRate = taxResult.taxRate ?? taxRate;\n }\n }\n\n const metadata =\n typeof parsed.metadata === \"object\" && parsed.metadata\n ? { ...parsed.metadata }\n : existingSnapshot?.metadata\n ? cloneJson(existingSnapshot.metadata)\n : {};\n if (parsed.priceId) metadata.priceId = parsed.priceId;\n if (priceMode) metadata.priceMode = priceMode;\n\n const statusEntryId =\n parsed.statusEntryId ?? (existingSnapshot as any)?.statusEntryId ?? null;\n const lineId = parsed.id ?? existingSnapshot?.id ?? randomUUID();\n const lineUomInput = {\n productId: parsed.productId ?? existingSnapshot?.productId ?? null,\n productVariantId:\n parsed.productVariantId ?? existingSnapshot?.productVariantId ?? null,\n quantity: parsed.quantity ?? existingSnapshot?.quantity ?? 0,\n quantityUnit: parsed.quantityUnit ?? existingSnapshot?.quantityUnit ?? null,\n normalizedQuantity: existingSnapshot?.normalizedQuantity ?? null,\n normalizedUnit: existingSnapshot?.normalizedUnit ?? null,\n uomSnapshot: existingSnapshot?.uomSnapshot ?? null,\n };\n const uomResolver = createUomResolver();\n let normalizedUom = await normalizeLineUom({\n em,\n resolver: uomResolver,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n line: {\n ...lineUomInput,\n unitPriceNet: unitPriceNet ?? 0,\n unitPriceGross: unitPriceGross ?? unitPriceNet ?? 0,\n },\n });\n const convertedPrices = convertLineUnitPricesOnUnitChange({\n existingSnapshot,\n nextQuantityUnit: normalizedUom.quantityUnit,\n nextUomSnapshot: normalizedUom.uomSnapshot,\n unitPriceNet,\n unitPriceGross,\n });\n if (convertedPrices.didConvert) {\n unitPriceNet = convertedPrices.unitPriceNet;\n unitPriceGross = convertedPrices.unitPriceGross;\n normalizedUom = await normalizeLineUom({\n em,\n resolver: uomResolver,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n line: {\n ...lineUomInput,\n unitPriceNet: unitPriceNet ?? 0,\n unitPriceGross: unitPriceGross ?? unitPriceNet ?? 0,\n },\n });\n }\n const updatedSnapshot: SalesLineSnapshot & {\n statusEntryId?: string | null;\n catalogSnapshot?: Record<string, unknown> | null;\n promotionSnapshot?: Record<string, unknown> | null;\n } = {\n id: lineId,\n lineNumber:\n parsed.lineNumber ??\n existingSnapshot?.lineNumber ??\n lineSnapshots.length + 1,\n kind: parsed.kind ?? existingSnapshot?.kind ?? \"product\",\n productId: parsed.productId ?? existingSnapshot?.productId ?? null,\n productVariantId:\n parsed.productVariantId ?? existingSnapshot?.productVariantId ?? null,\n name: parsed.name ?? existingSnapshot?.name ?? null,\n description: parsed.description ?? existingSnapshot?.description ?? null,\n comment: parsed.comment ?? existingSnapshot?.comment ?? null,\n quantity: normalizedUom.quantity,\n quantityUnit: normalizedUom.quantityUnit,\n normalizedQuantity: normalizedUom.normalizedQuantity,\n normalizedUnit: normalizedUom.normalizedUnit,\n uomSnapshot: normalizedUom.uomSnapshot\n ? cloneJson(normalizedUom.uomSnapshot)\n : null,\n currencyCode:\n parsed.currencyCode ??\n existingSnapshot?.currencyCode ??\n order.currencyCode,\n unitPriceNet: unitPriceNet ?? 0,\n unitPriceGross: unitPriceGross ?? unitPriceNet ?? 0,\n discountAmount:\n parsed.discountAmount ?? existingSnapshot?.discountAmount ?? 0,\n discountPercent:\n parsed.discountPercent ?? existingSnapshot?.discountPercent ?? 0,\n taxRate: taxRate ?? 0,\n taxAmount: parsed.taxAmount ?? existingSnapshot?.taxAmount ?? null,\n totalNetAmount:\n parsed.totalNetAmount ?? existingSnapshot?.totalNetAmount ?? null,\n totalGrossAmount:\n parsed.totalGrossAmount ?? existingSnapshot?.totalGrossAmount ?? null,\n configuration:\n parsed.configuration ?? existingSnapshot?.configuration ?? null,\n promotionCode:\n parsed.promotionCode ?? existingSnapshot?.promotionCode ?? null,\n metadata,\n customFieldSetId:\n parsed.customFieldSetId ?? existingSnapshot?.customFieldSetId ?? null,\n customFields:\n parsed.customFields && typeof parsed.customFields === \"object\"\n ? cloneJson(parsed.customFields)\n : ((existingSnapshot as any)?.customFields ?? null),\n };\n (updatedSnapshot as any).statusEntryId = statusEntryId;\n (updatedSnapshot as any).catalogSnapshot =\n parsed.catalogSnapshot ??\n (existingSnapshot as any)?.catalogSnapshot ??\n null;\n (updatedSnapshot as any).promotionSnapshot =\n parsed.promotionSnapshot ??\n (existingSnapshot as any)?.promotionSnapshot ??\n null;\n\n let nextLines = parsed.id\n ? lineSnapshots.map((line) =>\n line.id === parsed.id ? updatedSnapshot : line,\n )\n : [...lineSnapshots, updatedSnapshot];\n nextLines = nextLines\n .sort((a, b) => (a.lineNumber ?? 0) - (b.lineNumber ?? 0))\n .map((line, index) => ({ ...line, lineNumber: index + 1 }));\n\n const sourceInputs = nextLines.map((line, index) => ({\n ...line,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n lineNumber: line.lineNumber ?? index + 1,\n }));\n const calcLines: SalesLineSnapshot[] = sourceInputs.map((line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const adjustmentDrafts = adjustments.map(mapOrderAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n currencyCode: order.currencyCode,\n shippingSnapshot: order.shippingMethodSnapshot,\n paymentSnapshot: order.paymentMethodSnapshot,\n shippingMethodId: order.shippingMethodId ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n });\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n // Persist the line changes and recalculated totals atomically so a\n // mid-build failure cannot leave a half-updated order committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n await applyOrderLineResults({\n em,\n order,\n calculation,\n sourceLines: sourceInputs,\n existingLines,\n });\n applyOrderTotals(order, calculation.totals, calculation.lines.length);\n await emitTotalsCalculated(eventBus, {\n documentKind: \"order\",\n documentId: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n customerId: order.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n },\n ],\n { transaction: true },\n );\n return { orderId: order.id, lineId };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadOrderSnapshot(em, result.orderId);\n },\n buildLog: async ({ result, snapshots }) => {\n const before = snapshots.before as OrderGraphSnapshot | undefined;\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.orders.lines.upsert\",\n \"Upsert order line\",\n ),\n resourceKind: \"sales.order\",\n resourceId: result.orderId,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureOrderScope(ctx, before.order.organizationId, before.order.tenantId);\n await restoreOrderGraph(em, before);\n await em.flush();\n },\n};\n\nconst orderLineDeleteCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { orderId: string; lineId: string }\n> = {\n id: \"sales.orders.lines.delete\",\n async prepare(input, ctx) {\n const raw = (input?.body as Record<string, unknown> | undefined) ?? {};\n const orderId = typeof raw.orderId === \"string\" ? raw.orderId : null;\n if (!orderId) return {};\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadOrderSnapshot(em, orderId);\n if (snapshot)\n ensureOrderScope(\n ctx,\n snapshot.order.organizationId,\n snapshot.order.tenantId,\n );\n return snapshot ? { before: snapshot } : {};\n },\n async execute(input, ctx) {\n const { translate } = await resolveTranslations();\n const parsed = orderLineDeleteSchema.parse(\n (input?.body as Record<string, unknown> | undefined) ?? {},\n );\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const order = await em.findOne(SalesOrder, {\n id: parsed.orderId,\n deletedAt: null,\n });\n if (!order)\n throw new CrudHttpError(404, {\n error: translate(\n \"sales.documents.detail.error\",\n \"Document not found or inaccessible.\",\n ),\n });\n ensureOrderScope(ctx, order.organizationId, order.tenantId);\n enforceSalesDocumentOptimisticLock(ctx, order, SALES_RESOURCE_KIND_ORDER);\n const shipmentCount = await em.count(SalesShipmentItem, {\n orderLine: parsed.id,\n shipment: { deletedAt: null },\n });\n if (shipmentCount > 0) {\n throw new CrudHttpError(409, {\n error: translate(\n \"sales.documents.items.errorDeleteShipped\",\n \"Cannot delete a line that has shipped items.\",\n ),\n });\n }\n const existingLines = await em.find(\n SalesOrderLine,\n { order },\n { orderBy: { lineNumber: \"asc\" } },\n );\n const adjustments = await em.find(\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n );\n const filtered = existingLines.filter((line) => line.id !== parsed.id);\n if (filtered.length === existingLines.length) {\n throw new CrudHttpError(404, {\n error: translate(\n \"sales.documents.detail.error\",\n \"Document not found or inaccessible.\",\n ),\n });\n }\n const sourceInputs = filtered.map((line, index) => ({\n ...mapOrderLineEntityToSnapshot(line),\n statusEntryId: line.statusEntryId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n lineNumber: index + 1,\n }));\n const calcLines = sourceInputs.map((line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const adjustmentDrafts = adjustments.map(mapOrderAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n currencyCode: order.currencyCode,\n shippingSnapshot: order.shippingMethodSnapshot,\n paymentSnapshot: order.paymentMethodSnapshot,\n shippingMethodId: order.shippingMethodId ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n });\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n // Persist the line removal and recalculated totals atomically so a\n // mid-build failure cannot leave a half-updated order committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n await applyOrderLineResults({\n em,\n order,\n calculation,\n sourceLines: sourceInputs,\n existingLines,\n });\n applyOrderTotals(order, calculation.totals, calculation.lines.length);\n await emitTotalsCalculated(eventBus, {\n documentKind: \"order\",\n documentId: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n customerId: order.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n },\n ],\n { transaction: true },\n );\n return { orderId: order.id, lineId: parsed.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadOrderSnapshot(em, result.orderId);\n },\n buildLog: async ({ result, snapshots }) => {\n const before = snapshots.before as OrderGraphSnapshot | undefined;\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.orders.lines.delete\",\n \"Delete order line\",\n ),\n resourceKind: \"sales.order\",\n resourceId: result.orderId,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureOrderScope(ctx, before.order.organizationId, before.order.tenantId);\n await restoreOrderGraph(em, before);\n await em.flush();\n },\n};\n\nconst quoteLineUpsertCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { quoteId: string; lineId: string }\n> = {\n id: \"sales.quotes.lines.upsert\",\n async prepare(input, ctx) {\n const raw = (input?.body as Record<string, unknown> | undefined) ?? {};\n const quoteId = typeof raw.quoteId === \"string\" ? raw.quoteId : null;\n if (!quoteId) return {};\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadQuoteSnapshot(em, quoteId);\n if (snapshot)\n ensureQuoteScope(\n ctx,\n snapshot.quote.organizationId,\n snapshot.quote.tenantId,\n );\n return snapshot ? { before: snapshot } : {};\n },\n async execute(input, ctx) {\n const rawBody = (input?.body as Record<string, unknown> | undefined) ?? {};\n const parsed = quoteLineUpsertSchema.parse(rawBody);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const quote = await em.findOne(SalesQuote, {\n id: parsed.quoteId,\n deletedAt: null,\n });\n if (!quote)\n throw new CrudHttpError(404, { error: \"Sales quote not found\" });\n ensureQuoteScope(ctx, quote.organizationId, quote.tenantId);\n enforceSalesDocumentOptimisticLock(ctx, quote, SALES_RESOURCE_KIND_QUOTE);\n const [existingLines, adjustments] = await Promise.all([\n em.find(SalesQuoteLine, { quote }, { orderBy: { lineNumber: \"asc\" } }),\n em.find(\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const lineSnapshots = existingLines.map(mapQuoteLineEntityToSnapshot);\n const existingSnapshot = parsed.id\n ? (lineSnapshots.find((line) => line.id === parsed.id) ?? null)\n : null;\n const priceMode =\n parsed.priceMode === \"gross\"\n ? \"gross\"\n : parsed.priceMode === \"net\"\n ? \"net\"\n : null;\n let unitPriceNet =\n parsed.unitPriceNet ?? existingSnapshot?.unitPriceNet ?? null;\n let unitPriceGross =\n parsed.unitPriceGross ?? existingSnapshot?.unitPriceGross ?? null;\n let taxRate = parsed.taxRate ?? existingSnapshot?.taxRate ?? null;\n if (priceMode && (unitPriceNet === null || unitPriceGross === null)) {\n let taxService: TaxCalculationService | null = null;\n try {\n taxService = ctx.container.resolve(\n \"taxCalculationService\",\n ) as TaxCalculationService;\n } catch {\n taxService = null;\n }\n if (taxService) {\n const taxResult = await taxService.calculateUnitAmounts({\n amount:\n priceMode === \"gross\"\n ? (unitPriceGross ?? unitPriceNet ?? 0)\n : (unitPriceNet ?? unitPriceGross ?? 0),\n mode: priceMode,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n taxRateId: parsed.taxRateId ?? undefined,\n taxRate: taxRate ?? undefined,\n });\n unitPriceNet = unitPriceNet ?? taxResult.netAmount;\n unitPriceGross = unitPriceGross ?? taxResult.grossAmount;\n taxRate = taxResult.taxRate ?? taxRate;\n }\n }\n const metadata =\n typeof parsed.metadata === \"object\" && parsed.metadata\n ? { ...parsed.metadata }\n : existingSnapshot?.metadata\n ? cloneJson(existingSnapshot.metadata)\n : {};\n if (parsed.priceId) metadata.priceId = parsed.priceId;\n if (priceMode) metadata.priceMode = priceMode;\n\n const statusEntryId =\n parsed.statusEntryId ?? (existingSnapshot as any)?.statusEntryId ?? null;\n const lineId = parsed.id ?? existingSnapshot?.id ?? randomUUID();\n const lineUomInput = {\n productId: parsed.productId ?? existingSnapshot?.productId ?? null,\n productVariantId:\n parsed.productVariantId ?? existingSnapshot?.productVariantId ?? null,\n quantity: parsed.quantity ?? existingSnapshot?.quantity ?? 0,\n quantityUnit: parsed.quantityUnit ?? existingSnapshot?.quantityUnit ?? null,\n normalizedQuantity: existingSnapshot?.normalizedQuantity ?? null,\n normalizedUnit: existingSnapshot?.normalizedUnit ?? null,\n uomSnapshot: existingSnapshot?.uomSnapshot ?? null,\n };\n const uomResolver = createUomResolver();\n let normalizedUom = await normalizeLineUom({\n em,\n resolver: uomResolver,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n line: {\n ...lineUomInput,\n unitPriceNet: unitPriceNet ?? 0,\n unitPriceGross: unitPriceGross ?? unitPriceNet ?? 0,\n },\n });\n const convertedPrices = convertLineUnitPricesOnUnitChange({\n existingSnapshot,\n nextQuantityUnit: normalizedUom.quantityUnit,\n nextUomSnapshot: normalizedUom.uomSnapshot,\n unitPriceNet,\n unitPriceGross,\n });\n if (convertedPrices.didConvert) {\n unitPriceNet = convertedPrices.unitPriceNet;\n unitPriceGross = convertedPrices.unitPriceGross;\n normalizedUom = await normalizeLineUom({\n em,\n resolver: uomResolver,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n line: {\n ...lineUomInput,\n unitPriceNet: unitPriceNet ?? 0,\n unitPriceGross: unitPriceGross ?? unitPriceNet ?? 0,\n },\n });\n }\n const updatedSnapshot: SalesLineSnapshot & {\n statusEntryId?: string | null;\n catalogSnapshot?: Record<string, unknown> | null;\n promotionSnapshot?: Record<string, unknown> | null;\n } = {\n id: lineId,\n lineNumber:\n parsed.lineNumber ??\n existingSnapshot?.lineNumber ??\n lineSnapshots.length + 1,\n kind: parsed.kind ?? existingSnapshot?.kind ?? \"product\",\n productId: parsed.productId ?? existingSnapshot?.productId ?? null,\n productVariantId:\n parsed.productVariantId ?? existingSnapshot?.productVariantId ?? null,\n name: parsed.name ?? existingSnapshot?.name ?? null,\n description: parsed.description ?? existingSnapshot?.description ?? null,\n comment: parsed.comment ?? existingSnapshot?.comment ?? null,\n quantity: normalizedUom.quantity,\n quantityUnit: normalizedUom.quantityUnit,\n normalizedQuantity: normalizedUom.normalizedQuantity,\n normalizedUnit: normalizedUom.normalizedUnit,\n uomSnapshot: normalizedUom.uomSnapshot\n ? cloneJson(normalizedUom.uomSnapshot)\n : null,\n currencyCode:\n parsed.currencyCode ??\n existingSnapshot?.currencyCode ??\n quote.currencyCode,\n unitPriceNet: unitPriceNet ?? 0,\n unitPriceGross: unitPriceGross ?? unitPriceNet ?? 0,\n discountAmount:\n parsed.discountAmount ?? existingSnapshot?.discountAmount ?? 0,\n discountPercent:\n parsed.discountPercent ?? existingSnapshot?.discountPercent ?? 0,\n taxRate: taxRate ?? 0,\n taxAmount: parsed.taxAmount ?? existingSnapshot?.taxAmount ?? null,\n totalNetAmount:\n parsed.totalNetAmount ?? existingSnapshot?.totalNetAmount ?? null,\n totalGrossAmount:\n parsed.totalGrossAmount ?? existingSnapshot?.totalGrossAmount ?? null,\n configuration:\n parsed.configuration ?? existingSnapshot?.configuration ?? null,\n promotionCode:\n parsed.promotionCode ?? existingSnapshot?.promotionCode ?? null,\n metadata,\n customFieldSetId:\n parsed.customFieldSetId ?? existingSnapshot?.customFieldSetId ?? null,\n customFields:\n parsed.customFields && typeof parsed.customFields === \"object\"\n ? cloneJson(parsed.customFields)\n : ((existingSnapshot as any)?.customFields ?? null),\n };\n (updatedSnapshot as any).statusEntryId = statusEntryId;\n (updatedSnapshot as any).catalogSnapshot =\n parsed.catalogSnapshot ??\n (existingSnapshot as any)?.catalogSnapshot ??\n null;\n (updatedSnapshot as any).promotionSnapshot =\n parsed.promotionSnapshot ??\n (existingSnapshot as any)?.promotionSnapshot ??\n null;\n\n let nextLines = parsed.id\n ? lineSnapshots.map((line) =>\n line.id === parsed.id ? updatedSnapshot : line,\n )\n : [...lineSnapshots, updatedSnapshot];\n nextLines = nextLines\n .sort((a, b) => (a.lineNumber ?? 0) - (b.lineNumber ?? 0))\n .map((line, index) => ({ ...line, lineNumber: index + 1 }));\n\n const sourceInputs = nextLines.map((line, index) => ({\n ...line,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n lineNumber: line.lineNumber ?? index + 1,\n }));\n const calcLines: SalesLineSnapshot[] = sourceInputs.map((line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const adjustmentDrafts = adjustments.map(mapQuoteAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n currencyCode: quote.currencyCode,\n shippingSnapshot: quote.shippingMethodSnapshot,\n paymentSnapshot: quote.paymentMethodSnapshot,\n shippingMethodId: quote.shippingMethodId ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n });\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n // Persist the line changes and recalculated totals atomically so a\n // mid-build failure cannot leave a half-updated quote committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n await applyQuoteLineResults({\n em,\n quote,\n calculation,\n sourceLines: sourceInputs,\n existingLines,\n });\n applyQuoteTotals(quote, calculation.totals, calculation.lines.length);\n await emitTotalsCalculated(eventBus, {\n documentKind: \"quote\",\n documentId: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n customerId: quote.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n },\n ],\n { transaction: true },\n );\n return { quoteId: quote.id, lineId };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadQuoteSnapshot(em, result.quoteId);\n },\n buildLog: async ({ result, snapshots }) => {\n const before = snapshots.before as QuoteGraphSnapshot | undefined;\n const after = snapshots.after as QuoteGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.quotes.lines.upsert\",\n \"Upsert quote line\",\n ),\n resourceKind: \"sales.quote\",\n resourceId: result.quoteId,\n tenantId: after.quote.tenantId,\n organizationId: after.quote.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureQuoteScope(ctx, before.quote.organizationId, before.quote.tenantId);\n await restoreQuoteGraph(em, before);\n await em.flush();\n },\n};\n\nconst quoteLineDeleteCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { quoteId: string; lineId: string }\n> = {\n id: \"sales.quotes.lines.delete\",\n async prepare(input, ctx) {\n const raw = (input?.body as Record<string, unknown> | undefined) ?? {};\n const quoteId = typeof raw.quoteId === \"string\" ? raw.quoteId : null;\n if (!quoteId) return {};\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadQuoteSnapshot(em, quoteId);\n if (snapshot)\n ensureQuoteScope(\n ctx,\n snapshot.quote.organizationId,\n snapshot.quote.tenantId,\n );\n return snapshot ? { before: snapshot } : {};\n },\n async execute(input, ctx) {\n const parsed = quoteLineDeleteSchema.parse(\n (input?.body as Record<string, unknown> | undefined) ?? {},\n );\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const quote = await em.findOne(SalesQuote, {\n id: parsed.quoteId,\n deletedAt: null,\n });\n if (!quote)\n throw new CrudHttpError(404, { error: \"Sales quote not found\" });\n ensureQuoteScope(ctx, quote.organizationId, quote.tenantId);\n enforceSalesDocumentOptimisticLock(ctx, quote, SALES_RESOURCE_KIND_QUOTE);\n const existingLines = await em.find(\n SalesQuoteLine,\n { quote },\n { orderBy: { lineNumber: \"asc\" } },\n );\n const adjustments = await em.find(\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n );\n const filtered = existingLines.filter((line) => line.id !== parsed.id);\n if (filtered.length === existingLines.length) {\n throw new CrudHttpError(404, { error: \"Quote line not found\" });\n }\n const sourceInputs = filtered.map((line, index) => ({\n ...mapQuoteLineEntityToSnapshot(line),\n statusEntryId: line.statusEntryId ?? null,\n catalogSnapshot: line.catalogSnapshot\n ? cloneJson(line.catalogSnapshot)\n : null,\n promotionSnapshot: line.promotionSnapshot\n ? cloneJson(line.promotionSnapshot)\n : null,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n lineNumber: index + 1,\n }));\n const calcLines = sourceInputs.map((line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const adjustmentDrafts = adjustments.map(mapQuoteAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n currencyCode: quote.currencyCode,\n shippingSnapshot: quote.shippingMethodSnapshot,\n paymentSnapshot: quote.paymentMethodSnapshot,\n shippingMethodId: quote.shippingMethodId ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n });\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n // Persist the line removal and recalculated totals atomically so a\n // mid-build failure cannot leave a half-updated quote committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n await applyQuoteLineResults({\n em,\n quote,\n calculation,\n sourceLines: sourceInputs,\n existingLines,\n });\n applyQuoteTotals(quote, calculation.totals, calculation.lines.length);\n await emitTotalsCalculated(eventBus, {\n documentKind: \"quote\",\n documentId: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n customerId: quote.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n },\n ],\n { transaction: true },\n );\n return { quoteId: quote.id, lineId: parsed.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadQuoteSnapshot(em, result.quoteId);\n },\n buildLog: async ({ result, snapshots }) => {\n const before = snapshots.before as QuoteGraphSnapshot | undefined;\n const after = snapshots.after as QuoteGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.quotes.lines.delete\",\n \"Delete quote line\",\n ),\n resourceKind: \"sales.quote\",\n resourceId: result.quoteId,\n tenantId: after.quote.tenantId,\n organizationId: after.quote.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureQuoteScope(ctx, before.quote.organizationId, before.quote.tenantId);\n await restoreQuoteGraph(em, before);\n await em.flush();\n },\n};\n\nconst orderAdjustmentUpsertCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { orderId: string; adjustmentId: string }\n> = {\n id: \"sales.orders.adjustments.upsert\",\n async prepare(input, ctx) {\n const raw = (input?.body as Record<string, unknown> | undefined) ?? {};\n const orderId = typeof raw.orderId === \"string\" ? raw.orderId : null;\n if (!orderId) return {};\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadOrderSnapshot(em, orderId);\n if (snapshot)\n ensureOrderScope(\n ctx,\n snapshot.order.organizationId,\n snapshot.order.tenantId,\n );\n return snapshot ? { before: snapshot } : {};\n },\n async execute(input, ctx) {\n const parsed = orderAdjustmentUpsertSchema.parse(\n (input?.body as Record<string, unknown> | undefined) ?? {},\n );\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const order = await em.findOne(SalesOrder, {\n id: parsed.orderId,\n deletedAt: null,\n });\n if (!order)\n throw new CrudHttpError(404, { error: \"Sales order not found\" });\n ensureOrderScope(ctx, order.organizationId, order.tenantId);\n enforceSalesDocumentOptimisticLock(ctx, order, SALES_RESOURCE_KIND_ORDER);\n if (parsed.scope === \"line\") {\n throw new CrudHttpError(400, {\n error: \"Line-scoped adjustments are not supported yet.\",\n });\n }\n\n const [existingLines, existingAdjustments] = await Promise.all([\n em.find(SalesOrderLine, { order }, { orderBy: { lineNumber: \"asc\" } }),\n em.find(\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const lineSnapshots = existingLines.map(mapOrderLineEntityToSnapshot);\n const adjustmentDrafts = existingAdjustments.map(mapOrderAdjustmentToDraft);\n const existingSnapshot = parsed.id\n ? (adjustmentDrafts.find((adj) => adj.id === parsed.id) ?? null)\n : null;\n const adjustmentId = parsed.id ?? existingSnapshot?.id ?? randomUUID();\n let metadata =\n typeof parsed.metadata === \"object\" && parsed.metadata\n ? cloneJson(parsed.metadata)\n : existingSnapshot?.metadata\n ? cloneJson(existingSnapshot.metadata)\n : null;\n const calculatorKey =\n parsed.calculatorKey ?? existingSnapshot?.calculatorKey ?? null;\n if (\n parsed.id &&\n calculatorKey &&\n (calculatorKey.startsWith(\"shipping-provider:\") ||\n calculatorKey.startsWith(\"payment-provider:\"))\n ) {\n metadata = { ...(metadata ?? {}), manualOverride: true };\n }\n let nextAdjustments = parsed.id\n ? adjustmentDrafts.map((adj) =>\n adj.id === parsed.id\n ? {\n ...adj,\n id: adjustmentId,\n scope: parsed.scope ?? adj.scope ?? \"order\",\n kind: parsed.kind ?? adj.kind ?? \"custom\",\n code: parsed.code ?? adj.code ?? null,\n label: parsed.label ?? adj.label ?? null,\n calculatorKey:\n parsed.calculatorKey ?? adj.calculatorKey ?? null,\n promotionId: parsed.promotionId ?? adj.promotionId ?? null,\n rate: parsed.rate ?? adj.rate ?? null,\n amountNet: parsed.amountNet ?? adj.amountNet ?? null,\n amountGross: parsed.amountGross ?? adj.amountGross ?? null,\n currencyCode:\n parsed.currencyCode ?? adj.currencyCode ?? order.currencyCode,\n metadata,\n customFields:\n parsed.customFields !== undefined\n ? parsed.customFields\n : ((adj as any).customFields ?? null),\n position:\n parsed.position ?? adj.position ?? adjustmentDrafts.length,\n }\n : adj,\n )\n : [\n ...adjustmentDrafts,\n {\n id: adjustmentId,\n scope: parsed.scope ?? \"order\",\n kind: parsed.kind ?? \"custom\",\n code: parsed.code ?? null,\n label: parsed.label ?? null,\n calculatorKey: parsed.calculatorKey ?? null,\n promotionId: parsed.promotionId ?? null,\n rate: parsed.rate ?? null,\n amountNet: parsed.amountNet ?? null,\n amountGross: parsed.amountGross ?? null,\n currencyCode: parsed.currencyCode ?? order.currencyCode,\n metadata,\n customFields: parsed.customFields ?? null,\n position: parsed.position ?? adjustmentDrafts.length,\n },\n ];\n\n nextAdjustments = nextAdjustments\n .sort((a, b) => (a.position ?? 0) - (b.position ?? 0))\n .map((adj, index) => ({ ...adj, position: adj.position ?? index }));\n\n const sourceLines = lineSnapshots.map((line, index) => ({\n ...line,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n lineNumber: line.lineNumber ?? index + 1,\n }));\n const calcLines = sourceLines.map((line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n currencyCode: order.currencyCode,\n shippingSnapshot: order.shippingMethodSnapshot,\n paymentSnapshot: order.paymentMethodSnapshot,\n shippingMethodId: order.shippingMethodId ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n });\n const effectiveAdjustment = nextAdjustments.find(\n (adj) => adj.id === adjustmentId,\n );\n if (effectiveAdjustment?.kind === \"return\") {\n const baselineAdjustments = nextAdjustments.filter(\n (adj) => adj.id !== adjustmentId,\n );\n const baselineCalculation =\n await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: calcLines,\n adjustments: baselineAdjustments,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n });\n const issues = validateReturnAdjustmentWithinRemaining({\n kind: \"return\",\n amountNet:\n effectiveAdjustment.amountNet ?? effectiveAdjustment.amountGross ?? 0,\n amountGross:\n effectiveAdjustment.amountGross ?? effectiveAdjustment.amountNet ?? 0,\n remainingNet: Number(\n baselineCalculation.totals?.grandTotalNetAmount ?? 0,\n ),\n remainingGross: Number(\n baselineCalculation.totals?.grandTotalGrossAmount ?? 0,\n ),\n });\n if (issues.length > 0) {\n const { translate } = await resolveTranslations();\n const grossIssue = issues.find((issue) => issue.path === \"amountGross\");\n const netIssue = issues.find((issue) => issue.path === \"amountNet\");\n const fieldErrors: Record<string, string> = {};\n if (grossIssue) {\n fieldErrors.amountGross = translate(\n \"sales.adjustments.error.returnExceedsRemainingGrandTotalGross\",\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_GROSS_MESSAGE,\n );\n }\n if (netIssue) {\n fieldErrors.amountNet = translate(\n \"sales.adjustments.error.returnExceedsRemainingGrandTotalNet\",\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_NET_MESSAGE,\n );\n }\n throw new CrudHttpError(400, {\n error:\n fieldErrors.amountGross ??\n fieldErrors.amountNet ??\n translate(\n \"sales.adjustments.error.returnExceedsRemainingGrandTotalGross\",\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_GROSS_MESSAGE,\n ),\n fieldErrors,\n });\n }\n }\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: calcLines,\n adjustments: nextAdjustments,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n });\n const adjustmentInputs = nextAdjustments.map((adj, index) => ({\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n scope: adj.scope ?? \"order\",\n kind: adj.kind ?? \"custom\",\n code: adj.code ?? undefined,\n label: adj.label ?? undefined,\n calculatorKey: adj.calculatorKey ?? undefined,\n promotionId: adj.promotionId ?? undefined,\n rate: adj.rate ?? undefined,\n amountNet: adj.amountNet ?? undefined,\n amountGross: adj.amountGross ?? undefined,\n currencyCode: adj.currencyCode ?? order.currencyCode,\n metadata: adj.metadata ?? undefined,\n customFields: (adj as any).customFields ?? undefined,\n position: adj.position ?? index,\n }));\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n // Persist the adjustment change and recalculated totals atomically so a\n // mid-build failure cannot leave a half-updated order committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n await replaceOrderAdjustments(em, order, calculation, adjustmentInputs);\n applyOrderTotals(order, calculation.totals, calculation.lines.length);\n order.updatedAt = new Date();\n await emitTotalsCalculated(eventBus, {\n documentKind: \"order\",\n documentId: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n customerId: order.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n },\n ],\n { transaction: true },\n );\n return { orderId: order.id, adjustmentId };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadOrderSnapshot(em, result.orderId);\n },\n buildLog: async ({ snapshots, result }) => {\n const before = snapshots.before as OrderGraphSnapshot | undefined;\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.orders.adjustments.upsert\",\n \"Upsert order adjustment\",\n ),\n resourceKind: \"sales.order\",\n resourceId: result.orderId,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureOrderScope(ctx, before.order.organizationId, before.order.tenantId);\n await restoreOrderGraph(em, before);\n await em.flush();\n },\n};\n\nconst orderAdjustmentDeleteCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { orderId: string; adjustmentId: string }\n> = {\n id: \"sales.orders.adjustments.delete\",\n async prepare(input, ctx) {\n const raw = (input?.body as Record<string, unknown> | undefined) ?? {};\n const orderId = typeof raw.orderId === \"string\" ? raw.orderId : null;\n if (!orderId) return {};\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadOrderSnapshot(em, orderId);\n if (snapshot)\n ensureOrderScope(\n ctx,\n snapshot.order.organizationId,\n snapshot.order.tenantId,\n );\n return snapshot ? { before: snapshot } : {};\n },\n async execute(input, ctx) {\n const parsed = orderAdjustmentDeleteSchema.parse(\n (input?.body as Record<string, unknown> | undefined) ?? {},\n );\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const order = await em.findOne(SalesOrder, {\n id: parsed.orderId,\n deletedAt: null,\n });\n if (!order)\n throw new CrudHttpError(404, { error: \"Sales order not found\" });\n ensureOrderScope(ctx, order.organizationId, order.tenantId);\n enforceSalesDocumentOptimisticLock(ctx, order, SALES_RESOURCE_KIND_ORDER);\n\n const [existingLines, adjustments] = await Promise.all([\n em.find(SalesOrderLine, { order }, { orderBy: { lineNumber: \"asc\" } }),\n em.find(\n SalesOrderAdjustment,\n { order },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const filtered = adjustments.filter((adj) => adj.id !== parsed.id);\n if (filtered.length === adjustments.length) {\n throw new CrudHttpError(404, { error: \"Adjustment not found\" });\n }\n const lineSnapshots = existingLines.map(mapOrderLineEntityToSnapshot);\n const calcLines = lineSnapshots.map((line, index) =>\n createLineSnapshotFromInput(\n {\n ...line,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n lineNumber: line.lineNumber ?? index + 1,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n },\n line.lineNumber ?? index + 1,\n ),\n );\n const adjustmentDrafts = filtered.map(mapOrderAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: order.tenantId,\n organizationId: order.organizationId,\n currencyCode: order.currencyCode,\n shippingSnapshot: order.shippingMethodSnapshot,\n paymentSnapshot: order.paymentMethodSnapshot,\n shippingMethodId: order.shippingMethodId ?? null,\n paymentMethodId: order.paymentMethodId ?? null,\n shippingMethodCode: order.shippingMethodCode ?? null,\n paymentMethodCode: order.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"order\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n existingTotals: resolveExistingPaymentTotals(order),\n });\n const adjustmentInputs = adjustmentDrafts.map((adj, index) => ({\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n orderId: order.id,\n scope: adj.scope ?? \"order\",\n kind: adj.kind ?? \"custom\",\n code: adj.code ?? undefined,\n label: adj.label ?? undefined,\n calculatorKey: adj.calculatorKey ?? undefined,\n promotionId: adj.promotionId ?? undefined,\n rate: adj.rate ?? undefined,\n amountNet: adj.amountNet ?? undefined,\n amountGross: adj.amountGross ?? undefined,\n currencyCode: adj.currencyCode ?? order.currencyCode,\n metadata: adj.metadata ?? undefined,\n position: adj.position ?? index,\n }));\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n // Persist the adjustment removal and recalculated totals atomically so a\n // mid-build failure cannot leave a half-updated order committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n await replaceOrderAdjustments(em, order, calculation, adjustmentInputs);\n applyOrderTotals(order, calculation.totals, calculation.lines.length);\n order.updatedAt = new Date();\n await emitTotalsCalculated(eventBus, {\n documentKind: \"order\",\n documentId: order.id,\n organizationId: order.organizationId,\n tenantId: order.tenantId,\n customerId: order.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n },\n ],\n { transaction: true },\n );\n return { orderId: order.id, adjustmentId: parsed.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadOrderSnapshot(em, result.orderId);\n },\n buildLog: async ({ snapshots, result }) => {\n const before = snapshots.before as OrderGraphSnapshot | undefined;\n const after = snapshots.after as OrderGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.orders.adjustments.delete\",\n \"Delete order adjustment\",\n ),\n resourceKind: \"sales.order\",\n resourceId: result.orderId,\n tenantId: after.order.tenantId,\n organizationId: after.order.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies OrderUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<OrderUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureOrderScope(ctx, before.order.organizationId, before.order.tenantId);\n await restoreOrderGraph(em, before);\n await em.flush();\n },\n};\n\nconst quoteAdjustmentUpsertCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { quoteId: string; adjustmentId: string }\n> = {\n id: \"sales.quotes.adjustments.upsert\",\n async prepare(input, ctx) {\n const raw = (input?.body as Record<string, unknown> | undefined) ?? {};\n const quoteId = typeof raw.quoteId === \"string\" ? raw.quoteId : null;\n if (!quoteId) return {};\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadQuoteSnapshot(em, quoteId);\n if (snapshot)\n ensureQuoteScope(\n ctx,\n snapshot.quote.organizationId,\n snapshot.quote.tenantId,\n );\n return snapshot ? { before: snapshot } : {};\n },\n async execute(input, ctx) {\n const parsed = quoteAdjustmentUpsertSchema.parse(\n (input?.body as Record<string, unknown> | undefined) ?? {},\n );\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const quote = await em.findOne(SalesQuote, {\n id: parsed.quoteId,\n deletedAt: null,\n });\n if (!quote)\n throw new CrudHttpError(404, { error: \"Sales quote not found\" });\n ensureQuoteScope(ctx, quote.organizationId, quote.tenantId);\n enforceSalesDocumentOptimisticLock(ctx, quote, SALES_RESOURCE_KIND_QUOTE);\n if (parsed.scope === \"line\") {\n throw new CrudHttpError(400, {\n error: \"Line-scoped adjustments are not supported yet.\",\n });\n }\n\n const [existingLines, existingAdjustments] = await Promise.all([\n em.find(SalesQuoteLine, { quote }, { orderBy: { lineNumber: \"asc\" } }),\n em.find(\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const lineSnapshots = existingLines.map(mapQuoteLineEntityToSnapshot);\n const adjustmentDrafts = existingAdjustments.map(mapQuoteAdjustmentToDraft);\n const existingSnapshot = parsed.id\n ? (adjustmentDrafts.find((adj) => adj.id === parsed.id) ?? null)\n : null;\n const adjustmentId = parsed.id ?? existingSnapshot?.id ?? randomUUID();\n let metadata =\n typeof parsed.metadata === \"object\" && parsed.metadata\n ? cloneJson(parsed.metadata)\n : existingSnapshot?.metadata\n ? cloneJson(existingSnapshot.metadata)\n : null;\n const calculatorKey =\n parsed.calculatorKey ?? existingSnapshot?.calculatorKey ?? null;\n if (\n parsed.id &&\n calculatorKey &&\n (calculatorKey.startsWith(\"shipping-provider:\") ||\n calculatorKey.startsWith(\"payment-provider:\"))\n ) {\n metadata = { ...(metadata ?? {}), manualOverride: true };\n }\n let nextAdjustments = parsed.id\n ? adjustmentDrafts.map((adj) =>\n adj.id === parsed.id\n ? {\n ...adj,\n id: adjustmentId,\n scope: parsed.scope ?? adj.scope ?? \"order\",\n kind: parsed.kind ?? adj.kind ?? \"custom\",\n code: parsed.code ?? adj.code ?? null,\n label: parsed.label ?? adj.label ?? null,\n calculatorKey:\n parsed.calculatorKey ?? adj.calculatorKey ?? null,\n promotionId: parsed.promotionId ?? adj.promotionId ?? null,\n rate: parsed.rate ?? adj.rate ?? null,\n amountNet: parsed.amountNet ?? adj.amountNet ?? null,\n amountGross: parsed.amountGross ?? adj.amountGross ?? null,\n currencyCode:\n parsed.currencyCode ?? adj.currencyCode ?? quote.currencyCode,\n metadata,\n customFields:\n parsed.customFields !== undefined\n ? parsed.customFields\n : ((adj as any).customFields ?? null),\n position:\n parsed.position ?? adj.position ?? adjustmentDrafts.length,\n }\n : adj,\n )\n : [\n ...adjustmentDrafts,\n {\n id: adjustmentId,\n scope: parsed.scope ?? \"order\",\n kind: parsed.kind ?? \"custom\",\n code: parsed.code ?? null,\n label: parsed.label ?? null,\n calculatorKey: parsed.calculatorKey ?? null,\n promotionId: parsed.promotionId ?? null,\n rate: parsed.rate ?? null,\n amountNet: parsed.amountNet ?? null,\n amountGross: parsed.amountGross ?? null,\n currencyCode: parsed.currencyCode ?? quote.currencyCode,\n metadata,\n customFields: parsed.customFields ?? null,\n position: parsed.position ?? adjustmentDrafts.length,\n },\n ];\n\n nextAdjustments = nextAdjustments\n .sort((a, b) => (a.position ?? 0) - (b.position ?? 0))\n .map((adj, index) => ({ ...adj, position: adj.position ?? index }));\n\n const sourceLines = lineSnapshots.map((line, index) => ({\n ...line,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n lineNumber: line.lineNumber ?? index + 1,\n }));\n const calcLines = sourceLines.map((line, index) =>\n createLineSnapshotFromInput(line, line.lineNumber ?? index + 1),\n );\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n currencyCode: quote.currencyCode,\n shippingSnapshot: quote.shippingMethodSnapshot,\n paymentSnapshot: quote.paymentMethodSnapshot,\n shippingMethodId: quote.shippingMethodId ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n });\n const effectiveAdjustment = nextAdjustments.find(\n (adj) => adj.id === adjustmentId,\n );\n if (effectiveAdjustment?.kind === \"return\") {\n const baselineAdjustments = nextAdjustments.filter(\n (adj) => adj.id !== adjustmentId,\n );\n const baselineCalculation =\n await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: calcLines,\n adjustments: baselineAdjustments,\n context: calculationContext,\n });\n const issues = validateReturnAdjustmentWithinRemaining({\n kind: \"return\",\n amountNet:\n effectiveAdjustment.amountNet ?? effectiveAdjustment.amountGross ?? 0,\n amountGross:\n effectiveAdjustment.amountGross ?? effectiveAdjustment.amountNet ?? 0,\n remainingNet: Number(\n baselineCalculation.totals?.grandTotalNetAmount ?? 0,\n ),\n remainingGross: Number(\n baselineCalculation.totals?.grandTotalGrossAmount ?? 0,\n ),\n });\n if (issues.length > 0) {\n const { translate } = await resolveTranslations();\n const grossIssue = issues.find((issue) => issue.path === \"amountGross\");\n const netIssue = issues.find((issue) => issue.path === \"amountNet\");\n const fieldErrors: Record<string, string> = {};\n if (grossIssue) {\n fieldErrors.amountGross = translate(\n \"sales.adjustments.error.returnExceedsRemainingGrandTotalGross\",\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_GROSS_MESSAGE,\n );\n }\n if (netIssue) {\n fieldErrors.amountNet = translate(\n \"sales.adjustments.error.returnExceedsRemainingGrandTotalNet\",\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_NET_MESSAGE,\n );\n }\n throw new CrudHttpError(400, {\n error:\n fieldErrors.amountGross ??\n fieldErrors.amountNet ??\n translate(\n \"sales.adjustments.error.returnExceedsRemainingGrandTotalGross\",\n RETURN_ADJUSTMENT_EXCEEDS_REMAINING_GROSS_MESSAGE,\n ),\n fieldErrors,\n });\n }\n }\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: calcLines,\n adjustments: nextAdjustments,\n context: calculationContext,\n });\n const adjustmentInputs = nextAdjustments.map((adj, index) => ({\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n scope: adj.scope ?? \"order\",\n kind: adj.kind ?? \"custom\",\n code: adj.code ?? undefined,\n label: adj.label ?? undefined,\n calculatorKey: adj.calculatorKey ?? undefined,\n promotionId: adj.promotionId ?? undefined,\n rate: adj.rate ?? undefined,\n amountNet: adj.amountNet ?? undefined,\n amountGross: adj.amountGross ?? undefined,\n currencyCode: adj.currencyCode ?? quote.currencyCode,\n metadata: adj.metadata ?? undefined,\n customFields: (adj as any).customFields ?? undefined,\n position: adj.position ?? index,\n }));\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n // Persist the adjustment change and recalculated totals atomically so a\n // mid-build failure cannot leave a half-updated quote committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n await replaceQuoteAdjustments(em, quote, calculation, adjustmentInputs);\n applyQuoteTotals(quote, calculation.totals, calculation.lines.length);\n quote.updatedAt = new Date();\n await emitTotalsCalculated(eventBus, {\n documentKind: \"quote\",\n documentId: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n customerId: quote.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n },\n ],\n { transaction: true },\n );\n return { quoteId: quote.id, adjustmentId };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadQuoteSnapshot(em, result.quoteId);\n },\n buildLog: async ({ snapshots, result }) => {\n const before = snapshots.before as QuoteGraphSnapshot | undefined;\n const after = snapshots.after as QuoteGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.quotes.adjustments.upsert\",\n \"Upsert quote adjustment\",\n ),\n resourceKind: \"sales.quote\",\n resourceId: result.quoteId,\n tenantId: after.quote.tenantId,\n organizationId: after.quote.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureQuoteScope(ctx, before.quote.organizationId, before.quote.tenantId);\n await restoreQuoteGraph(em, before);\n await em.flush();\n },\n};\n\nconst quoteAdjustmentDeleteCommand: CommandHandler<\n { body?: Record<string, unknown>; query?: Record<string, unknown> },\n { quoteId: string; adjustmentId: string }\n> = {\n id: \"sales.quotes.adjustments.delete\",\n async prepare(input, ctx) {\n const raw = (input?.body as Record<string, unknown> | undefined) ?? {};\n const quoteId = typeof raw.quoteId === \"string\" ? raw.quoteId : null;\n if (!quoteId) return {};\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadQuoteSnapshot(em, quoteId);\n if (snapshot)\n ensureQuoteScope(\n ctx,\n snapshot.quote.organizationId,\n snapshot.quote.tenantId,\n );\n return snapshot ? { before: snapshot } : {};\n },\n async execute(input, ctx) {\n const parsed = quoteAdjustmentDeleteSchema.parse(\n (input?.body as Record<string, unknown> | undefined) ?? {},\n );\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const quote = await em.findOne(SalesQuote, {\n id: parsed.quoteId,\n deletedAt: null,\n });\n if (!quote)\n throw new CrudHttpError(404, { error: \"Sales quote not found\" });\n ensureQuoteScope(ctx, quote.organizationId, quote.tenantId);\n enforceSalesDocumentOptimisticLock(ctx, quote, SALES_RESOURCE_KIND_QUOTE);\n\n const [existingLines, adjustments] = await Promise.all([\n em.find(SalesQuoteLine, { quote }, { orderBy: { lineNumber: \"asc\" } }),\n em.find(\n SalesQuoteAdjustment,\n { quote },\n { orderBy: { position: \"asc\" } },\n ),\n ]);\n const filtered = adjustments.filter((adj) => adj.id !== parsed.id);\n if (filtered.length === adjustments.length) {\n throw new CrudHttpError(404, { error: \"Adjustment not found\" });\n }\n const lineSnapshots = existingLines.map(mapQuoteLineEntityToSnapshot);\n const calcLines = lineSnapshots.map((line, index) =>\n createLineSnapshotFromInput(\n {\n ...line,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n lineNumber: line.lineNumber ?? index + 1,\n statusEntryId: (line as any).statusEntryId ?? null,\n catalogSnapshot: (line as any).catalogSnapshot ?? null,\n promotionSnapshot: (line as any).promotionSnapshot ?? null,\n },\n line.lineNumber ?? index + 1,\n ),\n );\n const adjustmentDrafts = filtered.map(mapQuoteAdjustmentToDraft);\n const salesCalculationService =\n ctx.container.resolve<SalesCalculationService>(\"salesCalculationService\");\n const calculationContext = buildCalculationContext({\n tenantId: quote.tenantId,\n organizationId: quote.organizationId,\n currencyCode: quote.currencyCode,\n shippingSnapshot: quote.shippingMethodSnapshot,\n paymentSnapshot: quote.paymentMethodSnapshot,\n shippingMethodId: quote.shippingMethodId ?? null,\n paymentMethodId: quote.paymentMethodId ?? null,\n shippingMethodCode: quote.shippingMethodCode ?? null,\n paymentMethodCode: quote.paymentMethodCode ?? null,\n });\n const calculation = await salesCalculationService.calculateDocumentTotals({\n documentKind: \"quote\",\n lines: calcLines,\n adjustments: adjustmentDrafts,\n context: calculationContext,\n });\n const adjustmentInputs = adjustmentDrafts.map((adj, index) => ({\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n quoteId: quote.id,\n scope: adj.scope ?? \"order\",\n kind: adj.kind ?? \"custom\",\n code: adj.code ?? undefined,\n label: adj.label ?? undefined,\n calculatorKey: adj.calculatorKey ?? undefined,\n promotionId: adj.promotionId ?? undefined,\n rate: adj.rate ?? undefined,\n amountNet: adj.amountNet ?? undefined,\n amountGross: adj.amountGross ?? undefined,\n currencyCode: adj.currencyCode ?? quote.currencyCode,\n metadata: adj.metadata ?? undefined,\n position: adj.position ?? index,\n }));\n let eventBus: EventBus | null = null;\n try {\n eventBus = ctx.container.resolve(\"eventBus\") as EventBus;\n } catch {\n eventBus = null;\n }\n // Persist the adjustment removal and recalculated totals atomically so a\n // mid-build failure cannot leave a half-updated quote committed (#2336).\n await withAtomicFlush(\n em,\n [\n async () => {\n await replaceQuoteAdjustments(em, quote, calculation, adjustmentInputs);\n applyQuoteTotals(quote, calculation.totals, calculation.lines.length);\n quote.updatedAt = new Date();\n await emitTotalsCalculated(eventBus, {\n documentKind: \"quote\",\n documentId: quote.id,\n organizationId: quote.organizationId,\n tenantId: quote.tenantId,\n customerId: quote.customerEntityId ?? null,\n totals: calculation.totals,\n lineCount: calculation.lines.length,\n });\n },\n ],\n { transaction: true },\n );\n return { quoteId: quote.id, adjustmentId: parsed.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadQuoteSnapshot(em, result.quoteId);\n },\n buildLog: async ({ snapshots, result }) => {\n const before = snapshots.before as QuoteGraphSnapshot | undefined;\n const after = snapshots.after as QuoteGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\n \"sales.audit.quotes.adjustments.delete\",\n \"Delete quote adjustment\",\n ),\n resourceKind: \"sales.quote\",\n resourceId: result.quoteId,\n tenantId: after.quote.tenantId,\n organizationId: after.quote.organizationId,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies QuoteUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<QuoteUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureQuoteScope(ctx, before.quote.organizationId, before.quote.tenantId);\n await restoreQuoteGraph(em, before);\n await em.flush();\n },\n};\n\n// ---------------------------------------------------------------------------\n// Invoice CRUD commands\n// ---------------------------------------------------------------------------\n\nconst invoiceCrudEvents: CrudEventsConfig<SalesInvoice> = {\n module: \"sales\",\n entity: \"invoice\",\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n};\n\nconst createInvoiceCommand: CommandHandler<\n InvoiceCreateInput,\n { invoiceId: string }\n> = {\n id: \"sales.invoices.create\",\n async execute(rawInput, ctx) {\n const generator = ctx.container.resolve(\n \"salesDocumentNumberGenerator\",\n ) as SalesDocumentNumberGenerator;\n const initial = invoiceCreateSchema.parse(rawInput ?? {});\n const invoiceNumber =\n typeof initial.invoiceNumber === \"string\" &&\n initial.invoiceNumber.trim().length\n ? initial.invoiceNumber.trim()\n : (\n await generator.generate({\n kind: \"invoice\",\n organizationId: initial.organizationId,\n tenantId: initial.tenantId,\n })\n ).number;\n const parsed = invoiceCreateSchema.parse({ ...initial, invoiceNumber });\n const ensuredInvoiceNumber = parsed.invoiceNumber ?? invoiceNumber;\n if (!ensuredInvoiceNumber) {\n throw new CrudHttpError(400, { error: \"Invoice number is required.\" });\n }\n ensureOrganizationScope(ctx, parsed.organizationId);\n ensureTenantScope(ctx, parsed.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const status = await resolveDictionaryEntryValue(\n em,\n parsed.statusEntryId ?? null,\n { tenantId: parsed.tenantId },\n );\n\n // Validate orderId belongs to same org/tenant\n if (parsed.orderId) {\n const orderExists = await em.findOne(SalesOrder, {\n id: parsed.orderId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n deletedAt: null,\n });\n if (!orderExists) {\n throw new CrudHttpError(400, { error: \"Referenced order not found in current scope.\" });\n }\n }\n\n const invoiceId = randomUUID();\n const invoice = em.create(SalesInvoice, {\n id: invoiceId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n invoiceNumber: ensuredInvoiceNumber,\n orderId: parsed.orderId ?? null,\n statusEntryId: parsed.statusEntryId ?? null,\n status,\n issueDate: parsed.issueDate ?? new Date(),\n dueDate: parsed.dueDate ?? null,\n currencyCode: parsed.currencyCode,\n subtotalNetAmount: toNumericString(parsed.subtotalNetAmount ?? 0),\n subtotalGrossAmount: toNumericString(parsed.subtotalGrossAmount ?? 0),\n discountTotalAmount: toNumericString(parsed.discountTotalAmount ?? 0),\n taxTotalAmount: toNumericString(parsed.taxTotalAmount ?? 0),\n grandTotalNetAmount: toNumericString(parsed.grandTotalNetAmount ?? 0),\n grandTotalGrossAmount: toNumericString(parsed.grandTotalGrossAmount ?? 0),\n paidTotalAmount: toNumericString(parsed.paidTotalAmount ?? 0),\n outstandingAmount: toNumericString(parsed.outstandingAmount ?? 0),\n metadata: parsed.metadata ?? null,\n customFieldSetId: parsed.customFieldSetId ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n\n // Header + lines + custom-field writes must commit atomically.\n // setRecordCustomFields flushes mid-build, so without a transaction a\n // partial write could persist the header without its lines/custom fields.\n await withAtomicFlush(\n em,\n [\n async () => {\n em.persist(invoice);\n\n if (parsed.lines?.length) {\n for (let i = 0; i < parsed.lines.length; i++) {\n const line = parsed.lines[i];\n em.persist(\n em.create(SalesInvoiceLine, {\n id: randomUUID(),\n invoice,\n orderLineId: line.orderLineId ?? null,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n lineNumber: line.lineNumber ?? i + 1,\n kind: line.kind ?? \"product\",\n name: line.name ?? null,\n sku: line.sku ?? null,\n description: line.description ?? null,\n quantity: toNumericString(line.quantity ?? 0),\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: toNumericString(line.normalizedQuantity ?? 0),\n normalizedUnit: line.normalizedUnit ?? null,\n uomSnapshot: line.uomSnapshot ?? null,\n currencyCode: line.currencyCode ?? parsed.currencyCode,\n unitPriceNet: toNumericString(line.unitPriceNet ?? 0),\n unitPriceGross: toNumericString(line.unitPriceGross ?? 0),\n discountAmount: toNumericString(line.discountAmount ?? 0),\n discountPercent: toNumericString(line.discountPercent ?? 0),\n taxRate: toNumericString(line.taxRate ?? 0),\n taxAmount: toNumericString(line.taxAmount ?? 0),\n totalNetAmount: toNumericString(line.totalNetAmount ?? 0),\n totalGrossAmount: toNumericString(line.totalGrossAmount ?? 0),\n metadata: line.metadata ?? null,\n }),\n );\n }\n }\n\n if (parsed.customFieldSetId) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_invoice,\n recordId: invoiceId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n values: normalizeCustomFieldValues(\n ((parsed as Record<string, unknown>).customFields as Record<string, unknown>) ?? {},\n ),\n });\n }\n },\n ],\n { transaction: true },\n );\n\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"created\",\n entity: invoice,\n identifiers: {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n },\n events: invoiceCrudEvents,\n indexer: { entityType: E.sales.sales_invoice },\n });\n\n await invalidateCrudCache(\n ctx.container,\n \"sales.invoice\",\n {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"created\",\n );\n\n return { invoiceId: invoice.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadInvoiceSnapshot(em, result.invoiceId);\n },\n buildLog: async ({ result, snapshots }) => {\n const after = snapshots.after as InvoiceGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.invoices.create\", \"Create invoice\"),\n resourceKind: \"sales.invoice\",\n resourceId: result.invoiceId,\n tenantId: after.invoice.tenantId,\n organizationId: after.invoice.organizationId,\n snapshotAfter: after,\n payload: {\n undo: { after } satisfies InvoiceUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<InvoiceUndoPayload>(logEntry);\n const after = payload?.after;\n if (!after) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const invoice = await em.findOne(SalesInvoice, { id: after.invoice.id });\n if (!invoice) return;\n ensureOrganizationScope(ctx, invoice.organizationId);\n ensureTenantScope(ctx, invoice.tenantId);\n await em.nativeDelete(SalesInvoiceLine, { invoice: invoice.id });\n em.remove(invoice);\n await em.flush();\n },\n};\n\nconst updateInvoiceCommand: CommandHandler<\n z.infer<typeof invoiceUpdateSchema>,\n { invoiceId: string }\n> = {\n id: \"sales.invoices.update\",\n async prepare(input, ctx) {\n const id = requireId(input);\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadInvoiceSnapshot(em, id);\n if (snapshot) {\n ensureOrganizationScope(ctx, snapshot.invoice.organizationId);\n ensureTenantScope(ctx, snapshot.invoice.tenantId);\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const parsed = invoiceUpdateSchema.parse(rawInput ?? {});\n const id = requireId(parsed);\n ensureOrganizationScope(ctx, parsed.organizationId);\n ensureTenantScope(ctx, parsed.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const invoice = await em.findOneOrFail(SalesInvoice, {\n id,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n deletedAt: null,\n });\n\n const changes = buildChanges(invoice, parsed, [\n \"invoiceNumber\",\n \"statusEntryId\",\n \"status\",\n \"issueDate\",\n \"dueDate\",\n \"currencyCode\",\n \"subtotalNetAmount\",\n \"subtotalGrossAmount\",\n \"discountTotalAmount\",\n \"taxTotalAmount\",\n \"grandTotalNetAmount\",\n \"grandTotalGrossAmount\",\n \"paidTotalAmount\",\n \"outstandingAmount\",\n \"metadata\",\n ]);\n\n if (parsed.statusEntryId !== undefined) {\n invoice.status = await resolveDictionaryEntryValue(em, parsed.statusEntryId ?? null, { tenantId: invoice.tenantId });\n }\n\n Object.assign(invoice, changes);\n invoice.updatedAt = new Date();\n await em.flush();\n\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"updated\",\n entity: invoice,\n identifiers: {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n },\n events: invoiceCrudEvents,\n indexer: { entityType: E.sales.sales_invoice },\n });\n\n await invalidateCrudCache(\n ctx.container,\n \"sales.invoice\",\n {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"updated\",\n );\n\n return { invoiceId: invoice.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadInvoiceSnapshot(em, result.invoiceId);\n },\n buildLog: async ({ result, snapshots }) => {\n const before = snapshots.before as InvoiceGraphSnapshot | undefined;\n const after = snapshots.after as InvoiceGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.invoices.update\", \"Update invoice\"),\n resourceKind: \"sales.invoice\",\n resourceId: result.invoiceId,\n tenantId: after.invoice.tenantId,\n organizationId: after.invoice.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies InvoiceUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<InvoiceUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const invoice = await em.findOne(SalesInvoice, { id: before.invoice.id });\n if (!invoice) return;\n ensureOrganizationScope(ctx, invoice.organizationId);\n ensureTenantScope(ctx, invoice.tenantId);\n invoice.invoiceNumber = before.invoice.invoiceNumber;\n invoice.orderId = before.invoice.orderId;\n invoice.statusEntryId = before.invoice.statusEntryId;\n invoice.status = before.invoice.status;\n invoice.issueDate = before.invoice.issueDate ? new Date(before.invoice.issueDate as string) : null;\n invoice.dueDate = before.invoice.dueDate ? new Date(before.invoice.dueDate as string) : null;\n invoice.currencyCode = before.invoice.currencyCode;\n invoice.subtotalNetAmount = before.invoice.subtotalNetAmount;\n invoice.subtotalGrossAmount = before.invoice.subtotalGrossAmount;\n invoice.discountTotalAmount = before.invoice.discountTotalAmount;\n invoice.taxTotalAmount = before.invoice.taxTotalAmount;\n invoice.grandTotalNetAmount = before.invoice.grandTotalNetAmount;\n invoice.grandTotalGrossAmount = before.invoice.grandTotalGrossAmount;\n invoice.paidTotalAmount = before.invoice.paidTotalAmount;\n invoice.outstandingAmount = before.invoice.outstandingAmount;\n invoice.metadata = before.invoice.metadata;\n invoice.updatedAt = new Date();\n await em.flush();\n },\n};\n\nconst deleteInvoiceCommand: CommandHandler<\n { id: string; organizationId: string; tenantId: string },\n { invoiceId: string }\n> = {\n id: \"sales.invoices.delete\",\n async prepare(input, ctx) {\n const id = requireId(input);\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadInvoiceSnapshot(em, id);\n if (snapshot) {\n ensureOrganizationScope(ctx, snapshot.invoice.organizationId);\n ensureTenantScope(ctx, snapshot.invoice.tenantId);\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const id = requireId(rawInput);\n ensureOrganizationScope(ctx, rawInput.organizationId);\n ensureTenantScope(ctx, rawInput.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const invoice = await em.findOneOrFail(SalesInvoice, {\n id,\n organizationId: rawInput.organizationId,\n tenantId: rawInput.tenantId,\n deletedAt: null,\n });\n invoice.deletedAt = new Date();\n invoice.updatedAt = new Date();\n await em.flush();\n\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"deleted\",\n entity: invoice,\n identifiers: {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n },\n events: invoiceCrudEvents,\n indexer: { entityType: E.sales.sales_invoice },\n });\n\n await invalidateCrudCache(\n ctx.container,\n \"sales.invoice\",\n {\n id: invoice.id,\n organizationId: invoice.organizationId,\n tenantId: invoice.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"deleted\",\n );\n\n return { invoiceId: invoice.id };\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as InvoiceGraphSnapshot | undefined;\n if (!before) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.invoices.delete\", \"Delete invoice\"),\n resourceKind: \"sales.invoice\",\n resourceId: before.invoice.id,\n tenantId: before.invoice.tenantId,\n organizationId: before.invoice.organizationId,\n snapshotBefore: before,\n payload: {\n undo: { before } satisfies InvoiceUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<InvoiceUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureOrganizationScope(ctx, before.invoice.organizationId);\n ensureTenantScope(ctx, before.invoice.tenantId);\n const restored = em.create(SalesInvoice, {\n id: before.invoice.id,\n organizationId: before.invoice.organizationId,\n tenantId: before.invoice.tenantId,\n invoiceNumber: before.invoice.invoiceNumber,\n orderId: before.invoice.orderId,\n statusEntryId: before.invoice.statusEntryId,\n status: before.invoice.status,\n issueDate: before.invoice.issueDate ? new Date(before.invoice.issueDate as string) : new Date(),\n dueDate: before.invoice.dueDate ? new Date(before.invoice.dueDate as string) : null,\n currencyCode: before.invoice.currencyCode,\n subtotalNetAmount: before.invoice.subtotalNetAmount,\n subtotalGrossAmount: before.invoice.subtotalGrossAmount,\n discountTotalAmount: before.invoice.discountTotalAmount,\n taxTotalAmount: before.invoice.taxTotalAmount,\n grandTotalNetAmount: before.invoice.grandTotalNetAmount,\n grandTotalGrossAmount: before.invoice.grandTotalGrossAmount,\n paidTotalAmount: before.invoice.paidTotalAmount,\n outstandingAmount: before.invoice.outstandingAmount,\n metadata: before.invoice.metadata,\n customFieldSetId: before.invoice.customFieldSetId,\n deletedAt: null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(restored);\n for (const line of before.lines) {\n em.persist(em.create(SalesInvoiceLine, {\n id: line.id,\n invoice: restored,\n orderLineId: line.orderLineId,\n organizationId: before.invoice.organizationId,\n tenantId: before.invoice.tenantId,\n lineNumber: line.lineNumber,\n kind: line.kind,\n name: line.name,\n sku: line.sku,\n description: line.description,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit,\n normalizedQuantity: line.normalizedQuantity,\n normalizedUnit: line.normalizedUnit,\n uomSnapshot: line.uomSnapshot,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n discountAmount: line.discountAmount,\n discountPercent: line.discountPercent,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n totalNetAmount: line.totalNetAmount,\n totalGrossAmount: line.totalGrossAmount,\n metadata: line.metadata,\n }));\n }\n await em.flush();\n },\n};\n\n// ---------------------------------------------------------------------------\n// Credit Memo CRUD commands\n// ---------------------------------------------------------------------------\n\nconst creditMemoCrudEvents: CrudEventsConfig<SalesCreditMemo> = {\n module: \"sales\",\n entity: \"credit_memo\",\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n};\n\nconst createCreditMemoCommand: CommandHandler<\n CreditMemoCreateInput,\n { creditMemoId: string }\n> = {\n id: \"sales.credit_memos.create\",\n async execute(rawInput, ctx) {\n const generator = ctx.container.resolve(\n \"salesDocumentNumberGenerator\",\n ) as SalesDocumentNumberGenerator;\n const initial = creditMemoCreateSchema.parse(rawInput ?? {});\n const creditMemoNumber =\n typeof initial.creditMemoNumber === \"string\" &&\n initial.creditMemoNumber.trim().length\n ? initial.creditMemoNumber.trim()\n : (\n await generator.generate({\n kind: \"credit_memo\",\n organizationId: initial.organizationId,\n tenantId: initial.tenantId,\n })\n ).number;\n const parsed = creditMemoCreateSchema.parse({ ...initial, creditMemoNumber });\n const ensuredCreditMemoNumber = parsed.creditMemoNumber ?? creditMemoNumber;\n if (!ensuredCreditMemoNumber) {\n throw new CrudHttpError(400, { error: \"Credit memo number is required.\" });\n }\n ensureOrganizationScope(ctx, parsed.organizationId);\n ensureTenantScope(ctx, parsed.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const status = await resolveDictionaryEntryValue(\n em,\n parsed.statusEntryId ?? null,\n { tenantId: parsed.tenantId },\n );\n\n // Validate orderId belongs to same org/tenant\n if (parsed.orderId) {\n const orderExists = await em.findOne(SalesOrder, {\n id: parsed.orderId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n deletedAt: null,\n });\n if (!orderExists) {\n throw new CrudHttpError(400, { error: \"Referenced order not found in current scope.\" });\n }\n }\n\n // Validate invoiceId belongs to same org/tenant\n if (parsed.invoiceId) {\n const invoiceExists = await em.findOne(SalesInvoice, {\n id: parsed.invoiceId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n deletedAt: null,\n });\n if (!invoiceExists) {\n throw new CrudHttpError(400, { error: \"Referenced invoice not found in current scope.\" });\n }\n }\n\n const creditMemoId = randomUUID();\n const creditMemo = em.create(SalesCreditMemo, {\n id: creditMemoId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n creditMemoNumber: ensuredCreditMemoNumber,\n orderId: parsed.orderId ?? null,\n invoiceId: parsed.invoiceId ?? null,\n statusEntryId: parsed.statusEntryId ?? null,\n status,\n reason: parsed.reason ?? null,\n issueDate: parsed.issueDate ?? new Date(),\n currencyCode: parsed.currencyCode,\n subtotalNetAmount: toNumericString(parsed.subtotalNetAmount ?? 0),\n subtotalGrossAmount: toNumericString(parsed.subtotalGrossAmount ?? 0),\n taxTotalAmount: toNumericString(parsed.taxTotalAmount ?? 0),\n grandTotalNetAmount: toNumericString(parsed.grandTotalNetAmount ?? 0),\n grandTotalGrossAmount: toNumericString(parsed.grandTotalGrossAmount ?? 0),\n metadata: parsed.metadata ?? null,\n customFieldSetId: parsed.customFieldSetId ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n\n // Header + lines + custom-field writes must commit atomically.\n // setRecordCustomFields flushes mid-build, so without a transaction a\n // partial write could persist the header without its lines/custom fields.\n await withAtomicFlush(\n em,\n [\n async () => {\n em.persist(creditMemo);\n\n if (parsed.lines?.length) {\n for (let i = 0; i < parsed.lines.length; i++) {\n const line = parsed.lines[i];\n em.persist(\n em.create(SalesCreditMemoLine, {\n id: randomUUID(),\n creditMemo,\n orderLineId: line.orderLineId ?? null,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n lineNumber: line.lineNumber ?? i + 1,\n name: line.name ?? null,\n sku: line.sku ?? null,\n description: line.description ?? null,\n quantity: toNumericString(line.quantity ?? 0),\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: toNumericString(line.normalizedQuantity ?? 0),\n normalizedUnit: line.normalizedUnit ?? null,\n uomSnapshot: line.uomSnapshot ?? null,\n currencyCode: line.currencyCode ?? parsed.currencyCode,\n unitPriceNet: toNumericString(line.unitPriceNet ?? 0),\n unitPriceGross: toNumericString(line.unitPriceGross ?? 0),\n taxRate: toNumericString(line.taxRate ?? 0),\n taxAmount: toNumericString(line.taxAmount ?? 0),\n totalNetAmount: toNumericString(line.totalNetAmount ?? 0),\n totalGrossAmount: toNumericString(line.totalGrossAmount ?? 0),\n metadata: line.metadata ?? null,\n }),\n );\n }\n }\n\n if (parsed.customFieldSetId) {\n await setRecordCustomFields(em, {\n entityId: E.sales.sales_credit_memo,\n recordId: creditMemoId,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n values: normalizeCustomFieldValues(\n ((parsed as Record<string, unknown>).customFields as Record<string, unknown>) ?? {},\n ),\n });\n }\n },\n ],\n { transaction: true },\n );\n\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"created\",\n entity: creditMemo,\n identifiers: {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n },\n events: creditMemoCrudEvents,\n indexer: { entityType: E.sales.sales_credit_memo },\n });\n\n await invalidateCrudCache(\n ctx.container,\n \"sales.credit_memo\",\n {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"created\",\n );\n\n return { creditMemoId: creditMemo.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadCreditMemoSnapshot(em, result.creditMemoId);\n },\n buildLog: async ({ result, snapshots }) => {\n const after = snapshots.after as CreditMemoGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.credit_memos.create\", \"Create credit memo\"),\n resourceKind: \"sales.credit_memo\",\n resourceId: result.creditMemoId,\n tenantId: after.creditMemo.tenantId,\n organizationId: after.creditMemo.organizationId,\n snapshotAfter: after,\n payload: {\n undo: { after } satisfies CreditMemoUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CreditMemoUndoPayload>(logEntry);\n const after = payload?.after;\n if (!after) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const creditMemo = await em.findOne(SalesCreditMemo, { id: after.creditMemo.id });\n if (!creditMemo) return;\n ensureOrganizationScope(ctx, creditMemo.organizationId);\n ensureTenantScope(ctx, creditMemo.tenantId);\n await em.nativeDelete(SalesCreditMemoLine, { creditMemo: creditMemo.id });\n em.remove(creditMemo);\n await em.flush();\n },\n};\n\nconst updateCreditMemoCommand: CommandHandler<\n z.infer<typeof creditMemoUpdateSchema>,\n { creditMemoId: string }\n> = {\n id: \"sales.credit_memos.update\",\n async prepare(input, ctx) {\n const id = requireId(input);\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadCreditMemoSnapshot(em, id);\n if (snapshot) {\n ensureOrganizationScope(ctx, snapshot.creditMemo.organizationId);\n ensureTenantScope(ctx, snapshot.creditMemo.tenantId);\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const parsed = creditMemoUpdateSchema.parse(rawInput ?? {});\n const id = requireId(parsed);\n ensureOrganizationScope(ctx, parsed.organizationId);\n ensureTenantScope(ctx, parsed.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const creditMemo = await em.findOneOrFail(SalesCreditMemo, {\n id,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n deletedAt: null,\n });\n\n const changes = buildChanges(creditMemo, parsed, [\n \"creditMemoNumber\",\n \"statusEntryId\",\n \"status\",\n \"reason\",\n \"issueDate\",\n \"currencyCode\",\n \"subtotalNetAmount\",\n \"subtotalGrossAmount\",\n \"taxTotalAmount\",\n \"grandTotalNetAmount\",\n \"grandTotalGrossAmount\",\n \"metadata\",\n ]);\n\n if (parsed.statusEntryId !== undefined) {\n creditMemo.status = await resolveDictionaryEntryValue(em, parsed.statusEntryId ?? null, { tenantId: creditMemo.tenantId });\n }\n\n Object.assign(creditMemo, changes);\n creditMemo.updatedAt = new Date();\n await em.flush();\n\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"updated\",\n entity: creditMemo,\n identifiers: {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n },\n events: creditMemoCrudEvents,\n indexer: { entityType: E.sales.sales_credit_memo },\n });\n\n await invalidateCrudCache(\n ctx.container,\n \"sales.credit_memo\",\n {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"updated\",\n );\n\n return { creditMemoId: creditMemo.id };\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n return loadCreditMemoSnapshot(em, result.creditMemoId);\n },\n buildLog: async ({ result, snapshots }) => {\n const before = snapshots.before as CreditMemoGraphSnapshot | undefined;\n const after = snapshots.after as CreditMemoGraphSnapshot | undefined;\n if (!after) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.credit_memos.update\", \"Update credit memo\"),\n resourceKind: \"sales.credit_memo\",\n resourceId: result.creditMemoId,\n tenantId: after.creditMemo.tenantId,\n organizationId: after.creditMemo.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n payload: {\n undo: { before, after } satisfies CreditMemoUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CreditMemoUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const creditMemo = await em.findOne(SalesCreditMemo, { id: before.creditMemo.id });\n if (!creditMemo) return;\n ensureOrganizationScope(ctx, creditMemo.organizationId);\n ensureTenantScope(ctx, creditMemo.tenantId);\n creditMemo.creditMemoNumber = before.creditMemo.creditMemoNumber;\n creditMemo.orderId = before.creditMemo.orderId;\n creditMemo.invoiceId = before.creditMemo.invoiceId;\n creditMemo.statusEntryId = before.creditMemo.statusEntryId;\n creditMemo.status = before.creditMemo.status;\n creditMemo.reason = before.creditMemo.reason;\n creditMemo.issueDate = before.creditMemo.issueDate ? new Date(before.creditMemo.issueDate as string) : null;\n creditMemo.currencyCode = before.creditMemo.currencyCode;\n creditMemo.subtotalNetAmount = before.creditMemo.subtotalNetAmount;\n creditMemo.subtotalGrossAmount = before.creditMemo.subtotalGrossAmount;\n creditMemo.taxTotalAmount = before.creditMemo.taxTotalAmount;\n creditMemo.grandTotalNetAmount = before.creditMemo.grandTotalNetAmount;\n creditMemo.grandTotalGrossAmount = before.creditMemo.grandTotalGrossAmount;\n creditMemo.metadata = before.creditMemo.metadata;\n creditMemo.updatedAt = new Date();\n await em.flush();\n },\n};\n\nconst deleteCreditMemoCommand: CommandHandler<\n { id: string; organizationId: string; tenantId: string },\n { creditMemoId: string }\n> = {\n id: \"sales.credit_memos.delete\",\n async prepare(input, ctx) {\n const id = requireId(input);\n const em = ctx.container.resolve(\"em\") as EntityManager;\n const snapshot = await loadCreditMemoSnapshot(em, id);\n if (snapshot) {\n ensureOrganizationScope(ctx, snapshot.creditMemo.organizationId);\n ensureTenantScope(ctx, snapshot.creditMemo.tenantId);\n }\n return snapshot ? { before: snapshot } : {};\n },\n async execute(rawInput, ctx) {\n const id = requireId(rawInput);\n ensureOrganizationScope(ctx, rawInput.organizationId);\n ensureTenantScope(ctx, rawInput.tenantId);\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n const creditMemo = await em.findOneOrFail(SalesCreditMemo, {\n id,\n organizationId: rawInput.organizationId,\n tenantId: rawInput.tenantId,\n deletedAt: null,\n });\n creditMemo.deletedAt = new Date();\n creditMemo.updatedAt = new Date();\n await em.flush();\n\n const dataEngine = ctx.container.resolve(\"dataEngine\") as DataEngine;\n await emitCrudSideEffects({\n dataEngine,\n action: \"deleted\",\n entity: creditMemo,\n identifiers: {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n },\n events: creditMemoCrudEvents,\n indexer: { entityType: E.sales.sales_credit_memo },\n });\n\n await invalidateCrudCache(\n ctx.container,\n \"sales.credit_memo\",\n {\n id: creditMemo.id,\n organizationId: creditMemo.organizationId,\n tenantId: creditMemo.tenantId,\n },\n ctx.auth?.tenantId ?? null,\n \"deleted\",\n );\n\n return { creditMemoId: creditMemo.id };\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as CreditMemoGraphSnapshot | undefined;\n if (!before) return null;\n const { translate } = await resolveTranslations();\n return {\n actionLabel: translate(\"sales.audit.credit_memos.delete\", \"Delete credit memo\"),\n resourceKind: \"sales.credit_memo\",\n resourceId: before.creditMemo.id,\n tenantId: before.creditMemo.tenantId,\n organizationId: before.creditMemo.organizationId,\n snapshotBefore: before,\n payload: {\n undo: { before } satisfies CreditMemoUndoPayload,\n },\n };\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CreditMemoUndoPayload>(logEntry);\n const before = payload?.before;\n if (!before) return;\n const em = (ctx.container.resolve(\"em\") as EntityManager).fork();\n ensureOrganizationScope(ctx, before.creditMemo.organizationId);\n ensureTenantScope(ctx, before.creditMemo.tenantId);\n const restored = em.create(SalesCreditMemo, {\n id: before.creditMemo.id,\n organizationId: before.creditMemo.organizationId,\n tenantId: before.creditMemo.tenantId,\n creditMemoNumber: before.creditMemo.creditMemoNumber,\n orderId: before.creditMemo.orderId,\n invoiceId: before.creditMemo.invoiceId,\n statusEntryId: before.creditMemo.statusEntryId,\n status: before.creditMemo.status,\n reason: before.creditMemo.reason,\n issueDate: before.creditMemo.issueDate ? new Date(before.creditMemo.issueDate as string) : new Date(),\n currencyCode: before.creditMemo.currencyCode,\n subtotalNetAmount: before.creditMemo.subtotalNetAmount,\n subtotalGrossAmount: before.creditMemo.subtotalGrossAmount,\n taxTotalAmount: before.creditMemo.taxTotalAmount,\n grandTotalNetAmount: before.creditMemo.grandTotalNetAmount,\n grandTotalGrossAmount: before.creditMemo.grandTotalGrossAmount,\n metadata: before.creditMemo.metadata,\n customFieldSetId: before.creditMemo.customFieldSetId,\n deletedAt: null,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n em.persist(restored);\n for (const line of before.lines) {\n em.persist(em.create(SalesCreditMemoLine, {\n id: line.id,\n creditMemo: restored,\n orderLineId: line.orderLineId,\n organizationId: before.creditMemo.organizationId,\n tenantId: before.creditMemo.tenantId,\n lineNumber: line.lineNumber,\n name: line.name,\n sku: line.sku,\n description: line.description,\n quantity: line.quantity,\n quantityUnit: line.quantityUnit,\n normalizedQuantity: line.normalizedQuantity,\n normalizedUnit: line.normalizedUnit,\n uomSnapshot: line.uomSnapshot,\n currencyCode: line.currencyCode,\n unitPriceNet: line.unitPriceNet,\n unitPriceGross: line.unitPriceGross,\n taxRate: line.taxRate,\n taxAmount: line.taxAmount,\n totalNetAmount: line.totalNetAmount,\n totalGrossAmount: line.totalGrossAmount,\n metadata: line.metadata,\n }));\n }\n await em.flush();\n },\n};\n\nregisterCommand(updateQuoteCommand);\nregisterCommand(createQuoteCommand);\nregisterCommand(deleteQuoteCommand);\nregisterCommand(convertQuoteToOrderCommand);\nregisterCommand(updateOrderCommand);\nregisterCommand(createOrderCommand);\nregisterCommand(deleteOrderCommand);\nregisterCommand(orderLineUpsertCommand);\nregisterCommand(orderLineDeleteCommand);\nregisterCommand(quoteLineUpsertCommand);\nregisterCommand(quoteLineDeleteCommand);\nregisterCommand(orderAdjustmentUpsertCommand);\nregisterCommand(orderAdjustmentDeleteCommand);\nregisterCommand(quoteAdjustmentUpsertCommand);\nregisterCommand(quoteAdjustmentDeleteCommand);\nregisterCommand(createInvoiceCommand);\nregisterCommand(updateInvoiceCommand);\nregisterCommand(deleteInvoiceCommand);\nregisterCommand(createCreditMemoCommand);\nregisterCommand(updateCreditMemoCommand);\nregisterCommand(deleteCreditMemoCommand);\n"],
5
+ "mappings": "AAEA,SAAS,kBAAkB;AAC3B,SAAS,SAAS;AAClB,SAAS,uBAAuB;AAEhC,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,gBAAgB;AAIzB,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,kCAAkC;AAC3C,SAAS,wCAAwC;AACjD,SAAS,6BAA6B;AACtC,SAAS,6BAA6B;AACtC,SAAS,kCAAkC;AAC3C,SAAS,SAAS;AAClB,SAAS,oBAAoB,6BAA6B;AAC1D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,YAAY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