@open-mercato/core 0.11.1-develop.8557.1.e615240a3e → 0.11.1-develop.8567.1.a167594505

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 (134) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/api_keys/di.js +6 -2
  3. package/dist/modules/api_keys/di.js.map +2 -2
  4. package/dist/modules/api_keys/services/oneTimeIssuerService.js +47 -0
  5. package/dist/modules/api_keys/services/oneTimeIssuerService.js.map +7 -0
  6. package/dist/modules/audit_logs/di.js +2 -1
  7. package/dist/modules/audit_logs/di.js.map +2 -2
  8. package/dist/modules/audit_logs/services/actionLogService.js +65 -1
  9. package/dist/modules/audit_logs/services/actionLogService.js.map +2 -2
  10. package/dist/modules/auth/cli.js +1 -0
  11. package/dist/modules/auth/cli.js.map +2 -2
  12. package/dist/modules/auth/commands/users.js +10 -2
  13. package/dist/modules/auth/commands/users.js.map +2 -2
  14. package/dist/modules/auth/lib/setup-app.js +19 -5
  15. package/dist/modules/auth/lib/setup-app.js.map +2 -2
  16. package/dist/modules/configs/cli.js +26 -29
  17. package/dist/modules/configs/cli.js.map +2 -2
  18. package/dist/modules/configs/di.js +3 -1
  19. package/dist/modules/configs/di.js.map +2 -2
  20. package/dist/modules/configs/lib/instance-config-initializer.js +44 -0
  21. package/dist/modules/configs/lib/instance-config-initializer.js.map +7 -0
  22. package/dist/modules/configs/lib/instance-defaults.js +204 -0
  23. package/dist/modules/configs/lib/instance-defaults.js.map +7 -0
  24. package/dist/modules/configs/lib/module-config-service.js +115 -1
  25. package/dist/modules/configs/lib/module-config-service.js.map +2 -2
  26. package/dist/modules/entities/api/definitions.batch.js +55 -25
  27. package/dist/modules/entities/api/definitions.batch.js.map +2 -2
  28. package/dist/modules/entities/api/definitions.js +35 -8
  29. package/dist/modules/entities/api/definitions.js.map +2 -2
  30. package/dist/modules/entities/backend/entities/user/[entityId]/page.js +14 -8
  31. package/dist/modules/entities/backend/entities/user/[entityId]/page.js.map +2 -2
  32. package/dist/modules/notifications/lib/deliveryConfig.js +19 -12
  33. package/dist/modules/notifications/lib/deliveryConfig.js.map +2 -2
  34. package/dist/modules/notifications/setup.js +10 -0
  35. package/dist/modules/notifications/setup.js.map +2 -2
  36. package/dist/modules/translations/components/TranslationManager.js +47 -10
  37. package/dist/modules/translations/components/TranslationManager.js.map +2 -2
  38. package/dist/modules/wms/components/backend/CompletePutawayTaskDialog.js +8 -1
  39. package/dist/modules/wms/components/backend/CompletePutawayTaskDialog.js.map +2 -2
  40. package/dist/modules/workflows/ai-tools/authoring-pack.js +1 -1
  41. package/dist/modules/workflows/ai-tools/authoring-pack.js.map +2 -2
  42. package/dist/modules/workflows/api/instances/[id]/advance/route.js +1 -0
  43. package/dist/modules/workflows/api/instances/[id]/advance/route.js.map +2 -2
  44. package/dist/modules/workflows/api/instances/route.js +1 -1
  45. package/dist/modules/workflows/api/instances/route.js.map +2 -2
  46. package/dist/modules/workflows/api/instances/validate-start/route.js +3 -1
  47. package/dist/modules/workflows/api/instances/validate-start/route.js.map +2 -2
  48. package/dist/modules/workflows/di.js +3 -1
  49. package/dist/modules/workflows/di.js.map +2 -2
  50. package/dist/modules/workflows/lib/activity-executor.js +35 -7
  51. package/dist/modules/workflows/lib/activity-executor.js.map +2 -2
  52. package/dist/modules/workflows/lib/condition-handler.js +1 -1
  53. package/dist/modules/workflows/lib/condition-handler.js.map +2 -2
  54. package/dist/modules/workflows/lib/error-handler.js +1 -1
  55. package/dist/modules/workflows/lib/error-handler.js.map +2 -2
  56. package/dist/modules/workflows/lib/event-trigger-service.js +1 -1
  57. package/dist/modules/workflows/lib/event-trigger-service.js.map +2 -2
  58. package/dist/modules/workflows/lib/example-definition-authoring.js +90 -0
  59. package/dist/modules/workflows/lib/example-definition-authoring.js.map +7 -0
  60. package/dist/modules/workflows/lib/named-rules.js +42 -0
  61. package/dist/modules/workflows/lib/named-rules.js.map +7 -0
  62. package/dist/modules/workflows/lib/owned-definition.js +2 -0
  63. package/dist/modules/workflows/lib/owned-definition.js.map +2 -2
  64. package/dist/modules/workflows/lib/parallel-handler.js +1 -1
  65. package/dist/modules/workflows/lib/parallel-handler.js.map +2 -2
  66. package/dist/modules/workflows/lib/signal-handler.js +1 -0
  67. package/dist/modules/workflows/lib/signal-handler.js.map +2 -2
  68. package/dist/modules/workflows/lib/start-validator.js +87 -85
  69. package/dist/modules/workflows/lib/start-validator.js.map +2 -2
  70. package/dist/modules/workflows/lib/step-handler.js +1 -1
  71. package/dist/modules/workflows/lib/step-handler.js.map +2 -2
  72. package/dist/modules/workflows/lib/task-handler.js +1 -0
  73. package/dist/modules/workflows/lib/task-handler.js.map +2 -2
  74. package/dist/modules/workflows/lib/timer-handler.js +1 -0
  75. package/dist/modules/workflows/lib/timer-handler.js.map +2 -2
  76. package/dist/modules/workflows/lib/transition-handler.js +48 -166
  77. package/dist/modules/workflows/lib/transition-handler.js.map +3 -3
  78. package/dist/modules/workflows/lib/workflow-executor.js +3 -2
  79. package/dist/modules/workflows/lib/workflow-executor.js.map +2 -2
  80. package/package.json +8 -8
  81. package/src/modules/api_keys/di.ts +7 -2
  82. package/src/modules/api_keys/services/oneTimeIssuerService.ts +61 -0
  83. package/src/modules/audit_logs/di.ts +1 -0
  84. package/src/modules/audit_logs/services/actionLogService.ts +132 -1
  85. package/src/modules/auth/cli.ts +1 -0
  86. package/src/modules/auth/commands/users.ts +10 -2
  87. package/src/modules/auth/i18n/de.json +2 -0
  88. package/src/modules/auth/i18n/en.json +2 -0
  89. package/src/modules/auth/i18n/es.json +2 -0
  90. package/src/modules/auth/i18n/ko.json +2 -0
  91. package/src/modules/auth/i18n/pl.json +2 -0
  92. package/src/modules/auth/lib/setup-app.ts +30 -7
  93. package/src/modules/configs/cli.ts +39 -37
  94. package/src/modules/configs/di.ts +2 -0
  95. package/src/modules/configs/lib/instance-config-initializer.ts +56 -0
  96. package/src/modules/configs/lib/instance-defaults.ts +262 -0
  97. package/src/modules/configs/lib/module-config-service.ts +156 -0
  98. package/src/modules/entities/api/definitions.batch.ts +65 -27
  99. package/src/modules/entities/api/definitions.ts +40 -11
  100. package/src/modules/entities/backend/entities/user/[entityId]/page.tsx +14 -7
  101. package/src/modules/notifications/lib/deliveryConfig.ts +20 -11
  102. package/src/modules/notifications/setup.ts +11 -0
  103. package/src/modules/translations/components/TranslationManager.tsx +49 -10
  104. package/src/modules/translations/i18n/de.json +1 -0
  105. package/src/modules/translations/i18n/en.json +1 -0
  106. package/src/modules/translations/i18n/es.json +1 -0
  107. package/src/modules/translations/i18n/ko.json +1 -0
  108. package/src/modules/translations/i18n/pl.json +1 -0
  109. package/src/modules/wms/components/backend/CompletePutawayTaskDialog.tsx +8 -1
  110. package/src/modules/wms/i18n/de.json +1 -0
  111. package/src/modules/wms/i18n/en.json +1 -0
  112. package/src/modules/wms/i18n/es.json +1 -0
  113. package/src/modules/wms/i18n/ko.json +1 -0
  114. package/src/modules/wms/i18n/pl.json +1 -0
  115. package/src/modules/workflows/ai-tools/authoring-pack.ts +3 -1
  116. package/src/modules/workflows/api/instances/[id]/advance/route.ts +1 -0
  117. package/src/modules/workflows/api/instances/route.ts +1 -1
  118. package/src/modules/workflows/api/instances/validate-start/route.ts +3 -1
  119. package/src/modules/workflows/di.ts +2 -0
  120. package/src/modules/workflows/lib/activity-executor.ts +48 -30
  121. package/src/modules/workflows/lib/condition-handler.ts +1 -1
  122. package/src/modules/workflows/lib/error-handler.ts +1 -1
  123. package/src/modules/workflows/lib/event-trigger-service.ts +1 -1
  124. package/src/modules/workflows/lib/example-definition-authoring.ts +114 -0
  125. package/src/modules/workflows/lib/named-rules.ts +54 -0
  126. package/src/modules/workflows/lib/owned-definition.ts +4 -1
  127. package/src/modules/workflows/lib/parallel-handler.ts +1 -1
  128. package/src/modules/workflows/lib/signal-handler.ts +1 -0
  129. package/src/modules/workflows/lib/start-validator.ts +96 -94
  130. package/src/modules/workflows/lib/step-handler.ts +1 -1
  131. package/src/modules/workflows/lib/task-handler.ts +1 -0
  132. package/src/modules/workflows/lib/timer-handler.ts +1 -0
  133. package/src/modules/workflows/lib/transition-handler.ts +74 -238
  134. package/src/modules/workflows/lib/workflow-executor.ts +7 -4
