@open-mercato/core 0.6.6-develop.6228.1.cf483c68b5 → 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
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../../src/modules/integrations/backend/integrations/bundle/%5Bid%5D/page.tsx"],
4
- "sourcesContent": ["\"use client\"\nimport * as React from 'react'\nimport Link from 'next/link'\nimport { usePathname } from 'next/navigation'\nimport { Page, PageBody } from '@open-mercato/ui/backend/Page'\nimport { Card, CardHeader, CardTitle, CardContent } from '@open-mercato/ui/primitives/card'\nimport { Badge } from '@open-mercato/ui/primitives/badge'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { Switch } from '@open-mercato/ui/primitives/switch'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from '@open-mercato/ui/primitives/select'\nimport { Spinner } from '@open-mercato/ui/primitives/spinner'\nimport { apiCall, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport type { CredentialFieldType, IntegrationCredentialField } from '@open-mercato/shared/modules/integrations/types'\nimport { LoadingMessage, ErrorMessage, RecordNotFoundState } from '@open-mercato/ui/backend/detail'\n\ntype CredentialField = IntegrationCredentialField\n\nconst UNSUPPORTED_CREDENTIAL_FIELD_TYPES = new Set<CredentialFieldType>(['oauth', 'ssh_keypair'])\n\nfunction isEditableCredentialField(field: CredentialField): boolean {\n return !UNSUPPORTED_CREDENTIAL_FIELD_TYPES.has(field.type)\n}\n\ntype BundleIntegration = {\n id: string\n title: string\n description?: string\n category?: string\n isEnabled: boolean\n}\n\ntype BundleDetail = {\n integration: {\n id: string\n title: string\n description?: string\n bundleId?: string\n }\n bundle?: {\n id: string\n title: string\n description?: string\n credentials?: { fields: CredentialField[] }\n }\n bundleIntegrations: BundleIntegration[]\n state: { isEnabled: boolean }\n hasCredentials: boolean\n}\n\ntype BundleConfigPageProps = {\n params?: {\n id?: string | string[]\n }\n}\n\nfunction resolveRouteId(value: string | string[] | undefined): string | undefined {\n if (Array.isArray(value)) return value[0]\n return value\n}\n\nfunction resolvePathnameId(pathname: string): string | undefined {\n const parts = pathname.split('/').filter(Boolean)\n const bundleId = parts.at(-1)\n if (!bundleId || bundleId === 'bundle' || bundleId === 'integrations') return undefined\n return decodeURIComponent(bundleId)\n}\n\nexport default function BundleConfigPage({ params }: BundleConfigPageProps) {\n const pathname = usePathname()\n const bundleId = resolveRouteId(params?.id) ?? resolvePathnameId(pathname)\n const t = useT()\n\n const [detail, setDetail] = React.useState<BundleDetail | null>(null)\n const [isLoading, setIsLoading] = React.useState(true)\n const [error, setError] = React.useState<string | null>(null)\n const [isNotFound, setIsNotFound] = React.useState(false)\n const [credValues, setCredValues] = React.useState<Record<string, unknown>>({})\n const [isSavingCreds, setIsSavingCreds] = React.useState(false)\n const [togglingIds, setTogglingIds] = React.useState<Set<string>>(new Set())\n\n const mutationContextId = React.useMemo(\n () => `integrations.bundle:${bundleId ?? 'unknown'}`,\n [bundleId],\n )\n const { runMutation, retryLastMutation } = useGuardedMutation<Record<string, unknown>>({\n contextId: mutationContextId,\n })\n\n const resolveCurrentBundleId = React.useCallback(() => {\n return bundleId ?? (\n typeof window !== 'undefined'\n ? resolvePathnameId(window.location.pathname)\n : undefined\n )\n }, [bundleId])\n\n const load = React.useCallback(async () => {\n const currentBundleId = resolveCurrentBundleId()\n if (!currentBundleId) {\n setError(t('integrations.detail.loadError'))\n setIsLoading(false)\n return\n }\n setIsLoading(true)\n setError(null)\n setIsNotFound(false)\n const call = await apiCall<BundleDetail>(\n `/api/integrations/${encodeURIComponent(currentBundleId)}`,\n undefined,\n { fallback: null },\n )\n if (!call.ok || !call.result) {\n if (call.status === 404) {\n setIsNotFound(true)\n } else {\n setError(t('integrations.detail.loadError'))\n }\n setIsLoading(false)\n return\n }\n setDetail(call.result)\n\n const credCall = await apiCall<{ credentials: Record<string, unknown> }>(\n `/api/integrations/${encodeURIComponent(currentBundleId)}/credentials`,\n undefined,\n { fallback: null },\n )\n if (credCall.ok && credCall.result?.credentials) {\n const next = { ...credCall.result.credentials }\n if (currentBundleId === 'storage_s3') {\n const authMode = next.authMode\n if (authMode !== 'access_keys' && authMode !== 'ambient') {\n const hasKeys = Boolean(next.accessKeyId || next.secretAccessKey)\n next.authMode = hasKeys ? 'access_keys' : 'ambient'\n }\n }\n setCredValues(next)\n }\n setIsLoading(false)\n }, [resolveCurrentBundleId, t])\n\n React.useEffect(() => { void load() }, [load])\n\n const handleSaveCredentials = React.useCallback(async () => {\n const currentBundleId = resolveCurrentBundleId()\n if (!currentBundleId) return\n setIsSavingCreds(true)\n try {\n const call = await runMutation({\n mutationPayload: { bundleId: currentBundleId, credentials: credValues },\n context: {\n formId: mutationContextId,\n operation: 'update',\n actionId: 'save-credentials',\n resourceKind: 'integrations.bundle',\n resourceId: currentBundleId,\n bundleId: currentBundleId,\n retryLastMutation,\n },\n // TODO(#2373-B): thread updatedAt \u2014 integration detail/state response does not expose a record version yet\n operation: () => withScopedApiRequestHeaders(\n buildOptimisticLockHeader(undefined),\n () => apiCall(`/api/integrations/${encodeURIComponent(currentBundleId)}/credentials`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ credentials: credValues }),\n }, { fallback: null }),\n ),\n })\n if (call.ok) {\n flash(t('integrations.detail.credentials.saved'), 'success')\n } else {\n flash(t('integrations.detail.credentials.saveError'), 'error')\n }\n } catch {\n flash(t('integrations.detail.credentials.saveError'), 'error')\n } finally {\n setIsSavingCreds(false)\n }\n }, [resolveCurrentBundleId, runMutation, mutationContextId, retryLastMutation, credValues, t])\n\n const handleToggle = React.useCallback(async (integrationId: string, enabled: boolean) => {\n setTogglingIds((prev) => new Set(prev).add(integrationId))\n try {\n const call = await runMutation({\n mutationPayload: { integrationId, isEnabled: enabled },\n context: {\n formId: mutationContextId,\n operation: 'update',\n actionId: 'toggle-state',\n resourceKind: 'integrations.integration',\n resourceId: integrationId,\n integrationId,\n retryLastMutation,\n },\n // TODO(#2373-B): thread updatedAt \u2014 integration detail/state response does not expose a record version yet\n operation: () => withScopedApiRequestHeaders(\n buildOptimisticLockHeader(undefined),\n () => apiCall(`/api/integrations/${encodeURIComponent(integrationId)}/state`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ isEnabled: enabled }),\n }, { fallback: null }),\n ),\n })\n if (call.ok) {\n setDetail((prev) => {\n if (!prev) return prev\n return {\n ...prev,\n bundleIntegrations: prev.bundleIntegrations.map((item) =>\n item.id === integrationId ? { ...item, isEnabled: enabled } : item,\n ),\n }\n })\n } else {\n flash(t('integrations.detail.stateError'), 'error')\n }\n } catch {\n flash(t('integrations.detail.stateError'), 'error')\n } finally {\n setTogglingIds((prev) => { const next = new Set(prev); next.delete(integrationId); return next })\n }\n }, [runMutation, mutationContextId, retryLastMutation, t])\n\n const handleBulkToggle = React.useCallback(async (enabled: boolean) => {\n if (!detail) return\n const targets = detail.bundleIntegrations.filter((item) => item.isEnabled !== enabled)\n await Promise.all(targets.map((item) => handleToggle(item.id, enabled)))\n }, [detail, handleToggle])\n\n if (isLoading) return <Page><PageBody><LoadingMessage label={t('integrations.bundle.title')} /></PageBody></Page>\n if (isNotFound) {\n return (\n <Page>\n <PageBody>\n <RecordNotFoundState\n label={t('integrations.detail.notFound', 'Integration not found.')}\n backHref=\"/backend/integrations\"\n backLabel={t('integrations.detail.backToList', 'Back to integrations')}\n />\n </PageBody>\n </Page>\n )\n }\n if (error || !detail?.bundle) return <Page><PageBody><ErrorMessage label={error ?? t('integrations.detail.loadError')} /></PageBody></Page>\n\n const credFields = (detail.bundle.credentials?.fields ?? []).filter(isEditableCredentialField)\n\n function isFieldVisible(field: CredentialField): boolean {\n if (!field.visibleWhen) return true\n return credValues[field.visibleWhen.field] === field.visibleWhen.equals\n }\n\n return (\n <Page>\n <PageBody className=\"space-y-6\">\n <div>\n <Link href=\"/backend/integrations\" className=\"text-sm text-muted-foreground hover:underline\">\n {t('integrations.detail.back')}\n </Link>\n </div>\n\n <div>\n <h1 className=\"text-2xl font-semibold\">{detail.bundle.title}</h1>\n {detail.bundle.description && (\n <p className=\"text-muted-foreground mt-1\">{detail.bundle.description}</p>\n )}\n </div>\n\n {credFields.length > 0 && (\n <Card>\n <CardHeader>\n <CardTitle>{t('integrations.bundle.sharedCredentials')}</CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n {credFields.filter(isFieldVisible).map((field) => (\n <div key={field.key} className=\"space-y-1.5\">\n <label className=\"text-sm font-medium\">\n {field.label}{field.required && <span className=\"text-red-500 ml-0.5\">*</span>}\n </label>\n {field.type === 'select' && field.options ? (\n <Select\n value={(credValues[field.key] as string) || undefined}\n onValueChange={(value) => setCredValues((prev) => ({ ...prev, [field.key]: value ?? '' }))}\n >\n <SelectTrigger>\n <SelectValue placeholder=\"\u2014\" />\n </SelectTrigger>\n <SelectContent>\n {field.options.map((opt) => (\n <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>\n ))}\n </SelectContent>\n </Select>\n ) : field.type === 'boolean' ? (\n <Switch\n checked={Boolean(credValues[field.key])}\n onCheckedChange={(checked) => setCredValues((prev) => ({ ...prev, [field.key]: checked }))}\n />\n ) : (\n <Input\n type={field.type === 'secret' ? 'password' : 'text'}\n placeholder={field.placeholder}\n value={(credValues[field.key] as string) ?? ''}\n onChange={(e) => setCredValues((prev) => ({ ...prev, [field.key]: e.target.value }))}\n />\n )}\n </div>\n ))}\n <Button type=\"button\" onClick={() => void handleSaveCredentials()} disabled={isSavingCreds}>\n {isSavingCreds ? <Spinner className=\"mr-2 h-4 w-4\" /> : null}\n {t('integrations.detail.credentials.save')}\n </Button>\n </CardContent>\n </Card>\n )}\n\n <Card>\n <CardHeader>\n <div className=\"flex items-center justify-between\">\n <CardTitle>{t('integrations.bundle.integrationToggles')}</CardTitle>\n <div className=\"flex gap-2\">\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={() => void handleBulkToggle(true)}>\n {t('integrations.marketplace.enableAll')}\n </Button>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={() => void handleBulkToggle(false)}>\n {t('integrations.marketplace.disableAll')}\n </Button>\n </div>\n </div>\n </CardHeader>\n <CardContent>\n <div className=\"space-y-3\">\n {detail.bundleIntegrations.map((item) => (\n <div key={item.id} className=\"flex items-center justify-between rounded-lg border p-3\">\n <div>\n <Link\n href={`/backend/integrations/${encodeURIComponent(item.id)}`}\n className=\"text-sm font-medium hover:underline\"\n >\n {item.title}\n </Link>\n {item.category && (\n <Badge variant=\"secondary\" className=\"ml-2 text-xs\">{item.category}</Badge>\n )}\n {item.description && (\n <p className=\"text-xs text-muted-foreground mt-0.5\">{item.description}</p>\n )}\n </div>\n <div className=\"flex items-center gap-3\">\n <Button asChild variant=\"ghost\" size=\"sm\">\n <Link href={`/backend/integrations/${encodeURIComponent(item.id)}`}>\n {t('integrations.bundle.configureIntegration')}\n </Link>\n </Button>\n <Switch\n checked={item.isEnabled}\n disabled={togglingIds.has(item.id)}\n onCheckedChange={(checked) => void handleToggle(item.id, checked)}\n />\n </div>\n </div>\n ))}\n </div>\n </CardContent>\n </Card>\n </PageBody>\n </Page>\n )\n}\n"],
5
- "mappings": ";AAkPwC,cAgChC,YAhCgC;AAjPxC,YAAY,WAAW;AACvB,OAAO,UAAU;AACjB,SAAS,mBAAmB;AAC5B,SAAS,MAAM,gBA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AM,yBAAyB,mBAAmB,KAAK,EAAE,CAAC,IAC7D,YAAE,0CAA0C,GAC/C,GACF;AAAA,UACA;AAAA,YAAC;AAAA;AAAA,cACC,SAAS,KAAK;AAAA,cACd,UAAU,YAAY,IAAI,KAAK,EAAE;AAAA,cACjC,iBAAiB,CAAC,YAAY,KAAK,aAAa,KAAK,IAAI,OAAO;AAAA;AAAA,UAClE;AAAA,WACF;AAAA,WA1BQ,KAAK,EA2Bf,CACD,GACH,GACF;AAAA,OACF;AAAA,KACF,GACF;AAEJ;",
4
+ "sourcesContent": ["\"use client\"\nimport * as React from 'react'\nimport Link from 'next/link'\nimport { usePathname } from 'next/navigation'\nimport { Page, PageBody } from '@open-mercato/ui/backend/Page'\nimport { Card, CardHeader, CardTitle, CardContent } from '@open-mercato/ui/primitives/card'\nimport { Badge } from '@open-mercato/ui/primitives/badge'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { Switch } from '@open-mercato/ui/primitives/switch'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from '@open-mercato/ui/primitives/select'\nimport { Spinner } from '@open-mercato/ui/primitives/spinner'\nimport { apiCall, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport type { CredentialFieldType, IntegrationCredentialField } from '@open-mercato/shared/modules/integrations/types'\nimport { LoadingMessage, ErrorMessage, RecordNotFoundState } from '@open-mercato/ui/backend/detail'\n\ntype CredentialField = IntegrationCredentialField\n\nconst UNSUPPORTED_CREDENTIAL_FIELD_TYPES = new Set<CredentialFieldType>(['oauth', 'ssh_keypair'])\n\nfunction isEditableCredentialField(field: CredentialField): boolean {\n return !UNSUPPORTED_CREDENTIAL_FIELD_TYPES.has(field.type)\n}\n\ntype BundleIntegration = {\n id: string\n title: string\n description?: string\n category?: string\n isEnabled: boolean\n state?: { updatedAt?: string | null }\n}\n\ntype BundleDetail = {\n integration: {\n id: string\n title: string\n description?: string\n bundleId?: string\n }\n bundle?: {\n id: string\n title: string\n description?: string\n credentials?: { fields: CredentialField[] }\n }\n bundleIntegrations: BundleIntegration[]\n state: { isEnabled: boolean }\n hasCredentials: boolean\n credentialsUpdatedAt?: string | null\n}\n\ntype BundleConfigPageProps = {\n params?: {\n id?: string | string[]\n }\n}\n\nfunction resolveRouteId(value: string | string[] | undefined): string | undefined {\n if (Array.isArray(value)) return value[0]\n return value\n}\n\nfunction resolvePathnameId(pathname: string): string | undefined {\n const parts = pathname.split('/').filter(Boolean)\n const bundleId = parts.at(-1)\n if (!bundleId || bundleId === 'bundle' || bundleId === 'integrations') return undefined\n return decodeURIComponent(bundleId)\n}\n\nexport default function BundleConfigPage({ params }: BundleConfigPageProps) {\n const pathname = usePathname()\n const bundleId = resolveRouteId(params?.id) ?? resolvePathnameId(pathname)\n const t = useT()\n\n const [detail, setDetail] = React.useState<BundleDetail | null>(null)\n const [isLoading, setIsLoading] = React.useState(true)\n const [error, setError] = React.useState<string | null>(null)\n const [isNotFound, setIsNotFound] = React.useState(false)\n const [credValues, setCredValues] = React.useState<Record<string, unknown>>({})\n const [credentialsUpdatedAt, setCredentialsUpdatedAt] = React.useState<string | null>(null)\n const [isSavingCreds, setIsSavingCreds] = React.useState(false)\n const [togglingIds, setTogglingIds] = React.useState<Set<string>>(new Set())\n\n const mutationContextId = React.useMemo(\n () => `integrations.bundle:${bundleId ?? 'unknown'}`,\n [bundleId],\n )\n const { runMutation, retryLastMutation } = useGuardedMutation<Record<string, unknown>>({\n contextId: mutationContextId,\n })\n\n const resolveCurrentBundleId = React.useCallback(() => {\n return bundleId ?? (\n typeof window !== 'undefined'\n ? resolvePathnameId(window.location.pathname)\n : undefined\n )\n }, [bundleId])\n\n const load = React.useCallback(async () => {\n const currentBundleId = resolveCurrentBundleId()\n if (!currentBundleId) {\n setError(t('integrations.detail.loadError'))\n setIsLoading(false)\n return\n }\n setIsLoading(true)\n setError(null)\n setIsNotFound(false)\n const call = await apiCall<BundleDetail>(\n `/api/integrations/${encodeURIComponent(currentBundleId)}`,\n undefined,\n { fallback: null },\n )\n if (!call.ok || !call.result) {\n if (call.status === 404) {\n setIsNotFound(true)\n } else {\n setError(t('integrations.detail.loadError'))\n }\n setIsLoading(false)\n return\n }\n setDetail(call.result)\n\n const credCall = await apiCall<{ credentials: Record<string, unknown>; updatedAt?: string | null }>(\n `/api/integrations/${encodeURIComponent(currentBundleId)}/credentials`,\n undefined,\n { fallback: null },\n )\n if (credCall.ok && credCall.result) {\n setCredentialsUpdatedAt(credCall.result.updatedAt ?? null)\n }\n if (credCall.ok && credCall.result?.credentials) {\n const next = { ...credCall.result.credentials }\n if (currentBundleId === 'storage_s3') {\n const authMode = next.authMode\n if (authMode !== 'access_keys' && authMode !== 'ambient') {\n const hasKeys = Boolean(next.accessKeyId || next.secretAccessKey)\n next.authMode = hasKeys ? 'access_keys' : 'ambient'\n }\n }\n setCredValues(next)\n }\n setIsLoading(false)\n }, [resolveCurrentBundleId, t])\n\n React.useEffect(() => { void load() }, [load])\n\n const handleSaveCredentials = React.useCallback(async () => {\n const currentBundleId = resolveCurrentBundleId()\n if (!currentBundleId) return\n setIsSavingCreds(true)\n try {\n const call = await runMutation({\n mutationPayload: { bundleId: currentBundleId, credentials: credValues },\n context: {\n formId: mutationContextId,\n operation: 'update',\n actionId: 'save-credentials',\n resourceKind: 'integrations.bundle',\n resourceId: currentBundleId,\n bundleId: currentBundleId,\n retryLastMutation,\n },\n operation: () => withScopedApiRequestHeaders(\n buildOptimisticLockHeader(credentialsUpdatedAt),\n () => apiCall(`/api/integrations/${encodeURIComponent(currentBundleId)}/credentials`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ credentials: credValues }),\n }, { fallback: null }),\n ),\n })\n if (call.ok) {\n flash(t('integrations.detail.credentials.saved'), 'success')\n await load()\n } else {\n flash(t('integrations.detail.credentials.saveError'), 'error')\n }\n } catch {\n flash(t('integrations.detail.credentials.saveError'), 'error')\n } finally {\n setIsSavingCreds(false)\n }\n }, [resolveCurrentBundleId, runMutation, mutationContextId, retryLastMutation, credValues, credentialsUpdatedAt, load, t])\n\n const handleToggle = React.useCallback(async (integrationId: string, enabled: boolean, updatedAt?: string | null) => {\n setTogglingIds((prev) => new Set(prev).add(integrationId))\n try {\n const call = await runMutation({\n mutationPayload: { integrationId, isEnabled: enabled },\n context: {\n formId: mutationContextId,\n operation: 'update',\n actionId: 'toggle-state',\n resourceKind: 'integrations.integration',\n resourceId: integrationId,\n integrationId,\n retryLastMutation,\n },\n operation: () => withScopedApiRequestHeaders(\n buildOptimisticLockHeader(updatedAt),\n () => apiCall<{ updatedAt?: string | null }>(`/api/integrations/${encodeURIComponent(integrationId)}/state`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ isEnabled: enabled }),\n }, { fallback: null }),\n ),\n })\n if (call.ok) {\n const nextUpdatedAt = call.result?.updatedAt ?? null\n setDetail((prev) => {\n if (!prev) return prev\n return {\n ...prev,\n bundleIntegrations: prev.bundleIntegrations.map((item) =>\n item.id === integrationId\n ? { ...item, isEnabled: enabled, state: { updatedAt: nextUpdatedAt ?? item.state?.updatedAt ?? null } }\n : item,\n ),\n }\n })\n } else {\n flash(t('integrations.detail.stateError'), 'error')\n }\n } catch {\n flash(t('integrations.detail.stateError'), 'error')\n } finally {\n setTogglingIds((prev) => { const next = new Set(prev); next.delete(integrationId); return next })\n }\n }, [runMutation, mutationContextId, retryLastMutation, t])\n\n const handleBulkToggle = React.useCallback(async (enabled: boolean) => {\n if (!detail) return\n const targets = detail.bundleIntegrations.filter((item) => item.isEnabled !== enabled)\n await Promise.all(targets.map((item) => handleToggle(item.id, enabled, item.state?.updatedAt)))\n }, [detail, handleToggle])\n\n if (isLoading) return <Page><PageBody><LoadingMessage label={t('integrations.bundle.title')} /></PageBody></Page>\n if (isNotFound) {\n return (\n <Page>\n <PageBody>\n <RecordNotFoundState\n label={t('integrations.detail.notFound', 'Integration not found.')}\n backHref=\"/backend/integrations\"\n backLabel={t('integrations.detail.backToList', 'Back to integrations')}\n />\n </PageBody>\n </Page>\n )\n }\n if (error || !detail?.bundle) return <Page><PageBody><ErrorMessage label={error ?? t('integrations.detail.loadError')} /></PageBody></Page>\n\n const credFields = (detail.bundle.credentials?.fields ?? []).filter(isEditableCredentialField)\n\n function isFieldVisible(field: CredentialField): boolean {\n if (!field.visibleWhen) return true\n return credValues[field.visibleWhen.field] === field.visibleWhen.equals\n }\n\n return (\n <Page>\n <PageBody className=\"space-y-6\">\n <div>\n <Link href=\"/backend/integrations\" className=\"text-sm text-muted-foreground hover:underline\">\n {t('integrations.detail.back')}\n </Link>\n </div>\n\n <div>\n <h1 className=\"text-2xl font-semibold\">{detail.bundle.title}</h1>\n {detail.bundle.description && (\n <p className=\"text-muted-foreground mt-1\">{detail.bundle.description}</p>\n )}\n </div>\n\n {credFields.length > 0 && (\n <Card>\n <CardHeader>\n <CardTitle>{t('integrations.bundle.sharedCredentials')}</CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n {credFields.filter(isFieldVisible).map((field) => (\n <div key={field.key} className=\"space-y-1.5\">\n <label className=\"text-sm font-medium\">\n {field.label}{field.required && <span className=\"text-red-500 ml-0.5\">*</span>}\n </label>\n {field.type === 'select' && field.options ? (\n <Select\n value={(credValues[field.key] as string) || undefined}\n onValueChange={(value) => setCredValues((prev) => ({ ...prev, [field.key]: value ?? '' }))}\n >\n <SelectTrigger>\n <SelectValue placeholder=\"\u2014\" />\n </SelectTrigger>\n <SelectContent>\n {field.options.map((opt) => (\n <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>\n ))}\n </SelectContent>\n </Select>\n ) : field.type === 'boolean' ? (\n <Switch\n checked={Boolean(credValues[field.key])}\n onCheckedChange={(checked) => setCredValues((prev) => ({ ...prev, [field.key]: checked }))}\n />\n ) : (\n <Input\n type={field.type === 'secret' ? 'password' : 'text'}\n placeholder={field.placeholder}\n value={(credValues[field.key] as string) ?? ''}\n onChange={(e) => setCredValues((prev) => ({ ...prev, [field.key]: e.target.value }))}\n />\n )}\n </div>\n ))}\n <Button type=\"button\" onClick={() => void handleSaveCredentials()} disabled={isSavingCreds}>\n {isSavingCreds ? <Spinner className=\"mr-2 h-4 w-4\" /> : null}\n {t('integrations.detail.credentials.save')}\n </Button>\n </CardContent>\n </Card>\n )}\n\n <Card>\n <CardHeader>\n <div className=\"flex items-center justify-between\">\n <CardTitle>{t('integrations.bundle.integrationToggles')}</CardTitle>\n <div className=\"flex gap-2\">\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={() => void handleBulkToggle(true)}>\n {t('integrations.marketplace.enableAll')}\n </Button>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={() => void handleBulkToggle(false)}>\n {t('integrations.marketplace.disableAll')}\n </Button>\n </div>\n </div>\n </CardHeader>\n <CardContent>\n <div className=\"space-y-3\">\n {detail.bundleIntegrations.map((item) => (\n <div key={item.id} className=\"flex items-center justify-between rounded-lg border p-3\">\n <div>\n <Link\n href={`/backend/integrations/${encodeURIComponent(item.id)}`}\n className=\"text-sm font-medium hover:underline\"\n >\n {item.title}\n </Link>\n {item.category && (\n <Badge variant=\"secondary\" className=\"ml-2 text-xs\">{item.category}</Badge>\n )}\n {item.description && (\n <p className=\"text-xs text-muted-foreground mt-0.5\">{item.description}</p>\n )}\n </div>\n <div className=\"flex items-center gap-3\">\n <Button asChild variant=\"ghost\" size=\"sm\">\n <Link href={`/backend/integrations/${encodeURIComponent(item.id)}`}>\n {t('integrations.bundle.configureIntegration')}\n </Link>\n </Button>\n <Switch\n checked={item.isEnabled}\n disabled={togglingIds.has(item.id)}\n onCheckedChange={(checked) => void handleToggle(item.id,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BAAC,SAAI,WAAU,aACZ,iBAAO,mBAAmB,IAAI,CAAC,SAC9B,qBAAC,SAAkB,WAAU,2DAC3B;AAAA,6BAAC,SACC;AAAA;AAAA,YAAC;AAAA;AAAA,cACC,MAAM,yBAAyB,mBAAmB,KAAK,EAAE,CAAC;AAAA,cAC1D,WAAU;AAAA,cAET,eAAK;AAAA;AAAA,UACR;AAAA,UACC,KAAK,YACJ,oBAAC,SAAM,SAAQ,aAAY,WAAU,gBAAgB,eAAK,UAAS;AAAA,UAEpE,KAAK,eACJ,oBAAC,OAAE,WAAU,wCAAwC,eAAK,aAAY;AAAA,WAE1E;AAAA,QACA,qBAAC,SAAI,WAAU,2BACb;AAAA,8BAAC,UAAO,SAAO,MAAC,SAAQ,SAAQ,MAAK,MACnC,8BAAC,QAAK,MAAM,yBAAyB,mBAAmB,KAAK,EAAE,CAAC,IAC7D,YAAE,0CAA0C,GAC/C,GACF;AAAA,UACA;AAAA,YAAC;AAAA;AAAA,cACC,SAAS,KAAK;AAAA,cACd,UAAU,YAAY,IAAI,KAAK,EAAE;AAAA,cACjC,iBAAiB,CAAC,YAAY,KAAK,aAAa,KAAK,IAAI,SAAS,KAAK,OAAO,SAAS;AAAA;AAAA,UACzF;AAAA,WACF;AAAA,WA1BQ,KAAK,EA2Bf,CACD,GACH,GACF;AAAA,OACF;AAAA,KACF,GACF;AAEJ;",
6
6
  "names": []
7
7
  }
