@open-mercato/core 0.6.6-develop.6229.1.ebe6706732 → 0.6.6-develop.6241.1.47c01ad4ed

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 (125) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/auth/commands/users.js +1 -0
  3. package/dist/modules/auth/commands/users.js.map +2 -2
  4. package/dist/modules/communication_channels/data/enrichers.js +9 -1
  5. package/dist/modules/communication_channels/data/enrichers.js.map +2 -2
  6. package/dist/modules/communication_channels/widgets/injection/channel-payload-renderer/widget.client.js +3 -5
  7. package/dist/modules/communication_channels/widgets/injection/channel-payload-renderer/widget.client.js.map +2 -2
  8. package/dist/modules/communication_channels/widgets/injection/channel-payload-renderer/widget.js.map +2 -2
  9. package/dist/modules/customers/api/pipeline-stages/reorder/route.js +39 -1
  10. package/dist/modules/customers/api/pipeline-stages/reorder/route.js.map +2 -2
  11. package/dist/modules/customers/api/pipeline-stages/route.js +107 -12
  12. package/dist/modules/customers/api/pipeline-stages/route.js.map +2 -2
  13. package/dist/modules/customers/api/pipelines/route.js +107 -12
  14. package/dist/modules/customers/api/pipelines/route.js.map +2 -2
  15. package/dist/modules/customers/api/settings/address-format/route.js +33 -1
  16. package/dist/modules/customers/api/settings/address-format/route.js.map +2 -2
  17. package/dist/modules/customers/api/tags/assign/route.js +37 -0
  18. package/dist/modules/customers/api/tags/assign/route.js.map +2 -2
  19. package/dist/modules/customers/api/tags/unassign/route.js +37 -0
  20. package/dist/modules/customers/api/tags/unassign/route.js.map +2 -2
  21. package/dist/modules/entities/api/encryption.js +109 -38
  22. package/dist/modules/entities/api/encryption.js.map +2 -2
  23. package/dist/modules/entities/components/EncryptionManager.js +22 -9
  24. package/dist/modules/entities/components/EncryptionManager.js.map +2 -2
  25. package/dist/modules/integrations/api/[id]/credentials/route.js +23 -1
  26. package/dist/modules/integrations/api/[id]/credentials/route.js.map +2 -2
  27. package/dist/modules/integrations/api/[id]/route.js +10 -3
  28. package/dist/modules/integrations/api/[id]/route.js.map +2 -2
  29. package/dist/modules/integrations/api/[id]/state/route.js +20 -5
  30. package/dist/modules/integrations/api/[id]/state/route.js.map +2 -2
  31. package/dist/modules/integrations/api/[id]/version/route.js +17 -1
  32. package/dist/modules/integrations/api/[id]/version/route.js.map +2 -2
  33. package/dist/modules/integrations/api/route.js +2 -0
  34. package/dist/modules/integrations/api/route.js.map +2 -2
  35. package/dist/modules/integrations/backend/integrations/[id]/page.js +36 -19
  36. package/dist/modules/integrations/backend/integrations/[id]/page.js.map +2 -2
  37. package/dist/modules/integrations/backend/integrations/bundle/[id]/page.js +13 -9
  38. package/dist/modules/integrations/backend/integrations/bundle/[id]/page.js.map +2 -2
  39. package/dist/modules/integrations/backend/integrations/page.js +4 -3
  40. package/dist/modules/integrations/backend/integrations/page.js.map +2 -2
  41. package/dist/modules/integrations/data/entities.js +2 -2
  42. package/dist/modules/integrations/data/entities.js.map +2 -2
  43. package/dist/modules/integrations/lib/credentials-service.js +32 -0
  44. package/dist/modules/integrations/lib/credentials-service.js.map +2 -2
  45. package/dist/modules/integrations/lib/state-service.js +4 -2
  46. package/dist/modules/integrations/lib/state-service.js.map +2 -2
  47. package/dist/modules/notifications/lib/notificationService.js +42 -10
  48. package/dist/modules/notifications/lib/notificationService.js.map +2 -2
  49. package/dist/modules/payment_gateways/api/status/route.js +91 -6
  50. package/dist/modules/payment_gateways/api/status/route.js.map +2 -2
  51. package/dist/modules/payment_gateways/backend/payment-gateways/page.js +25 -11
  52. package/dist/modules/payment_gateways/backend/payment-gateways/page.js.map +2 -2
  53. package/dist/modules/sales/backend/sales/channels/offers/page.js +25 -7
  54. package/dist/modules/sales/backend/sales/channels/offers/page.js.map +2 -2
  55. package/dist/modules/sales/backend/sales/channels/page.js +25 -7
  56. package/dist/modules/sales/backend/sales/channels/page.js.map +2 -2
  57. package/dist/modules/sales/components/AdjustmentKindSettings.js +52 -24
  58. package/dist/modules/sales/components/AdjustmentKindSettings.js.map +2 -2
  59. package/dist/modules/sales/components/DocumentNumberSettings.js +26 -9
  60. package/dist/modules/sales/components/DocumentNumberSettings.js.map +2 -2
  61. package/dist/modules/sales/components/OrderEditingSettings.js +26 -9
  62. package/dist/modules/sales/components/OrderEditingSettings.js.map +2 -2
  63. package/dist/modules/sales/components/StatusSettings.js +66 -31
  64. package/dist/modules/sales/components/StatusSettings.js.map +2 -2
  65. package/dist/modules/sales/components/channels/SalesChannelOffersPanel.js +25 -7
  66. package/dist/modules/sales/components/channels/SalesChannelOffersPanel.js.map +2 -2
  67. package/dist/modules/shipping_carriers/api/cancel/route.js +38 -0
  68. package/dist/modules/shipping_carriers/api/cancel/route.js.map +2 -2
  69. package/dist/modules/shipping_carriers/api/shipments/route.js +12 -5
  70. package/dist/modules/shipping_carriers/api/shipments/route.js.map +2 -2
  71. package/dist/modules/staff/lib/timesheets-ui/TimerBar.js +7 -8
  72. package/dist/modules/staff/lib/timesheets-ui/TimerBar.js.map +2 -2
  73. package/dist/modules/staff/lib/timesheets-ui/timerErrors.js +12 -0
  74. package/dist/modules/staff/lib/timesheets-ui/timerErrors.js.map +7 -0
  75. package/dist/modules/staff/widgets/dashboard/timesheets-time-reporting/widget.client.js +4 -3
  76. package/dist/modules/staff/widgets/dashboard/timesheets-time-reporting/widget.client.js.map +2 -2
  77. package/dist/modules/workflows/backend/definitions/page.js +19 -10
  78. package/dist/modules/workflows/backend/definitions/page.js.map +2 -2
  79. package/package.json +7 -7
  80. package/src/modules/auth/commands/users.ts +1 -0
  81. package/src/modules/communication_channels/data/enrichers.ts +25 -0
  82. package/src/modules/communication_channels/widgets/injection/channel-payload-renderer/widget.client.tsx +7 -6
  83. package/src/modules/communication_channels/widgets/injection/channel-payload-renderer/widget.ts +5 -2
  84. package/src/modules/customers/api/pipeline-stages/reorder/route.ts +41 -1
  85. package/src/modules/customers/api/pipeline-stages/route.ts +112 -13
  86. package/src/modules/customers/api/pipelines/route.ts +112 -13
  87. package/src/modules/customers/api/settings/address-format/route.ts +36 -1
  88. package/src/modules/customers/api/tags/assign/route.ts +39 -0
  89. package/src/modules/customers/api/tags/unassign/route.ts +39 -0
  90. package/src/modules/customers/i18n/de.json +1 -0
  91. package/src/modules/customers/i18n/en.json +1 -0
  92. package/src/modules/customers/i18n/es.json +1 -0
  93. package/src/modules/customers/i18n/pl.json +1 -0
  94. package/src/modules/entities/api/encryption.ts +122 -39
  95. package/src/modules/entities/components/EncryptionManager.tsx +28 -9
  96. package/src/modules/integrations/api/[id]/credentials/route.ts +23 -0
  97. package/src/modules/integrations/api/[id]/route.ts +8 -1
  98. package/src/modules/integrations/api/[id]/state/route.ts +20 -4
  99. package/src/modules/integrations/api/[id]/version/route.ts +18 -1
  100. package/src/modules/integrations/api/route.ts +3 -0
  101. package/src/modules/integrations/backend/integrations/[id]/page.tsx +39 -20
  102. package/src/modules/integrations/backend/integrations/bundle/[id]/page.tsx +19 -11
  103. package/src/modules/integrations/backend/integrations/page.tsx +8 -5
  104. package/src/modules/integrations/data/entities.ts +2 -2
  105. package/src/modules/integrations/lib/credentials-service.ts +35 -0
  106. package/src/modules/integrations/lib/state-service.ts +3 -0
  107. package/src/modules/notifications/lib/notificationService.ts +74 -11
  108. package/src/modules/payment_gateways/api/status/route.ts +97 -5
  109. package/src/modules/payment_gateways/backend/payment-gateways/page.tsx +27 -11
  110. package/src/modules/sales/backend/sales/channels/offers/page.tsx +31 -7
  111. package/src/modules/sales/backend/sales/channels/page.tsx +31 -7
  112. package/src/modules/sales/components/AdjustmentKindSettings.tsx +60 -24
  113. package/src/modules/sales/components/DocumentNumberSettings.tsx +32 -10
  114. package/src/modules/sales/components/OrderEditingSettings.tsx +32 -10
  115. package/src/modules/sales/components/StatusSettings.tsx +74 -33
  116. package/src/modules/sales/components/channels/SalesChannelOffersPanel.tsx +30 -6
  117. package/src/modules/shipping_carriers/api/cancel/route.ts +46 -0
  118. package/src/modules/shipping_carriers/api/shipments/route.ts +21 -6
  119. package/src/modules/staff/i18n/de.json +5 -5
  120. package/src/modules/staff/i18n/es.json +5 -5
  121. package/src/modules/staff/i18n/pl.json +5 -5
  122. package/src/modules/staff/lib/timesheets-ui/TimerBar.tsx +7 -8
  123. package/src/modules/staff/lib/timesheets-ui/timerErrors.ts +23 -0
  124. package/src/modules/staff/widgets/dashboard/timesheets-time-reporting/widget.client.tsx +4 -3
  125. package/src/modules/workflows/backend/definitions/page.tsx +19 -10
@@ -13,8 +13,10 @@ import {
13
13
  } from "@open-mercato/ui/primitives/select";
14
14
  import { LoadingMessage, ErrorMessage } from "@open-mercato/ui/backend/detail";
15
15
  import { flash } from "@open-mercato/ui/backend/FlashMessages";