@@ -3,6 +3,8 @@ import { z } from 'zod'
3
3
  import type { CacheStrategy } from '@open-mercato/cache'
4
4
  import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
5
5
  import { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'
6
+ import { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'
7
+ import { enforceCommandOptimisticLock, readOptimisticLockExpected } from '@open-mercato/shared/lib/crud/optimistic-lock-command'
6
8
  import type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'
7
9
  import { CustomEntity, CustomFieldDef } from '@open-mercato/core/modules/entities/data/entities'
8
10
  import { upsertCustomFieldDefSchema, fieldsetCodeRegex } from '@open-mercato/core/modules/entities/data/validators'
@@ -663,27 +665,44 @@ export async function DELETE(req: Request) {
663
665
  })
664
666
  if (guard.blockedResponse) return guard.blockedResponse
665
667
 
668
+ const versionScope = { entityId, tenantId: scope.tenantId, organizationId: scope.organizationId }
669
+ const requestedAt = Date.now()
670
+ const expectedVersion = readOptimisticLockExpected(req)
671
+ const currentVersion = expectedVersion ? await resolveEntityDefinitionsVersion(em, versionScope) : null
672
+ try {
673
+ enforceCommandOptimisticLock({
674
+ resourceKind: FIELD_DEFINITION_RESOURCE_KIND,
675
+ resourceId: entityId,
676
+ current: currentVersion,
677
+ expected: expectedVersion,
678
+ })
679
+ } catch (error) {
680
+ if (isCrudHttpError(error) && error.status === 409) {
681
+ return NextResponse.json(error.body, { status: error.status })
682
+ }
683
+ throw error
684
+ }
685
+
686
+ const deletedAt = new Date(currentVersion ? Math.max(requestedAt, Date.parse(currentVersion) + 1) : requestedAt)
666
687
  if (!def) {
667
- def = createScopedDefinitionTombstone(em, inherited, scope)
688
+ def = createScopedDefinitionTombstone(em, inherited, scope, deletedAt)
668
689
  } else {
669
- markDefinitionTombstoned(def)
690
+ markDefinitionTombstoned(def, deletedAt)
670
691
  }
671
692
  em.persist(def)
672
693
  await em.flush()
694
+ const guardedVersion = currentVersion
695
+ ? new Date(Math.max(Date.parse(currentVersion), def.updatedAt.getTime())).toISOString()
696
+ : null
673
697
  await guard.runAfterSuccess()
674
698
  await invalidateDefinitionsCache(cache, {
675
699
  tenantId: scope.tenantId,
676
700
  organizationId: scope.organizationId,
677
701
  entityIds: [entityId],
678
702
  })
679
- // Changing field definitions may impact forms but not sidebar items; no nav cache touch
680
- // Return the post-delete aggregate version so the edit form keeps its optimistic-lock
681
- // token in sync after removing a field out-of-band (issue #3152).
682
- const version = await resolveEntityDefinitionsVersion(em, {
683
- entityId,
684
- tenantId: scope.tenantId,
685
- organizationId: scope.organizationId,
686
- })
703
+ // A guarded caller still holds the checked draft. Return only the version
704
+ // produced by this delete so another writer's version cannot bless that draft.
705
+ const version = guardedVersion ?? await resolveEntityDefinitionsVersion(em, versionScope)
687
706
  return NextResponse.json({ ok: true, version })
688
707
  }