@@ -163,12 +163,13 @@ function IntegrationsMarketplacePage() {
163
163
  if (!call.ok) {
164
164
  flash(t("integrations.detail.stateError"), "error");
165
165
  } else {
166
+ const nextUpdatedAt = call.result?.updatedAt ?? null;
166
167
  setData((prev) => {
167
168
  if (!prev) return prev;
168
169
  return {
169
170
  ...prev,
170
171
  items: prev.items.map(
171
- (item) => item.id === integrationId ? { ...item, isEnabled: enabled } : item
172
+ (item) => item.id === integrationId ? { ...item, isEnabled: enabled, stateUpdatedAt: nextUpdatedAt ?? item.stateUpdatedAt } : item
172
173
  )
173
174
  };
174
175
  });
@@ -368,7 +369,7 @@ function IntegrationsMarketplacePage() {
368
369
  {
369
370
  checked: item.isEnabled,
370
371
  disabled: togglingIds.has(item.id),
371
- onCheckedChange: (checked) => void handleToggle(item.id, checked, item.updatedAt),
372
+ onCheckedChange: (checked) => void handleToggle(item.id, checked, item.stateUpdatedAt),
372
373
  className: "shrink-0"
373
374
  }
374
375
  )
@@ -399,7 +400,7 @@ function IntegrationsMarketplacePage() {
399
400
  {
400
401
  checked: item.isEnabled,
401
402
  disabled: togglingIds.has(item.id),
402
- onCheckedChange: (checked) => void handleToggle(item.id, checked),
403
+ onCheckedChange: (checked) => void handleToggle(item.id, checked, item.stateUpdatedAt),
403
404
  className: "shrink-0"
404
405
  }
405
406
  )
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/integrations/backend/integrations/page.tsx"],
4
- "sourcesContent": ["\"use client\"\nimport * as React from 'react'\nimport Link from 'next/link'\nimport { Page, PageBody } from '@open-mercato/ui/backend/Page'\nimport { Card, CardHeader, CardTitle, CardContent } from '@open-mercato/ui/primitives/card'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { Switch } from '@open-mercato/ui/primitives/switch'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport { Spinner } from '@open-mercato/ui/primitives/spinner'\nimport { apiCall, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { useOrganizationScopeVersion } from '@open-mercato/shared/lib/frontend/useOrganizationScope'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { FilterBar, type FilterValues } from '@open-mercato/ui/backend/FilterBar'\nimport { Bell, Cog, CreditCard, HardDrive, LayoutGrid, MessageSquare, RefreshCw, Search, Truck, Webhook } from 'lucide-react'\nimport {\n buildIntegrationMarketplaceFilterDefs,\n getIntegrationMarketplaceCategory,\n getListQueryFromFilterValues,\n INTEGRATION_MARKETPLACE_CATEGORIES,\n normalizeIntegrationMarketplaceFilterValues,\n} from './filters'\n\ntype IntegrationAnalytics = {\n lastActivityAt: string | null\n totalCount: number\n errorCount: number\n errorRate: number\n dailyCounts: number[]\n}\n\ntype IntegrationItem = {\n id: string\n title: string\n description?: string\n category?: string\n tags?: string[]\n bundleId?: string\n author?: string\n company?: string\n version?: string\n isEnabled: boolean\n hasCredentials: boolean\n healthStatus: 'healthy' | 'degraded' | 'unhealthy' | 'unconfigured'\n analytics: IntegrationAnalytics\n updatedAt?: string | null\n}\n\ntype BundleItem = {\n id: string\n title: string\n description?: string\n icon?: string\n integrationCount: number\n enabledCount: number\n}\n\ntype ListResponse = {\n items: IntegrationItem[]\n bundles: BundleItem[]\n total: number\n page: number\n pageSize: number\n totalPages: number\n}\n\nconst CATEGORY_ICONS: Record<string, React.ElementType> = {\n all: LayoutGrid,\n payment: CreditCard,\n shipping: Truck,\n data_sync: RefreshCw,\n communication: MessageSquare,\n notification: Bell,\n storage: HardDrive,\n webhook: Webhook,\n}\n\nconst HEALTH_BADGE_CLASS: Record<string, string> = {\n healthy: 'bg-emerald-500/15 text-emerald-800 dark:text-emerald-300',\n degraded: 'bg-amber-500/15 text-amber-900 dark:text-amber-300',\n unhealthy: 'bg-destructive/15 text-destructive',\n unconfigured: 'bg-muted text-muted-foreground',\n}\n\nfunction buildListQueryString(input: {\n q?: string\n category?: string\n bundleId?: string\n isEnabled?: boolean\n healthStatus?: string\n sort?: string\n order?: string\n page?: number\n pageSize?: number\n}): string {\n const params = new URLSearchParams()\n if (input.q) params.set('q', input.q)\n if (input.category) params.set('category', input.category)\n if (input.bundleId) params.set('bundleId', input.bundleId)\n if (input.isEnabled !== undefined) params.set('isEnabled', String(input.isEnabled))\n if (input.healthStatus) params.set('healthStatus', input.healthStatus)\n if (input.sort) params.set('sort', input.sort)\n if (input.order) params.set('order', input.order)\n if (input.page != null && input.page > 1) params.set('page', String(input.page))\n if (input.pageSize != null && input.pageSize !== 100) params.set('pageSize', String(input.pageSize))\n const qs = params.toString()\n return qs ? `?${qs}` : ''\n}\n\nfunction LogSparkline({ counts, className }: { counts: number[]; className?: string }) {\n const max = Math.max(1, ...counts)\n const w = 72\n const h = 22\n const step = counts.length > 1 ? w / (counts.length - 1) : w\n const points = counts.map((count, index) => {\n const x = index * step\n const y = h - (count / max) * (h - 3) - 1.5\n return `${x},${y}`\n }).join(' ')\n return (\n <svg width={w} height={h} className={className} aria-hidden>\n <polyline\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.2\"\n strokeLinejoin=\"round\"\n strokeLinecap=\"round\"\n points={points}\n className=\"text-muted-foreground/80\"\n />\n </svg>\n )\n}\n\nexport default function IntegrationsMarketplacePage() {\n const [data, setData] = React.useState<ListResponse | null>(null)\n const [isLoading, setIsLoading] = React.useState(true)\n const [searchInput, setSearchInput] = React.useState('')\n const [debouncedSearch, setDebouncedSearch] = React.useState('')\n const [filterValues, setFilterValues] = React.useState<FilterValues>({})\n const [sortField, setSortField] = React.useState<'title' | 'category' | 'enabledAt' | 'healthStatus'>('title')\n const [sortOrder, setSortOrder] = React.useState<'asc' | 'desc'>('asc')\n const [page, setPage] = React.useState(1)\n const [togglingIds, setTogglingIds] = React.useState<Set<string>>(new Set())\n const scopeVersion = useOrganizationScopeVersion()\n const t = useT()\n const { runMutation, retryLastMutation } = useGuardedMutation<Record<string, unknown>>({\n contextId: 'integrations.marketplace',\n })\n\n React.useEffect(() => {\n const timer = setTimeout(() => setDebouncedSearch(searchInput.trim()), 300)\n return () => clearTimeout(timer)\n }, [searchInput])\n\n const selectedCategory = React.useMemo(() => getIntegrationMarketplaceCategory(filterValues), [filterValues])\n\n const listQuery = React.useMemo(() => {\n const fromFilters = getListQueryFromFilterValues(filterValues)\n const category = selectedCategory !== 'all' ? selectedCategory : fromFilters.category\n return buildListQueryString({\n q: debouncedSearch || undefined,\n ...(category ? { category } : {}),\n ...(fromFilters.bundleId ? { bundleId: fromFilters.bundleId } : {}),\n ...(fromFilters.isEnabled !== undefined ? { isEnabled: fromFilters.isEnabled } : {}),\n ...(fromFilters.healthStatus ? { healthStatus: fromFilters.healthStatus } : {}),\n sort: sortField,\n order: sortOrder,\n page,\n pageSize: 100,\n })\n }, [debouncedSearch, filterValues, page, selectedCategory, sortField, sortOrder])\n\n const bundleFilterOptions = React.useMemo(\n () => (data?.bundles ?? []).map((bundle) => ({ id: bundle.id, title: bundle.title })),\n [data?.bundles],\n )\n\n const categoryFilters = React.useMemo(\n () => buildIntegrationMarketplaceFilterDefs(t, bundleFilterOptions),\n [bundleFilterOptions, t],\n )\n\n const load = React.useCallback(async () => {\n setIsLoading(true)\n const fallback: ListResponse = { items: [], bundles: [], total: 0, page: 1, pageSize: 100, totalPages: 1 }\n const call = await apiCall<ListResponse>(`/api/integrations${listQuery}`, undefined, { fallback })\n if (!call.ok) {\n flash(t('integrations.marketplace.loadError'), 'error')\n setIsLoading(false)\n return\n }\n setData(call.result ?? fallback)\n setIsLoading(false)\n }, [listQuery, t])\n\n React.useEffect(() => {\n void load()\n }, [load, scopeVersion])\n\n React.useEffect(() => {\n setPage(1)\n }, [debouncedSearch, filterValues, selectedCategory, sortField, sortOrder])\n\n const handleToggle = React.useCallback(async (integrationId: string, enabled: boolean, updatedAt?: string | null) => {\n setTogglingIds((prev) => new Set(prev).add(integrationId))\n try {\n const call = await runMutation({\n mutationPayload: { integrationId, isEnabled: enabled },\n context: {\n formId: 'integrations.marketplace',\n operation: 'update',\n actionId: 'toggle-state',\n resourceKind: 'integrations.integration',\n resourceId: integrationId,\n integrationId,\n retryLastMutation,\n },\n operation: () => withScopedApiRequestHeaders(\n buildOptimisticLockHeader(updatedAt),\n () => apiCall(`/api/integrations/${encodeURIComponent(integrationId)}/state`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ isEnabled: enabled }),\n }, { fallback: null }),\n ),\n })\n\n if (!call.ok) {\n flash(t('integrations.detail.stateError'), 'error')\n } else {\n setData((prev) => {\n if (!prev) return prev\n return {\n ...prev,\n items: prev.items.map((item) =>\n item.id === integrationId ? { ...item, isEnabled: enabled } : item,\n ),\n }\n })\n }\n } catch {\n flash(t('integrations.detail.stateError'), 'error')\n } finally {\n setTogglingIds((prev) => { const next = new Set(prev); next.delete(integrationId); return next })\n }\n }, [retryLastMutation, runMutation, t])\n\n const grouped = React.useMemo(() => {\n if (!data) return { bundles: [] as Array<BundleItem & { integrations: IntegrationItem[] }>, standalone: [] as IntegrationItem[] }\n\n const bundled = new Map<string, IntegrationItem[]>()\n const standalone: IntegrationItem[] = []\n for (const item of data.items) {\n if (item.bundleId) {\n const list = bundled.get(item.bundleId) ?? []\n list.push(item)\n bundled.set(item.bundleId, list)\n } else {\n standalone.push(item)\n }\n }\n\n const bundles = (data.bundles ?? [])\n .filter((b) => bundled.has(b.id))\n .map((b) => ({ ...b, integrations: bundled.get(b.id) ?? [] }))\n\n return { bundles, standalone }\n }, [data])\n\n const renderCategoryIcon = React.useCallback((category: string | undefined, className: string) => {\n if (!category) return null\n const Icon = CATEGORY_ICONS[category]\n if (!Icon) return null\n return <Icon className={className} />\n }, [])\n\n const renderHealthBadge = React.useCallback((status: IntegrationItem['healthStatus']) => {\n return (\n <span\n className={`inline-flex shrink-0 items-center rounded-full px-2 py-0.5 text-xs font-semibold uppercase tracking-wide ${HEALTH_BADGE_CLASS[status] ?? HEALTH_BADGE_CLASS.unconfigured}`}\n >\n {t(`integrations.marketplace.health.${status}`, status)}\n </span>\n )\n }, [t])\n\n if (isLoading && !data) {\n return (\n <Page>\n <PageBody>\n <div className=\"flex items-center justify-center py-16\">\n <Spinner />\n </div>\n </PageBody>\n </Page>\n )\n }\n\n return (\n <Page>\n <PageBody className=\"space-y-6\">\n <section className=\"space-y-6 rounded-lg border bg-background p-6\">\n <header className=\"flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between\">\n <div className=\"space-y-0.5\">\n <h2 className=\"text-lg font-semibold\">{t('integrations.marketplace.title')}</h2>\n <p className=\"text-sm text-muted-foreground\">\n {t('integrations.marketplace.description')}\n </p>\n </div>\n <div className=\"flex flex-wrap items-center gap-2\">\n <div className=\"relative w-full min-w-[200px] max-w-xs lg:w-64\">\n <Search className=\"absolute left-2.5 top-1/2 -translate-y-1/2 size-4 text-muted-foreground pointer-events-none\" />\n <Input\n placeholder={t('integrations.marketplace.search')}\n value={searchInput}\n onChange={(e) => setSearchInput(e.target.value)}\n className=\"pl-8\"\n />\n </div>\n <label className=\"flex items-center gap-2 text-sm text-muted-foreground\">\n <span className=\"sr-only\">{t('integrations.marketplace.sort.label', 'Sort by')}</span>\n <select\n className=\"h-9 rounded-md border border-input bg-background px-2 text-sm\"\n value={sortField}\n onChange={(e) => setSortField(e.target.value as typeof sortField)}\n >\n <option value=\"title\">{t('integrations.marketplace.sort.title', 'Title')}</option>\n <option value=\"category\">{t('integrations.marketplace.sort.category', 'Category')}</option>\n <option value=\"enabledAt\">{t('integrations.marketplace.sort.enabledAt', 'Enabled date')}</option>\n <option value=\"healthStatus\">{t('integrations.marketplace.sort.health', 'Health')}</option>\n </select>\n </label>\n <select\n className=\"h-9 rounded-md border border-input bg-background px-2 text-sm\"\n value={sortOrder}\n onChange={(e) => setSortOrder(e.target.value as typeof sortOrder)}\n aria-label={t('integrations.marketplace.sort.order', 'Sort order')}\n >\n <option value=\"asc\">{t('integrations.marketplace.sort.asc', 'Ascending')}</option>\n <option value=\"desc\">{t('integrations.marketplace.sort.desc', 'Descending')}</option>\n </select>\n </div>\n </header>\n\n <div className=\"lg:hidden\">\n <FilterBar\n searchValue={searchInput}\n onSearchChange={setSearchInput}\n searchPlaceholder={t('integrations.marketplace.search')}\n searchAlign=\"left\"\n filters={categoryFilters}\n values={filterValues}\n onApply={(values) => setFilterValues(normalizeIntegrationMarketplaceFilterValues(values))}\n onClear={() => setFilterValues({})}\n />\n </div>\n\n <div className=\"hidden lg:flex flex-wrap gap-1.5\">\n {INTEGRATION_MARKETPLACE_CATEGORIES.map((category) => {\n const Icon = CATEGORY_ICONS[category]\n return (\n <Button\n key={category}\n type=\"button\"\n variant={selectedCategory === category ? 'default' : 'outline'}\n size=\"sm\"\n onClick={() => setFilterValues(normalizeIntegrationMarketplaceFilterValues({ category }))}\n >\n {Icon ? <Icon className=\"mr-1.5 h-3.5 w-3.5\" /> : null}\n {t(`integrations.marketplace.categories.${category}`)}\n </Button>\n )\n })}\n </div>\n\n {isLoading ? (\n <div className=\"flex justify-center py-8\">\n <Spinner />\n </div>\n ) : null}\n\n {data && data.totalPages > 1 ? (\n <div className=\"flex flex-wrap items-center justify-between gap-2 text-sm text-muted-foreground\">\n <span>\n {data.total === 0\n ? t('integrations.marketplace.pagination.empty', 'No results')\n : t('integrations.marketplace.pagination.summary', {\n from: (data.page - 1) * data.pageSize + 1,\n to: Math.min(data.page * data.pageSize, data.total),\n total: data.total,\n })}\n </span>\n <div className=\"flex gap-2\">\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n disabled={data.page <= 1}\n onClick={() => setPage((p) => Math.max(1, p - 1))}\n >\n {t('integrations.marketplace.pagination.prev', 'Previous')}\n </Button>\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n disabled={data.page >= data.totalPages}\n onClick={() => setPage((p) => p + 1)}\n >\n {t('integrations.marketplace.pagination.next', 'Next')}\n </Button>\n </div>\n </div>\n ) : null}\n\n {grouped.bundles.map((bundle) => (\n <Card key={bundle.id}>\n <CardHeader>\n <div className=\"flex items-center justify-between\">\n <div>\n <CardTitle>{bundle.title}</CardTitle>\n {bundle.description && (\n <p className=\"text-muted-foreground text-sm mt-1\">{bundle.description}</p>\n )}\n <p className=\"text-muted-foreground text-xs mt-1\">\n {t('integrations.marketplace.integrations', { count: bundle.integrations.length })}\n </p>\n </div>\n <Button asChild variant=\"outline\" size=\"sm\">\n <Link href={`/backend/integrations/bundle/${encodeURIComponent(bundle.id)}`}>\n <Cog className=\"mr-1.5 h-4 w-4\" />\n {t('integrations.marketplace.configure')}\n </Link>\n </Button>\n </div>\n </CardHeader>\n <CardContent>\n <div className=\"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3\">\n {bundle.integrations.map((item) => (\n <div\n key={item.id}\n className=\"flex flex-col gap-2 rounded-lg border p-3\"\n >\n <div className=\"flex items-start justify-between gap-2\">\n <div className=\"min-w-0 space-y-1\">\n <div className=\"flex flex-wrap items-center gap-2\">\n {renderCategoryIcon(item.category, 'h-4 w-4 text-muted-foreground shrink-0')}\n <Link\n href={`/backend/integrations/${encodeURIComponent(item.id)}`}\n className=\"truncate text-sm font-medium hover:underline\"\n >\n {item.title}\n </Link>\n {renderHealthBadge(item.healthStatus)}\n </div>\n {(item.company || item.author || item.version) ? (\n <p className=\"text-xs text-muted-foreground\">\n {[item.company || item.author, item.version ? `v${item.version}` : null].filter(Boolean).join(' \u00B7 ')}\n </p>\n ) : null}\n </div>\n <Switch\n checked={item.isEnabled}\n disabled={togglingIds.has(item.id)}\n onCheckedChange={(checked) => void handleToggle(item.id, checked, item.updatedAt)}\n className=\"shrink-0\"\n />\n </div>\n <div className=\"flex items-end justify-between gap-2 border-t pt-2\">\n <div className=\"text-xs text-muted-foreground space-y-0.5\">\n <div>\n {t('integrations.marketplace.analytics.events', { count: item.analytics.totalCount })}\n </div>\n <div>\n {t('integrations.marketplace.analytics.errorRate', {\n rate: `${Math.round(item.analytics.errorRate * 1000) / 10}%`,\n })}\n </div>\n </div>\n <LogSparkline counts={item.analytics.dailyCounts} />\n </div>\n </div>\n ))}\n </div>\n </CardContent>\n </Card>\n ))}\n\n {grouped.standalone.length > 0 && (\n <div className=\"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4\">\n {grouped.standalone.map((item) => (\n <Card key={item.id} className=\"flex flex-col\">\n <CardHeader>\n <div className=\"flex items-start justify-between gap-2\">\n <div className=\"flex min-w-0 flex-wrap items-center gap-2\">\n {renderCategoryIcon(item.category, 'h-4 w-4 text-muted-foreground shrink-0')}\n <CardTitle className=\"text-base\">{item.title}</CardTitle>\n {renderHealthBadge(item.healthStatus)}\n </div>\n <Switch\n checked={item.isEnabled}\n disabled={togglingIds.has(item.id)}\n onCheckedChange={(checked) => void handleToggle(item.id, checked)}\n className=\"shrink-0\"\n />\n </div>\n </CardHeader>\n <CardContent className=\"flex-1 space-y-2\">\n {item.description && (\n <p className=\"text-muted-foreground text-sm\">{item.description}</p>\n )}\n {(item.company || item.author || item.version) && (\n <p className=\"text-muted-foreground text-xs\">\n {[item.company || item.author, item.version ? `v${item.version}` : null].filter(Boolean).join(' \u00B7 ')}\n </p>\n )}\n <div className=\"flex items-end justify-between gap-2 border-t pt-3\">\n <div className=\"text-xs text-muted-foreground space-y-0.5\">\n <div>\n {t('integrations.marketplace.analytics.events', { count: item.analytics.totalCount })}\n </div>\n <div>\n {t('integrations.marketplace.analytics.errorRate', {\n rate: `${Math.round(item.analytics.errorRate * 1000) / 10}%`,\n })}\n </div>\n </div>\n <LogSparkline counts={item.analytics.dailyCounts} />\n </div>\n </CardContent>\n <div className=\"px-6 pb-4\">\n <Button asChild variant=\"outline\" size=\"sm\" className=\"w-full\">\n <Link href={`/backend/integrations/${encodeURIComponent(item.id)}`}>\n <Cog className=\"mr-1.5 h-4 w-4\" />\n {t('integrations.marketplace.configure')}\n </Link>\n </Button>\n </div>\n </Card>\n ))}\n </div>\n )}\n\n {grouped.bundles.length === 0 && grouped.standalone.length === 0 && !isLoading && (\n <div className=\"text-center py-12 text-muted-foreground\">\n {t('integrations.marketplace.noResults')}\n </div>\n )}\n </section>\n </PageBody>\n </Page>\n )\n}\n"],
5
- "mappings": ";AA2HM,cAuLM,YAvLN;AA1HN,YAAY,WAAW;AACvB,OAAO,UAAU;AACjB,SAAS,MAAM,gBAAgB;AAC/B,SAAS,MAAM,YAAY,WAAW,mBAAmB;AACzD,SAAS,cAAc;AACvB,SAAS,cAAc;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AA,SAE/D,KAAK,WAAW,KAAK,UAAU,KAAK,YACpC,oBAAC,OAAE,WAAU,iCACV,WAAC,KAAK,WAAW,KAAK,QAAQ,KAAK,UAAU,IAAI,KAAK,OAAO,KAAK,IAAI,EAAE,OAAO,OAAO,EAAE,KAAK,QAAK,GACrG;AAAA,QAEF,qBAAC,SAAI,WAAU,sDACb;AAAA,+BAAC,SAAI,WAAU,6CACb;AAAA,gCAAC,SACE,YAAE,6CAA6C,EAAE,OAAO,KAAK,UAAU,WAAW,CAAC,GACtF;AAAA,YACA,oBAAC,SACE,YAAE,gDAAgD;AAAA,cACjD,MAAM,GAAG,KAAK,MAAM,KAAK,UAAU,YAAY,GAAI,IAAI,EAAE;AAAA,YAC3D,CAAC,GACH;AAAA,aACF;AAAA,UACA,oBAAC,gBAAa,QAAQ,KAAK,UAAU,aAAa;AAAA,WACpD;AAAA,SACF;AAAA,MACA,oBAAC,SAAI,WAAU,aACb,8BAAC,UAAO,SAAO,MAAC,SAAQ,WAAU,MAAK,MAAK,WAAU,UACpD,+BAAC,QAAK,MAAM,yBAAyB,mBAAmB,KAAK,EAAE,CAAC,IAC9D;AAAA,4BAAC,OAAI,WAAU,kBAAiB;AAAA,QAC/B,EAAE,oCAAoC;AAAA,SACzC,GACF,GACF;AAAA,SA9CS,KAAK,EA+ChB,CACD,GACH;AAAA,IAGD,QAAQ,QAAQ,WAAW,KAAK,QAAQ,WAAW,WAAW,KAAK,CAAC,aACnE,oBAAC,SAAI,WAAU,2CACZ,YAAE,oCAAoC,GACzC;AAAA,KAEJ,GACF,GACF;AAEJ;",
4
+ "sourcesContent": ["\"use client\"\nimport * as React from 'react'\nimport Link from 'next/link'\nimport { Page, PageBody } from '@open-mercato/ui/backend/Page'\nimport { Card, CardHeader, CardTitle, CardContent } from '@open-mercato/ui/primitives/card'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { Switch } from '@open-mercato/ui/primitives/switch'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport { Spinner } from '@open-mercato/ui/primitives/spinner'\nimport { apiCall, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { useOrganizationScopeVersion } from '@open-mercato/shared/lib/frontend/useOrganizationScope'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { FilterBar, type FilterValues } from '@open-mercato/ui/backend/FilterBar'\nimport { Bell, Cog, CreditCard, HardDrive, LayoutGrid, MessageSquare, RefreshCw, Search, Truck, Webhook } from 'lucide-react'\nimport {\n buildIntegrationMarketplaceFilterDefs,\n getIntegrationMarketplaceCategory,\n getListQueryFromFilterValues,\n INTEGRATION_MARKETPLACE_CATEGORIES,\n normalizeIntegrationMarketplaceFilterValues,\n} from './filters'\n\ntype IntegrationAnalytics = {\n lastActivityAt: string | null\n totalCount: number\n errorCount: number\n errorRate: number\n dailyCounts: number[]\n}\n\ntype IntegrationItem = {\n id: string\n title: string\n description?: string\n category?: string\n tags?: string[]\n bundleId?: string\n author?: string\n company?: string\n version?: string\n isEnabled: boolean\n hasCredentials: boolean\n healthStatus: 'healthy' | 'degraded' | 'unhealthy' | 'unconfigured'\n analytics: IntegrationAnalytics\n stateUpdatedAt?: string | null\n}\n\ntype BundleItem = {\n id: string\n title: string\n description?: string\n icon?: string\n integrationCount: number\n enabledCount: number\n}\n\ntype ListResponse = {\n items: IntegrationItem[]\n bundles: BundleItem[]\n total: number\n page: number\n pageSize: number\n totalPages: number\n}\n\nconst CATEGORY_ICONS: Record<string, React.ElementType> = {\n all: LayoutGrid,\n payment: CreditCard,\n shipping: Truck,\n data_sync: RefreshCw,\n communication: MessageSquare,\n notification: Bell,\n storage: HardDrive,\n webhook: Webhook,\n}\n\nconst HEALTH_BADGE_CLASS: Record<string, string> = {\n healthy: 'bg-emerald-500/15 text-emerald-800 dark:text-emerald-300',\n degraded: 'bg-amber-500/15 text-amber-900 dark:text-amber-300',\n unhealthy: 'bg-destructive/15 text-destructive',\n unconfigured: 'bg-muted text-muted-foreground',\n}\n\nfunction buildListQueryString(input: {\n q?: string\n category?: string\n bundleId?: string\n isEnabled?: boolean\n healthStatus?: string\n sort?: string\n order?: string\n page?: number\n pageSize?: number\n}): string {\n const params = new URLSearchParams()\n if (input.q) params.set('q', input.q)\n if (input.category) params.set('category', input.category)\n if (input.bundleId) params.set('bundleId', input.bundleId)\n if (input.isEnabled !== undefined) params.set('isEnabled', String(input.isEnabled))\n if (input.healthStatus) params.set('healthStatus', input.healthStatus)\n if (input.sort) params.set('sort', input.sort)\n if (input.order) params.set('order', input.order)\n if (input.page != null && input.page > 1) params.set('page', String(input.page))\n if (input.pageSize != null && input.pageSize !== 100) params.set('pageSize', String(input.pageSize))\n const qs = params.toString()\n return qs ? `?${qs}` : ''\n}\n\nfunction LogSparkline({ counts, className }: { counts: number[]; className?: string }) {\n const max = Math.max(1, ...counts)\n const w = 72\n const h = 22\n const step = counts.length > 1 ? w / (counts.length - 1) : w\n const points = counts.map((count, index) => {\n const x = index * step\n const y = h - (count / max) * (h - 3) - 1.5\n return `${x},${y}`\n }).join(' ')\n return (\n <svg width={w} height={h} className={className} aria-hidden>\n <polyline\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.2\"\n strokeLinejoin=\"round\"\n strokeLinecap=\"round\"\n points={points}\n className=\"text-muted-foreground/80\"\n />\n </svg>\n )\n}\n\nexport default function IntegrationsMarketplacePage() {\n const [data, setData] = React.useState<ListResponse | null>(null)\n const [isLoading, setIsLoading] = React.useState(true)\n const [searchInput, setSearchInput] = React.useState('')\n const [debouncedSearch, setDebouncedSearch] = React.useState('')\n const [filterValues, setFilterValues] = React.useState<FilterValues>({})\n const [sortField, setSortField] = React.useState<'title' | 'category' | 'enabledAt' | 'healthStatus'>('title')\n const [sortOrder, setSortOrder] = React.useState<'asc' | 'desc'>('asc')\n const [page, setPage] = React.useState(1)\n const [togglingIds, setTogglingIds] = React.useState<Set<string>>(new Set())\n const scopeVersion = useOrganizationScopeVersion()\n const t = useT()\n const { runMutation, retryLastMutation } = useGuardedMutation<Record<string, unknown>>({\n contextId: 'integrations.marketplace',\n })\n\n React.useEffect(() => {\n const timer = setTimeout(() => setDebouncedSearch(searchInput.trim()), 300)\n return () => clearTimeout(timer)\n }, [searchInput])\n\n const selectedCategory = React.useMemo(() => getIntegrationMarketplaceCategory(filterValues), [filterValues])\n\n const listQuery = React.useMemo(() => {\n const fromFilters = getListQueryFromFilterValues(filterValues)\n const category = selectedCategory !== 'all' ? selectedCategory : fromFilters.category\n return buildListQueryString({\n q: debouncedSearch || undefined,\n ...(category ? { category } : {}),\n ...(fromFilters.bundleId ? { bundleId: fromFilters.bundleId } : {}),\n ...(fromFilters.isEnabled !== undefined ? { isEnabled: fromFilters.isEnabled } : {}),\n ...(fromFilters.healthStatus ? { healthStatus: fromFilters.healthStatus } : {}),\n sort: sortField,\n order: sortOrder,\n page,\n pageSize: 100,\n })\n }, [debouncedSearch, filterValues, page, selectedCategory, sortField, sortOrder])\n\n const bundleFilterOptions = React.useMemo(\n () => (data?.bundles ?? []).map((bundle) => ({ id: bundle.id, title: bundle.title })),\n [data?.bundles],\n )\n\n const categoryFilters = React.useMemo(\n () => buildIntegrationMarketplaceFilterDefs(t, bundleFilterOptions),\n [bundleFilterOptions, t],\n )\n\n const load = React.useCallback(async () => {\n setIsLoading(true)\n const fallback: ListResponse = { items: [], bundles: [], total: 0, page: 1, pageSize: 100, totalPages: 1 }\n const call = await apiCall<ListResponse>(`/api/integrations${listQuery}`, undefined, { fallback })\n if (!call.ok) {\n flash(t('integrations.marketplace.loadError'), 'error')\n setIsLoading(false)\n return\n }\n setData(call.result ?? fallback)\n setIsLoading(false)\n }, [listQuery, t])\n\n React.useEffect(() => {\n void load()\n }, [load, scopeVersion])\n\n React.useEffect(() => {\n setPage(1)\n }, [debouncedSearch, filterValues, selectedCategory, sortField, sortOrder])\n\n const handleToggle = React.useCallback(async (integrationId: string, enabled: boolean, updatedAt?: string | null) => {\n setTogglingIds((prev) => new Set(prev).add(integrationId))\n try {\n const call = await runMutation({\n mutationPayload: { integrationId, isEnabled: enabled },\n context: {\n formId: 'integrations.marketplace',\n operation: 'update',\n actionId: 'toggle-state',\n resourceKind: 'integrations.integration',\n resourceId: integrationId,\n integrationId,\n retryLastMutation,\n },\n operation: () => withScopedApiRequestHeaders(\n buildOptimisticLockHeader(updatedAt),\n () => apiCall<{ updatedAt?: string | null }>(`/api/integrations/${encodeURIComponent(integrationId)}/state`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ isEnabled: enabled }),\n }, { fallback: null }),\n ),\n })\n\n if (!call.ok) {\n flash(t('integrations.detail.stateError'), 'error')\n } else {\n const nextUpdatedAt = call.result?.updatedAt ?? null\n setData((prev) => {\n if (!prev) return prev\n return {\n ...prev,\n items: prev.items.map((item) =>\n item.id === integrationId\n ? { ...item, isEnabled: enabled, stateUpdatedAt: nextUpdatedAt ?? item.stateUpdatedAt }\n : item,\n ),\n }\n })\n }\n } catch {\n flash(t('integrations.detail.stateError'), 'error')\n } finally {\n setTogglingIds((prev) => { const next = new Set(prev); next.delete(integrationId); return next })\n }\n }, [retryLastMutation, runMutation, t])\n\n const grouped = React.useMemo(() => {\n if (!data) return { bundles: [] as Array<BundleItem & { integrations: IntegrationItem[] }>, standalone: [] as IntegrationItem[] }\n\n const bundled = new Map<string, IntegrationItem[]>()\n const standalone: IntegrationItem[] = []\n for (const item of data.items) {\n if (item.bundleId) {\n const list = bundled.get(item.bundleId) ?? []\n list.push(item)\n bundled.set(item.bundleId, list)\n } else {\n standalone.push(item)\n }\n }\n\n const bundles = (data.bundles ?? [])\n .filter((b) => bundled.has(b.id))\n .map((b) => ({ ...b, integrations: bundled.get(b.id) ?? [] }))\n\n return { bundles, standalone }\n }, [data])\n\n const renderCategoryIcon = React.useCallback((category: string | undefined, className: string) => {\n if (!category) return null\n const Icon = CATEGORY_ICONS[category]\n if (!Icon) return null\n return <Icon className={className} />\n }, [])\n\n const renderHealthBadge = React.useCallback((status: IntegrationItem['healthStatus']) => {\n return (\n <span\n className={`inline-flex shrink-0 items-center rounded-full px-2 py-0.5 text-xs font-semibold uppercase tracking-wide ${HEALTH_BADGE_CLASS[status] ?? HEALTH_BADGE_CLASS.unconfigured}`}\n >\n {t(`integrations.marketplace.health.${status}`, status)}\n </span>\n )\n }, [t])\n\n if (isLoading && !data) {\n return (\n <Page>\n <PageBody>\n <div className=\"flex items-center justify-center py-16\">\n <Spinner />\n </div>\n </PageBody>\n </Page>\n )\n }\n\n return (\n <Page>\n <PageBody className=\"space-y-6\">\n <section className=\"space-y-6 rounded-lg border bg-background p-6\">\n <header className=\"flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between\">\n <div className=\"space-y-0.5\">\n <h2 className=\"text-lg font-semibold\">{t('integrations.marketplace.title')}</h2>\n <p className=\"text-sm text-muted-foreground\">\n {t('integrations.marketplace.description')}\n </p>\n </div>\n <div className=\"flex flex-wrap items-center gap-2\">\n <div className=\"relative w-full min-w-[200px] max-w-xs lg:w-64\">\n <Search className=\"absolute left-2.5 top-1/2 -translate-y-1/2 size-4 text-muted-foreground pointer-events-none\" />\n <Input\n placeholder={t('integrations.marketplace.search')}\n value={searchInput}\n onChange={(e) => setSearchInput(e.target.value)}\n className=\"pl-8\"\n />\n </div>\n <label className=\"flex items-center gap-2 text-sm text-muted-foreground\">\n <span className=\"sr-only\">{t('integrations.marketplace.sort.label', 'Sort by')}</span>\n <select\n className=\"h-9 rounded-md border border-input bg-background px-2 text-sm\"\n value={sortField}\n onChange={(e) => setSortField(e.target.value as typeof sortField)}\n >\n <option value=\"title\">{t('integrations.marketplace.sort.title', 'Title')}</option>\n <option value=\"category\">{t('integrations.marketplace.sort.category', 'Category')}</option>\n <option value=\"enabledAt\">{t('integrations.marketplace.sort.enabledAt', 'Enabled date')}</option>\n <option value=\"healthStatus\">{t('integrations.marketplace.sort.health', 'Health')}</option>\n </select>\n </label>\n <select\n className=\"h-9 rounded-md border border-input bg-background px-2 text-sm\"\n value={sortOrder}\n onChange={(e) => setSortOrder(e.target.value as typeof sortOrder)}\n aria-label={t('integrations.marketplace.sort.order', 'Sort order')}\n >\n <option value=\"asc\">{t('integrations.marketplace.sort.asc', 'Ascending')}</option>\n <option value=\"desc\">{t('integrations.marketplace.sort.desc', 'Descending')}</option>\n </select>\n </div>\n </header>\n\n <div className=\"lg:hidden\">\n <FilterBar\n searchValue={searchInput}\n onSearchChange={setSearchInput}\n searchPlaceholder={t('integrations.marketplace.search')}\n searchAlign=\"left\"\n filters={categoryFilters}\n values={filterValues}\n onApply={(values) => setFilterValues(normalizeIntegrationMarketplaceFilterValues(values))}\n onClear={() => setFilterValues({})}\n />\n </div>\n\n <div className=\"hidden lg:flex flex-wrap gap-1.5\">\n {INTEGRATION_MARKETPLACE_CATEGORIES.map((category) => {\n const Icon = CATEGORY_ICONS[category]\n return (\n <Button\n key={category}\n type=\"button\"\n variant={selectedCategory === category ? 'default' : 'outline'}\n size=\"sm\"\n onClick={() => setFilterValues(normalizeIntegrationMarketplaceFilterValues({ category }))}\n >\n {Icon ? <Icon className=\"mr-1.5 h-3.5 w-3.5\" /> : null}\n {t(`integrations.marketplace.categories.${category}`)}\n </Button>\n )\n })}\n </div>\n\n {isLoading ? (\n <div className=\"flex justify-center py-8\">\n <Spinner />\n </div>\n ) : null}\n\n {data && data.totalPages > 1 ? (\n <div className=\"flex flex-wrap items-center justify-between gap-2 text-sm text-muted-foreground\">\n <span>\n {data.total === 0\n ? t('integrations.marketplace.pagination.empty', 'No results')\n : t('integrations.marketplace.pagination.summary', {\n from: (data.page - 1) * data.pageSize + 1,\n to: Math.min(data.page * data.pageSize, data.total),\n total: data.total,\n })}\n </span>\n <div className=\"flex gap-2\">\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n disabled={data.page <= 1}\n onClick={() => setPage((p) => Math.max(1, p - 1))}\n >\n {t('integrations.marketplace.pagination.prev', 'Previous')}\n </Button>\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n disabled={data.page >= data.totalPages}\n onClick={() => setPage((p) => p + 1)}\n >\n {t('integrations.marketplace.pagination.next', 'Next')}\n </Button>\n </div>\n </div>\n ) : null}\n\n {grouped.bundles.map((bundle) => (\n <Card key={bundle.id}>\n <CardHeader>\n <div className=\"flex items-center justify-between\">\n <div>\n <CardTitle>{bundle.title}</CardTitle>\n {bundle.description && (\n <p className=\"text-muted-foreground text-sm mt-1\">{bundle.description}</p>\n )}\n <p className=\"text-muted-foreground text-xs mt-1\">\n {t('integrations.marketplace.integrations', { count: bundle.integrations.length })}\n </p>\n </div>\n <Button asChild variant=\"outline\" size=\"sm\">\n <Link href={`/backend/integrations/bundle/${encodeURIComponent(bundle.id)}`}>\n <Cog className=\"mr-1.5 h-4 w-4\" />\n {t('integrations.marketplace.configure')}\n </Link>\n </Button>\n </div>\n </CardHeader>\n <CardContent>\n <div className=\"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3\">\n {bundle.integrations.map((item) => (\n <div\n key={item.id}\n className=\"flex flex-col gap-2 rounded-lg border p-3\"\n >\n <div className=\"flex items-start justify-between gap-2\">\n <div className=\"min-w-0 space-y-1\">\n <div className=\"flex flex-wrap items-center gap-2\">\n {renderCategoryIcon(item.category, 'h-4 w-4 text-muted-foreground shrink-0')}\n <Link\n href={`/backend/integrations/${encodeURIComponent(item.id)}`}\n className=\"truncate text-sm font-medium hover:underline\"\n >\n {item.title}\n </Link>\n {renderHealthBadge(item.healthStatus)}\n </div>\n {(item.company || item.author || item.version) ? (\n <p className=\"text-xs text-muted-foreground\">\n {[item.company || item.author, item.version ? `v${item.version}` : null].filter(Boolean).join(' \u00B7 ')}\n </p>\n ) : null}\n </div>\n <Switch\n checked={item.isEnabled}\n disabled={togglingIds.has(item.id)}\n onCheckedChange={(checked) => void handleToggle(item.id, checked, item.stateUpdatedAt)}\n className=\"shrink-0\"\n />\n </div>\n <div className=\"flex items-end justify-between gap-2 border-t pt-2\">\n <div className=\"text-xs text-muted-foreground space-y-0.5\">\n <div>\n {t('integrations.marketplace.analytics.events', { count: item.analytics.totalCount })}\n </div>\n <div>\n {t('integrations.marketplace.analytics.errorRate', {\n rate: `${Math.round(item.analytics.errorRate * 1000) / 10}%`,\n })}\n </div>\n </div>\n <LogSparkline counts={item.analytics.dailyCounts} />\n </div>\n </div>\n ))}\n </div>\n </CardContent>\n </Card>\n ))}\n\n {grouped.standalone.length > 0 && (\n <div className=\"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4\">\n {grouped.standalone.map((item) => (\n <Card key={item.id} className=\"flex flex-col\">\n <CardHeader>\n <div className=\"flex items-start justify-between gap-2\">\n <div className=\"flex min-w-0 flex-wrap items-center gap-2\">\n {renderCategoryIcon(item.category, 'h-4 w-4 text-muted-foreground shrink-0')}\n <CardTitle className=\"text-base\">{item.title}</CardTitle>\n {renderHealthBadge(item.healthStatus)}\n </div>\n <Switch\n checked={item.isEnabled}\n disabled={togglingIds.has(item.id)}\n onCheckedChange={(checked) => void handleToggle(item.id, checked, item.stateUpdatedAt)}\n className=\"shrink-0\"\n />\n </div>\n </CardHeader>\n <CardContent className=\"flex-1 space-y-2\">\n {item.description && (\n <p className=\"text-muted-foreground text-sm\">{item.description}</p>\n )}\n {(item.company || item.author || item.version) && (\n <p className=\"text-muted-foreground text-xs\">\n {[item.company || item.author, item.version ? `v${item.version}` : null].filter(Boolean).join(' \u00B7 ')}\n </p>\n )}\n <div className=\"flex items-end justify-between gap-2 border-t pt-3\">\n <div className=\"text-xs text-muted-foreground space-y-0.5\">\n <div>\n {t('integrations.marketplace.analytics.events', { count: item.analytics.totalCount })}\n </div>\n <div>\n {t('integrations.marketplace.analytics.errorRate', {\n rate: `${Math.round(item.analytics.errorRate * 1000) / 10}%`,\n })}\n </div>\n </div>\n <LogSparkline counts={item.analytics.dailyCounts} />\n </div>\n </CardContent>\n <div className=\"px-6 pb-4\">\n <Button asChild variant=\"outline\" size=\"sm\" className=\"w-full\">\n <Link href={`/backend/integrations/${encodeURIComponent(item.id)}`}>\n <Cog className=\"mr-1.5 h-4 w-4\" />\n {t('integrations.marketplace.configure')}\n </Link>\n </Button>\n </div>\n </Card>\n ))}\n </div>\n )}\n\n {grouped.bundles.length === 0 && grouped.standalone.length === 0 && !isLoading && (\n <div className=\"text-center py-12 text-muted-foreground\">\n {t('integrations.marketplace.noResults')}\n </div>\n )}\n </section>\n </PageBody>\n </Page>\n )\n}\n"],
5
+ "mappings": ";AA2HM,cA0LM,YA1LN;AA1HN,YAAY,WAAW;AACvB,OAAO,UAAU;AACjB,SAAS,MAAM,gBAAgB;AAC/B,SAAS,MAAM,YAAY,WAAW,mBAAmB;AACzD,SAAS,cAAc;AACvB,SAAS,cAAc;AACvB,SAAS,aAAa;AACtB,SAAS,eAAe;AACxB,SAAS,SAAS,mCAAmC;AACrD,SAAS,iCAAiC;AAC1C,SAAS,0BAA0B;AACnC,SAAS,aAAa;AACtB,SAAS,mCAAmC;AAC5C,SAAS,YAAY;AACrB,SAAS,iBAAoC;AAC7C,SAAS,MAAM,KAAK,YAAY,WAAW,YAAY,eAAe,WAAW,QAAQ,OAAO,eAAe;AAC/G;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AA6CP,MAAM,iBAAoD;AAAA,EACxD,KAAK;AAAA,EACL,SAAS;AAAA,EACT,UAAU;AAAA,EACV,WAAW;AAAA,EACX,eAAe;AAAA,EACf,cAAc;AAAA,EACd,SAAS;AAAA,EACT,SAAS;AACX;AAEA,MAAM,qBAA6C;AAAA,EACjD,SAAS;AAAA,EACT,UAAU;AAAA,EACV,WAAW;AAAA,EACX,cAAc;AAChB;AAEA,SAAS,qBAAqB,OAUnB;AACT,QAAM,SAAS,IAAI,gBAAgB;AACnC,MAAI,MAAM,EAAG,QA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SAAO,MAAC,SAAQ,WAAU,MAAK,MAAK,WAAU,UACpD,+BAAC,QAAK,MAAM,yBAAyB,mBAAmB,KAAK,EAAE,CAAC,IAC9D;AAAA,4BAAC,OAAI,WAAU,kBAAiB;AAAA,QAC/B,EAAE,oCAAoC;AAAA,SACzC,GACF,GACF;AAAA,SA9CS,KAAK,EA+ChB,CACD,GACH;AAAA,IAGD,QAAQ,QAAQ,WAAW,KAAK,QAAQ,WAAW,WAAW,KAAK,CAAC,aACnE,oBAAC,SAAI,WAAU,2CACZ,YAAE,oCAAoC,GACzC;AAAA,KAEJ,GACF,GACF;AAEJ;",
6
6
  "names": []
7
7
  }
@@ -88,7 +88,7 @@ __decorateClass([
88
88
  Property({ name: "created_at", type: Date, onCreate: () => /* @__PURE__ */ new Date() })
89
89
  ], IntegrationCredentials.prototype, "createdAt", 2);
90
90
  __decorateClass([
91
- Property({ name: "updated_at", type: Date, onUpdate: () => /* @__PURE__ */ new Date() })
91
+ Property({ name: "updated_at", type: Date, onCreate: () => /* @__PURE__ */ new Date(), onUpdate: () => /* @__PURE__ */ new Date() })
92
92
  ], IntegrationCredentials.prototype, "updatedAt", 2);
93
93
  __decorateClass([
94
94
  Property({ name: "deleted_at", type: Date, nullable: true })
@@ -147,7 +147,7 @@ __decorateClass([
147
147
  Property({ name: "created_at", type: Date, onCreate: () => /* @__PURE__ */ new Date() })
148
148
  ], IntegrationState.prototype, "createdAt", 2);
149
149
  __decorateClass([
150
- Property({ name: "updated_at", type: Date, onUpdate: () => /* @__PURE__ */ new Date() })
150
+ Property({ name: "updated_at", type: Date, onCreate: () => /* @__PURE__ */ new Date(), onUpdate: () => /* @__PURE__ */ new Date() })
151
151
  ], IntegrationState.prototype, "updatedAt", 2);
152
152
  __decorateClass([
153
153
  Property({ name: "deleted_at", type: Date, nullable: true })
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/integrations/data/entities.ts"],
4
- "sourcesContent": ["import { OptionalProps } from '@mikro-orm/core'\nimport { Entity, Index, PrimaryKey, Property } from '@mikro-orm/decorators/legacy'\n\n@Entity({ tableName: 'sync_external_id_mappings' })\n@Index({ properties: ['internalEntityType', 'internalEntityId', 'organizationId'] })\n@Index({ properties: ['integrationId', 'externalId', 'organizationId'] })\nexport class SyncExternalIdMapping {\n [OptionalProps]?: 'syncStatus' | 'lastSyncedAt' | 'createdAt' | 'updatedAt' | 'deletedAt'\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n @Property({ name: 'integration_id', type: 'text' })\n integrationId!: string\n\n @Property({ name: 'internal_entity_type', type: 'text' })\n internalEntityType!: string\n\n @Property({ name: 'internal_entity_id', type: 'uuid' })\n internalEntityId!: string\n\n @Property({ name: 'external_id', type: 'text' })\n externalId!: string\n\n @Property({ name: 'sync_status', type: 'text', default: 'not_synced' })\n syncStatus: 'synced' | 'pending' | 'error' | 'not_synced' = 'not_synced'\n\n @Property({ name: 'last_synced_at', type: Date, nullable: true })\n lastSyncedAt?: Date | null\n\n @Property({ name: 'organization_id', type: 'uuid' })\n organizationId!: string\n\n @Property({ name: 'tenant_id', type: 'uuid' })\n tenantId!: string\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n\n @Property({ name: 'updated_at', type: Date, onUpdate: () => new Date() })\n updatedAt: Date = new Date()\n\n @Property({ name: 'deleted_at', type: Date, nullable: true })\n deletedAt?: Date | null\n}\n\n@Entity({ tableName: 'integration_credentials' })\n@Index({ properties: ['integrationId', 'organizationId', 'tenantId'] })\n@Index({\n name: 'integration_credentials_user_lookup_idx',\n expression:\n `create unique index \"integration_credentials_user_lookup_idx\" on \"integration_credentials\" (\"integration_id\", \"organization_id\", \"tenant_id\", \"user_id\") where \"user_id\" is not null and \"deleted_at\" is null`,\n})\nexport class IntegrationCredentials {\n [OptionalProps]?: 'createdAt' | 'updatedAt' | 'deletedAt' | 'userId'\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n @Property({ name: 'integration_id', type: 'text' })\n integrationId!: string\n\n @Property({ name: 'credentials', type: 'json' })\n credentials!: Record<string, unknown>\n\n @Property({ name: 'organization_id', type: 'uuid' })\n organizationId!: string\n\n @Property({ name: 'tenant_id', type: 'uuid' })\n tenantId!: string\n\n /**\n * Per-user secret scoping (additive \u2014 added by the email integration spec).\n *\n * NULL = tenant-wide secret (existing behaviour, e.g. shared WhatsApp Business token).\n * Set = per-user secret (e.g. Jane's personal Gmail OAuth refresh token).\n *\n * Cross-module link to `auth:user` is declared in\n * `packages/core/src/modules/communication_channels/data/extensions.ts` via\n * `EntityExtension` \u2014 no raw FOREIGN KEY constraint (root `AGENTS.md` rule:\n * \"No direct ORM relationships between modules\"). App-layer query callers\n * MUST scope by `user_id` on every per-user credential read.\n */\n @Property({ name: 'user_id', type: 'uuid', nullable: true })\n userId?: string | null\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n\n @Property({ name: 'updated_at', type: Date, onUpdate: () => new Date() })\n updatedAt: Date = new Date()\n\n @Property({ name: 'deleted_at', type: Date, nullable: true })\n deletedAt?: Date | null\n}\n\n@Entity({ tableName: 'integration_states' })\n@Index({ properties: ['integrationId', 'organizationId', 'tenantId'] })\nexport class IntegrationState {\n [OptionalProps]?: 'isEnabled' | 'apiVersion' | 'reauthRequired' | 'lastHealthStatus' | 'lastHealthCheckedAt' | 'lastHealthLatencyMs' | 'enabledAt' | 'createdAt' | 'updatedAt' | 'deletedAt'\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n @Property({ name: 'integration_id', type: 'text' })\n integrationId!: string\n\n @Property({ name: 'is_enabled', type: 'boolean', default: true })\n isEnabled: boolean = true\n\n @Property({ name: 'api_version', type: 'text', nullable: true })\n apiVersion?: string | null\n\n @Property({ name: 'reauth_required', type: 'boolean', default: false })\n reauthRequired: boolean = false\n\n @Property({ name: 'last_health_status', type: 'text', nullable: true })\n lastHealthStatus?: 'healthy' | 'degraded' | 'unhealthy' | null\n\n @Property({ name: 'last_health_checked_at', type: Date, nullable: true })\n lastHealthCheckedAt?: Date | null\n\n @Property({ name: 'last_health_latency_ms', type: 'int', nullable: true })\n lastHealthLatencyMs?: number | null\n\n @Property({ name: 'enabled_at', type: Date, nullable: true })\n enabledAt?: Date | null\n\n @Property({ name: 'organization_id', type: 'uuid' })\n organizationId!: string\n\n @Property({ name: 'tenant_id', type: 'uuid' })\n tenantId!: string\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n\n @Property({ name: 'updated_at', type: Date, onUpdate: () => new Date() })\n updatedAt: Date = new Date()\n\n @Property({ name: 'deleted_at', type: Date, nullable: true })\n deletedAt?: Date | null\n}\n\n@Entity({ tableName: 'integration_logs' })\n@Index({ properties: ['integrationId', 'organizationId', 'tenantId', 'createdAt'] })\n@Index({ properties: ['level', 'organizationId', 'tenantId', 'createdAt'] })\nexport class IntegrationLog {\n [OptionalProps]?: 'runId' | 'scopeEntityType' | 'scopeEntityId' | 'code' | 'payload' | 'createdAt'\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n @Property({ name: 'integration_id', type: 'text' })\n integrationId!: string\n\n @Property({ name: 'run_id', type: 'uuid', nullable: true })\n runId?: string | null\n\n @Property({ name: 'scope_entity_type', type: 'text', nullable: true })\n scopeEntityType?: string | null\n\n @Property({ name: 'scope_entity_id', type: 'uuid', nullable: true })\n scopeEntityId?: string | null\n\n @Property({ name: 'level', type: 'text' })\n level!: 'info' | 'warn' | 'error'\n\n @Property({ name: 'message', type: 'text' })\n message!: string\n\n @Property({ name: 'code', type: 'text', nullable: true })\n code?: string | null\n\n @Property({ name: 'payload', type: 'json', nullable: true })\n payload?: Record<string, unknown> | null\n\n @Property({ name: 'organization_id', type: 'uuid' })\n organizationId!: string\n\n @Property({ name: 'tenant_id', type: 'uuid' })\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jB9B,eAkBX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,WAAW,MAAM,OAAO,CAAC;AAAA,GApBhC,eAqBX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,QAAQ,MAAM,QAAQ,UAAU,KAAK,CAAC;AAAA,GAvB7C,eAwBX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,WAAW,MAAM,QAAQ,UAAU,KAAK,CAAC;AAAA,GA1BhD,eA2BX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,mBAAmB,MAAM,OAAO,CAAC;AAAA,GA7BxC,eA8BX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,aAAa,MAAM,OAAO,CAAC;AAAA,GAhClC,eAiCX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,cAAc,MAAM,MAAM,UAAU,MAAM,oBAAI,KAAK,EAAE,CAAC;AAAA,GAnC7D,eAoCX;AApCW,iBAAN;AAAA,EAHN,OAAO,EAAE,WAAW,mBAAmB,CAAC;AAAA,EACxC,MAAM,EAAE,YAAY,CAAC,iBAAiB,kBAAkB,YAAY,WAAW,EAAE,CAAC;AAAA,EAClF,MAAM,EAAE,YAAY,CAAC,SAAS,kBAAkB,YAAY,WAAW,EAAE,CAAC;AAAA,GAC9D;",
4
+ "sourcesContent": ["import { OptionalProps } from '@mikro-orm/core'\nimport { Entity, Index, PrimaryKey, Property } from '@mikro-orm/decorators/legacy'\n\n@Entity({ tableName: 'sync_external_id_mappings' })\n@Index({ properties: ['internalEntityType', 'internalEntityId', 'organizationId'] })\n@Index({ properties: ['integrationId', 'externalId', 'organizationId'] })\nexport class SyncExternalIdMapping {\n [OptionalProps]?: 'syncStatus' | 'lastSyncedAt' | 'createdAt' | 'updatedAt' | 'deletedAt'\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n @Property({ name: 'integration_id', type: 'text' })\n integrationId!: string\n\n @Property({ name: 'internal_entity_type', type: 'text' })\n internalEntityType!: string\n\n @Property({ name: 'internal_entity_id', type: 'uuid' })\n internalEntityId!: string\n\n @Property({ name: 'external_id', type: 'text' })\n externalId!: string\n\n @Property({ name: 'sync_status', type: 'text', default: 'not_synced' })\n syncStatus: 'synced' | 'pending' | 'error' | 'not_synced' = 'not_synced'\n\n @Property({ name: 'last_synced_at', type: Date, nullable: true })\n lastSyncedAt?: Date | null\n\n @Property({ name: 'organization_id', type: 'uuid' })\n organizationId!: string\n\n @Property({ name: 'tenant_id', type: 'uuid' })\n tenantId!: string\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n\n @Property({ name: 'updated_at', type: Date, onUpdate: () => new Date() })\n updatedAt: Date = new Date()\n\n @Property({ name: 'deleted_at', type: Date, nullable: true })\n deletedAt?: Date | null\n}\n\n@Entity({ tableName: 'integration_credentials' })\n@Index({ properties: ['integrationId', 'organizationId', 'tenantId'] })\n@Index({\n name: 'integration_credentials_user_lookup_idx',\n expression:\n `create unique index \"integration_credentials_user_lookup_idx\" on \"integration_credentials\" (\"integration_id\", \"organization_id\", \"tenant_id\", \"user_id\") where \"user_id\" is not null and \"deleted_at\" is null`,\n})\nexport class IntegrationCredentials {\n [OptionalProps]?: 'createdAt' | 'updatedAt' | 'deletedAt' | 'userId'\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n @Property({ name: 'integration_id', type: 'text' })\n integrationId!: string\n\n @Property({ name: 'credentials', type: 'json' })\n credentials!: Record<string, unknown>\n\n @Property({ name: 'organization_id', type: 'uuid' })\n organizationId!: string\n\n @Property({ name: 'tenant_id', type: 'uuid' })\n tenantId!: string\n\n /**\n * Per-user secret scoping (additive \u2014 added by the email integration spec).\n *\n * NULL = tenant-wide secret (existing behaviour, e.g. shared WhatsApp Business token).\n * Set = per-user secret (e.g. Jane's personal Gmail OAuth refresh token).\n *\n * Cross-module link to `auth:user` is declared in\n * `packages/core/src/modules/communication_channels/data/extensions.ts` via\n * `EntityExtension` \u2014 no raw FOREIGN KEY constraint (root `AGENTS.md` rule:\n * \"No direct ORM relationships between modules\"). App-layer query callers\n * MUST scope by `user_id` on every per-user credential read.\n */\n @Property({ name: 'user_id', type: 'uuid', nullable: true })\n userId?: string | null\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n\n @Property({ name: 'updated_at', type: Date, onCreate: () => new Date(), onUpdate: () => new Date() })\n updatedAt: Date = new Date()\n\n @Property({ name: 'deleted_at', type: Date, nullable: true })\n deletedAt?: Date | null\n}\n\n@Entity({ tableName: 'integration_states' })\n@Index({ properties: ['integrationId', 'organizationId', 'tenantId'] })\nexport class IntegrationState {\n [OptionalProps]?: 'isEnabled' | 'apiVersion' | 'reauthRequired' | 'lastHealthStatus' | 'lastHealthCheckedAt' | 'lastHealthLatencyMs' | 'enabledAt' | 'createdAt' | 'updatedAt' | 'deletedAt'\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n @Property({ name: 'integration_id', type: 'text' })\n integrationId!: string\n\n @Property({ name: 'is_enabled', type: 'boolean', default: true })\n isEnabled: boolean = true\n\n @Property({ name: 'api_version', type: 'text', nullable: true })\n apiVersion?: string | null\n\n @Property({ name: 'reauth_required', type: 'boolean', default: false })\n reauthRequired: boolean = false\n\n @Property({ name: 'last_health_status', type: 'text', nullable: true })\n lastHealthStatus?: 'healthy' | 'degraded' | 'unhealthy' | null\n\n @Property({ name: 'last_health_checked_at', type: Date, nullable: true })\n lastHealthCheckedAt?: Date | null\n\n @Property({ name: 'last_health_latency_ms', type: 'int', nullable: true })\n lastHealthLatencyMs?: number | null\n\n @Property({ name: 'enabled_at', type: Date, nullable: true })\n enabledAt?: Date | null\n\n @Property({ name: 'organization_id', type: 'uuid' })\n organizationId!: string\n\n @Property({ name: 'tenant_id', type: 'uuid' })\n tenantId!: string\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n\n @Property({ name: 'updated_at', type: Date, onCreate: () => new Date(), onUpdate: () => new Date() })\n updatedAt: Date = new Date()\n\n @Property({ name: 'deleted_at', type: Date, nullable: true })\n deletedAt?: Date | null\n}\n\n@Entity({ tableName: 'integration_logs' })\n@Index({ properties: ['integrationId', 'organizationId', 'tenantId', 'createdAt'] })\n@Index({ properties: ['level', 'organizationId', 'tenantId', 'createdAt'] })\nexport class IntegrationLog {\n [OptionalProps]?: 'runId' | 'scopeEntityType' | 'scopeEntityId' | 'code' | 'payload' | 'createdAt'\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n @Property({ name: 'integration_id', type: 'text' })\n integrationId!: string\n\n @Property({ name: 'run_id', type: 'uuid', nullable: true })\n runId?: string | null\n\n @Property({ name: 'scope_entity_type', type: 'text', nullable: true })\n scopeEntityType?: string | null\n\n @Property({ name: 'scope_entity_id', type: 'uuid', nullable: true })\n scopeEntityId?: string | null\n\n @Property({ name: 'level', type: 'text' })\n level!: 'info' | 'warn' | 'error'\n\n @Property({ name: 'message', type: 'text' })\n message!: string\n\n @Property({ name: 'code', type: 'text', nullable: true })\n code?: string | null\n\n @Property({ name: 'payload', type: 'json', nullable: true })\n payload?: Record<string, unknown> | null\n\n @Property({ name: 'organization_id', type: 'uuid' })\n organizationId!: string\n\n @Property({ name: 'tenant_id', type: 'uuid' })\n tenantId!: string\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n}\n"],
5
+ "mappings": ";;;;;;;;;;AAAA,SAAS,qBAAqB;AAC9B,SAAS,QAAQ,OAAO,YAAY,gBAAgB;AAMjD;AADI,IAAM,wBAAN,MAA4B;AAAA,EAA5B;AAkBL,sBAA4D;AAY5D,qBAAkB,oBAAI,KAAK;AAG3B,qBAAkB,oBAAI,KAAK;AAAA;AAI7B;AAlCE;AAAA,EADC,WAAW,EAAE,MAAM,QAAQ,YAAY,oBAAoB,CAAC;AAAA,GAFlD,sBAGX;AAGA;AAAA,EADC,SA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O,CAAC;AAAA,GA7BxC,eA8BX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,aAAa,MAAM,OAAO,CAAC;AAAA,GAhClC,eAiCX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,cAAc,MAAM,MAAM,UAAU,MAAM,oBAAI,KAAK,EAAE,CAAC;AAAA,GAnC7D,eAoCX;AApCW,iBAAN;AAAA,EAHN,OAAO,EAAE,WAAW,mBAAmB,CAAC;AAAA,EACxC,MAAM,EAAE,YAAY,CAAC,iBAAiB,kBAAkB,YAAY,WAAW,EAAE,CAAC;AAAA,EAClF,MAAM,EAAE,YAAY,CAAC,SAAS,kBAAkB,YAAY,WAAW,EAAE,CAAC;AAAA,GAC9D;",
6
6
  "names": []
7
7
  }
@@ -124,6 +124,38 @@ function createCredentialsService(em) {
124
124
  if (!row) return null;
125
125
  return decryptCredentialsBlob(row.credentials, scope);
126
126
  },
127
+ async getRowUpdatedAt(integrationId, scope) {
128
+ let row = await findOneWithDecryption(
129
+ em,
130
+ IntegrationCredentials,
131
+ buildCredentialsFilter(integrationId, scope),
132
+ void 0,
133
+ scope
134
+ );
135
+ if (!row && scope.userId) {
136
+ row = await findOneWithDecryption(
137
+ em,
138
+ IntegrationCredentials,
139
+ buildCredentialsFilter(integrationId, { ...scope, userId: null }),
140
+ void 0,
141
+ scope
142
+ );
143
+ }
144
+ return row?.updatedAt ?? null;
145
+ },
146
+ /**
147
+ * Resolve the persisted `updated_at` version for the credentials a caller
148
+ * would read via {@link resolve} (direct row first, then the bundle
149
+ * fallthrough). Returns `null` when no credentials row exists yet — the
150
+ * optimistic-lock guard treats a missing current version as "no conflict".
151
+ */
152
+ async resolveUpdatedAt(integrationId, scope) {
153
+ const direct = await this.getRowUpdatedAt(integrationId, scope);
154
+ if (direct) return direct;
155
+ const definition = getIntegration(integrationId);
156
+ if (!definition?.bundleId) return null;
157
+ return this.getRowUpdatedAt(definition.bundleId, scope);
158
+ },
127
159
  async resolve(integrationId, scope) {
128
160
  const direct = await this.getRaw(integrationId, scope);
129
161
  if (direct) return direct;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/integrations/lib/credentials-service.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { decryptWithAesGcm, encryptWithAesGcm } from '@open-mercato/shared/lib/encryption/aes'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { createKmsService } from '@open-mercato/shared/lib/encryption/kms'\nimport { parseDecryptedFieldValue } from '@open-mercato/shared/lib/encryption/tenantDataEncryptionService'\nimport {\n getBundle,\n getIntegration,\n resolveIntegrationCredentialsSchema,\n type IntegrationScope,\n} from '@open-mercato/shared/modules/integrations/types'\nimport { EncryptionMap } from '../../entities/data/entities'\nimport { IntegrationCredentials } from '../data/entities'\n\nconst ENCRYPTED_CREDENTIALS_BLOB_KEY = '__om_encrypted_credentials_blob_v1'\n\n/**\n * Raised when integration credentials cannot be encrypted or decrypted because\n * no tenant DEK is available \u2014 typically a production deployment with neither\n * Vault nor `TENANT_DATA_ENCRYPTION_FALLBACK_KEY` (or equivalent env vars)\n * configured. The credentials path deliberately fails closed instead of using\n * a hardcoded fallback secret; see security tracker finding #7.\n */\nexport class CredentialsEncryptionUnavailableError extends Error {\n readonly code = 'CREDENTIALS_ENCRYPTION_UNAVAILABLE'\n constructor(tenantId: string) {\n super(\n `Cannot encrypt or decrypt integration credentials for tenant ${tenantId}: ` +\n `no tenant DEK is available. Configure Vault (VAULT_ADDR/VAULT_TOKEN) or ` +\n `set TENANT_DATA_ENCRYPTION_FALLBACK_KEY in the environment.`,\n )\n this.name = 'CredentialsEncryptionUnavailableError'\n }\n}\n\nexport function isCredentialsEncryptionUnavailableError(error: unknown): error is CredentialsEncryptionUnavailableError {\n return error instanceof CredentialsEncryptionUnavailableError\n}\n\nfunction isRecordValue(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction normalizeCredentialsRecord(value: unknown): Record<string, unknown> {\n if (isRecordValue(value)) return value\n if (typeof value !== 'string') return {}\n\n const parsed = parseDecryptedFieldValue(value)\n return isRecordValue(parsed) ? parsed : {}\n}\n\n/**\n * Build the where-filter for credential lookups.\n *\n * Per-user scoping (added 2026-05-26): when `scope.userId` is set, the filter\n * matches the row owned by that user \u2014 different users on the same tenant get\n * their OWN row for the same provider. When `scope.userId` is `undefined` /\n * `null`, the filter matches tenant-wide credentials (existing behaviour,\n * e.g. shared Stripe/Akeneo API keys).\n *\n * The partial unique index `integration_credentials_user_lookup_idx` enforces\n * uniqueness across `(integration_id, organization_id, tenant_id, user_id)`\n * when `user_id IS NOT NULL`.\n */\nexport function buildCredentialsFilter(integrationId: string, scope: IntegrationScope) {\n const base = {\n integrationId,\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n deletedAt: null,\n } as Record<string, unknown>\n if (scope.userId) {\n base.userId = scope.userId\n } else {\n base.userId = null\n }\n return base\n}\n\nexport function createCredentialsService(em: EntityManager) {\n const credentialsEncryptionSpec = [{ field: 'credentials' }]\n\n async function ensureCredentialsEncryptionMap(scope: IntegrationScope): Promise<void> {\n const existing = await findOneWithDecryption(\n em,\n EncryptionMap,\n {\n entityId: 'integrations:integration_credentials',\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n },\n undefined,\n scope,\n )\n\n if (!existing) {\n const created = em.create(EncryptionMap, {\n entityId: 'integrations:integration_credentials',\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n fieldsJson: credentialsEncryptionSpec,\n isActive: true,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n em.persist(created)\n return\n }\n\n existing.fieldsJson = credentialsEncryptionSpec\n existing.isActive = true\n }\n\n async function resolveCredentialsDek(scope: IntegrationScope): Promise<string> {\n const kms = createKmsService()\n const existing = await kms.getTenantDek(scope.tenantId)\n if (existing?.key) return existing.key\n\n const created = await kms.createTenantDek(scope.tenantId)\n if (created?.key) return created.key\n\n throw new CredentialsEncryptionUnavailableError(scope.tenantId)\n }\n\n async function encryptCredentialsBlob(\n credentials: Record<string, unknown>,\n scope: IntegrationScope,\n ): Promise<Record<string, unknown>> {\n const dek = await resolveCredentialsDek(scope)\n const payload = encryptWithAesGcm(JSON.stringify(credentials), dek)\n return { [ENCRYPTED_CREDENTIALS_BLOB_KEY]: payload.value }\n }\n\n async function decryptCredentialsBlob(\n credentialsInput: unknown,\n scope: IntegrationScope,\n ): Promise<Record<string, unknown>> {\n const credentials = normalizeCredentialsRecord(credentialsInput)\n const encrypted = credentials[ENCRYPTED_CREDENTIALS_BLOB_KEY]\n if (typeof encrypted !== 'string' || !encrypted) return credentials\n\n const dek = await resolveCredentialsDek(scope)\n const decryptedRaw = decryptWithAesGcm(encrypted, dek)\n if (!decryptedRaw) return {}\n\n try {\n const parsed = JSON.parse(decryptedRaw) as unknown\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {}\n } catch {\n return {}\n }\n }\n\n return {\n async getRaw(integrationId: string, scope: IntegrationScope): Promise<Record<string, unknown> | null> {\n let row = await findOneWithDecryption(\n em,\n IntegrationCredentials,\n buildCredentialsFilter(integrationId, scope),\n undefined,\n scope,\n )\n // Spec 2026-05-21 (email-integration-foundation) \"Hub credentials store\":\n // per-user secrets resolve as `WHERE user_id = currentUser.id OR user_id IS NULL`.\n // A user-scoped read of a TENANT-WIDE integration (sync_excel, Stripe, Akeneo,\n // S3, the channel OAuth *client* config) MUST still find the shared\n // `user_id = NULL` row \u2014 the per-user row takes precedence, and we only fall\n // back to the tenant-wide row when the user has none of their own. Writes stay\n // strict (`save` uses the unmodified filter) so a per-user save never clobbers\n // the shared credential.\n if (!row && scope.userId) {\n row = await findOneWithDecryption(\n em,\n IntegrationCredentials,\n buildCredentialsFilter(integrationId, { ...scope, userId: null }),\n undefined,\n scope,\n )\n }\n if (!row) return null\n return decryptCredentialsBlob(row.credentials, scope)\n },\n\n async resolve(integrationId: string, scope: IntegrationScope): Promise<Record<string, unknown> | null> {\n const direct = await this.getRaw(integrationId, scope)\n if (direct) return direct\n\n const definition = getIntegration(integrationId)\n if (!definition?.bundleId) return null\n return this.getRaw(definition.bundleId, scope)\n },\n\n async save(integrationId: string, credentials: Record<string, unknown>, scope: IntegrationScope): Promise<void> {\n const encryptedCredentials = await encryptCredentialsBlob(credentials, scope)\n await ensureCredentialsEncryptionMap(scope)\n\n const row = await findOneWithDecryption(\n em,\n IntegrationCredentials,\n buildCredentialsFilter(integrationId, scope),\n undefined,\n scope,\n )\n\n if (row) {\n row.credentials = encryptedCredentials\n await em.flush()\n return\n }\n\n const created = em.create(IntegrationCredentials, {\n integrationId,\n credentials: encryptedCredentials,\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n ...(scope.userId ? { userId: scope.userId } : {}),\n })\n await em.persist(created).flush()\n },\n\n async saveField(\n integrationId: string,\n fieldKey: string,\n value: unknown,\n scope: IntegrationScope,\n ): Promise<Record<string, unknown>> {\n const current = (await this.getRaw(integrationId, scope)) ?? {}\n const updated = { ...current, [fieldKey]: value }\n await this.save(integrationId, updated, scope)\n return updated\n },\n\n getSchema(integrationId: string) {\n const definition = getIntegration(integrationId)\n if (!definition) return undefined\n\n if (definition.bundleId) {\n const bundle = getBundle(definition.bundleId)\n return bundle?.credentials ?? resolveIntegrationCredentialsSchema(integrationId)\n }\n\n return definition.credentials ?? resolveIntegrationCredentialsSchema(integrationId)\n },\n }\n}\n\nexport type CredentialsService = ReturnType<typeof createCredentialsService>\n"],
5
- "mappings": "AACA,SAAS,mBAAmB,yBAAyB;AACrD,SAAS,6BAA6B;AACtC,SAAS,wBAAwB;AACjC,SAAS,gCAAgC;AACzC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,qBAAqB;AAC9B,SAAS,8BAA8B;AAEvC,MAAM,iCAAiC;AAShC,MAAM,8CAA8C,MAAM;AAAA,EAE/D,YAAY,UAAkB;AAC5B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AAAA,IACT;AAAA,IAEA,UAAU,eAAuB;AAC/B,YAAM,aAAa,eAAe,aAAa;AAC/C,UAAI,CAAC,WAAY,QAAO;AAExB,UAAI,WAAW,UAAU;AACvB,cAAM,SAAS,UAAU,WAAW,QAAQ;AAC5C,eAAO,QAAQ,eAAe,oCAAoC,aAAa;AAAA,MACjF;AAEA,aAAO,WAAW,eAAe,oCAAoC,aAAa;AAAA,IACpF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { decryptWithAesGcm, encryptWithAesGcm } from '@open-mercato/shared/lib/encryption/aes'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { createKmsService } from '@open-mercato/shared/lib/encryption/kms'\nimport { parseDecryptedFieldValue } from '@open-mercato/shared/lib/encryption/tenantDataEncryptionService'\nimport {\n getBundle,\n getIntegration,\n resolveIntegrationCredentialsSchema,\n type IntegrationScope,\n} from '@open-mercato/shared/modules/integrations/types'\nimport { EncryptionMap } from '../../entities/data/entities'\nimport { IntegrationCredentials } from '../data/entities'\n\nconst ENCRYPTED_CREDENTIALS_BLOB_KEY = '__om_encrypted_credentials_blob_v1'\n\n/**\n * Raised when integration credentials cannot be encrypted or decrypted because\n * no tenant DEK is available \u2014 typically a production deployment with neither\n * Vault nor `TENANT_DATA_ENCRYPTION_FALLBACK_KEY` (or equivalent env vars)\n * configured. The credentials path deliberately fails closed instead of using\n * a hardcoded fallback secret; see security tracker finding #7.\n */\nexport class CredentialsEncryptionUnavailableError extends Error {\n readonly code = 'CREDENTIALS_ENCRYPTION_UNAVAILABLE'\n constructor(tenantId: string) {\n super(\n `Cannot encrypt or decrypt integration credentials for tenant ${tenantId}: ` +\n `no tenant DEK is available. Configure Vault (VAULT_ADDR/VAULT_TOKEN) or ` +\n `set TENANT_DATA_ENCRYPTION_FALLBACK_KEY in the environment.`,\n )\n this.name = 'CredentialsEncryptionUnavailableError'\n }\n}\n\nexport function isCredentialsEncryptionUnavailableError(error: unknown): error is CredentialsEncryptionUnavailableError {\n return error instanceof CredentialsEncryptionUnavailableError\n}\n\nfunction isRecordValue(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction normalizeCredentialsRecord(value: unknown): Record<string, unknown> {\n if (isRecordValue(value)) return value\n if (typeof value !== 'string') return {}\n\n const parsed = parseDecryptedFieldValue(value)\n return isRecordValue(parsed) ? parsed : {}\n}\n\n/**\n * Build the where-filter for credential lookups.\n *\n * Per-user scoping (added 2026-05-26): when `scope.userId` is set, the filter\n * matches the row owned by that user \u2014 different users on the same tenant get\n * their OWN row for the same provider. When `scope.userId` is `undefined` /\n * `null`, the filter matches tenant-wide credentials (existing behaviour,\n * e.g. shared Stripe/Akeneo API keys).\n *\n * The partial unique index `integration_credentials_user_lookup_idx` enforces\n * uniqueness across `(integration_id, organization_id, tenant_id, user_id)`\n * when `user_id IS NOT NULL`.\n */\nexport function buildCredentialsFilter(integrationId: string, scope: IntegrationScope) {\n const base = {\n integrationId,\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n deletedAt: null,\n } as Record<string, unknown>\n if (scope.userId) {\n base.userId = scope.userId\n } else {\n base.userId = null\n }\n return base\n}\n\nexport function createCredentialsService(em: EntityManager) {\n const credentialsEncryptionSpec = [{ field: 'credentials' }]\n\n async function ensureCredentialsEncryptionMap(scope: IntegrationScope): Promise<void> {\n const existing = await findOneWithDecryption(\n em,\n EncryptionMap,\n {\n entityId: 'integrations:integration_credentials',\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n },\n undefined,\n scope,\n )\n\n if (!existing) {\n const created = em.create(EncryptionMap, {\n entityId: 'integrations:integration_credentials',\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n fieldsJson: credentialsEncryptionSpec,\n isActive: true,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n em.persist(created)\n return\n }\n\n existing.fieldsJson = credentialsEncryptionSpec\n existing.isActive = true\n }\n\n async function resolveCredentialsDek(scope: IntegrationScope): Promise<string> {\n const kms = createKmsService()\n const existing = await kms.getTenantDek(scope.tenantId)\n if (existing?.key) return existing.key\n\n const created = await kms.createTenantDek(scope.tenantId)\n if (created?.key) return created.key\n\n throw new CredentialsEncryptionUnavailableError(scope.tenantId)\n }\n\n async function encryptCredentialsBlob(\n credentials: Record<string, unknown>,\n scope: IntegrationScope,\n ): Promise<Record<string, unknown>> {\n const dek = await resolveCredentialsDek(scope)\n const payload = encryptWithAesGcm(JSON.stringify(credentials), dek)\n return { [ENCRYPTED_CREDENTIALS_BLOB_KEY]: payload.value }\n }\n\n async function decryptCredentialsBlob(\n credentialsInput: unknown,\n scope: IntegrationScope,\n ): Promise<Record<string, unknown>> {\n const credentials = normalizeCredentialsRecord(credentialsInput)\n const encrypted = credentials[ENCRYPTED_CREDENTIALS_BLOB_KEY]\n if (typeof encrypted !== 'string' || !encrypted) return credentials\n\n const dek = await resolveCredentialsDek(scope)\n const decryptedRaw = decryptWithAesGcm(encrypted, dek)\n if (!decryptedRaw) return {}\n\n try {\n const parsed = JSON.parse(decryptedRaw) as unknown\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {}\n } catch {\n return {}\n }\n }\n\n return {\n async getRaw(integrationId: string, scope: IntegrationScope): Promise<Record<string, unknown> | null> {\n let row = await findOneWithDecryption(\n em,\n IntegrationCredentials,\n buildCredentialsFilter(integrationId, scope),\n undefined,\n scope,\n )\n // Spec 2026-05-21 (email-integration-foundation) \"Hub credentials store\":\n // per-user secrets resolve as `WHERE user_id = currentUser.id OR user_id IS NULL`.\n // A user-scoped read of a TENANT-WIDE integration (sync_excel, Stripe, Akeneo,\n // S3, the channel OAuth *client* config) MUST still find the shared\n // `user_id = NULL` row \u2014 the per-user row takes precedence, and we only fall\n // back to the tenant-wide row when the user has none of their own. Writes stay\n // strict (`save` uses the unmodified filter) so a per-user save never clobbers\n // the shared credential.\n if (!row && scope.userId) {\n row = await findOneWithDecryption(\n em,\n IntegrationCredentials,\n buildCredentialsFilter(integrationId, { ...scope, userId: null }),\n undefined,\n scope,\n )\n }\n if (!row) return null\n return decryptCredentialsBlob(row.credentials, scope)\n },\n\n async getRowUpdatedAt(integrationId: string, scope: IntegrationScope): Promise<Date | null> {\n let row = await findOneWithDecryption(\n em,\n IntegrationCredentials,\n buildCredentialsFilter(integrationId, scope),\n undefined,\n scope,\n )\n if (!row && scope.userId) {\n row = await findOneWithDecryption(\n em,\n IntegrationCredentials,\n buildCredentialsFilter(integrationId, { ...scope, userId: null }),\n undefined,\n scope,\n )\n }\n return row?.updatedAt ?? null\n },\n\n /**\n * Resolve the persisted `updated_at` version for the credentials a caller\n * would read via {@link resolve} (direct row first, then the bundle\n * fallthrough). Returns `null` when no credentials row exists yet \u2014 the\n * optimistic-lock guard treats a missing current version as \"no conflict\".\n */\n async resolveUpdatedAt(integrationId: string, scope: IntegrationScope): Promise<Date | null> {\n const direct = await this.getRowUpdatedAt(integrationId, scope)\n if (direct) return direct\n\n const definition = getIntegration(integrationId)\n if (!definition?.bundleId) return null\n return this.getRowUpdatedAt(definition.bundleId, scope)\n },\n\n async resolve(integrationId: string, scope: IntegrationScope): Promise<Record<string, unknown> | null> {\n const direct = await this.getRaw(integrationId, scope)\n if (direct) return direct\n\n const definition = getIntegration(integrationId)\n if (!definition?.bundleId) return null\n return this.getRaw(definition.bundleId, scope)\n },\n\n async save(integrationId: string, credentials: Record<string, unknown>, scope: IntegrationScope): Promise<void> {\n const encryptedCredentials = await encryptCredentialsBlob(credentials, scope)\n await ensureCredentialsEncryptionMap(scope)\n\n const row = await findOneWithDecryption(\n em,\n IntegrationCredentials,\n buildCredentialsFilter(integrationId, scope),\n undefined,\n scope,\n )\n\n if (row) {\n row.credentials = encryptedCredentials\n await em.flush()\n return\n }\n\n const created = em.create(IntegrationCredentials, {\n integrationId,\n credentials: encryptedCredentials,\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n ...(scope.userId ? { userId: scope.userId } : {}),\n })\n await em.persist(created).flush()\n },\n\n async saveField(\n integrationId: string,\n fieldKey: string,\n value: unknown,\n scope: IntegrationScope,\n ): Promise<Record<string, unknown>> {\n const current = (await this.getRaw(integrationId, scope)) ?? {}\n const updated = { ...current, [fieldKey]: value }\n await this.save(integrationId, updated, scope)\n return updated\n },\n\n getSchema(integrationId: string) {\n const definition = getIntegration(integrationId)\n if (!definition) return undefined\n\n if (definition.bundleId) {\n const bundle = getBundle(definition.bundleId)\n return bundle?.credentials ?? resolveIntegrationCredentialsSchema(integrationId)\n }\n\n return definition.credentials ?? resolveIntegrationCredentialsSchema(integrationId)\n },\n }\n}\n\nexport type CredentialsService = ReturnType<typeof createCredentialsService>\n"],
5
+ "mappings": "AACA,SAAS,mBAAmB,yBAAyB;AACrD,SAAS,6BAA6B;AACtC,SAAS,wBAAwB;AACjC,SAAS,gCAAgC;AACzC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,qBAAqB;AAC9B,SAAS,8BAA8B;AAEvC,MAAM,iCAAiC;AAShC,MAAM,8CAA8C,MAAM;AAAA,EAE/D,YAAY,UAAkB;AAC5B;AAAA,MACE,gEAAgE,QAAQ;AAAA,IAG1E;AANF,SAAS,OAAO;AAOd,SAAK,OAAO;AAAA,EACd;AACF;AAEO,SAAS,wCAAwC,OAAgE;AACtH,SAAO,iBAAiB;AAC1B;AAEA,SAAS,cAAc,OAAkD;AACvE,SAAO,CAAC,CAAC,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AACrE;AAEA,SAAS,2BAA2B,OAAyC;AAC3E,MAAI,cAAc,KAAK,EAAG,QAAO;AACjC,MAAI,OAAO,UAAU,SAAU,QAAO,CAAC;AAEvC,QAAM,SAAS,yBAAyB,KAAK;AAC7C,SAAO,cAAc,MAAM,IAAI,SAAS,CAAC;AAC3C;AAeO,SAAS,uBAAuB,eAAuB,OAAyB;AACrF,QAAM,OAAO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AAM,KAAK,OAAO,eAAe,KAAK,KAAM,CAAC;AAC9D,YAAM,UAAU,EAAE,GAAG,SAAS,CAAC,QAAQ,GAAG,MAAM;AAChD,YAAM,KAAK,KAAK,eAAe,SAAS,KAAK;AAC7C,aAAO;AAAA,IACT;AAAA,IAEA,UAAU,eAAuB;AAC/B,YAAM,aAAa,eAAe,aAAa;AAC/C,UAAI,CAAC,WAAY,QAAO;AAExB,UAAI,WAAW,UAAU;AACvB,cAAM,SAAS,UAAU,WAAW,QAAQ;AAC5C,eAAO,QAAQ,eAAe,oCAAoC,aAAa;AAAA,MACjF;AAEA,aAAO,WAAW,eAAe,oCAAoC,aAAa;AAAA,IACpF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -11,7 +11,8 @@ function createIntegrationStateService(em) {
11
11
  lastHealthStatus: null,
12
12
  lastHealthCheckedAt: null,
13
13
  lastHealthLatencyMs: null,
14
- enabledAt: null
14
+ enabledAt: null,
15
+ updatedAt: null
15
16
  };
16
17
  }
17
18
  return {
@@ -39,7 +40,8 @@ function createIntegrationStateService(em) {
39
40
  lastHealthStatus: state?.lastHealthStatus ?? null,
40
41
  lastHealthCheckedAt: state?.lastHealthCheckedAt ?? null,
41
42
  lastHealthLatencyMs: state?.lastHealthLatencyMs ?? null,
42
- enabledAt: state?.enabledAt ?? null
43
+ enabledAt: state?.enabledAt ?? null,
44
+ updatedAt: state?.updatedAt ?? null
43
45
  };
44
46
  },
45
47
  async isEnabled(integrationId, scope) {