16
- import { apiCall, readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
16
+ import { apiCall, readApiResultOrThrow, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
17
17
  import { raiseCrudError } from "@open-mercato/ui/backend/utils/serverErrors";
18
+ import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
19
+ import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
18
20
  import { useCustomFieldDefs } from "@open-mercato/ui/backend/utils/customFieldDefs";
19
21
  import { Plus, Save, Trash2 } from "lucide-react";
20
22
  import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
@@ -181,6 +183,7 @@ function EncryptionManager() {
181
183
  setHasUserEdited(false);
182
184
  lastMapSignatureRef.current = signature;
183
185
  }, [mapSignature, map, canonicalOptions, hasUserEdited]);
186
+ const { runMutation } = useGuardedMutation({ contextId: "entities.encryption-map" });
184
187
  const mutation = useMutation({
185
188
  mutationFn: async () => {
186
189
  const trimmed = fields.map((row) => ({
@@ -196,15 +199,25 @@ function EncryptionManager() {
196
199
  if (!trimmed.length) {
197
200
  throw new Error(t("entities.encryption.errors.noFields", "Add at least one field to encrypt"));
198
201
  }
199
- const res = await apiCall("/api/entities/encryption", {
200
- method: "POST",
201
- headers: { "content-type": "application/json" },
202
- body: JSON.stringify({ entityId: selectedEntityId, fields: trimmed, isActive })
202
+ const payload = { entityId: selectedEntityId, fields: trimmed, isActive };
203
+ return runMutation({
204
+ operation: async () => {
205
+ const res = await withScopedApiRequestHeaders(
206
+ buildOptimisticLockHeader(map?.updatedAt ?? null),
207
+ () => apiCall("/api/entities/encryption", {
208
+ method: "POST",
209
+ headers: { "content-type": "application/json" },
210
+ body: JSON.stringify(payload)
211
+ })
212
+ );
213
+ if (!res.ok) {
214
+ await raiseCrudError(res.response, t("entities.encryption.errors.save", "Failed to save encryption map"));
215
+ }
216
+ return true;
217
+ },
218
+ context: {},
219
+ mutationPayload: payload
203
220
  });
204
- if (!res.ok) {
205
- await raiseCrudError(res.response, t("entities.encryption.errors.save", "Failed to save encryption map"));
206
- }
207
- return true;
208
221
  },
209
222
  onSuccess: () => {
210
223
  flash(t("entities.encryption.flash.saved", "Encryption map saved"), "success");
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/entities/components/EncryptionManager.tsx"],
4
- "sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { useQuery, useMutation } from '@tanstack/react-query'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { Checkbox } from '@open-mercato/ui/primitives/checkbox'\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from '@open-mercato/ui/primitives/select'\nimport { LoadingMessage, ErrorMessage } from '@open-mercato/ui/backend/detail'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { apiCall, readApiResultOrThrow } from '@open-mercato/ui/backend/utils/apiCall'\nimport { raiseCrudError } from '@open-mercato/ui/backend/utils/serverErrors'\nimport { useCustomFieldDefs, type CustomFieldDefDto } from '@open-mercato/ui/backend/utils/customFieldDefs'\nimport { Plus, Save, Trash2 } from 'lucide-react'\nimport { useOrganizationScopeVersion } from '@open-mercato/shared/lib/frontend/useOrganizationScope'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { getEntityFields } from '#generated/entity-fields-registry'\n\ntype EntityOption = { entityId: string; label?: string; source?: string }\ntype FieldOption = { value: string; label: string }\n\ntype EncryptionFieldRow = {\n id: string\n field: string\n hashField?: string | null\n}\n\ntype EncryptionMapResponse = {\n entityId: string\n fields?: Array<{ field: string; hashField?: string | null }>\n isActive?: boolean\n}\n\ntype CanonicalOption = { value: string; label?: string }\n\nconst EMPTY_FIELD_DEFS: CustomFieldDefDto[] = []\n\nfunction normalizeToken(value: string): string {\n return value\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[^a-z0-9]/gi, '')\n .toLowerCase()\n}\n\nfunction canonicalizeFieldName(raw: string, options: CanonicalOption[]): string {\n const trimmed = typeof raw === 'string' ? raw.trim() : ''\n if (!trimmed) return ''\n const normalized = normalizeToken(trimmed)\n for (const option of options) {\n const optionValue = typeof option.value === 'string' ? option.value.trim() : ''\n if (optionValue && normalizeToken(optionValue) === normalized) return optionValue\n if (option.label && normalizeToken(option.label) === normalized) return optionValue\n }\n return trimmed\n}\n\nfunction normalizeFieldRows(raw: EncryptionMapResponse | undefined, options: CanonicalOption[]): EncryptionFieldRow[] {\n const rows = Array.isArray(raw?.fields) ? raw!.fields : []\n return rows.map((entry, idx) => ({\n id: `${entry.field}-${idx}`,\n field: canonicalizeFieldName(entry.field, options),\n hashField: entry.hashField ? canonicalizeFieldName(entry.hashField, options) : null,\n }))\n}\n\nfunction areFieldRowsEqual(a: EncryptionFieldRow[], b: EncryptionFieldRow[]): boolean {\n if (a === b) return true\n if (a.length !== b.length) return false\n return a.every((row, idx) => {\n const other = b[idx]\n return !!other && row.id === other.id && row.field === other.field && (row.hashField ?? null) === (other.hashField ?? null)\n })\n}\n\nfunction areFieldOptionsEqual(a: FieldOption[], b: FieldOption[]): boolean {\n if (a === b) return true\n if (a.length !== b.length) return false\n return a.every((option, idx) => {\n const other = b[idx]\n return !!other && option.value === other.value && option.label === other.label\n })\n}\n\nfunction buildRowId(): string {\n if (typeof crypto !== 'undefined' && crypto.randomUUID) return crypto.randomUUID()\n return `row-${Math.random().toString(36).slice(2)}`\n}\n\nexport function EncryptionManager() {\n const t = useT()\n const scopeVersion = useOrganizationScopeVersion()\n const [selectedEntityId, setSelectedEntityId] = React.useState('')\n const [fields, setFields] = React.useState<EncryptionFieldRow[]>([])\n const [isActive, setIsActive] = React.useState(true)\n const [baseFieldOptions, setBaseFieldOptions] = React.useState<FieldOption[]>([])\n const [hasUserEdited, setHasUserEdited] = React.useState(false)\n const { data: rawFieldDefs, isLoading: loadingFieldDefs } = useCustomFieldDefs(selectedEntityId ? [selectedEntityId] : [], {\n enabled: !!selectedEntityId,\n })\n const fieldDefs = rawFieldDefs ?? EMPTY_FIELD_DEFS\n const canonicalOptions = React.useMemo<CanonicalOption[]>(() => {\n const options: CanonicalOption[] = []\n for (const option of baseFieldOptions) {\n if (!option.value) continue\n if (options.some((opt) => opt.value === option.value)) continue\n options.push(option)\n }\n for (const def of fieldDefs) {\n const key = typeof def.key === 'string' ? def.key.trim() : ''\n if (!key || options.some((opt) => opt.value === key)) continue\n const label = typeof def.label === 'string' ? def.label : undefined\n options.push({ value: key, label })\n }\n return options\n }, [baseFieldOptions, fieldDefs])\n const fieldOptions = React.useMemo(() => {\n const entries = new Map<string, string>()\n for (const option of baseFieldOptions) {\n if (!option.value || entries.has(option.value)) continue\n entries.set(option.value, option.label || option.value)\n }\n for (const def of fieldDefs) {\n const key = typeof def.key === 'string' ? def.key.trim() : ''\n if (!key || entries.has(key)) continue\n const label = typeof def.label === 'string' && def.label.trim().length ? def.label : key\n entries.set(key, label)\n }\n for (const row of fields) {\n const main = row.field?.trim()\n if (main && !entries.has(main)) entries.set(main, main)\n const hash = row.hashField?.trim()\n if (hash && !entries.has(hash)) entries.set(hash, hash)\n }\n return Array.from(entries.entries()).map(([value, label]) => ({ value, label }))\n }, [baseFieldOptions, fieldDefs, fields])\n\n const { data: entities, isLoading: loadingEntities, error: entitiesError } = useQuery<{ items: EntityOption[] }>({\n queryKey: ['entities-list', scopeVersion],\n queryFn: async () =>\n readApiResultOrThrow('/api/entities/entities', undefined, {\n errorMessage: t('entities.encryption.errors.loadEntities', 'Failed to load entities'),\n }),\n })\n\n React.useEffect(() => {\n if (!selectedEntityId && entities?.items?.length) {\n const first = entities.items[0]\n setSelectedEntityId(first.entityId)\n }\n }, [entities, selectedEntityId])\n\n React.useEffect(() => {\n if (!selectedEntityId) {\n setBaseFieldOptions((prev) => (prev.length ? [] : prev))\n return\n }\n const parts = selectedEntityId.split(':')\n const entitySlug = parts[1]\n if (!entitySlug) {\n setBaseFieldOptions((prev) => (prev.length ? [] : prev))\n return\n }\n\n // Use static registry instead of dynamic import for Turbopack compatibility\n const mod = getEntityFields(entitySlug)\n if (!mod) {\n console.warn('[encryption] No fields found for entity', entitySlug)\n setBaseFieldOptions((prev) => (prev.length ? [] : prev))\n return\n }\n\n const options: FieldOption[] = []\n for (const raw of Object.values(mod)) {\n if (typeof raw !== 'string' || !raw.trim()) continue\n const value = raw.trim()\n if (options.some((opt) => opt.value === value)) continue\n const label = value\n .split('_')\n .map((segment) => (segment ? `${segment[0].toUpperCase()}${segment.slice(1)}` : ''))\n .join(' ')\n .trim() || value\n options.push({ value, label })\n }\n setBaseFieldOptions((prev) => (areFieldOptionsEqual(prev, options) ? prev : options))\n }, [selectedEntityId])\n\n const {\n data: map,\n isLoading: loadingMap,\n isError: mapError,\n refetch: refetchMap,\n } = useQuery<EncryptionMapResponse>({\n queryKey: ['encryption-map', selectedEntityId, scopeVersion],\n enabled: !!selectedEntityId,\n queryFn: async () =>\n readApiResultOrThrow(`/api/entities/encryption?entityId=${encodeURIComponent(selectedEntityId)}`, undefined, {\n errorMessage: t('entities.encryption.errors.loadMap', 'Failed to load encryption map'),\n }),\n })\n\n const mapSignature = React.useMemo(() => JSON.stringify(map ?? null), [map])\n const lastMapSignatureRef = React.useRef<string | null>(null)\n\n React.useEffect(() => {\n const signature = mapSignature\n const isSameMap = signature === lastMapSignatureRef.current\n if (isSameMap && hasUserEdited) return\n if (!map) {\n setFields((prev) => (prev.length ? [] : prev))\n setIsActive((prev) => (prev === true ? prev : true))\n setHasUserEdited(false)\n lastMapSignatureRef.current = signature\n return\n }\n const nextFields = normalizeFieldRows(map, canonicalOptions)\n setFields((prev) => (areFieldRowsEqual(prev, nextFields) ? prev : nextFields))\n const nextIsActive = map?.isActive !== false\n setIsActive((prev) => (prev === nextIsActive ? prev : nextIsActive))\n setHasUserEdited(false)\n lastMapSignatureRef.current = signature\n }, [mapSignature, map, canonicalOptions, hasUserEdited])\n\n const mutation = useMutation({\n mutationFn: async () => {\n const trimmed = fields\n .map((row) => ({\n field: canonicalizeFieldName(row.field, canonicalOptions).trim(),\n hashField: row.hashField ? canonicalizeFieldName(row.hashField, canonicalOptions).trim() : '',\n }))\n .filter((row) => row.field.length > 0)\n .map((row) => ({\n field: row.field,\n hashField: row.hashField ? row.hashField : null,\n }))\n if (!selectedEntityId) {\n throw new Error(t('entities.encryption.errors.selectEntity', 'Select an entity before saving'))\n }\n if (!trimmed.length) {\n throw new Error(t('entities.encryption.errors.noFields', 'Add at least one field to encrypt'))\n }\n const res = await apiCall('/api/entities/encryption', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ entityId: selectedEntityId, fields: trimmed, isActive }),\n })\n if (!res.ok) {\n await raiseCrudError(res.response, t('entities.encryption.errors.save', 'Failed to save encryption map'))\n }\n return true\n },\n onSuccess: () => {\n flash(t('entities.encryption.flash.saved', 'Encryption map saved'), 'success')\n void refetchMap()\n },\n onError: (err: any) => {\n const message = err?.message || t('entities.encryption.errors.save', 'Failed to save encryption map')\n flash(message, 'error')\n },\n })\n\n const addField = () => {\n setHasUserEdited(true)\n setFields((prev) => [...prev, { id: buildRowId(), field: '', hashField: null }])\n }\n\n const updateField = (id: string, patch: Partial<EncryptionFieldRow>) => {\n setHasUserEdited(true)\n setFields((prev) => prev.map((row) => (row.id === id ? { ...row, ...patch } : row)))\n }\n\n const removeField = (id: string) => {\n setHasUserEdited(true)\n setFields((prev) => prev.filter((row) => row.id !== id))\n }\n\n const renderFields = () => {\n if (loadingMap || loadingFieldDefs) {\n return (\n <LoadingMessage\n label={t('entities.encryption.loading', 'Loading encryption map\u2026')}\n className=\"border-0 bg-transparent p-4\"\n />\n )\n }\n if (mapError) {\n return (\n <ErrorMessage\n label={t('entities.encryption.errors.loadMap', 'Failed to load encryption map')}\n action={(\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={() => void refetchMap()}>\n {t('entities.encryption.actions.retry', 'Retry')}\n </Button>\n )}\n />\n )\n }\n if (!fields.length) {\n return (\n <div className=\"rounded border bg-background/80 p-4 text-sm text-muted-foreground\">\n {t('entities.encryption.empty', 'No fields are encrypted yet. Add the first one below.')}\n </div>\n )\n }\n const withFallbackOption = (value?: string | null) => {\n if (value && !fieldOptions.some((opt) => opt.value === value)) {\n return [...fieldOptions, { value, label: value }]\n }\n return fieldOptions\n }\n return (\n <div className=\"overflow-x-auto\">\n <table className=\"w-full min-w-[720px] text-sm\">\n <thead>\n <tr className=\"text-xs uppercase tracking-wide text-muted-foreground\">\n <th className=\"px-3 py-2 text-left\">\n {t('entities.encryption.fields.field', 'Field name')}\n </th>\n <th className=\"px-3 py-2 text-left\">\n {t('entities.encryption.fields.hash', 'Hash field (optional)')}\n </th>\n <th className=\"px-3 py-2 text-right\">\n {t('entities.encryption.fields.actions', 'Actions')}\n </th>\n </tr>\n </thead>\n <tbody>\n {fields.map((row) => {\n const fieldOpts = withFallbackOption(row.field)\n const hashOpts = withFallbackOption(row.hashField)\n return (\n <tr key={row.id} className=\"border-t\">\n <td className=\"px-3 py-2 align-top\">\n <Select\n value={row.field || undefined}\n onValueChange={(value) => updateField(row.id, { field: value ?? '' })}\n >\n <SelectTrigger>\n <SelectValue placeholder={t('entities.encryption.fields.selectField', 'Select field')} />\n </SelectTrigger>\n <SelectContent>\n {fieldOpts.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n {option.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </td>\n <td className=\"px-3 py-2 align-top\">\n <Select\n value={row.hashField || undefined}\n onValueChange={(value) => updateField(row.id, { hashField: value || null })}\n >\n <SelectTrigger>\n <SelectValue placeholder={t('entities.encryption.fields.selectHash', 'Select hash field (optional)')} />\n </SelectTrigger>\n <SelectContent>\n {hashOpts.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n {option.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <p className=\"mt-1 text-overline text-muted-foreground\">\n {t('entities.encryption.fields.hashHint', 'Use when lookups must stay deterministic (e.g., login by email).')}\n </p>\n </td>\n <td className=\"px-3 py-2 align-top text-right\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n className=\"h-9 w-9 px-0\"\n aria-label={t('entities.encryption.actions.remove', 'Remove')}\n onClick={() => removeField(row.id)}\n >\n <Trash2 className=\"h-4 w-4\" />\n </Button>\n </td>\n </tr>\n )\n })}\n </tbody>\n </table>\n </div>\n )\n }\n\n return (\n <div className=\"space-y-6\">\n <div className=\"flex flex-col gap-3 rounded-lg border bg-card p-4 shadow-sm\">\n <div className=\"space-y-2\">\n <h2 className=\"text-xl font-semibold\">{t('entities.encryption.title', 'Encryption')}</h2>\n <p className=\"text-sm text-muted-foreground\">\n {t('entities.encryption.description', 'Manage which entity fields are encrypted with tenant keys and optional hash columns.')}\n </p>\n </div>\n <div className=\"flex flex-col gap-4 sm:flex-row sm:items-end\">\n <div className=\"flex-1 space-y-3\">\n <div>\n <label className=\"text-xs text-muted-foreground\">\n {t('entities.encryption.selectEntity', 'Choose entity')}\n </label>\n <Select\n value={selectedEntityId || undefined}\n onValueChange={(value) => setSelectedEntityId(value ?? '')}\n disabled={loadingEntities || !!entitiesError}\n >\n <SelectTrigger className=\"mt-1\">\n <SelectValue placeholder={t('entities.encryption.placeholder', 'Select an entity')} />\n </SelectTrigger>\n <SelectContent>\n {(entities?.items || []).map((item) => (\n <SelectItem key={item.entityId} value={item.entityId}>\n {item.label || item.entityId} {item.source === 'custom' ? `(${t('entities.encryption.source.custom', 'custom')})` : ''}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n {entitiesError ? (\n <p className=\"mt-1 text-xs text-status-error-text\">\n {t('entities.encryption.errors.loadEntities', 'Failed to load entities')}\n </p>\n ) : (\n <p className=\"mt-1 text-xs text-muted-foreground\">\n {t('entities.encryption.entityHint', 'Maps apply per tenant/organization. Use field names from your entities.')}\n </p>\n )}\n </div>\n <div className=\"inline-flex items-center gap-2 text-sm\">\n <Checkbox\n id=\"entities-encryption-active\"\n checked={isActive}\n onCheckedChange={(checked) => setIsActive(checked === true)}\n />\n <label htmlFor=\"entities-encryption-active\">\n {t('entities.encryption.active', 'Encryption enabled for this entity')}\n </label>\n </div>\n </div>\n </div>\n <div className=\"rounded-lg border bg-background/80 p-4\">\n <div className=\"mb-3 flex items-center justify-between\">\n <div>\n <h3 className=\"text-sm font-medium\">{t('entities.encryption.fields.title', 'Encrypted fields')}</h3>\n <p className=\"text-xs text-muted-foreground\">\n {t('entities.encryption.fields.subtitle', 'List the attributes that should be encrypted with the tenant key.')}\n </p>\n </div>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={addField}>\n <Plus className=\"mr-2 h-4 w-4\" />\n {t('entities.encryption.actions.add', 'Add field')}\n </Button>\n </div>\n {renderFields()}\n </div>\n <div className=\"flex justify-end\">\n <Button\n type=\"button\"\n onClick={() => mutation.mutate()}\n disabled={mutation.isPending || loadingEntities || !!entitiesError || !selectedEntityId}\n >\n <Save className=\"mr-2 h-4 w-4\" />\n {mutation.isPending\n ? t('entities.encryption.actions.saving', 'Saving\u2026')\n : t('entities.encryption.actions.save', 'Save encryption map')}\n </Button>\n </div>\n </div>\n </div>\n )\n}\n"],
5
- "mappings": ";AA2RQ,cAmCI,YAnCJ;AAzRR,YAAY,WAAW;AACvB,SAAS,UAAU,mBAAmB;AACtC,SAAS,cAAc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gBAAe;AAAA,UAC9B,SAAS,YACN,EAAE,sCAAsC,cAAS,IACjD,EAAE,oCAAoC,qBAAqB;AAAA;AAAA;AAAA,IACjE,GACF;AAAA,KACF,GACF;AAEJ;",
4
+ "sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { useQuery, useMutation } from '@tanstack/react-query'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { Checkbox } from '@open-mercato/ui/primitives/checkbox'\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from '@open-mercato/ui/primitives/select'\nimport { LoadingMessage, ErrorMessage } from '@open-mercato/ui/backend/detail'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { apiCall, readApiResultOrThrow, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { raiseCrudError } from '@open-mercato/ui/backend/utils/serverErrors'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { useCustomFieldDefs, type CustomFieldDefDto } from '@open-mercato/ui/backend/utils/customFieldDefs'\nimport { Plus, Save, Trash2 } from 'lucide-react'\nimport { useOrganizationScopeVersion } from '@open-mercato/shared/lib/frontend/useOrganizationScope'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { getEntityFields } from '#generated/entity-fields-registry'\n\ntype EntityOption = { entityId: string; label?: string; source?: string }\ntype FieldOption = { value: string; label: string }\n\ntype EncryptionFieldRow = {\n id: string\n field: string\n hashField?: string | null\n}\n\ntype EncryptionMapResponse = {\n entityId: string\n fields?: Array<{ field: string; hashField?: string | null }>\n isActive?: boolean\n updatedAt?: string | null\n}\n\ntype CanonicalOption = { value: string; label?: string }\n\nconst EMPTY_FIELD_DEFS: CustomFieldDefDto[] = []\n\nfunction normalizeToken(value: string): string {\n return value\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[^a-z0-9]/gi, '')\n .toLowerCase()\n}\n\nfunction canonicalizeFieldName(raw: string, options: CanonicalOption[]): string {\n const trimmed = typeof raw === 'string' ? raw.trim() : ''\n if (!trimmed) return ''\n const normalized = normalizeToken(trimmed)\n for (const option of options) {\n const optionValue = typeof option.value === 'string' ? option.value.trim() : ''\n if (optionValue && normalizeToken(optionValue) === normalized) return optionValue\n if (option.label && normalizeToken(option.label) === normalized) return optionValue\n }\n return trimmed\n}\n\nfunction normalizeFieldRows(raw: EncryptionMapResponse | undefined, options: CanonicalOption[]): EncryptionFieldRow[] {\n const rows = Array.isArray(raw?.fields) ? raw!.fields : []\n return rows.map((entry, idx) => ({\n id: `${entry.field}-${idx}`,\n field: canonicalizeFieldName(entry.field, options),\n hashField: entry.hashField ? canonicalizeFieldName(entry.hashField, options) : null,\n }))\n}\n\nfunction areFieldRowsEqual(a: EncryptionFieldRow[], b: EncryptionFieldRow[]): boolean {\n if (a === b) return true\n if (a.length !== b.length) return false\n return a.every((row, idx) => {\n const other = b[idx]\n return !!other && row.id === other.id && row.field === other.field && (row.hashField ?? null) === (other.hashField ?? null)\n })\n}\n\nfunction areFieldOptionsEqual(a: FieldOption[], b: FieldOption[]): boolean {\n if (a === b) return true\n if (a.length !== b.length) return false\n return a.every((option, idx) => {\n const other = b[idx]\n return !!other && option.value === other.value && option.label === other.label\n })\n}\n\nfunction buildRowId(): string {\n if (typeof crypto !== 'undefined' && crypto.randomUUID) return crypto.randomUUID()\n return `row-${Math.random().toString(36).slice(2)}`\n}\n\nexport function EncryptionManager() {\n const t = useT()\n const scopeVersion = useOrganizationScopeVersion()\n const [selectedEntityId, setSelectedEntityId] = React.useState('')\n const [fields, setFields] = React.useState<EncryptionFieldRow[]>([])\n const [isActive, setIsActive] = React.useState(true)\n const [baseFieldOptions, setBaseFieldOptions] = React.useState<FieldOption[]>([])\n const [hasUserEdited, setHasUserEdited] = React.useState(false)\n const { data: rawFieldDefs, isLoading: loadingFieldDefs } = useCustomFieldDefs(selectedEntityId ? [selectedEntityId] : [], {\n enabled: !!selectedEntityId,\n })\n const fieldDefs = rawFieldDefs ?? EMPTY_FIELD_DEFS\n const canonicalOptions = React.useMemo<CanonicalOption[]>(() => {\n const options: CanonicalOption[] = []\n for (const option of baseFieldOptions) {\n if (!option.value) continue\n if (options.some((opt) => opt.value === option.value)) continue\n options.push(option)\n }\n for (const def of fieldDefs) {\n const key = typeof def.key === 'string' ? def.key.trim() : ''\n if (!key || options.some((opt) => opt.value === key)) continue\n const label = typeof def.label === 'string' ? def.label : undefined\n options.push({ value: key, label })\n }\n return options\n }, [baseFieldOptions, fieldDefs])\n const fieldOptions = React.useMemo(() => {\n const entries = new Map<string, string>()\n for (const option of baseFieldOptions) {\n if (!option.value || entries.has(option.value)) continue\n entries.set(option.value, option.label || option.value)\n }\n for (const def of fieldDefs) {\n const key = typeof def.key === 'string' ? def.key.trim() : ''\n if (!key || entries.has(key)) continue\n const label = typeof def.label === 'string' && def.label.trim().length ? def.label : key\n entries.set(key, label)\n }\n for (const row of fields) {\n const main = row.field?.trim()\n if (main && !entries.has(main)) entries.set(main, main)\n const hash = row.hashField?.trim()\n if (hash && !entries.has(hash)) entries.set(hash, hash)\n }\n return Array.from(entries.entries()).map(([value, label]) => ({ value, label }))\n }, [baseFieldOptions, fieldDefs, fields])\n\n const { data: entities, isLoading: loadingEntities, error: entitiesError } = useQuery<{ items: EntityOption[] }>({\n queryKey: ['entities-list', scopeVersion],\n queryFn: async () =>\n readApiResultOrThrow('/api/entities/entities', undefined, {\n errorMessage: t('entities.encryption.errors.loadEntities', 'Failed to load entities'),\n }),\n })\n\n React.useEffect(() => {\n if (!selectedEntityId && entities?.items?.length) {\n const first = entities.items[0]\n setSelectedEntityId(first.entityId)\n }\n }, [entities, selectedEntityId])\n\n React.useEffect(() => {\n if (!selectedEntityId) {\n setBaseFieldOptions((prev) => (prev.length ? [] : prev))\n return\n }\n const parts = selectedEntityId.split(':')\n const entitySlug = parts[1]\n if (!entitySlug) {\n setBaseFieldOptions((prev) => (prev.length ? [] : prev))\n return\n }\n\n // Use static registry instead of dynamic import for Turbopack compatibility\n const mod = getEntityFields(entitySlug)\n if (!mod) {\n console.warn('[encryption] No fields found for entity', entitySlug)\n setBaseFieldOptions((prev) => (prev.length ? [] : prev))\n return\n }\n\n const options: FieldOption[] = []\n for (const raw of Object.values(mod)) {\n if (typeof raw !== 'string' || !raw.trim()) continue\n const value = raw.trim()\n if (options.some((opt) => opt.value === value)) continue\n const label = value\n .split('_')\n .map((segment) => (segment ? `${segment[0].toUpperCase()}${segment.slice(1)}` : ''))\n .join(' ')\n .trim() || value\n options.push({ value, label })\n }\n setBaseFieldOptions((prev) => (areFieldOptionsEqual(prev, options) ? prev : options))\n }, [selectedEntityId])\n\n const {\n data: map,\n isLoading: loadingMap,\n isError: mapError,\n refetch: refetchMap,\n } = useQuery<EncryptionMapResponse>({\n queryKey: ['encryption-map', selectedEntityId, scopeVersion],\n enabled: !!selectedEntityId,\n queryFn: async () =>\n readApiResultOrThrow(`/api/entities/encryption?entityId=${encodeURIComponent(selectedEntityId)}`, undefined, {\n errorMessage: t('entities.encryption.errors.loadMap', 'Failed to load encryption map'),\n }),\n })\n\n const mapSignature = React.useMemo(() => JSON.stringify(map ?? null), [map])\n const lastMapSignatureRef = React.useRef<string | null>(null)\n\n React.useEffect(() => {\n const signature = mapSignature\n const isSameMap = signature === lastMapSignatureRef.current\n if (isSameMap && hasUserEdited) return\n if (!map) {\n setFields((prev) => (prev.length ? [] : prev))\n setIsActive((prev) => (prev === true ? prev : true))\n setHasUserEdited(false)\n lastMapSignatureRef.current = signature\n return\n }\n const nextFields = normalizeFieldRows(map, canonicalOptions)\n setFields((prev) => (areFieldRowsEqual(prev, nextFields) ? prev : nextFields))\n const nextIsActive = map?.isActive !== false\n setIsActive((prev) => (prev === nextIsActive ? prev : nextIsActive))\n setHasUserEdited(false)\n lastMapSignatureRef.current = signature\n }, [mapSignature, map, canonicalOptions, hasUserEdited])\n\n const { runMutation } = useGuardedMutation({ contextId: 'entities.encryption-map' })\n\n const mutation = useMutation({\n mutationFn: async () => {\n const trimmed = fields\n .map((row) => ({\n field: canonicalizeFieldName(row.field, canonicalOptions).trim(),\n hashField: row.hashField ? canonicalizeFieldName(row.hashField, canonicalOptions).trim() : '',\n }))\n .filter((row) => row.field.length > 0)\n .map((row) => ({\n field: row.field,\n hashField: row.hashField ? row.hashField : null,\n }))\n if (!selectedEntityId) {\n throw new Error(t('entities.encryption.errors.selectEntity', 'Select an entity before saving'))\n }\n if (!trimmed.length) {\n throw new Error(t('entities.encryption.errors.noFields', 'Add at least one field to encrypt'))\n }\n const payload = { entityId: selectedEntityId, fields: trimmed, isActive }\n // Route the write through the guarded mutation helper so global injection\n // modules (mutation guard, record-lock conflict handling) can run, and send\n // the loaded map's version so a stale tab cannot silently overwrite a newer\n // encryption configuration (the server rejects mismatches with a 409).\n return runMutation({\n operation: async () => {\n const res = await withScopedApiRequestHeaders(\n buildOptimisticLockHeader(map?.updatedAt ?? null),\n () => apiCall('/api/entities/encryption', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(payload),\n }),\n )\n if (!res.ok) {\n await raiseCrudError(res.response, t('entities.encryption.errors.save', 'Failed to save encryption map'))\n }\n return true\n },\n context: {},\n mutationPayload: payload,\n })\n },\n onSuccess: () => {\n flash(t('entities.encryption.flash.saved', 'Encryption map saved'), 'success')\n void refetchMap()\n },\n onError: (err: any) => {\n const message = err?.message || t('entities.encryption.errors.save', 'Failed to save encryption map')\n flash(message, 'error')\n },\n })\n\n const addField = () => {\n setHasUserEdited(true)\n setFields((prev) => [...prev, { id: buildRowId(), field: '', hashField: null }])\n }\n\n const updateField = (id: string, patch: Partial<EncryptionFieldRow>) => {\n setHasUserEdited(true)\n setFields((prev) => prev.map((row) => (row.id === id ? { ...row, ...patch } : row)))\n }\n\n const removeField = (id: string) => {\n setHasUserEdited(true)\n setFields((prev) => prev.filter((row) => row.id !== id))\n }\n\n const renderFields = () => {\n if (loadingMap || loadingFieldDefs) {\n return (\n <LoadingMessage\n label={t('entities.encryption.loading', 'Loading encryption map\u2026')}\n className=\"border-0 bg-transparent p-4\"\n />\n )\n }\n if (mapError) {\n return (\n <ErrorMessage\n label={t('entities.encryption.errors.loadMap', 'Failed to load encryption map')}\n action={(\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={() => void refetchMap()}>\n {t('entities.encryption.actions.retry', 'Retry')}\n </Button>\n )}\n />\n )\n }\n if (!fields.length) {\n return (\n <div className=\"rounded border bg-background/80 p-4 text-sm text-muted-foreground\">\n {t('entities.encryption.empty', 'No fields are encrypted yet. Add the first one below.')}\n </div>\n )\n }\n const withFallbackOption = (value?: string | null) => {\n if (value && !fieldOptions.some((opt) => opt.value === value)) {\n return [...fieldOptions, { value, label: value }]\n }\n return fieldOptions\n }\n return (\n <div className=\"overflow-x-auto\">\n <table className=\"w-full min-w-[720px] text-sm\">\n <thead>\n <tr className=\"text-xs uppercase tracking-wide text-muted-foreground\">\n <th className=\"px-3 py-2 text-left\">\n {t('entities.encryption.fields.field', 'Field name')}\n </th>\n <th className=\"px-3 py-2 text-left\">\n {t('entities.encryption.fields.hash', 'Hash field (optional)')}\n </th>\n <th className=\"px-3 py-2 text-right\">\n {t('entities.encryption.fields.actions', 'Actions')}\n </th>\n </tr>\n </thead>\n <tbody>\n {fields.map((row) => {\n const fieldOpts = withFallbackOption(row.field)\n const hashOpts = withFallbackOption(row.hashField)\n return (\n <tr key={row.id} className=\"border-t\">\n <td className=\"px-3 py-2 align-top\">\n <Select\n value={row.field || undefined}\n onValueChange={(value) => updateField(row.id, { field: value ?? '' })}\n >\n <SelectTrigger>\n <SelectValue placeholder={t('entities.encryption.fields.selectField', 'Select field')} />\n </SelectTrigger>\n <SelectContent>\n {fieldOpts.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n {option.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </td>\n <td className=\"px-3 py-2 align-top\">\n <Select\n value={row.hashField || undefined}\n onValueChange={(value) => updateField(row.id, { hashField: value || null })}\n >\n <SelectTrigger>\n <SelectValue placeholder={t('entities.encryption.fields.selectHash', 'Select hash field (optional)')} />\n </SelectTrigger>\n <SelectContent>\n {hashOpts.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n {option.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <p className=\"mt-1 text-overline text-muted-foreground\">\n {t('entities.encryption.fields.hashHint', 'Use when lookups must stay deterministic (e.g., login by email).')}\n </p>\n </td>\n <td className=\"px-3 py-2 align-top text-right\">\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n className=\"h-9 w-9 px-0\"\n aria-label={t('entities.encryption.actions.remove', 'Remove')}\n onClick={() => removeField(row.id)}\n >\n <Trash2 className=\"h-4 w-4\" />\n </Button>\n </td>\n </tr>\n )\n })}\n </tbody>\n </table>\n </div>\n )\n }\n\n return (\n <div className=\"space-y-6\">\n <div className=\"flex flex-col gap-3 rounded-lg border bg-card p-4 shadow-sm\">\n <div className=\"space-y-2\">\n <h2 className=\"text-xl font-semibold\">{t('entities.encryption.title', 'Encryption')}</h2>\n <p className=\"text-sm text-muted-foreground\">\n {t('entities.encryption.description', 'Manage which entity fields are encrypted with tenant keys and optional hash columns.')}\n </p>\n </div>\n <div className=\"flex flex-col gap-4 sm:flex-row sm:items-end\">\n <div className=\"flex-1 space-y-3\">\n <div>\n <label className=\"text-xs text-muted-foreground\">\n {t('entities.encryption.selectEntity', 'Choose entity')}\n </label>\n <Select\n value={selectedEntityId || undefined}\n onValueChange={(value) => setSelectedEntityId(value ?? '')}\n disabled={loadingEntities || !!entitiesError}\n >\n <SelectTrigger className=\"mt-1\">\n <SelectValue placeholder={t('entities.encryption.placeholder', 'Select an entity')} />\n </SelectTrigger>\n <SelectContent>\n {(entities?.items || []).map((item) => (\n <SelectItem key={item.entityId} value={item.entityId}>\n {item.label || item.entityId} {item.source === 'custom' ? `(${t('entities.encryption.source.custom', 'custom')})` : ''}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n {entitiesError ? (\n <p className=\"mt-1 text-xs text-status-error-text\">\n {t('entities.encryption.errors.loadEntities', 'Failed to load entities')}\n </p>\n ) : (\n <p className=\"mt-1 text-xs text-muted-foreground\">\n {t('entities.encryption.entityHint', 'Maps apply per tenant/organization. Use field names from your entities.')}\n </p>\n )}\n </div>\n <div className=\"inline-flex items-center gap-2 text-sm\">\n <Checkbox\n id=\"entities-encryption-active\"\n checked={isActive}\n onCheckedChange={(checked) => setIsActive(checked === true)}\n />\n <label htmlFor=\"entities-encryption-active\">\n {t('entities.encryption.active', 'Encryption enabled for this entity')}\n </label>\n </div>\n </div>\n </div>\n <div className=\"rounded-lg border bg-background/80 p-4\">\n <div className=\"mb-3 flex items-center justify-between\">\n <div>\n <h3 className=\"text-sm font-medium\">{t('entities.encryption.fields.title', 'Encrypted fields')}</h3>\n <p className=\"text-xs text-muted-foreground\">\n {t('entities.encryption.fields.subtitle', 'List the attributes that should be encrypted with the tenant key.')}\n </p>\n </div>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={addField}>\n <Plus className=\"mr-2 h-4 w-4\" />\n {t('entities.encryption.actions.add', 'Add field')}\n </Button>\n </div>\n {renderFields()}\n </div>\n <div className=\"flex justify-end\">\n <Button\n type=\"button\"\n onClick={() => mutation.mutate()}\n disabled={mutation.isPending || loadingEntities || !!entitiesError || !selectedEntityId}\n >\n <Save className=\"mr-2 h-4 w-4\" />\n {mutation.isPending\n ? t('entities.encryption.actions.saving', 'Saving\u2026')\n : t('entities.encryption.actions.save', 'Save encryption map')}\n </Button>\n </div>\n </div>\n </div>\n )\n}\n"],
5
+ "mappings": ";AA8SQ,cAmCI,YAnCJ;AA5SR,YAAY,WAAW;AACvB,SAAS,UAAU,mBAAmB;AACtC,SAAS,cAAc;AACvB,SAAS,gBAAgB;AACzB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gBAA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B;AAAA,IACA,oBAAC,SAAI,WAAU,oBACb;AAAA,MAAC;AAAA;AAAA,QACC,MAAK;AAAA,QACL,SAAS,MAAM,SAAS,OAAO;AAAA,QAC/B,UAAU,SAAS,aAAa,mBAAmB,CAAC,CAAC,iBAAiB,CAAC;AAAA,QAEvE;AAAA,8BAAC,QAAK,WAAU,gBAAe;AAAA,UAC9B,SAAS,YACN,EAAE,sCAAsC,cAAS,IACjD,EAAE,oCAAoC,qBAAqB;AAAA;AAAA;AAAA,IACjE,GACF;AAAA,KACF,GACF;AAEJ;",
6
6
  "names": []
7
7
  }
@@ -3,6 +3,8 @@ import { z } from "zod";
3
3
  import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
4
4
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
5
5
  import { getIntegration } from "@open-mercato/shared/modules/integrations/types";
6
+ import { enforceCommandOptimisticLock } from "@open-mercato/shared/lib/crud/optimistic-lock-command";
7
+ import { isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
6
8
  import { emitIntegrationsEvent } from "../../../events.js";
7
9
  import { saveCredentialsSchema } from "../../../data/validators.js";
8
10
  import {
@@ -48,8 +50,10 @@ async function GET(req, ctx) {
48
50
  const credentialsService = container.resolve("integrationCredentialsService");
49
51
  const scope = { organizationId: auth.orgId, tenantId: auth.tenantId };
50
52
  let values;
53
+ let updatedAt;
51
54
  try {
52
55
  values = await credentialsService.resolve(integration.id, scope);
56
+ updatedAt = await credentialsService.resolveUpdatedAt(integration.id, scope);
53
57
  } catch (error) {
54
58
  if (isCredentialsEncryptionUnavailableError(error)) {
55
59
  return NextResponse.json({ error: "Integration credentials encryption is unavailable" }, { status: 503 });
@@ -59,7 +63,8 @@ async function GET(req, ctx) {
59
63
  return NextResponse.json({
60
64
  integrationId: integration.id,
61
65
  schema: credentialsService.getSchema(integration.id),
62
- credentials: values ?? {}
66
+ credentials: values ?? {},
67
+ updatedAt: updatedAt?.toISOString() ?? null
63
68
  });
64
69
  }
65
70
  async function PUT(req, ctx) {
@@ -111,6 +116,23 @@ async function PUT(req, ctx) {
111
116
  }
112
117
  const credentialsService = container.resolve("integrationCredentialsService");
113
118
  const scope = { organizationId: auth.orgId, tenantId: auth.tenantId };
119
+ try {
120
+ const currentUpdatedAt = await credentialsService.resolveUpdatedAt(integration.id, scope);
121
+ enforceCommandOptimisticLock({
122
+ resourceKind: "integrations.integration",
123
+ resourceId: integration.id,
124
+ current: currentUpdatedAt,
125
+ request: req
126
+ });
127
+ } catch (error) {
128
+ if (isCrudHttpError(error)) {
129
+ return NextResponse.json(error.body, { status: error.status });
130
+ }
131
+ if (isCredentialsEncryptionUnavailableError(error)) {
132
+ return NextResponse.json({ error: "Integration credentials encryption is unavailable" }, { status: 503 });
133
+ }
134
+ throw error;
135
+ }
114
136
  const credentialFieldErrors = collectCredentialUrlValidationErrors(
115
137
  credentialsService.getSchema(integration.id),
116
138
  payloadData.credentials
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/modules/integrations/api/%5Bid%5D/credentials/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getIntegration } from '@open-mercato/shared/modules/integrations/types'\nimport { emitIntegrationsEvent } from '../../../events'\nimport { saveCredentialsSchema } from '../../../data/validators'\nimport {\n isCredentialsEncryptionUnavailableError,\n type CredentialsService,\n} from '../../../lib/credentials-service'\nimport { collectCredentialUrlValidationErrors } from '../../../lib/credentials-field-validation'\nimport {\n resolveUserFeatures,\n runIntegrationMutationGuardAfterSuccess,\n runIntegrationMutationGuards,\n} from '../../guards'\n\nconst idParamsSchema = z.object({ id: z.string().min(1) })\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['integrations.credentials.manage'] },\n PUT: { requireAuth: true, requireFeatures: ['integrations.credentials.manage'] },\n}\n\nexport const openApi = {\n tags: ['Integrations'],\n summary: 'Get or save integration credentials',\n}\n\nfunction resolveParams(ctx: { params?: Promise<{ id?: string }> | { id?: string } }): Promise<{ id?: string } | undefined> | { id?: string } | undefined {\n if (!ctx.params) return undefined\n if (typeof (ctx.params as Promise<unknown>).then === 'function') {\n return ctx.params as Promise<{ id?: string }>\n }\n return ctx.params as { id?: string }\n}\n\nexport async function GET(req: Request, ctx: { params?: Promise<{ id?: string }> | { id?: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId || !auth.orgId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const rawParams = await resolveParams(ctx)\n const parsedParams = idParamsSchema.safeParse(rawParams)\n if (!parsedParams.success) {\n return NextResponse.json({ error: 'Invalid integration id' }, { status: 400 })\n }\n\n const integration = getIntegration(parsedParams.data.id)\n if (!integration) {\n return NextResponse.json({ error: 'Integration not found' }, { status: 404 })\n }\n\n const container = await createRequestContainer()\n const credentialsService = container.resolve('integrationCredentialsService') as CredentialsService\n const scope = { organizationId: auth.orgId as string, tenantId: auth.tenantId }\n\n let values: Record<string, unknown> | null\n try {\n values = await credentialsService.resolve(integration.id, scope)\n } catch (error) {\n if (isCredentialsEncryptionUnavailableError(error)) {\n return NextResponse.json({ error: 'Integration credentials encryption is unavailable' }, { status: 503 })\n }\n throw error\n }\n\n return NextResponse.json({\n integrationId: integration.id,\n schema: credentialsService.getSchema(integration.id),\n credentials: values ?? {},\n })\n}\n\nexport async function PUT(req: Request, ctx: { params?: Promise<{ id?: string }> | { id?: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId || !auth.orgId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const rawParams = await resolveParams(ctx)\n const parsedParams = idParamsSchema.safeParse(rawParams)\n if (!parsedParams.success) {\n return NextResponse.json({ error: 'Invalid integration id' }, { status: 400 })\n }\n\n const integration = getIntegration(parsedParams.data.id)\n if (!integration) {\n return NextResponse.json({ error: 'Integration not found' }, { status: 404 })\n }\n\n const payload = await req.json().catch(() => null)\n const parsedBody = saveCredentialsSchema.safeParse(payload)\n if (!parsedBody.success) {\n return NextResponse.json({ error: 'Invalid credentials payload', details: parsedBody.error.flatten() }, { status: 422 })\n }\n\n const container = await createRequestContainer()\n const guardResult = await runIntegrationMutationGuards(\n container,\n {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n userId: auth.sub ?? '',\n resourceKind: 'integrations.integration',\n resourceId: integration.id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: parsedBody.data as Record<string, unknown>,\n },\n resolveUserFeatures(auth),\n )\n if (!guardResult.ok) {\n return NextResponse.json(guardResult.errorBody ?? { error: 'Operation blocked by guard' }, { status: guardResult.errorStatus ?? 422 })\n }\n\n let payloadData = parsedBody.data\n if (guardResult.modifiedPayload) {\n const mergedPayload = { ...parsedBody.data, ...guardResult.modifiedPayload }\n const reparsed = saveCredentialsSchema.safeParse(mergedPayload)\n if (!reparsed.success) {\n return NextResponse.json({ error: 'Invalid credentials payload after guard transform', details: reparsed.error.flatten() }, { status: 422 })\n }\n payloadData = reparsed.data\n }\n\n const credentialsService = container.resolve('integrationCredentialsService') as CredentialsService\n const scope = { organizationId: auth.orgId as string, tenantId: auth.tenantId }\n\n const credentialFieldErrors = collectCredentialUrlValidationErrors(\n credentialsService.getSchema(integration.id),\n payloadData.credentials,\n )\n if (Object.keys(credentialFieldErrors).length > 0) {\n return NextResponse.json(\n { error: 'Invalid credentials payload', details: { fieldErrors: credentialFieldErrors } },\n { status: 422 },\n )\n }\n\n try {\n await credentialsService.save(integration.id, payloadData.credentials, scope)\n } catch (error) {\n if (isCredentialsEncryptionUnavailableError(error)) {\n return NextResponse.json({ error: 'Integration credentials encryption is unavailable' }, { status: 503 })\n }\n throw error\n }\n\n await emitIntegrationsEvent('integrations.credentials.updated', {\n integrationId: integration.id,\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n userId: auth.sub,\n })\n\n await runIntegrationMutationGuardAfterSuccess(guardResult.afterSuccessCallbacks, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n userId: auth.sub ?? '',\n resourceKind: 'integrations.integration',\n resourceId: integration.id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n })\n\n return NextResponse.json({ ok: true })\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,sBAAsB;AAC/B,SAAS,6BAA6B;AACtC,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,OAEK;AACP,SAAS,4CAA4C;AACrD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,iBAAiB,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,CAAC;AAElD,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,iCAAiC,EAAE;AAAA,EAC/E,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,iCAAiC,EAAE;AACjF;AAEO,MAAM,UAAU;AAAA,EACrB,MAAM,CAAC,cAAc;AAAA,EACrB,SAAS;AACX;AAEA,SAAS,cAAc,KAAkI;AACvJ,MAAI,CAAC,IAAI,OAAQ,QAAO;AACxB,MAAI,OAAQ,IAAI,OAA4B,SAAS,YAAY;AAC/D,WAAO,IAAI;AAAA,EACb;AACA,SAAO,IAAI;AACb;AAEA,eAAsB,IAAI,KAAc,KAA8D;AACpG,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,MAAM,YAAY,CAAC,KAAK,OAAO;AAClC,WAAO,aAAa,KAAK,EAAE,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACrE;AAEA,QAAM,YAAY,MAAM,cAAc,GAAG;AACzC,QAAM,eAAe,eAAe,UAAU,SAAS;AAC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,+BAA+B;AAC5E,QAAM,QAAQ,EAAE,gBAAgB,KAAK,OAAiB,UAAU,KAAK,SAAS;AAE9E,QAAM,wBAAwB;AAAA,IAC5B,mBAAmB,UAAU,YAAY,EAAE;AAAA,IAC3C,YAAY;AAAA,EACd;AACA,MAAI,OAAO,KAAK,qBAAqB,EAAE,SAAS,GAAG;AACjD,WAAO,aAAa;AAAA,MAClB,EAAE,OAAO,+BAA+B,SAAS,EAAE,aAAa,sBAAsB,EAAE;AAAA,MACxF,EAAE,QAAQ,IAAI;AAAA,IAChB;AAAA,EACF;AAEA,MAAI;AACF,UAAM,mBAAmB,KAAK,YAAY,IAAI,YAAY,aAAa,KAAK;AAAA,EAC9E,SAAS,OAAO;AACd,QAAI,wCAAwC,KAAK,GAAG;AAClD,aAAO,aAAa,KAAK,EAAE,OAAO,oDAAoD,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IAC1G;AACA,UAAM;AAAA,EACR;AAEA,QAAM,sBAAsB,oCAAoC;AAAA,IAC9D,eAAe,YAAY;AAAA,IAC3B,UAAU,KAAK;AAAA,IACf,gBAAgB,KAAK;AAAA,IACrB,QAAQ,KAAK;AAAA,EACf,CAAC;AAED,QAAM,wCAAwC,YAAY,uBAAuB;AAAA,IAC7E,UAAU,KAAK;AAAA,IACf,gBAAgB,KAAK;AAAA,IACrB,QAAQ,KAAK,OAAO;AAAA,IACpB,cAAc;AAAA,IACd,YAAY,YAAY;AAAA,IACxB,WAAW;AAAA,IACX,eAAe,IAAI;AAAA,IACnB,gBAAgB,IAAI;AAAA,EACtB,CAAC;AAEH,SAAO,aAAa,KAAK,EAAE,IAAI,KAAK,CAAC;AACvC;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getIntegration } from '@open-mercato/shared/modules/integrations/types'\nimport { enforceCommandOptimisticLock } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { emitIntegrationsEvent } from '../../../events'\nimport { saveCredentialsSchema } from '../../../data/validators'\nimport {\n isCredentialsEncryptionUnavailableError,\n type CredentialsService,\n} from '../../../lib/credentials-service'\nimport { collectCredentialUrlValidationErrors } from '../../../lib/credentials-field-validation'\nimport {\n resolveUserFeatures,\n runIntegrationMutationGuardAfterSuccess,\n runIntegrationMutationGuards,\n} from '../../guards'\n\nconst idParamsSchema = z.object({ id: z.string().min(1) })\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['integrations.credentials.manage'] },\n PUT: { requireAuth: true, requireFeatures: ['integrations.credentials.manage'] },\n}\n\nexport const openApi = {\n tags: ['Integrations'],\n summary: 'Get or save integration credentials',\n}\n\nfunction resolveParams(ctx: { params?: Promise<{ id?: string }> | { id?: string } }): Promise<{ id?: string } | undefined> | { id?: string } | undefined {\n if (!ctx.params) return undefined\n if (typeof (ctx.params as Promise<unknown>).then === 'function') {\n return ctx.params as Promise<{ id?: string }>\n }\n return ctx.params as { id?: string }\n}\n\nexport async function GET(req: Request, ctx: { params?: Promise<{ id?: string }> | { id?: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId || !auth.orgId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const rawParams = await resolveParams(ctx)\n const parsedParams = idParamsSchema.safeParse(rawParams)\n if (!parsedParams.success) {\n return NextResponse.json({ error: 'Invalid integration id' }, { status: 400 })\n }\n\n const integration = getIntegration(parsedParams.data.id)\n if (!integration) {\n return NextResponse.json({ error: 'Integration not found' }, { status: 404 })\n }\n\n const container = await createRequestContainer()\n const credentialsService = container.resolve('integrationCredentialsService') as CredentialsService\n const scope = { organizationId: auth.orgId as string, tenantId: auth.tenantId }\n\n let values: Record<string, unknown> | null\n let updatedAt: Date | null\n try {\n values = await credentialsService.resolve(integration.id, scope)\n updatedAt = await credentialsService.resolveUpdatedAt(integration.id, scope)\n } catch (error) {\n if (isCredentialsEncryptionUnavailableError(error)) {\n return NextResponse.json({ error: 'Integration credentials encryption is unavailable' }, { status: 503 })\n }\n throw error\n }\n\n return NextResponse.json({\n integrationId: integration.id,\n schema: credentialsService.getSchema(integration.id),\n credentials: values ?? {},\n updatedAt: updatedAt?.toISOString() ?? null,\n })\n}\n\nexport async function PUT(req: Request, ctx: { params?: Promise<{ id?: string }> | { id?: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId || !auth.orgId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const rawParams = await resolveParams(ctx)\n const parsedParams = idParamsSchema.safeParse(rawParams)\n if (!parsedParams.success) {\n return NextResponse.json({ error: 'Invalid integration id' }, { status: 400 })\n }\n\n const integration = getIntegration(parsedParams.data.id)\n if (!integration) {\n return NextResponse.json({ error: 'Integration not found' }, { status: 404 })\n }\n\n const payload = await req.json().catch(() => null)\n const parsedBody = saveCredentialsSchema.safeParse(payload)\n if (!parsedBody.success) {\n return NextResponse.json({ error: 'Invalid credentials payload', details: parsedBody.error.flatten() }, { status: 422 })\n }\n\n const container = await createRequestContainer()\n const guardResult = await runIntegrationMutationGuards(\n container,\n {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n userId: auth.sub ?? '',\n resourceKind: 'integrations.integration',\n resourceId: integration.id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: parsedBody.data as Record<string, unknown>,\n },\n resolveUserFeatures(auth),\n )\n if (!guardResult.ok) {\n return NextResponse.json(guardResult.errorBody ?? { error: 'Operation blocked by guard' }, { status: guardResult.errorStatus ?? 422 })\n }\n\n let payloadData = parsedBody.data\n if (guardResult.modifiedPayload) {\n const mergedPayload = { ...parsedBody.data, ...guardResult.modifiedPayload }\n const reparsed = saveCredentialsSchema.safeParse(mergedPayload)\n if (!reparsed.success) {\n return NextResponse.json({ error: 'Invalid credentials payload after guard transform', details: reparsed.error.flatten() }, { status: 422 })\n }\n payloadData = reparsed.data\n }\n\n const credentialsService = container.resolve('integrationCredentialsService') as CredentialsService\n const scope = { organizationId: auth.orgId as string, tenantId: auth.tenantId }\n\n try {\n const currentUpdatedAt = await credentialsService.resolveUpdatedAt(integration.id, scope)\n enforceCommandOptimisticLock({\n resourceKind: 'integrations.integration',\n resourceId: integration.id,\n current: currentUpdatedAt,\n request: req,\n })\n } catch (error) {\n if (isCrudHttpError(error)) {\n return NextResponse.json(error.body, { status: error.status })\n }\n if (isCredentialsEncryptionUnavailableError(error)) {\n return NextResponse.json({ error: 'Integration credentials encryption is unavailable' }, { status: 503 })\n }\n throw error\n }\n\n const credentialFieldErrors = collectCredentialUrlValidationErrors(\n credentialsService.getSchema(integration.id),\n payloadData.credentials,\n )\n if (Object.keys(credentialFieldErrors).length > 0) {\n return NextResponse.json(\n { error: 'Invalid credentials payload', details: { fieldErrors: credentialFieldErrors } },\n { status: 422 },\n )\n }\n\n try {\n await credentialsService.save(integration.id, payloadData.credentials, scope)\n } catch (error) {\n if (isCredentialsEncryptionUnavailableError(error)) {\n return NextResponse.json({ error: 'Integration credentials encryption is unavailable' }, { status: 503 })\n }\n throw error\n }\n\n await emitIntegrationsEvent('integrations.credentials.updated', {\n integrationId: integration.id,\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n userId: auth.sub,\n })\n\n await runIntegrationMutationGuardAfterSuccess(guardResult.afterSuccessCallbacks, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n userId: auth.sub ?? '',\n resourceKind: 'integrations.integration',\n resourceId: integration.id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n })\n\n return NextResponse.json({ ok: true })\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,sBAAsB;AAC/B,SAAS,oCAAoC;AAC7C,SAAS,uBAAuB;AAChC,SAA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AC;AACvC;",
6
6
  "names": []
7
7
  }
@@ -46,11 +46,15 @@ async function GET(req, ctx) {
46
46
  const stateService = container.resolve("integrationStateService");
47
47
  const logService = container.resolve("integrationLogService");
48
48
  const scope = { organizationId: auth.orgId, tenantId: auth.tenantId };
49
- const [credentials, state, analyticsMap] = await Promise.all([
49
+ const [credentials, credentialsUpdatedAt, state, analyticsMap] = await Promise.all([
50
50
  credentialsService.resolve(integration.id, scope).catch((err) => {
51
51
  if (err instanceof CredentialsEncryptionUnavailableError) return null;
52
52
  throw err;
53
53
  }),
54
+ credentialsService.resolveUpdatedAt(integration.id, scope).catch((err) => {
55
+ if (err instanceof CredentialsEncryptionUnavailableError) return null;
56
+ throw err;
57
+ }),
54
58
  stateService.resolveState(integration.id, scope),
55
59
  logService.aggregateAnalytics([integration.id], scope, 30)
56
60
  ]);
@@ -84,7 +88,8 @@ async function GET(req, ctx) {
84
88
  lastHealthStatus: resolvedState.lastHealthStatus,
85
89
  lastHealthCheckedAt: resolvedState.lastHealthCheckedAt?.toISOString() ?? null,
86
90
  lastHealthLatencyMs: resolvedState.lastHealthLatencyMs,
87
- enabledAt: resolvedState.enabledAt?.toISOString() ?? null
91
+ enabledAt: resolvedState.enabledAt?.toISOString() ?? null,
92
+ updatedAt: resolvedState.updatedAt?.toISOString() ?? null
88
93
  }
89
94
  };
90
95
  })
@@ -112,9 +117,11 @@ async function GET(req, ctx) {
112
117
  lastHealthStatus: state.lastHealthStatus,
113
118
  lastHealthCheckedAt: state.lastHealthCheckedAt?.toISOString() ?? null,
114
119
  lastHealthLatencyMs: state.lastHealthLatencyMs,
115
- enabledAt: state.enabledAt?.toISOString() ?? null
120
+ enabledAt: state.enabledAt?.toISOString() ?? null,
121
+ updatedAt: state.updatedAt?.toISOString() ?? null
116
122
  },
117
123
  hasCredentials,
124
+ credentialsUpdatedAt: credentialsUpdatedAt?.toISOString() ?? null,
118
125
  healthStatus,
119
126
  analytics
120
127
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/integrations/api/%5Bid%5D/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getBundle, getBundleIntegrations, getIntegration } from '@open-mercato/shared/modules/integrations/types'\nimport { CredentialsEncryptionUnavailableError, type CredentialsService } from '../../lib/credentials-service'\nimport type { IntegrationStateService } from '../../lib/state-service'\nimport type { IntegrationLogService } from '../../lib/log-service'\nimport { deriveIntegrationHealthStatus, getEffectiveHealthCheckConfig } from '../../lib/health-service'\nimport {\n finalizeIntegrationsReadResponse,\n integrationApiRoutePaths,\n runIntegrationsReadBeforeInterceptors,\n} from '../umes-read'\n\nconst idParamsSchema = z.object({ id: z.string().min(1) })\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['integrations.view'] },\n}\n\nexport const openApi = {\n tags: ['Integrations'],\n summary: 'Get integration detail',\n}\n\nexport async function GET(req: Request, ctx: { params?: Promise<{ id?: string }> | { id?: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId || !auth.orgId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const rawParams = (ctx.params && typeof (ctx.params as Promise<unknown>).then === 'function')\n ? await (ctx.params as Promise<{ id?: string }>)\n : (ctx.params as { id?: string } | undefined)\n\n const parsedParams = idParamsSchema.safeParse(rawParams)\n if (!parsedParams.success) {\n return NextResponse.json({ error: 'Invalid integration id' }, { status: 400 })\n }\n\n const integration = getIntegration(parsedParams.data.id)\n if (!integration) {\n return NextResponse.json({ error: 'Integration not found' }, { status: 404 })\n }\n\n const container = await createRequestContainer()\n const beforeInterceptors = await runIntegrationsReadBeforeInterceptors({\n routePath: integrationApiRoutePaths.detail,\n request: req,\n auth,\n container,\n })\n if (!beforeInterceptors.ok) {\n return NextResponse.json(beforeInterceptors.body, { status: beforeInterceptors.statusCode })\n }\n const credentialsService = container.resolve('integrationCredentialsService') as CredentialsService\n const stateService = container.resolve('integrationStateService') as IntegrationStateService\n const logService = container.resolve('integrationLogService') as IntegrationLogService\n const scope = { organizationId: auth.orgId as string, tenantId: auth.tenantId }\n\n const [credentials, state, analyticsMap] = await Promise.all([\n credentialsService.resolve(integration.id, scope).catch((err) => {\n if (err instanceof CredentialsEncryptionUnavailableError) return null\n throw err\n }),\n stateService.resolveState(integration.id, scope),\n logService.aggregateAnalytics([integration.id], scope, 30),\n ])\n\n const hasCredentials = credentials != null && Object.keys(credentials).length > 0\n const healthConfig = getEffectiveHealthCheckConfig(integration.id)\n const hasHealthCheck = Boolean(healthConfig?.service)\n const healthStatus = deriveIntegrationHealthStatus({\n hasHealthCheck,\n hasCredentials,\n lastHealthStatus: state.lastHealthStatus,\n lastHealthCheckedAt: state.lastHealthCheckedAt,\n })\n\n const analytics = analyticsMap.get(integration.id) ?? {\n lastActivityAt: null,\n totalCount: 0,\n errorCount: 0,\n errorRate: 0,\n dailyCounts: Array.from({ length: 30 }, () => 0),\n }\n\n const bundle = integration.bundleId ? getBundle(integration.bundleId) : undefined\n const bundleIntegrations = integration.bundleId\n ? await Promise.all(\n getBundleIntegrations(integration.bundleId).map(async (item) => {\n const resolvedState = await stateService.resolveState(item.id, scope)\n return {\n ...item,\n isEnabled: resolvedState.isEnabled,\n state: {\n isEnabled: resolvedState.isEnabled,\n apiVersion: resolvedState.apiVersion,\n reauthRequired: resolvedState.reauthRequired,\n lastHealthStatus: resolvedState.lastHealthStatus,\n lastHealthCheckedAt: resolvedState.lastHealthCheckedAt?.toISOString() ?? null,\n lastHealthLatencyMs: resolvedState.lastHealthLatencyMs,\n enabledAt: resolvedState.enabledAt?.toISOString() ?? null,\n },\n }\n }),\n )\n : []\n\n return finalizeIntegrationsReadResponse({\n routePath: integrationApiRoutePaths.detail,\n request: req,\n auth,\n container,\n interceptorRequest: beforeInterceptors.request,\n beforeMetadata: beforeInterceptors.metadataByInterceptor,\n enrich: {\n targetEntity: 'integrations.integration',\n recordKeys: ['integration'],\n listKeys: ['bundleIntegrations'],\n },\n body: {\n integration,\n bundle,\n bundleIntegrations,\n state: {\n isEnabled: state.isEnabled,\n apiVersion: state.apiVersion,\n reauthRequired: state.reauthRequired,\n lastHealthStatus: state.lastHealthStatus,\n lastHealthCheckedAt: state.lastHealthCheckedAt?.toISOString() ?? null,\n lastHealthLatencyMs: state.lastHealthLatencyMs,\n enabledAt: state.enabledAt?.toISOString() ?? null,\n },\n hasCredentials,\n healthStatus,\n analytics,\n },\n })\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,WAAW,uBAAuB,sBAAsB;AACjE,SAAS,6CAAsE;AAG/E,SAAS,+BAA+B,qCAAqC;AAC7E;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,iBAAiB,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,CAAC;AAElD,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,mBAAmB,EAAE;AACnE;AAEO,MAAM,UAAU;AAAA,EACrB,MAAM,CAAC,cAAc;AAAA,EACrB,SAAS;AACX;AAEA,eAAsB,IAAI,KAAc,KAA8D;AACpG,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,MAAM,YAAY,CAAC,KAAK,OAAO;AAClC,WAAO,aAAa,KAAK,EAAE,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACrE;AAEA,QAAM,YAAa,IAAI,UAAU,OAAQ,IAAI,OAA4B,SAAS,aAC9E,MAAO,IAAI,SACV,IAAI;AAET,QAAM,eAAe,eAAe,UAAU,SAAS;AACvD,MAAI,CAAC,aAAa,SAAS;AACzB,WAAO,aAAa,KAAK,E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MAAM,qBAAqB,YAAY,KAAK;AAAA,QACjE,qBAAqB,MAAM;AAAA,QAC3B,WAAW,MAAM,WAAW,YAAY,KAAK;AAAA,MAC/C;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF,CAAC;AACH;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getBundle, getBundleIntegrations, getIntegration } from '@open-mercato/shared/modules/integrations/types'\nimport { CredentialsEncryptionUnavailableError, type CredentialsService } from '../../lib/credentials-service'\nimport type { IntegrationStateService } from '../../lib/state-service'\nimport type { IntegrationLogService } from '../../lib/log-service'\nimport { deriveIntegrationHealthStatus, getEffectiveHealthCheckConfig } from '../../lib/health-service'\nimport {\n finalizeIntegrationsReadResponse,\n integrationApiRoutePaths,\n runIntegrationsReadBeforeInterceptors,\n} from '../umes-read'\n\nconst idParamsSchema = z.object({ id: z.string().min(1) })\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['integrations.view'] },\n}\n\nexport const openApi = {\n tags: ['Integrations'],\n summary: 'Get integration detail',\n}\n\nexport async function GET(req: Request, ctx: { params?: Promise<{ id?: string }> | { id?: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId || !auth.orgId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const rawParams = (ctx.params && typeof (ctx.params as Promise<unknown>).then === 'function')\n ? await (ctx.params as Promise<{ id?: string }>)\n : (ctx.params as { id?: string } | undefined)\n\n const parsedParams = idParamsSchema.safeParse(rawParams)\n if (!parsedParams.success) {\n return NextResponse.json({ error: 'Invalid integration id' }, { status: 400 })\n }\n\n const integration = getIntegration(parsedParams.data.id)\n if (!integration) {\n return NextResponse.json({ error: 'Integration not found' }, { status: 404 })\n }\n\n const container = await createRequestContainer()\n const beforeInterceptors = await runIntegrationsReadBeforeInterceptors({\n routePath: integrationApiRoutePaths.detail,\n request: req,\n auth,\n container,\n })\n if (!beforeInterceptors.ok) {\n return NextResponse.json(beforeInterceptors.body, { status: beforeInterceptors.statusCode })\n }\n const credentialsService = container.resolve('integrationCredentialsService') as CredentialsService\n const stateService = container.resolve('integrationStateService') as IntegrationStateService\n const logService = container.resolve('integrationLogService') as IntegrationLogService\n const scope = { organizationId: auth.orgId as string, tenantId: auth.tenantId }\n\n const [credentials, credentialsUpdatedAt, state, analyticsMap] = await Promise.all([\n credentialsService.resolve(integration.id, scope).catch((err) => {\n if (err instanceof CredentialsEncryptionUnavailableError) return null\n throw err\n }),\n credentialsService.resolveUpdatedAt(integration.id, scope).catch((err) => {\n if (err instanceof CredentialsEncryptionUnavailableError) return null\n throw err\n }),\n stateService.resolveState(integration.id, scope),\n logService.aggregateAnalytics([integration.id], scope, 30),\n ])\n\n const hasCredentials = credentials != null && Object.keys(credentials).length > 0\n const healthConfig = getEffectiveHealthCheckConfig(integration.id)\n const hasHealthCheck = Boolean(healthConfig?.service)\n const healthStatus = deriveIntegrationHealthStatus({\n hasHealthCheck,\n hasCredentials,\n lastHealthStatus: state.lastHealthStatus,\n lastHealthCheckedAt: state.lastHealthCheckedAt,\n })\n\n const analytics = analyticsMap.get(integration.id) ?? {\n lastActivityAt: null,\n totalCount: 0,\n errorCount: 0,\n errorRate: 0,\n dailyCounts: Array.from({ length: 30 }, () => 0),\n }\n\n const bundle = integration.bundleId ? getBundle(integration.bundleId) : undefined\n const bundleIntegrations = integration.bundleId\n ? await Promise.all(\n getBundleIntegrations(integration.bundleId).map(async (item) => {\n const resolvedState = await stateService.resolveState(item.id, scope)\n return {\n ...item,\n isEnabled: resolvedState.isEnabled,\n state: {\n isEnabled: resolvedState.isEnabled,\n apiVersion: resolvedState.apiVersion,\n reauthRequired: resolvedState.reauthRequired,\n lastHealthStatus: resolvedState.lastHealthStatus,\n lastHealthCheckedAt: resolvedState.lastHealthCheckedAt?.toISOString() ?? null,\n lastHealthLatencyMs: resolvedState.lastHealthLatencyMs,\n enabledAt: resolvedState.enabledAt?.toISOString() ?? null,\n updatedAt: resolvedState.updatedAt?.toISOString() ?? null,\n },\n }\n }),\n )\n : []\n\n return finalizeIntegrationsReadResponse({\n routePath: integrationApiRoutePaths.detail,\n request: req,\n auth,\n container,\n interceptorRequest: beforeInterceptors.request,\n beforeMetadata: beforeInterceptors.metadataByInterceptor,\n enrich: {\n targetEntity: 'integrations.integration',\n recordKeys: ['integration'],\n listKeys: ['bundleIntegrations'],\n },\n body: {\n integration,\n bundle,\n bundleIntegrations,\n state: {\n isEnabled: state.isEnabled,\n apiVersion: state.apiVersion,\n reauthRequired: state.reauthRequired,\n lastHealthStatus: state.lastHealthStatus,\n lastHealthCheckedAt: state.lastHealthCheckedAt?.toISOString() ?? null,\n lastHealthLatencyMs: state.lastHealthLatencyMs,\n enabledAt: state.enabledAt?.toISOString() ?? null,\n updatedAt: state.updatedAt?.toISOString() ?? null,\n },\n hasCredentials,\n credentialsUpdatedAt: credentialsUpdatedAt?.toISOString() ?? null,\n healthStatus,\n analytics,\n },\n })\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,WAAW,uBAAuB,sBAAsB;AACjE,SAAS,6CAAsE;AAG/E,SAAS,+BAA+B,qCAAqC;AAC7E;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,iBAAiB,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,CAAC;AAElD,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,mBAAmB,EAAE;AACnE;AAEO,MAAM,UAAU;AAAA,EACrB,MAAM,CAAC,cAAc;AAAA,EACrB,SAAS;AACX;AAEA,eAAsB,IAAI,KAAc,KAA8D;AACpG,QAAM,OAAO,MAAM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AAK;AAAA,QACvD;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH,IACE,CAAC;AAEL,SAAO,iCAAiC;AAAA,IACtC,WAAW,yBAAyB;AAAA,IACpC,SAAS;AAAA,IACT;AAAA,IACA;AAAA,IACA,oBAAoB,mBAAmB;AAAA,IACvC,gBAAgB,mBAAmB;AAAA,IACnC,QAAQ;AAAA,MACN,cAAc;AAAA,MACd,YAAY,CAAC,aAAa;AAAA,MAC1B,UAAU,CAAC,oBAAoB;AAAA,IACjC;AAAA,IACA,MAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA;AAAA,MACA,OAAO;AAAA,QACL,WAAW,MAAM;AAAA,QACjB,YAAY,MAAM;AAAA,QAClB,gBAAgB,MAAM;AAAA,QACtB,kBAAkB,MAAM;AAAA,QACxB,qBAAqB,MAAM,qBAAqB,YAAY,KAAK;AAAA,QACjE,qBAAqB,MAAM;AAAA,QAC3B,WAAW,MAAM,WAAW,YAAY,KAAK;AAAA,QAC7C,WAAW,MAAM,WAAW,YAAY,KAAK;AAAA,MAC/C;AAAA,MACA;AAAA,MACA,sBAAsB,sBAAsB,YAAY,KAAK;AAAA,MAC7D;AAAA,MACA;AAAA,IACF;AAAA,EACF,CAAC;AACH;",
6
6
  "names": []
7
7
  }
@@ -3,6 +3,8 @@ import { z } from "zod";
3
3
  import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
4
4
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
5
5
  import { getIntegration } from "@open-mercato/shared/modules/integrations/types";
6
+ import { enforceCommandOptimisticLock } from "@open-mercato/shared/lib/crud/optimistic-lock-command";
7
+ import { isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
6
8
  import { emitIntegrationsEvent } from "../../../events.js";
7
9
  import { updateStateSchema } from "../../../data/validators.js";
8
10
  import {
@@ -66,16 +68,28 @@ async function PUT(req, ctx) {
66
68
  payloadData = reparsed.data;
67
69
  }
68
70
  const stateService = container.resolve("integrationStateService");
71
+ const stateScope = { organizationId: auth.orgId, tenantId: auth.tenantId };
72
+ try {
73
+ const current = await stateService.resolveState(integration.id, stateScope);
74
+ enforceCommandOptimisticLock({
75
+ resourceKind: "integrations.integration",
76
+ resourceId: integration.id,
77
+ current: current.updatedAt,
78
+ request: req
79
+ });
80
+ } catch (error) {
81
+ if (isCrudHttpError(error)) {
82
+ return NextResponse.json(error.body, { status: error.status });
83
+ }
84
+ throw error;
85
+ }
69
86
  const state = await stateService.upsert(
70
87
  integration.id,
71
88
  {
72
89
  isEnabled: payloadData.isEnabled,
73
90
  reauthRequired: payloadData.reauthRequired
74
91
  },
75
- {
76
- organizationId: auth.orgId,
77
- tenantId: auth.tenantId
78
- }
92
+ stateScope
79
93
  );
80
94
  await emitIntegrationsEvent("integrations.state.updated", {
81
95
  integrationId: integration.id,
@@ -98,7 +112,8 @@ async function PUT(req, ctx) {
98
112
  return NextResponse.json({
99
113
  isEnabled: state.isEnabled,
100
114
  reauthRequired: state.reauthRequired,
101
- apiVersion: state.apiVersion ?? null
115
+ apiVersion: state.apiVersion ?? null,
116
+ updatedAt: state.updatedAt?.toISOString() ?? null
102
117
  });
103
118
  }
104
119
  export {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/modules/integrations/api/%5Bid%5D/state/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getIntegration } from '@open-mercato/shared/modules/integrations/types'\nimport { emitIntegrationsEvent } from '../../../events'\nimport { updateStateSchema } from '../../../data/validators'\nimport type { IntegrationStateService } from '../../../lib/state-service'\nimport {\n resolveUserFeatures,\n runIntegrationMutationGuardAfterSuccess,\n runIntegrationMutationGuards,\n} from '../../guards'\n\nconst idParamsSchema = z.object({ id: z.string().min(1) })\n\nexport const metadata = {\n PUT: { requireAuth: true, requireFeatures: ['integrations.manage'] },\n}\n\nexport const openApi = {\n tags: ['Integrations'],\n summary: 'Update integration state',\n}\n\nexport async function PUT(req: Request, ctx: { params?: Promise<{ id?: string }> | { id?: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId || !auth.orgId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const rawParams = (ctx.params && typeof (ctx.params as Promise<unknown>).then === 'function')\n ? await (ctx.params as Promise<{ id?: string }>)\n : (ctx.params as { id?: string } | undefined)\n\n const parsedParams = idParamsSchema.safeParse(rawParams)\n if (!parsedParams.success) {\n return NextResponse.json({ error: 'Invalid integration id' }, { status: 400 })\n }\n\n const integration = getIntegration(parsedParams.data.id)\n if (!integration) {\n return NextResponse.json({ error: 'Integration not found' }, { status: 404 })\n }\n\n const payload = await req.json().catch(() => null)\n const parsedBody = updateStateSchema.safeParse(payload)\n if (!parsedBody.success) {\n return NextResponse.json({ error: 'Invalid state payload', details: parsedBody.error.flatten() }, { status: 422 })\n }\n\n const container = await createRequestContainer()\n const guardResult = await runIntegrationMutationGuards(\n container,\n {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n userId: auth.sub ?? '',\n resourceKind: 'integrations.integration',\n resourceId: integration.id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: parsedBody.data as Record<string, unknown>,\n },\n resolveUserFeatures(auth),\n )\n if (!guardResult.ok) {\n return NextResponse.json(guardResult.errorBody ?? { error: 'Operation blocked by guard' }, { status: guardResult.errorStatus ?? 422 })\n }\n\n let payloadData = parsedBody.data\n if (guardResult.modifiedPayload) {\n const mergedPayload = { ...parsedBody.data, ...guardResult.modifiedPayload }\n const reparsed = updateStateSchema.safeParse(mergedPayload)\n if (!reparsed.success) {\n return NextResponse.json({ error: 'Invalid state payload after guard transform', details: reparsed.error.flatten() }, { status: 422 })\n }\n payloadData = reparsed.data\n }\n\n const stateService = container.resolve('integrationStateService') as IntegrationStateService\n\n const state = await stateService.upsert(\n integration.id,\n {\n isEnabled: payloadData.isEnabled,\n reauthRequired: payloadData.reauthRequired,\n },\n {\n organizationId: auth.orgId as string,\n tenantId: auth.tenantId,\n },\n )\n\n await emitIntegrationsEvent('integrations.state.updated', {\n integrationId: integration.id,\n isEnabled: state.isEnabled,\n reauthRequired: state.reauthRequired,\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n userId: auth.sub,\n })\n\n await runIntegrationMutationGuardAfterSuccess(guardResult.afterSuccessCallbacks, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n userId: auth.sub ?? '',\n resourceKind: 'integrations.integration',\n resourceId: integration.id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n })\n\n return NextResponse.json({\n isEnabled: state.isEnabled,\n reauthRequired: state.reauthRequired,\n apiVersion: state.apiVersion ?? null,\n })\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,sBAAsB;AAC/B,SAAS,6BAA6B;AACtC,SAAS,yBAAyB;AAElC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,iBAAiB,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,CAAC;AAElD,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,qBAAqB,EAAE;AACrE;AAEO,MAAM,UAAU;AAAA,EACrB,MAAM,CAAC,cAAc;AAAA,EACrB,SAAS;AACX;AAEA,eAAsB,IAAI,KAAc,KAA8D;AACpG,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,MAAM,YAAY,CAAC,KAAK,OAAO;AAClC,WAAO,aAAa,KAAK,EAAE,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACrE;AAEA,QAAM,YAAa,IAAI,UAAU,OAAQ,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BAAkB,UAAU,aAAa;AAC1D,QAAI,CAAC,SAAS,SAAS;AACrB,aAAO,aAAa,KAAK,EAAE,OAAO,+CAA+C,SAAS,SAAS,MAAM,QAAQ,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IACvI;AACA,kBAAc,SAAS;AAAA,EACzB;AAEA,QAAM,eAAe,UAAU,QAAQ,yBAAyB;AAEhE,QAAM,QAAQ,MAAM,aAAa;AAAA,IAC/B,YAAY;AAAA,IACZ;AAAA,MACE,WAAW,YAAY;AAAA,MACvB,gBAAgB,YAAY;AAAA,IAC9B;AAAA,IACA;AAAA,MACE,gBAAgB,KAAK;AAAA,MACrB,UAAU,KAAK;AAAA,IACjB;AAAA,EACF;AAEA,QAAM,sBAAsB,8BAA8B;AAAA,IACxD,eAAe,YAAY;AAAA,IAC3B,WAAW,MAAM;AAAA,IACjB,gBAAgB,MAAM;AAAA,IACtB,UAAU,KAAK;AAAA,IACf,gBAAgB,KAAK;AAAA,IACrB,QAAQ,KAAK;AAAA,EACf,CAAC;AAED,QAAM,wCAAwC,YAAY,uBAAuB;AAAA,IAC7E,UAAU,KAAK;AAAA,IACf,gBAAgB,KAAK;AAAA,IACrB,QAAQ,KAAK,OAAO;AAAA,IACpB,cAAc;AAAA,IACd,YAAY,YAAY;AAAA,IACxB,WAAW;AAAA,IACX,eAAe,IAAI;AAAA,IACnB,gBAAgB,IAAI;AAAA,EACtB,CAAC;AAEH,SAAO,aAAa,KAAK;AAAA,IACvB,WAAW,MAAM;AAAA,IACjB,gBAAgB,MAAM;AAAA,IACtB,YAAY,MAAM,cAAc;AAAA,EAClC,CAAC;AACH;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getIntegration } from '@open-mercato/shared/modules/integrations/types'\nimport { enforceCommandOptimisticLock } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { emitIntegrationsEvent } from '../../../events'\nimport { updateStateSchema } from '../../../data/validators'\nimport type { IntegrationStateService } from '../../../lib/state-service'\nimport {\n resolveUserFeatures,\n runIntegrationMutationGuardAfterSuccess,\n runIntegrationMutationGuards,\n} from '../../guards'\n\nconst idParamsSchema = z.object({ id: z.string().min(1) })\n\nexport const metadata = {\n PUT: { requireAuth: true, requireFeatures: ['integrations.manage'] },\n}\n\nexport const openApi = {\n tags: ['Integrations'],\n summary: 'Update integration state',\n}\n\nexport async function PUT(req: Request, ctx: { params?: Promise<{ id?: string }> | { id?: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId || !auth.orgId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const rawParams = (ctx.params && typeof (ctx.params as Promise<unknown>).then === 'function')\n ? await (ctx.params as Promise<{ id?: string }>)\n : (ctx.params as { id?: string } | undefined)\n\n const parsedParams = idParamsSchema.safeParse(rawParams)\n if (!parsedParams.success) {\n return NextResponse.json({ error: 'Invalid integration id' }, { status: 400 })\n }\n\n const integration = getIntegration(parsedParams.data.id)\n if (!integration) {\n return NextResponse.json({ error: 'Integration not found' }, { status: 404 })\n }\n\n const payload = await req.json().catch(() => null)\n const parsedBody = updateStateSchema.safeParse(payload)\n if (!parsedBody.success) {\n return NextResponse.json({ error: 'Invalid state payload', details: parsedBody.error.flatten() }, { status: 422 })\n }\n\n const container = await createRequestContainer()\n const guardResult = await runIntegrationMutationGuards(\n container,\n {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n userId: auth.sub ?? '',\n resourceKind: 'integrations.integration',\n resourceId: integration.id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: parsedBody.data as Record<string, unknown>,\n },\n resolveUserFeatures(auth),\n )\n if (!guardResult.ok) {\n return NextResponse.json(guardResult.errorBody ?? { error: 'Operation blocked by guard' }, { status: guardResult.errorStatus ?? 422 })\n }\n\n let payloadData = parsedBody.data\n if (guardResult.modifiedPayload) {\n const mergedPayload = { ...parsedBody.data, ...guardResult.modifiedPayload }\n const reparsed = updateStateSchema.safeParse(mergedPayload)\n if (!reparsed.success) {\n return NextResponse.json({ error: 'Invalid state payload after guard transform', details: reparsed.error.flatten() }, { status: 422 })\n }\n payloadData = reparsed.data\n }\n\n const stateService = container.resolve('integrationStateService') as IntegrationStateService\n const stateScope = { organizationId: auth.orgId as string, tenantId: auth.tenantId }\n\n try {\n const current = await stateService.resolveState(integration.id, stateScope)\n enforceCommandOptimisticLock({\n resourceKind: 'integrations.integration',\n resourceId: integration.id,\n current: current.updatedAt,\n request: req,\n })\n } catch (error) {\n if (isCrudHttpError(error)) {\n return NextResponse.json(error.body, { status: error.status })\n }\n throw error\n }\n\n const state = await stateService.upsert(\n integration.id,\n {\n isEnabled: payloadData.isEnabled,\n reauthRequired: payloadData.reauthRequired,\n },\n stateScope,\n )\n\n await emitIntegrationsEvent('integrations.state.updated', {\n integrationId: integration.id,\n isEnabled: state.isEnabled,\n reauthRequired: state.reauthRequired,\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n userId: auth.sub,\n })\n\n await runIntegrationMutationGuardAfterSuccess(guardResult.afterSuccessCallbacks, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n userId: auth.sub ?? '',\n resourceKind: 'integrations.integration',\n resourceId: integration.id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n })\n\n return NextResponse.json({\n isEnabled: state.isEnabled,\n reauthRequired: state.reauthRequired,\n apiVersion: state.apiVersion ?? null,\n updatedAt: state.updatedAt?.toISOString() ?? null,\n })\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,sBAAsB;AAC/B,SAAS,oCAAoC;AAC7C,SAAS,uBAAuB;AAChC,SAAS,6BA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,aAAa;AAAA,IAC/B,YAAY;AAAA,IACZ;AAAA,MACE,WAAW,YAAY;AAAA,MACvB,gBAAgB,YAAY;AAAA,IAC9B;AAAA,IACA;AAAA,EACF;AAEA,QAAM,sBAAsB,8BAA8B;AAAA,IACxD,eAAe,YAAY;AAAA,IAC3B,WAAW,MAAM;AAAA,IACjB,gBAAgB,MAAM;AAAA,IACtB,UAAU,KAAK;AAAA,IACf,gBAAgB,KAAK;AAAA,IACrB,QAAQ,KAAK;AAAA,EACf,CAAC;AAED,QAAM,wCAAwC,YAAY,uBAAuB;AAAA,IAC7E,UAAU,KAAK;AAAA,IACf,gBAAgB,KAAK;AAAA,IACrB,QAAQ,KAAK,OAAO;AAAA,IACpB,cAAc;AAAA,IACd,YAAY,YAAY;AAAA,IACxB,WAAW;AAAA,IACX,eAAe,IAAI;AAAA,IACnB,gBAAgB,IAAI;AAAA,EACtB,CAAC;AAEH,SAAO,aAAa,KAAK;AAAA,IACvB,WAAW,MAAM;AAAA,IACjB,gBAAgB,MAAM;AAAA,IACtB,YAAY,MAAM,cAAc;AAAA,IAChC,WAAW,MAAM,WAAW,YAAY,KAAK;AAAA,EAC/C,CAAC;AACH;",
6
6
  "names": []
7
7
  }
@@ -3,6 +3,8 @@ import { z } from "zod";
3
3
  import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
4
4
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
5
5
  import { getIntegration } from "@open-mercato/shared/modules/integrations/types";
6
+ import { enforceCommandOptimisticLock } from "@open-mercato/shared/lib/crud/optimistic-lock-command";
7
+ import { isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
6
8
  import { emitIntegrationsEvent } from "../../../events.js";
7
9
  import { updateVersionSchema } from "../../../data/validators.js";
8
10
  import { resolveDefaultApiVersion } from "../../../lib/registry-service.js";
@@ -84,7 +86,21 @@ async function PUT(req, ctx) {
84
86
  }
85
87
  const stateService = container.resolve("integrationStateService");
86
88
  const scope = { organizationId: auth.orgId, tenantId: auth.tenantId };
87
- const before = await stateService.resolveApiVersion(integration.id, scope);
89
+ const currentState = await stateService.resolveState(integration.id, scope);
90
+ try {
91
+ enforceCommandOptimisticLock({
92
+ resourceKind: "integrations.integration",
93
+ resourceId: integration.id,
94
+ current: currentState.updatedAt,
95
+ request: req
96
+ });
97
+ } catch (error) {
98
+ if (isCrudHttpError(error)) {
99
+ return NextResponse.json(error.body, { status: error.status });
100
+ }
101
+ throw error;
102
+ }
103
+ const before = currentState.apiVersion;
88
104
  await stateService.upsert(integration.id, { apiVersion: payloadData.apiVersion }, scope);
89
105
  await emitIntegrationsEvent("integrations.version.changed", {
90
106
  integrationId: integration.id,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/modules/integrations/api/%5Bid%5D/version/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getIntegration } from '@open-mercato/shared/modules/integrations/types'\nimport { emitIntegrationsEvent } from '../../../events'\nimport { updateVersionSchema } from '../../../data/validators'\nimport type { IntegrationStateService } from '../../../lib/state-service'\nimport { resolveDefaultApiVersion } from '../../../lib/registry-service'\nimport {\n resolveUserFeatures,\n runIntegrationMutationGuardAfterSuccess,\n runIntegrationMutationGuards,\n} from '../../guards'\n\nconst idParamsSchema = z.object({ id: z.string().min(1) })\n\nexport const metadata = {\n PUT: { requireAuth: true, requireFeatures: ['integrations.manage'] },\n}\n\nexport const openApi = {\n tags: ['Integrations'],\n summary: 'Change integration API version',\n}\n\nexport async function PUT(req: Request, ctx: { params?: Promise<{ id?: string }> | { id?: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId || !auth.orgId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const rawParams = (ctx.params && typeof (ctx.params as Promise<unknown>).then === 'function')\n ? await (ctx.params as Promise<{ id?: string }>)\n : (ctx.params as { id?: string } | undefined)\n\n const parsedParams = idParamsSchema.safeParse(rawParams)\n if (!parsedParams.success) {\n return NextResponse.json({ error: 'Invalid integration id' }, { status: 400 })\n }\n\n const integration = getIntegration(parsedParams.data.id)\n if (!integration) {\n return NextResponse.json({ error: 'Integration not found' }, { status: 404 })\n }\n\n const payload = await req.json().catch(() => null)\n const parsedBody = updateVersionSchema.safeParse(payload)\n if (!parsedBody.success) {\n return NextResponse.json({ error: 'Invalid payload', details: parsedBody.error.flatten() }, { status: 422 })\n }\n\n const requestedVersion = parsedBody.data.apiVersion\n const availableVersions = integration.apiVersions ?? []\n if (availableVersions.length === 0) {\n return NextResponse.json({ error: 'This integration is not versioned' }, { status: 422 })\n }\n\n const exists = availableVersions.some((version) => version.id === requestedVersion)\n if (!exists) {\n return NextResponse.json({ error: 'Unknown integration version' }, { status: 422 })\n }\n\n const defaultVersion = resolveDefaultApiVersion(availableVersions)\n if (!defaultVersion) {\n return NextResponse.json({ error: 'Integration version configuration is invalid' }, { status: 422 })\n }\n\n const container = await createRequestContainer()\n const guardResult = await runIntegrationMutationGuards(\n container,\n {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n userId: auth.sub ?? '',\n resourceKind: 'integrations.integration',\n resourceId: integration.id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: parsedBody.data as Record<string, unknown>,\n },\n resolveUserFeatures(auth),\n )\n if (!guardResult.ok) {\n return NextResponse.json(guardResult.errorBody ?? { error: 'Operation blocked by guard' }, { status: guardResult.errorStatus ?? 422 })\n }\n\n let payloadData = parsedBody.data\n if (guardResult.modifiedPayload) {\n const mergedPayload = { ...parsedBody.data, ...guardResult.modifiedPayload }\n const reparsed = updateVersionSchema.safeParse(mergedPayload)\n if (!reparsed.success) {\n return NextResponse.json({ error: 'Invalid payload after guard transform', details: reparsed.error.flatten() }, { status: 422 })\n }\n payloadData = reparsed.data\n }\n if (!availableVersions.some((version) => version.id === payloadData.apiVersion)) {\n return NextResponse.json({ error: 'Unknown integration version' }, { status: 422 })\n }\n\n const stateService = container.resolve('integrationStateService') as IntegrationStateService\n const scope = { organizationId: auth.orgId as string, tenantId: auth.tenantId }\n\n const before = await stateService.resolveApiVersion(integration.id, scope)\n await stateService.upsert(integration.id, { apiVersion: payloadData.apiVersion }, scope)\n\n await emitIntegrationsEvent('integrations.version.changed', {\n integrationId: integration.id,\n previousVersion: before ?? defaultVersion,\n apiVersion: payloadData.apiVersion,\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n userId: auth.sub,\n })\n\n await runIntegrationMutationGuardAfterSuccess(guardResult.afterSuccessCallbacks, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n userId: auth.sub ?? '',\n resourceKind: 'integrations.integration',\n resourceId: integration.id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n })\n\n return NextResponse.json({\n apiVersion: payloadData.apiVersion,\n previousVersion: before ?? defaultVersion,\n })\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,sBAAsB;AAC/B,SAAS,6BAA6B;AACtC,SAAS,2BAA2B;AAEpC,SAAS,gCAAgC;AACzC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,iBAAiB,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,CAAC;AAElD,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,qBAAqB,EAAE;AACrE;AAEO,MAAM,UAAU;AAAA,EACrB,MAAM,CAAC,cAAc;AAAA,EACrB,SAAS;AACX;AAEA,eAAsB,IAAI,KAAc,KAA8D;AACpG,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,MAAM,YAAY,CAAC,KAAK,OAAO;AACl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G,KAAK;AAEvF,QAAM,sBAAsB,gCAAgC;AAAA,IAC1D,eAAe,YAAY;AAAA,IAC3B,iBAAiB,UAAU;AAAA,IAC3B,YAAY,YAAY;AAAA,IACxB,UAAU,KAAK;AAAA,IACf,gBAAgB,KAAK;AAAA,IACrB,QAAQ,KAAK;AAAA,EACf,CAAC;AAED,QAAM,wCAAwC,YAAY,uBAAuB;AAAA,IAC/E,UAAU,KAAK;AAAA,IACf,gBAAgB,KAAK;AAAA,IACrB,QAAQ,KAAK,OAAO;AAAA,IACpB,cAAc;AAAA,IACd,YAAY,YAAY;AAAA,IACxB,WAAW;AAAA,IACX,eAAe,IAAI;AAAA,IACnB,gBAAgB,IAAI;AAAA,EACtB,CAAC;AAED,SAAO,aAAa,KAAK;AAAA,IACvB,YAAY,YAAY;AAAA,IACxB,iBAAiB,UAAU;AAAA,EAC7B,CAAC;AACH;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getIntegration } from '@open-mercato/shared/modules/integrations/types'\nimport { enforceCommandOptimisticLock } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { emitIntegrationsEvent } from '../../../events'\nimport { updateVersionSchema } from '../../../data/validators'\nimport type { IntegrationStateService } from '../../../lib/state-service'\nimport { resolveDefaultApiVersion } from '../../../lib/registry-service'\nimport {\n resolveUserFeatures,\n runIntegrationMutationGuardAfterSuccess,\n runIntegrationMutationGuards,\n} from '../../guards'\n\nconst idParamsSchema = z.object({ id: z.string().min(1) })\n\nexport const metadata = {\n PUT: { requireAuth: true, requireFeatures: ['integrations.manage'] },\n}\n\nexport const openApi = {\n tags: ['Integrations'],\n summary: 'Change integration API version',\n}\n\nexport async function PUT(req: Request, ctx: { params?: Promise<{ id?: string }> | { id?: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId || !auth.orgId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const rawParams = (ctx.params && typeof (ctx.params as Promise<unknown>).then === 'function')\n ? await (ctx.params as Promise<{ id?: string }>)\n : (ctx.params as { id?: string } | undefined)\n\n const parsedParams = idParamsSchema.safeParse(rawParams)\n if (!parsedParams.success) {\n return NextResponse.json({ error: 'Invalid integration id' }, { status: 400 })\n }\n\n const integration = getIntegration(parsedParams.data.id)\n if (!integration) {\n return NextResponse.json({ error: 'Integration not found' }, { status: 404 })\n }\n\n const payload = await req.json().catch(() => null)\n const parsedBody = updateVersionSchema.safeParse(payload)\n if (!parsedBody.success) {\n return NextResponse.json({ error: 'Invalid payload', details: parsedBody.error.flatten() }, { status: 422 })\n }\n\n const requestedVersion = parsedBody.data.apiVersion\n const availableVersions = integration.apiVersions ?? []\n if (availableVersions.length === 0) {\n return NextResponse.json({ error: 'This integration is not versioned' }, { status: 422 })\n }\n\n const exists = availableVersions.some((version) => version.id === requestedVersion)\n if (!exists) {\n return NextResponse.json({ error: 'Unknown integration version' }, { status: 422 })\n }\n\n const defaultVersion = resolveDefaultApiVersion(availableVersions)\n if (!defaultVersion) {\n return NextResponse.json({ error: 'Integration version configuration is invalid' }, { status: 422 })\n }\n\n const container = await createRequestContainer()\n const guardResult = await runIntegrationMutationGuards(\n container,\n {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n userId: auth.sub ?? '',\n resourceKind: 'integrations.integration',\n resourceId: integration.id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: parsedBody.data as Record<string, unknown>,\n },\n resolveUserFeatures(auth),\n )\n if (!guardResult.ok) {\n return NextResponse.json(guardResult.errorBody ?? { error: 'Operation blocked by guard' }, { status: guardResult.errorStatus ?? 422 })\n }\n\n let payloadData = parsedBody.data\n if (guardResult.modifiedPayload) {\n const mergedPayload = { ...parsedBody.data, ...guardResult.modifiedPayload }\n const reparsed = updateVersionSchema.safeParse(mergedPayload)\n if (!reparsed.success) {\n return NextResponse.json({ error: 'Invalid payload after guard transform', details: reparsed.error.flatten() }, { status: 422 })\n }\n payloadData = reparsed.data\n }\n if (!availableVersions.some((version) => version.id === payloadData.apiVersion)) {\n return NextResponse.json({ error: 'Unknown integration version' }, { status: 422 })\n }\n\n const stateService = container.resolve('integrationStateService') as IntegrationStateService\n const scope = { organizationId: auth.orgId as string, tenantId: auth.tenantId }\n\n const currentState = await stateService.resolveState(integration.id, scope)\n try {\n enforceCommandOptimisticLock({\n resourceKind: 'integrations.integration',\n resourceId: integration.id,\n current: currentState.updatedAt,\n request: req,\n })\n } catch (error) {\n if (isCrudHttpError(error)) {\n return NextResponse.json(error.body, { status: error.status })\n }\n throw error\n }\n\n const before = currentState.apiVersion\n await stateService.upsert(integration.id, { apiVersion: payloadData.apiVersion }, scope)\n\n await emitIntegrationsEvent('integrations.version.changed', {\n integrationId: integration.id,\n previousVersion: before ?? defaultVersion,\n apiVersion: payloadData.apiVersion,\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n userId: auth.sub,\n })\n\n await runIntegrationMutationGuardAfterSuccess(guardResult.afterSuccessCallbacks, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n userId: auth.sub ?? '',\n resourceKind: 'integrations.integration',\n resourceId: integration.id,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n })\n\n return NextResponse.json({\n apiVersion: payloadData.apiVersion,\n previousVersion: before ?? defaultVersion,\n })\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,sBAAsB;AAC/B,SAAS,oCAAoC;AAC7C,SAAS,uBAAuB;AAChC,SAAS,6BAA6B;AACtC,SAAS,2BAA2B;AAEpC,SAAS,gCAAgC;AACzC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,iB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