689
708
 
@@ -840,7 +859,7 @@ export const openApi: OpenApiRouteDoc = {
840
859
  },
841
860
  DELETE: {
842
861
  summary: 'Soft delete custom field definition',
843
- description: 'Marks the specified definition inactive and tombstones it for the current scope.',
862
+ description: 'Marks the specified definition inactive and tombstones it for the current scope. An optional optimistic-lock header checks the aggregate definition version.',
844
863
  requestBody: {
845
864
  contentType: 'application/json',
846
865
  schema: deleteDefinitionRequestSchema,
@@ -866,6 +885,16 @@ export const openApi: OpenApiRouteDoc = {
866
885
  description: 'Definition not found',
867
886
  schema: z.object({ error: z.string() }),
868
887
  },
888
+ {
889
+ status: 409,
890
+ description: 'The field definitions changed after the client loaded them',
891
+ schema: z.object({
892
+ error: z.string(),
893
+ code: z.literal('optimistic_lock_conflict'),
894
+ currentUpdatedAt: z.string(),
895
+ expectedUpdatedAt: z.string(),
896
+ }),
897
+ },
869
898
  ],
870
899
  },
871
900
  },
@@ -285,12 +285,16 @@ export default function EditDefinitionsPage({ params }: { params?: { entityId?:
285
285
  if (!def) return
286
286
  if (def.key) {
287
287
  try {
288
- const call = await apiCall<DefinitionsBatchResponse>('/api/entities/definitions', {
289
- method: 'DELETE',
290
- headers: { 'content-type': 'application/json' },
291
- body: JSON.stringify({ entityId, key: def.key }),
292
- })
288
+ const call = await withScopedApiRequestHeaders(
289
+ buildOptimisticLockHeader(defsVersion),
290
+ () => apiCall<DefinitionsBatchResponse>('/api/entities/definitions', {
291
+ method: 'DELETE',
292
+ headers: { 'content-type': 'application/json' },
293
+ body: JSON.stringify({ entityId, key: def.key }),
294
+ }),
295
+ )
293
296
  if (!call.ok) {
297
+ if (surfaceRecordConflict({ status: call.status, body: call.result }, t)) return
294
298
  await raiseCrudError(call.response, t('entities.customFields.errors.deleteFailed', 'Failed to delete field.'))
295
299
  }
296
300
  // Keep the optimistic-lock token in sync after an out-of-band delete so a
@@ -303,7 +307,6 @@ export default function EditDefinitionsPage({ params }: { params?: { entityId?:
303
307
  }
304
308
  }
305
309
  setDefs((arr) => arr.filter((_, i) => i !== idx))
306
- setOrderDirty(true)
307
310
  if (def.key) {
308
311
  await invalidateCustomFieldDefs(queryClient, entityId)
309
312
  }
@@ -521,6 +524,7 @@ export default function EditDefinitionsPage({ params }: { params?: { entityId?:
521
524
  defs,
522
525
  fieldsets: buildFieldsetPayload(),
523
526
  singleFieldsetPerRecord,
527
+ preserveOrder: !orderDirty,
524
528
  })
525
529
  // Send the aggregate schema version so a concurrent edit is rejected with a 409
526
530
  // instead of silently overwriting the other tab (issue #3152). CrudForm's submit
@@ -537,10 +541,11 @@ export default function EditDefinitionsPage({ params }: { params?: { entityId?:
537
541
  await raiseCrudError(callDefs.response, t('entities.customFields.errors.saveFailed', 'Failed to save field definitions.'))
538
542
  }
539
543
  setDefsVersion(readVersionToken(callDefs.result?.version))
544
+ setOrderDirty(false)
540
545
  try { window.dispatchEvent(new Event('om:refresh-sidebar')) } catch {}
541
546
  await invalidateCustomFieldDefs(queryClient, entityId)
542
547
  flash(t('entities.customFields.flash.saved', 'Definitions saved'), 'success')
543
- }, [buildFieldsetPayload, defs, defsVersion, entityId, entitySource, queryClient, singleFieldsetPerRecord, t, validateAll])
548
+ }, [buildFieldsetPayload, defs, defsVersion, entityId, entitySource, orderDirty, queryClient, singleFieldsetPerRecord, t, validateAll])
544
549
 
545
550
  if (!entityId) {
546
551
  return (
@@ -636,9 +641,11 @@ export function buildDefinitionsBatchPayload(options: {
636
641
  defs: Array<Pick<Def, 'key' | 'kind' | 'configJson' | 'isActive'>>
637
642
  fieldsets: FieldsetDefinition[]
638
643
  singleFieldsetPerRecord: boolean
644
+ preserveOrder?: boolean
639
645
  }) {
640
646
  return {
641
647
  entityId: options.entityId,
648
+ ...(options.preserveOrder !== undefined && { preserveOrder: options.preserveOrder }),
642
649
  definitions: options.defs.filter((d) => !!d.key).map((d) => ({
643
650
  key: d.key,
644
651
  kind: d.kind,
@@ -76,7 +76,7 @@ const resolveEnvDefaults = () => {
76
76
  }
77
77
  }
78
78
 
79
- export const DEFAULT_NOTIFICATION_DELIVERY_CONFIG: NotificationDeliveryConfig = (() => {
79
+ export function resolveDefaultNotificationDeliveryConfig(): NotificationDeliveryConfig {
80
80
  const env = resolveEnvDefaults()
81
81
  return {
82
82
  appUrl: env.appUrl,
@@ -92,20 +92,29 @@ export const DEFAULT_NOTIFICATION_DELIVERY_CONFIG: NotificationDeliveryConfig =
92
92
  custom: {},
93
93
  },
94
94
  }
95
- })()
95
+ }
96
96
 
97
- export const STORED_DEFAULT_NOTIFICATION_DELIVERY_CONFIG: NotificationDeliveryConfig = {
98
- ...DEFAULT_NOTIFICATION_DELIVERY_CONFIG,
99
- strategies: {
100
- ...DEFAULT_NOTIFICATION_DELIVERY_CONFIG.strategies,
101
- email: {
102
- ...DEFAULT_NOTIFICATION_DELIVERY_CONFIG.strategies.email,
103
- from: undefined,
104
- replyTo: resolveStoredSenderAddress(DEFAULT_NOTIFICATION_DELIVERY_CONFIG.strategies.email.replyTo),
97
+ export function resolveStoredDefaultNotificationDeliveryConfig(): NotificationDeliveryConfig {
98
+ const defaults = resolveDefaultNotificationDeliveryConfig()
99
+ return {
100
+ ...defaults,
101
+ strategies: {
102
+ ...defaults.strategies,
103
+ email: {
104
+ ...defaults.strategies.email,
105
+ from: undefined,
106
+ replyTo: resolveStoredSenderAddress(defaults.strategies.email.replyTo),
107
+ },
105
108
  },
106
- },
109
+ }
107
110
  }
108
111
 
112
+ export const DEFAULT_NOTIFICATION_DELIVERY_CONFIG: NotificationDeliveryConfig =
113
+ resolveDefaultNotificationDeliveryConfig()
114
+
115
+ export const STORED_DEFAULT_NOTIFICATION_DELIVERY_CONFIG: NotificationDeliveryConfig =
116
+ resolveStoredDefaultNotificationDeliveryConfig()
117
+
109
118
  const parseDeliveryConfig = (input: unknown) => {
110
119
  const parsed = notificationDeliveryConfigSchema.safeParse(input)
111
120
  const onlyPanelPathInvalid = !parsed.success
@@ -1,10 +1,21 @@
1
1
  import type { ModuleSetupConfig } from '@open-mercato/shared/modules/setup'
2
2
  import { createLogger } from '@open-mercato/shared/lib/logger'
3
3
  import { TYPE_REGISTRY_SYNC_EVENT } from './events'
4
+ import {
5
+ NOTIFICATIONS_DELIVERY_CONFIG_KEY,
6
+ resolveStoredDefaultNotificationDeliveryConfig,
7
+ } from './lib/deliveryConfig'
4
8
 
5
9
  const logger = createLogger('notifications')
6
10
 
7
11
  export const setup: ModuleSetupConfig = {
12
+ instanceConfigDefaults: () => [
13
+ {
14
+ name: NOTIFICATIONS_DELIVERY_CONFIG_KEY,
15
+ value: resolveStoredDefaultNotificationDeliveryConfig(),
16
+ },
17
+ ],
18
+
8
19
  defaultRoleFeatures: {
9
20
  superadmin: ['notifications.*'],
10
21
  admin: ['notifications.*'],
@@ -18,6 +18,8 @@ import { raiseCrudError } from '@open-mercato/ui/backend/utils/serverErrors'
18
18
  import { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'
19
19
  import { useCustomFieldDefs } from '@open-mercato/ui/backend/utils/customFieldDefs'
20
20
  import { Save, Plus, X } from 'lucide-react'
21
+ import { parseSelectedOrganizationCookie, parseSelectedTenantCookie } from '@open-mercato/core/modules/directory/utils/scopeCookies'
22
+ import { readRequestOrganizationScope } from '@open-mercato/shared/lib/frontend/organizationEvents'
21
23
  import { useOrganizationScopeVersion } from '@open-mercato/shared/lib/frontend/useOrganizationScope'
22
24
  import { useT } from '@open-mercato/shared/lib/i18n/context'
23
25
  import { defaultLocale, locales as defaultLocales } from '@open-mercato/shared/lib/i18n/config'
@@ -58,6 +60,15 @@ type TranslationLocales = {
58
60
  servable: string[]
59
61
  }
60
62
 
63
+ function readTranslationRequestScopeKey(): string {
64
+ const cookies = typeof document === 'undefined' ? null : document.cookie
65
+ return JSON.stringify([
66
+ parseSelectedTenantCookie(cookies),
67
+ parseSelectedOrganizationCookie(cookies),
68
+ readRequestOrganizationScope() !== null,
69
+ ])
70
+ }
71
+
61
72
  function useTranslationLocales() {
62
73
  return useQuery<TranslationLocales>({
63
74
  queryKey: ['translation-locales'],
@@ -88,6 +99,15 @@ export function TranslationManager({
88
99
  const t = useT()
89
100
  const scopeVersion = useOrganizationScopeVersion()
90
101
  const isEmbedded = mode === 'embedded'
102
+ const [openedScopeKey] = React.useState(readTranslationRequestScopeKey)
103
+ const hasEditorScopeChanged = () => isEmbedded && readTranslationRequestScopeKey() !== openedScopeKey
104
+ const scopeChangedMessage = t(
105
+ 'translations.manager.errors.organizationChanged',
106
+ 'The organization selection changed. Close and reopen the translation editor to continue.',
107
+ )
108
+ const assertEditorScope = () => {
109
+ if (hasEditorScopeChanged()) throw new Error(scopeChangedMessage)
110
+ }
91
111
 
92
112
  const [selectedEntityType, setSelectedEntityType] = React.useState(propEntityType ?? '')
93
113
  const [selectedRecordId, setSelectedRecordId] = React.useState(propRecordId ?? '')
@@ -203,9 +223,10 @@ export function TranslationManager({
203
223
  isError: translationError,
204
224
  refetch: refetchTranslation,
205
225
  } = useQuery<TranslationsResponse | null>({
206
- queryKey: ['entity-translation', entityType, recordId, scopeVersion],
226
+ queryKey: ['entity-translation', entityType, recordId, scopeVersion, isEmbedded ? openedScopeKey : null],
207
227
  enabled: !!entityType && !!recordId,
208
228
  queryFn: async () => {
229
+ assertEditorScope()
209
230
  const res = await apiCall<TranslationsResponse>(
210
231
  `/api/translations/${encodeURIComponent(entityType)}/${encodeURIComponent(recordId)}`,
211
232
  )
@@ -268,6 +289,15 @@ export function TranslationManager({
268
289
  retryLastMutation: () => Promise<boolean>
269
290
  }>({ contextId: TRANSLATION_MUTATION_CONTEXT_ID })
270
291
 
292
+ const retryInEditorScope = async () => {
293
+ if (!hasEditorScopeChanged()) {
294
+ const succeeded = await retryLastMutation()
295
+ if (succeeded || !hasEditorScopeChanged()) return succeeded
296
+ }
297
+ flash(scopeChangedMessage, 'error')
298
+ return false
299
+ }
300
+
271
301
  const mutation = useMutation({
272
302
  mutationFn: async () => {
273
303
  if (!entityType || !recordId) {
@@ -289,18 +319,22 @@ export function TranslationManager({
289
319
  logger.warn('Save skipped: payload is empty — no locale contains any non-empty field')
290
320
  throw new Error(t('translations.manager.errors.nothingToSave', 'Nothing to save — enter a translation first'))
291
321
  }
322
+ assertEditorScope()
292
323
  return runMutation({
293
324
  operation: async () => {
294
325
  const res = await withScopedApiRequestHeaders(
295
326
  buildOptimisticLockHeader(translationRowUpdatedAt),
296
- () => apiCall(
297
- `/api/translations/${encodeURIComponent(entityType)}/${encodeURIComponent(recordId)}`,
298
- {
299
- method: 'PUT',
300
- headers: { 'content-type': 'application/json' },
301
- body: JSON.stringify(body),
302
- },
303
- ),
327
+ () => {
328
+ assertEditorScope()
329
+ return apiCall(
330
+ `/api/translations/${encodeURIComponent(entityType)}/${encodeURIComponent(recordId)}`,
331
+ {
332
+ method: 'PUT',
333
+ headers: { 'content-type': 'application/json' },
334
+ body: JSON.stringify(body),
335
+ },
336
+ )
337
+ },
304
338
  )
305
339
  if (!res.ok) {
306
340
  await raiseCrudError(res.response, t('translations.manager.errors.save', 'Failed to save translations'))
@@ -314,7 +348,7 @@ export function TranslationManager({
314
348
  resourceKind: 'translation',
315
349
  resourceId: recordId,
316
350
  data: translationData ?? null,
317
- retryLastMutation,
351
+ retryLastMutation: isEmbedded ? retryInEditorScope : retryLastMutation,
318
352
  },
319
353
  mutationPayload: body,
320
354
  })
@@ -326,6 +360,10 @@ export function TranslationManager({
326
360
  await refetchTranslation()
327
361
  },
328
362
  onError: (err: unknown) => {
363
+ if (hasEditorScopeChanged()) {
364
+ flash(scopeChangedMessage, 'error')
365
+ return
366
+ }
329
367
  if (surfaceRecordConflict(err, t)) return
330
368
  const message = err instanceof Error ? err.message : t('translations.manager.errors.save', 'Failed to save translations')
331
369
  flash(message, 'error')
@@ -410,6 +448,7 @@ export function TranslationManager({
410
448
  )
411
449
  }
412
450
  if (translationError) {
451
+ if (hasEditorScopeChanged()) return <ErrorMessage label={scopeChangedMessage} />
413
452
  return (
414
453
  <ErrorMessage
415
454
  label={t('translations.manager.errors.loadTranslation', 'Failed to load translations')}
@@ -19,6 +19,7 @@
19
19
  "translations.manager.errors.loadEntities": "Fehler beim Laden der Entitäten",
20
20
  "translations.manager.errors.loadTranslation": "Fehler beim Laden der Übersetzungen",
21
21
  "translations.manager.errors.nothingToSave": "Nichts zu speichern — gib zuerst eine Übersetzung ein",
22
+ "translations.manager.errors.organizationChanged": "Die Organisationsauswahl hat sich geändert. Schließe und öffne den Übersetzungseditor erneut, um fortzufahren.",
22
23
  "translations.manager.errors.save": "Fehler beim Speichern der Übersetzungen",
23
24
  "translations.manager.errors.selectRecord": "Wähle eine Entität und einen Datensatz vor dem Speichern",
24
25
  "translations.manager.fields.baseValue": "Basiswert",
@@ -19,6 +19,7 @@
19
19
  "translations.manager.errors.loadEntities": "Failed to load entities",
20
20
  "translations.manager.errors.loadTranslation": "Failed to load translations",
21
21
  "translations.manager.errors.nothingToSave": "Nothing to save — enter a translation first",
22
+ "translations.manager.errors.organizationChanged": "The organization selection changed. Close and reopen the translation editor to continue.",
22
23
  "translations.manager.errors.save": "Failed to save translations",
23
24
  "translations.manager.errors.selectRecord": "Select an entity and record before saving",
24
25
  "translations.manager.fields.baseValue": "Base value",
@@ -19,6 +19,7 @@
19
19
  "translations.manager.errors.loadEntities": "Error al cargar las entidades",
20
20
  "translations.manager.errors.loadTranslation": "Error al cargar las traducciones",
21
21
  "translations.manager.errors.nothingToSave": "Nada que guardar — introduce primero una traducción",
22
+ "translations.manager.errors.organizationChanged": "La organización seleccionada ha cambiado. Cierra y vuelve a abrir el editor de traducciones para continuar.",
22
23
  "translations.manager.errors.save": "Error al guardar las traducciones",
23
24
  "translations.manager.errors.selectRecord": "Selecciona una entidad y un registro antes de guardar",
24
25
  "translations.manager.fields.baseValue": "Valor base",
@@ -19,6 +19,7 @@
19
19
  "translations.manager.errors.loadEntities": "엔터티를 불러오지 못했습니다",
20
20
  "translations.manager.errors.loadTranslation": "번역을 불러오지 못했습니다",
21
21
  "translations.manager.errors.nothingToSave": "저장할 내용이 없습니다 — 먼저 번역을 입력하세요",
22
+ "translations.manager.errors.organizationChanged": "선택한 조직이 변경되었습니다. 계속하려면 번역 편집기를 닫았다가 다시 여세요.",
22
23
  "translations.manager.errors.save": "번역 저장에 실패했습니다",
23
24
  "translations.manager.errors.selectRecord": "저장하기 전에 엔터티와 레코드를 선택하세요",
24
25
  "translations.manager.fields.baseValue": "기본 값",
@@ -19,6 +19,7 @@
19
19
  "translations.manager.errors.loadEntities": "Nie udało się załadować encji",
20
20
  "translations.manager.errors.loadTranslation": "Nie udało się załadować tłumaczeń",
21
21
  "translations.manager.errors.nothingToSave": "Nic do zapisania — najpierw wprowadź tłumaczenie",
22
+ "translations.manager.errors.organizationChanged": "Wybrana organizacja uległa zmianie. Zamknij i ponownie otwórz edytor tłumaczeń, aby kontynuować.",
22
23
  "translations.manager.errors.save": "Nie udało się zapisać tłumaczeń",
23
24
  "translations.manager.errors.selectRecord": "Wybierz encję i rekord przed zapisaniem",
24
25
  "translations.manager.fields.baseValue": "Wartość bazowa",
@@ -145,13 +145,19 @@ export function CompletePutawayTaskDialog({
145
145
  if (!nextErrors[key]) nextErrors[key] = t(issue.message, issue.message)
146
146
  }
147
147
  }
148
+ if (confirmedQuantity > task.quantity + 0.000001) {
149
+ nextErrors.confirmedQuantity = t(
150
+ 'wms.backend.putaway.complete.errors.quantityExceedsTask',
151
+ 'Confirmed quantity cannot exceed the task quantity.',
152
+ )
153
+ }
148
154
  if (expectedSerial && serialConfirmation.trim() !== expectedSerial) {
149
155
  nextErrors.serialConfirmation = t(
150
156
  'wms.backend.putaway.complete.errors.serialMismatch',
151
157
  'The scanned serial does not match this task.',
152
158
  )
153
159
  }
154
- if (!parsed.success || nextErrors.serialConfirmation) {
160
+ if (!parsed.success || Object.keys(nextErrors).length > 0) {
155
161
  setFieldErrors(nextErrors)
156
162
  return
157
163
  }
@@ -314,6 +320,7 @@ export function CompletePutawayTaskDialog({
314
320
  type="number"
315
321
  min={0.0001}
316
322
  step="any"
323
+ readOnly={Boolean(expectedSerial) && task?.quantity === 1}
317
324
  value={confirmedQuantity}
318
325
  onChange={(event) => setConfirmedQuantity(Number(event.target.value))}
319
326
  disabled={submitting}
@@ -1044,6 +1044,7 @@
1044
1044
  "wms.backend.putaway.complete.dialog.shortcutHint": "zum Abschließen",
1045
1045
  "wms.backend.putaway.complete.dialog.submit": "Einlagerung abschließen",
1046
1046
  "wms.backend.putaway.complete.dialog.title": "Einlagerung abschließen",
1047
+ "wms.backend.putaway.complete.errors.quantityExceedsTask": "Die bestätigte Menge darf die Aufgabenmenge nicht überschreiten.",
1047
1048
  "wms.backend.putaway.complete.errors.quantityPositive": "Die bestätigte Menge muss größer als 0 sein.",
1048
1049
  "wms.backend.putaway.complete.errors.serialMismatch": "Die gescannte Seriennummer stimmt nicht mit dieser Aufgabe überein.",
1049
1050
  "wms.backend.putaway.complete.errors.submit": "Einlagerungsaufgabe konnte nicht abgeschlossen werden.",
@@ -1044,6 +1044,7 @@
1044
1044
  "wms.backend.putaway.complete.dialog.shortcutHint": "to complete",
1045
1045
  "wms.backend.putaway.complete.dialog.submit": "Complete putaway",
1046
1046
  "wms.backend.putaway.complete.dialog.title": "Complete putaway",
1047
+ "wms.backend.putaway.complete.errors.quantityExceedsTask": "Confirmed quantity cannot exceed the task quantity.",
1047
1048
  "wms.backend.putaway.complete.errors.quantityPositive": "Confirmed quantity must be greater than 0.",
1048
1049
  "wms.backend.putaway.complete.errors.serialMismatch": "The scanned serial does not match this task.",
1049
1050
  "wms.backend.putaway.complete.errors.submit": "Failed to complete putaway task.",
@@ -1044,6 +1044,7 @@
1044
1044
  "wms.backend.putaway.complete.dialog.shortcutHint": "para completar",
1045
1045
  "wms.backend.putaway.complete.dialog.submit": "Completar ubicación",
1046
1046
  "wms.backend.putaway.complete.dialog.title": "Completar ubicación",
1047
+ "wms.backend.putaway.complete.errors.quantityExceedsTask": "La cantidad confirmada no puede superar la cantidad de la tarea.",
1047
1048
  "wms.backend.putaway.complete.errors.quantityPositive": "La cantidad confirmada debe ser mayor que 0.",
1048
1049
  "wms.backend.putaway.complete.errors.serialMismatch": "El número de serie escaneado no coincide con esta tarea.",
1049
1050
  "wms.backend.putaway.complete.errors.submit": "No se pudo completar la tarea de ubicación.",
@@ -1044,6 +1044,7 @@
1044
1044
  "wms.backend.putaway.complete.dialog.shortcutHint": "완료",
1045
1045
  "wms.backend.putaway.complete.dialog.submit": "적치 완료",
1046
1046
  "wms.backend.putaway.complete.dialog.title": "적치 완료",
1047
+ "wms.backend.putaway.complete.errors.quantityExceedsTask": "확인 수량은 작업 수량을 초과할 수 없습니다.",
1047
1048
  "wms.backend.putaway.complete.errors.quantityPositive": "확인 수량은 0보다 커야 합니다.",
1048
1049
  "wms.backend.putaway.complete.errors.serialMismatch": "스캔한 시리얼이 이 작업과 일치하지 않습니다.",
1049
1050
  "wms.backend.putaway.complete.errors.submit": "적치 작업을 완료하지 못했습니다.",
@@ -1044,6 +1044,7 @@
1044
1044
  "wms.backend.putaway.complete.dialog.shortcutHint": "aby zakończyć",
1045
1045
  "wms.backend.putaway.complete.dialog.submit": "Zakończ rozlokowanie",
1046
1046
  "wms.backend.putaway.complete.dialog.title": "Zakończ rozlokowanie",
1047
+ "wms.backend.putaway.complete.errors.quantityExceedsTask": "Potwierdzona ilość nie może przekraczać ilości w zadaniu.",
1047
1048
  "wms.backend.putaway.complete.errors.quantityPositive": "Potwierdzona ilość musi być większa od 0.",
1048
1049
  "wms.backend.putaway.complete.errors.serialMismatch": "Zeskanowany numer seryjny nie pasuje do tego zadania.",
1049
1050
  "wms.backend.putaway.complete.errors.submit": "Nie udało się zakończyć zadania rozlokowania.",
@@ -41,6 +41,7 @@ import {
41
41
  } from '../data/validators'
42
42
  import { workflowDraftGenerationSchema } from '../lib/ai-authoring'
43
43
  import { isComponentKind } from '../lib/component-guard'
44
+ import type { WorkflowRuleContainer } from '../lib/named-rules'
44
45
  import {
45
46
  computeDefinitionContextLedger,
46
47
  narrowLedgerToStep,
@@ -624,6 +625,7 @@ const startTestRunTool: WorkflowsAiToolDefinition<z.infer<typeof startTestRunInp
624
625
  startWorkflow: (
625
626
  em: EntityManager,
626
627
  options: Record<string, unknown>,
628
+ container?: WorkflowRuleContainer,
627
629
  ) => Promise<WorkflowInstance>
628
630
  executeWorkflow: (
629
631
  em: EntityManager,
@@ -644,7 +646,7 @@ const startTestRunTool: WorkflowsAiToolDefinition<z.infer<typeof startTestRunInp
644
646
  isDryRun: true,
645
647
  tenantId: scope.tenantId,
646
648
  organizationId: scope.organizationId,
647
- })
649
+ }, ctx.container)
648
650
 
649
651
  let executionError: string | null = null
650
652
  try {
@@ -156,6 +156,7 @@ export async function POST(request: NextRequest, context: RouteContext) {
156
156
 
157
157
  // Build evaluation context
158
158
  const evalContext: transitionHandler.TransitionEvaluationContext = {
159
+ container,
159
160
  workflowContext: instance.context,
160
161
  userId: auth.sub,
161
162
  triggerData: input.triggerData,
@@ -338,7 +338,7 @@ export async function POST(request: NextRequest) {
338
338
  isDryRun: input.dryRun === true,
339
339
  tenantId,
340
340
  organizationId,
341
- })
341
+ }, container)
342
342
 
343
343
  // Advance the workflow asynchronously after responding (non-blocking, so the
344
344
  // frontend can poll step-by-step progress). This is a fire-and-forget task in
@@ -24,6 +24,7 @@ import {
24
24
  } from '../../openapi'
25
25
  import { createLogger } from '@open-mercato/shared/lib/logger'
26
26
  import { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'
27
+ import { reportError } from '@open-mercato/telemetry'
27
28
 
28
29
  const logger = createLogger('workflows')
29
30
 
@@ -87,7 +88,7 @@ export async function POST(request: NextRequest) {
87
88
  locale,
88
89
  tenantId,
89
90
  organizationId,
90
- })
91
+ }, { container })
91
92
 
92
93
  // Always return 200 with the validation result
93
94
  // The client can check canStart to determine if workflow can proceed
@@ -100,6 +101,7 @@ export async function POST(request: NextRequest) {
100
101
  } catch (error) {
101
102
  if (isCrudHttpError(error)) return NextResponse.json(error.body, { status: error.status })
102
103
  logger.error('Error validating workflow start', { err: error })
104
+ reportError(error, { module: 'workflows', code: 'workflows.start_validation_failed' })
103
105
  return NextResponse.json(
104
106
  { error: 'Failed to validate workflow start' },
105
107
  { status: 500 }
@@ -21,6 +21,7 @@ import * as conditionHandler from './lib/condition-handler'
21
21
  import * as taskHandler from './lib/task-handler'
22
22
  import * as workInboxService from './lib/work-inbox/service'
23
23
  import { createWorkflowDefinitionAuthoring } from './lib/owned-definition'
24
+ import { createWorkflowExampleAuthoring } from './lib/example-definition-authoring'
24
25
  import { registerWorkInboxSources } from './lib/work-inbox/provider'
25
26
  import { userTaskWorkInboxSource, WORKFLOWS_MODULE_ID } from './lib/work-inbox/user-task-source'
26
27
 
@@ -66,6 +67,7 @@ export function register(container: AwilixContainer): void {
66
67
  // Lets another module own a real workflow definition instead of building a
67
68
  // second executor for its simple case — see lib/owned-definition.ts.
68
69
  workflowDefinitionAuthoring: asScopedService((scope) => createWorkflowDefinitionAuthoring(scope)),
70
+ workflowExampleAuthoring: asScopedService((scope) => createWorkflowExampleAuthoring(scope)),
69
71
  })
70
72
  }
71
73