@asteby/metacore-runtime-react 53.4.1 → 53.6.0

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 (68) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +73 -0
  3. package/dist/index.d.ts +2 -0
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +4 -0
  6. package/dist/setup/addon-config-surface.d.ts +119 -0
  7. package/dist/setup/addon-config-surface.d.ts.map +1 -0
  8. package/dist/setup/addon-config-surface.js +662 -0
  9. package/dist/setup/connector-blocks-model.d.ts +79 -0
  10. package/dist/setup/connector-blocks-model.d.ts.map +1 -0
  11. package/dist/setup/connector-blocks-model.js +96 -0
  12. package/dist/setup/connector-blocks.d.ts +48 -0
  13. package/dist/setup/connector-blocks.d.ts.map +1 -0
  14. package/dist/setup/connector-blocks.js +132 -0
  15. package/dist/setup/connector-form-model.d.ts +40 -0
  16. package/dist/setup/connector-form-model.d.ts.map +1 -0
  17. package/dist/setup/connector-form-model.js +76 -0
  18. package/dist/setup/flow-model.d.ts +49 -0
  19. package/dist/setup/flow-model.d.ts.map +1 -0
  20. package/dist/setup/flow-model.js +124 -0
  21. package/dist/setup/health-card.d.ts +25 -0
  22. package/dist/setup/health-card.d.ts.map +1 -0
  23. package/dist/setup/health-card.js +21 -0
  24. package/dist/setup/index.d.ts +13 -0
  25. package/dist/setup/index.d.ts.map +1 -0
  26. package/dist/setup/index.js +15 -0
  27. package/dist/setup/messages.d.ts +15 -0
  28. package/dist/setup/messages.d.ts.map +1 -0
  29. package/dist/setup/messages.js +320 -0
  30. package/dist/setup/records-table.d.ts +24 -0
  31. package/dist/setup/records-table.d.ts.map +1 -0
  32. package/dist/setup/records-table.js +80 -0
  33. package/dist/setup/setup-flow.d.ts +30 -0
  34. package/dist/setup/setup-flow.d.ts.map +1 -0
  35. package/dist/setup/setup-flow.js +277 -0
  36. package/dist/setup/setup-form-step.d.ts +20 -0
  37. package/dist/setup/setup-form-step.d.ts.map +1 -0
  38. package/dist/setup/setup-form-step.js +173 -0
  39. package/dist/setup/step-status-badge.d.ts +12 -0
  40. package/dist/setup/step-status-badge.d.ts.map +1 -0
  41. package/dist/setup/step-status-badge.js +21 -0
  42. package/dist/setup/tone.d.ts +8 -0
  43. package/dist/setup/tone.d.ts.map +1 -0
  44. package/dist/setup/tone.js +33 -0
  45. package/dist/setup/types.d.ts +130 -0
  46. package/dist/setup/types.d.ts.map +1 -0
  47. package/dist/setup/types.js +1 -0
  48. package/package.json +9 -5
  49. package/src/__tests__/addon-config-surface.test.tsx +260 -0
  50. package/src/__tests__/connector-blocks.test.tsx +302 -0
  51. package/src/__tests__/setup-components.test.tsx +147 -0
  52. package/src/__tests__/setup-flow-model.test.ts +117 -0
  53. package/src/__tests__/setup-flow.test.tsx +424 -0
  54. package/src/index.ts +29 -0
  55. package/src/setup/addon-config-surface.tsx +1426 -0
  56. package/src/setup/connector-blocks-model.ts +163 -0
  57. package/src/setup/connector-blocks.tsx +341 -0
  58. package/src/setup/connector-form-model.ts +115 -0
  59. package/src/setup/flow-model.ts +156 -0
  60. package/src/setup/health-card.tsx +131 -0
  61. package/src/setup/index.ts +35 -0
  62. package/src/setup/messages.ts +334 -0
  63. package/src/setup/records-table.tsx +186 -0
  64. package/src/setup/setup-flow.tsx +562 -0
  65. package/src/setup/setup-form-step.tsx +342 -0
  66. package/src/setup/step-status-badge.tsx +47 -0
  67. package/src/setup/tone.ts +44 -0
  68. package/src/setup/types.ts +147 -0
@@ -0,0 +1,1426 @@
1
+ // AddonConfigSurface — the unified "Configurar addon" dialog, moved from the
2
+ // ops host (installed-addons) into the SDK so every host renders the same
3
+ // surface. It combines:
4
+ // • Credenciales — the addon's connector credential form (secrets are
5
+ // write-only: never read back, empty = keep the stored one). Required
6
+ // fields up top, optional under "Avanzado"; or grouped by `form_layout`
7
+ // (sections / steps). Saved via POST /integrations/:provider.
8
+ // • Ajustes — the addon's settings_defs (GET/PUT /addons/:key/settings),
9
+ // with per-branch overrides, `visible_when` and `write_only`.
10
+ // • Probar conexión (connector.test_export) and Sincronizar ahora.
11
+ // Fixed header + footer; only the body scrolls (a connector can declare many
12
+ // fields). Everything host-specific is injected: the API client (ApiProvider
13
+ // or `client`), the admin gate (`canManageIssuer`), the active branch, the
14
+ // addon i18n bundle loader and the notifier.
15
+ import { createContext, useContext, useEffect, useId, useRef, useState } from 'react'
16
+ import { useMutation } from '@tanstack/react-query'
17
+ import { useTranslation } from 'react-i18next'
18
+ import { toast } from 'sonner'
19
+ import { AlertCircle, Cable, Check, Link2, Loader2, RefreshCw, Settings } from 'lucide-react'
20
+ import {
21
+ Badge,
22
+ Button,
23
+ Dialog,
24
+ DialogContent,
25
+ DialogDescription,
26
+ DialogFooter,
27
+ DialogHeader,
28
+ DialogTitle,
29
+ Input,
30
+ Label,
31
+ Select,
32
+ SelectContent,
33
+ SelectItem,
34
+ SelectTrigger,
35
+ SelectValue,
36
+ Switch,
37
+ } from '@asteby/metacore-ui/primitives'
38
+ import { cn } from '@asteby/metacore-ui/lib'
39
+ import { useApi, type ApiClient } from '../api-context'
40
+ import { evaluateVisibleWhen, getVisibleWhen } from '../dynamic-form-schema'
41
+ import type { VisibleWhen } from '../types'
42
+ import { useSetupT } from './messages'
43
+ import { StepStatusBadge } from './step-status-badge'
44
+ import { ConnectorBlocks, HelpText } from './connector-blocks'
45
+ import {
46
+ buildWizardSteps,
47
+ errorMessage,
48
+ hasExplicitTest,
49
+ normalizeBlockResult,
50
+ stepStatus,
51
+ type BlockResult,
52
+ type ConnectorFormBlock,
53
+ } from './connector-blocks-model'
54
+ import {
55
+ isSecretCredential,
56
+ missingRequired,
57
+ parseSaveError,
58
+ shapeMismatch,
59
+ textOrFallback,
60
+ } from './connector-form-model'
61
+
62
+ export interface AddonSettingDef {
63
+ key: string
64
+ label: string
65
+ type: string
66
+ default_value?: unknown
67
+ options?: { value: unknown; label: string }[]
68
+ /** "org" (default) or "branch": each branch may override the value (POS-1). */
69
+ scope?: string
70
+ /** Shown only while the predicate holds against the live values. */
71
+ visible_when?: VisibleWhen
72
+ visibleWhen?: VisibleWhen
73
+ /** Never read back; an empty input keeps the stored value. */
74
+ write_only?: boolean
75
+ /** The server holds a value for this write_only setting. */
76
+ stored?: boolean
77
+ }
78
+
79
+ export interface AddonConfigAddon {
80
+ addon_key: string
81
+ manifest: {
82
+ name: string
83
+ display_name?: string
84
+ settings_defs?: AddonSettingDef[]
85
+ }
86
+ }
87
+
88
+ export interface ConnectorCredentialField {
89
+ key: string
90
+ type?: string // "secret" | "text" | "select" | "dynamic_select"
91
+ required?: boolean
92
+ secret?: boolean
93
+ label?: string // i18n key
94
+ description?: string // i18n key (help text)
95
+ default?: string
96
+ options?: { value: string; label: string }[]
97
+ options_source?: string // dynamic_select: export the host runs to list options
98
+ section?: string // binds to a form_layout section
99
+ }
100
+
101
+ export interface ConnectorFormLayoutSection {
102
+ key: string
103
+ title?: string // i18n key
104
+ description?: string // i18n key
105
+ /** Setup blocks (webhook_url / instructions / action), host-filled. */
106
+ blocks?: ConnectorFormBlock[]
107
+ }
108
+ export interface ConnectorFormLayout {
109
+ mode?: 'sections' | 'steps'
110
+ sections?: ConnectorFormLayoutSection[]
111
+ }
112
+
113
+ export interface ConnectorEntry {
114
+ addon_key: string
115
+ addon_name?: string
116
+ provider: string
117
+ key?: string
118
+ label?: string
119
+ auth?: string // "token" | "oauth2"
120
+ connected: boolean
121
+ status?: string
122
+ resources?: string[]
123
+ credentials?: ConnectorCredentialField[]
124
+ form_layout?: ConnectorFormLayout
125
+ test_export?: string
126
+ // ops-native connectors (e.g. `hub`) expose a route "Sincronizar ahora" POSTs to.
127
+ sync_endpoint?: string
128
+ }
129
+
130
+ export interface AddonConfigNotifier {
131
+ success: (message: string) => void
132
+ error: (message: string) => void
133
+ info: (message: string) => void
134
+ warning: (message: string) => void
135
+ }
136
+
137
+ // Empty write_only value (typed then erased) must not overwrite the stored secret.
138
+ const isBlank = (v: unknown) => v == null || (typeof v === 'string' && v.trim() === '')
139
+
140
+ const NO_OPTION_KINDS: Record<string, string> = {}
141
+
142
+ export interface AddonConfigSurfaceProps {
143
+ addon: AddonConfigAddon
144
+ connector: ConnectorEntry | null
145
+ open: boolean
146
+ onOpenChange: (open: boolean) => void
147
+ onSaved?: () => void
148
+ /**
149
+ * GET /integrations/:provider/values is org-admin only: pass false for other
150
+ * roles and the credentials area explains why instead of firing the request.
151
+ * Default true.
152
+ */
153
+ canManageIssuer?: boolean
154
+ /** Active branch (for per-branch settings); null/absent hides the branch picker. */
155
+ activeBranch?: { id: string; name?: string } | null
156
+ /** Pulls the addon's own i18n bundle when its labels do not resolve yet. */
157
+ ensureAddonBundle?: (addonKey: string, i18n: unknown) => void | Promise<unknown>
158
+ /** Default: sonner `toast`. */
159
+ notify?: AddonConfigNotifier
160
+ /** Overrides the `useApi()` client. */
161
+ client?: ApiClient
162
+ /**
163
+ * credential key -> expected `tipo` of the lookup options. When the source
164
+ * reports a `tipo`, the field lists only the matching options. Default: none
165
+ * (no filtering). Example: `{ serie_invoice: 'factura' }`.
166
+ */
167
+ expectedOptionKinds?: Record<string, string>
168
+ /** Title name; default `manifest.display_name ?? manifest.name`. */
169
+ displayName?: string
170
+ /**
171
+ * OAuth connectors (auth != "token") have no credential form: the surface
172
+ * shows the connection state and a "Conectar cuenta" button that calls this
173
+ * (the host starts its OAuth flow). Absent → no button.
174
+ */
175
+ onConnectOAuth?: (connector: ConnectorEntry) => void
176
+ }
177
+
178
+ /** Key of the implicit "Probar conexión" block (connector.test_export). */
179
+ const TEST_BLOCK_KEY = '__test_connection'
180
+ const SYNC_BLOCK_KEY = '__sync'
181
+
182
+ // ─── Connector credential field (reusable render) ───────────────────────────
183
+ // One connector credential field: label (i18n) + control (select|password|text)
184
+ // + optional help. Shared by the unified config dialog for both the essential
185
+ // and the advanced groups so the select/secret/label/help logic lives in a
186
+ // single place (DRY).
187
+ // Humanize an i18n key's last segment as a graceful fallback so a missing addon
188
+ // translation never surfaces the raw dotted key (e.g.
189
+ // "fiscal_mexico.connector.section.connection" → "Connection").
190
+ const humanizeKey = (k?: string) =>
191
+ (k?.split('.').pop() ?? '')
192
+ .replace(/[_-]+/g, ' ')
193
+ .replace(/\b\w/g, (m) => m.toUpperCase())
194
+
195
+ // What the dialog tells every credential field: which ones failed the last save
196
+ // (highlighted + described) and the full list, so a value pasted in the wrong
197
+ // box can be spotted against the form's own fields.
198
+ interface ConnectorFormState {
199
+ fields: ConnectorCredentialField[]
200
+ errors: Record<string, string>
201
+ /** Unique DOM-id prefix of this surface instance (useId). */
202
+ idPrefix: string
203
+ /** API client used by dynamic selects (prop `client` or the host's). */
204
+ client?: ApiClient
205
+ /** Host-injected: credential key -> expected option `tipo`. */
206
+ expectedOptionKinds: Record<string, string>
207
+ }
208
+ const ConnectorFormStateContext = createContext<ConnectorFormState>({
209
+ fields: [],
210
+ errors: {},
211
+ idPrefix: 'addon-config',
212
+ expectedOptionKinds: {},
213
+ })
214
+
215
+ function ConnectorCredentialFieldControl({
216
+ field,
217
+ value,
218
+ connected,
219
+ provider,
220
+ onChange,
221
+ }: {
222
+ field: ConnectorCredentialField
223
+ value: string
224
+ connected: boolean
225
+ provider: string
226
+ onChange: (value: string) => void
227
+ }) {
228
+ const { t } = useTranslation()
229
+ const st = useSetupT()
230
+ const form = useContext(ConnectorFormStateContext)
231
+ // label/description are i18n keys (addon locales are loaded into i18next);
232
+ // never surface a raw dotted key: fall back to the humanized field key.
233
+ const humanize = (k: string) =>
234
+ k.replace(/[_-]+/g, ' ').replace(/\b\w/g, (m) => m.toUpperCase())
235
+ const labelOf = (f: ConnectorCredentialField) =>
236
+ f.label ? textOrFallback(t(f.label, { defaultValue: humanize(f.key) }), f.label, humanize(f.key)) : humanize(f.key)
237
+ const label = labelOf(field)
238
+ const help = field.description
239
+ ? textOrFallback(t(field.description, { defaultValue: '' }), field.description, '')
240
+ : ''
241
+ const isSecret = isSecretCredential(field)
242
+ const isDynamic = field.type === 'dynamic_select' || !!field.options_source
243
+ const error = form.errors[field.key]
244
+ const mismatch = shapeMismatch(field, value, form.fields)
245
+ const target = mismatch?.suggestedKey
246
+ ? form.fields.find((f) => f.key === mismatch.suggestedKey)
247
+ : undefined
248
+ const warning = mismatch
249
+ ? st(
250
+ mismatch.shape === 'public_key'
251
+ ? 'installed_addons.shape_public_key'
252
+ : 'installed_addons.shape_secret_key',
253
+ { target: target ? labelOf(target) : '' },
254
+ )
255
+ : ''
256
+
257
+ return (
258
+ <div className='flex flex-col gap-1' data-field={field.key}>
259
+ <Label htmlFor={`${form.idPrefix}-cred-${field.key}`}>
260
+ {label}
261
+ {field.required ? <span className='text-destructive'> *</span> : null}
262
+ </Label>
263
+ {isDynamic ? (
264
+ <DynamicConnectorSelect
265
+ field={field}
266
+ value={value}
267
+ provider={provider}
268
+ connected={connected}
269
+ onChange={onChange}
270
+ />
271
+ ) : field.type === 'select' && field.options?.length ? (
272
+ <Select value={value} onValueChange={onChange}>
273
+ <SelectTrigger id={`${form.idPrefix}-cred-${field.key}`} aria-invalid={!!error || undefined}>
274
+ <SelectValue />
275
+ </SelectTrigger>
276
+ <SelectContent>
277
+ {field.options.map((o) => (
278
+ <SelectItem key={o.value} value={o.value}>
279
+ {t(o.label, { defaultValue: o.value })}
280
+ </SelectItem>
281
+ ))}
282
+ </SelectContent>
283
+ </Select>
284
+ ) : (
285
+ <Input
286
+ id={`${form.idPrefix}-cred-${field.key}`}
287
+ type={isSecret ? 'password' : 'text'}
288
+ // A secret must never be offered to (or filled by) the browser's
289
+ // password manager: "new-password" is the value browsers respect.
290
+ autoComplete={isSecret ? 'new-password' : 'off'}
291
+ data-1p-ignore={isSecret ? true : undefined}
292
+ data-lpignore={isSecret ? 'true' : undefined}
293
+ spellCheck={false}
294
+ autoCapitalize='off'
295
+ aria-invalid={!!error || undefined}
296
+ aria-describedby={error ? `${form.idPrefix}-cred-${field.key}-error` : undefined}
297
+ className={cn(error && 'border-destructive focus-visible:ring-destructive/40')}
298
+ placeholder={connected && isSecret ? '••••••••' : ''}
299
+ value={value}
300
+ onChange={(e) => onChange(e.target.value)}
301
+ />
302
+ )}
303
+ {error ? (
304
+ <p id={`${form.idPrefix}-cred-${field.key}-error`} role='alert' className='text-xs text-destructive'>
305
+ {error}
306
+ </p>
307
+ ) : null}
308
+ {warning ? (
309
+ <p className='text-xs text-amber-600 dark:text-amber-400' role='status'>
310
+ {warning}
311
+ </p>
312
+ ) : null}
313
+ {help ? <HelpText text={help} /> : null}
314
+ </div>
315
+ )
316
+ }
317
+
318
+ // Shared in-flight/result cache for connector option lookups, keyed by
319
+ // provider+credential. The 3 serie fields all call the SAME export and get the
320
+ // SAME list (they only differ in client-side `tipo` filtering), so without this
321
+ // they'd fire 3 identical concurrent POST /lookup on open — 3 wasm invocations +
322
+ // 3 external GETs. This dedupes them to ONE request whose result they share.
323
+ // `force` (the refresh button) bypasses the cache to re-fetch.
324
+ type LookupOption = { value: string; label: string; tipo?: string }
325
+ // useApi() hands every component its own wrapper object, so the cache cannot be
326
+ // keyed by client: it is module-level, keyed by provider + export, and dropped
327
+ // whenever a config surface closes (a new org / credentials never reads stale).
328
+ const lookupCache = new Map<string, Promise<LookupOption[]>>()
329
+ /** Drops the shared option-lookup cache (called when the surface closes). */
330
+ export function clearConnectorLookupCache() {
331
+ lookupCache.clear()
332
+ }
333
+ function fetchLookupOptions(
334
+ api: ApiClient,
335
+ provider: string,
336
+ field: ConnectorCredentialField,
337
+ force = false,
338
+ ): Promise<LookupOption[]> {
339
+ const key = `${provider}:${field.options_source || field.key}`
340
+ if (!force && lookupCache.has(key)) return lookupCache.get(key)!
341
+ const p = api
342
+ .post(`/integrations/${provider}/lookup`, { credential: field.key })
343
+ .then((res) => (res.data?.data?.options ?? []) as LookupOption[])
344
+ .catch((err) => {
345
+ lookupCache.delete(key) // don't cache failures
346
+ throw err
347
+ })
348
+ lookupCache.set(key, p)
349
+ return p
350
+ }
351
+
352
+ // A dynamic_select connector credential: the option list is fetched from the
353
+ // host, which runs the addon's `options_source` WASM export org-scoped (it reads
354
+ // the org's SAVED credentials via connector_get, e.g. lists factura.com series).
355
+ // So options only resolve once the connector is configured+saved — until then we
356
+ // show a hint and a manual free-text fallback so the field is never a dead end.
357
+ function DynamicConnectorSelect({
358
+ field,
359
+ value,
360
+ provider,
361
+ connected,
362
+ onChange,
363
+ }: {
364
+ field: ConnectorCredentialField
365
+ value: string
366
+ provider: string
367
+ connected: boolean
368
+ onChange: (value: string) => void
369
+ }) {
370
+ const st = useSetupT()
371
+ const form = useContext(ConnectorFormStateContext)
372
+ const hostApi = useApi()
373
+ const api = form.client ?? hostApi
374
+ const [options, setOptions] = useState<
375
+ { value: string; label: string; tipo?: string }[]
376
+ >([])
377
+ const [state, setState] = useState<'idle' | 'loading' | 'error' | 'done'>('idle')
378
+ const [error, setError] = useState('')
379
+
380
+ const load = async (force = false) => {
381
+ setState('loading')
382
+ setError('')
383
+ try {
384
+ const opts = await fetchLookupOptions(api, provider, field, force)
385
+ setOptions(opts)
386
+ setState('done')
387
+ } catch (err: any) {
388
+ setError(
389
+ err.response?.data?.message ||
390
+ st('installed_addons.dynamic_select_error', {
391
+ defaultValue:
392
+ 'No se pudieron listar las opciones. Guarda la conexión y vuelve a intentar.',
393
+ }),
394
+ )
395
+ setState('error')
396
+ }
397
+ }
398
+
399
+ // Auto-load once when the connector is already configured (editing an existing
400
+ // connection). Fresh configs load on demand via the refresh button.
401
+ useEffect(() => {
402
+ if (connected && state === 'idle') void load()
403
+ // eslint-disable-next-line react-hooks/exhaustive-deps
404
+ }, [connected])
405
+
406
+ // Scope the options to the kind (`tipo`) the host expects for this field,
407
+ // when the source reports one. The mapping is injected by the host
408
+ // (`expectedOptionKinds`); empty by default, so the SDK stays domain-agnostic.
409
+ const expected = form.expectedOptionKinds[field.key]
410
+ const filtered =
411
+ expected && options.some((o) => o.tipo === expected)
412
+ ? options.filter((o) => o.tipo === expected)
413
+ : options
414
+
415
+ return (
416
+ <div className='flex flex-col gap-1'>
417
+ <div className='flex items-center gap-2'>
418
+ {filtered.length > 0 ? (
419
+ <Select value={value} onValueChange={onChange}>
420
+ <SelectTrigger id={`${form.idPrefix}-cred-${field.key}`} className='flex-1'>
421
+ <SelectValue
422
+ placeholder={st('installed_addons.dynamic_select_choose', {
423
+ defaultValue: 'Elige una opción',
424
+ })}
425
+ />
426
+ </SelectTrigger>
427
+ <SelectContent>
428
+ {filtered.map((o) => (
429
+ <SelectItem key={o.value} value={o.value}>
430
+ {o.label}
431
+ </SelectItem>
432
+ ))}
433
+ </SelectContent>
434
+ </Select>
435
+ ) : (
436
+ <Input
437
+ id={`${form.idPrefix}-cred-${field.key}`}
438
+ value={value}
439
+ placeholder={st('installed_addons.dynamic_select_placeholder', {
440
+ defaultValue: 'Guarda la conexión y actualiza para elegir',
441
+ })}
442
+ onChange={(e) => onChange(e.target.value)}
443
+ />
444
+ )}
445
+ <Button
446
+ type='button'
447
+ variant='outline'
448
+ size='sm'
449
+ onClick={() => void load(true)}
450
+ disabled={state === 'loading'}
451
+ title={st('installed_addons.dynamic_select_refresh', {
452
+ defaultValue: 'Actualizar opciones',
453
+ })}
454
+ >
455
+ {state === 'loading' ? (
456
+ <Loader2 className='h-4 w-4 animate-spin' />
457
+ ) : (
458
+ <RefreshCw className='h-4 w-4' />
459
+ )}
460
+ </Button>
461
+ </div>
462
+ {state === 'error' && <p className='text-xs text-destructive'>{error}</p>}
463
+ </div>
464
+ )
465
+ }
466
+
467
+ // ─── Unified addon configuration dialog ─────────────────────────────────────
468
+ // One "Configuración del addon" surface per addon combining two sections:
469
+ // • Credenciales — the addon's `token` connector credential form. Essential
470
+ // (required) fields render up top; optional/advanced fields (base_url,
471
+ // stamp_path, …) collapse under an "Avanzado" <details>. Saved via
472
+ // POST /integrations/:provider (only non-empty values, so re-saving without
473
+ // retyping a stored secret doesn't wipe it).
474
+ // • Ajustes — the addon's settings_defs (GET/PUT /addons/:key/settings).
475
+ // Fixed header + footer, scrollable body — a connector can declare many fields
476
+ // (env, keys, RFC, régimen, CP, base_url, stamp/cancel path) that would
477
+ // otherwise overflow the viewport.
478
+ export function AddonConfigSurface({
479
+ addon,
480
+ connector,
481
+ open,
482
+ onOpenChange,
483
+ onSaved,
484
+ canManageIssuer = true,
485
+ activeBranch = null,
486
+ ensureAddonBundle,
487
+ notify = toast,
488
+ client,
489
+ expectedOptionKinds = NO_OPTION_KINDS,
490
+ displayName,
491
+ onConnectOAuth,
492
+ }: AddonConfigSurfaceProps) {
493
+ const idPrefix = useId()
494
+ const { t, i18n } = useTranslation()
495
+ const st = useSetupT()
496
+ const hostApi = useApi()
497
+ const api = client ?? hostApi
498
+ const activeBranchId = activeBranch?.id ?? ''
499
+ useEffect(() => {
500
+ if (!open) clearConnectorLookupCache()
501
+ }, [open])
502
+
503
+ const credFields = connector?.credentials ?? []
504
+ const requiredFields = credFields.filter((f) => f.required)
505
+ const advancedFields = credFields.filter((f) => !f.required)
506
+ // A connector with a form_layout groups its credentials into titled sections
507
+ // (a light wizard). Fall back to the required/advanced split when absent.
508
+ const layoutSections = connector?.form_layout?.sections ?? []
509
+ const useLayout = layoutSections.length > 0 && credFields.some((f) => !!f.section)
510
+
511
+ // A form_layout with mode "steps" drives a real wizard (one section at a time
512
+ // with Atrás/Siguiente), instead of stacked cards.
513
+ const stepMode = useLayout && connector?.form_layout?.mode === 'steps'
514
+
515
+ const [credValues, setCredValues] = useState<Record<string, string>>({})
516
+ const [settingsValues, setSettingsValues] = useState<Record<string, unknown>>({})
517
+ const [definitions, setDefinitions] = useState<AddonSettingDef[]>([])
518
+ const [loading, setLoading] = useState(false)
519
+ const [currentStep, setCurrentStep] = useState(0)
520
+ // Last failed save: the complete message (shown in full, not as a toast that
521
+ // cuts it) and the fields to highlight.
522
+ const [formError, setFormError] = useState<string | null>(null)
523
+ const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({})
524
+ const errorRef = useRef<HTMLDivElement>(null)
525
+ // Results of the step actions (by block key) and whether the operator typed
526
+ // credentials not saved yet (an action tests what is STORED: it saves first).
527
+ const [blockResults, setBlockResults] = useState<Record<string, BlockResult | undefined>>({})
528
+ const [credDirty, setCredDirty] = useState(false)
529
+ const stepHeadingRef = useRef<HTMLHeadingElement>(null)
530
+ const stepMoved = useRef(false)
531
+ const setCred = (key: string, val: string) => {
532
+ setCredValues((v) => ({ ...v, [key]: val }))
533
+ setCredDirty(true)
534
+ if (fieldErrors[key]) {
535
+ setFieldErrors((e) => {
536
+ const { [key]: _drop, ...rest } = e
537
+ return rest
538
+ })
539
+ }
540
+ }
541
+
542
+ // Per-branch settings (POS-1): a setting the manifest declares `scope: branch`
543
+ // can be overridden for the ACTIVE branch. `target` picks which level the form
544
+ // reads/writes; in "branch" mode only the branch-scoped settings show, only the
545
+ // ones the operator touched are saved (an untouched key keeps inheriting the org
546
+ // value) and «Heredar de la organización» clears an override.
547
+ const [target, setTarget] = useState<'org' | 'branch'>('org')
548
+ const [overrides, setOverrides] = useState<Record<string, unknown>>({})
549
+ const [touched, setTouched] = useState<Set<string>>(new Set())
550
+ const [cleared, setCleared] = useState<Set<string>>(new Set())
551
+ const hasBranchDefs = definitions.some((d) => d.scope === 'branch')
552
+ const canTargetBranch = !!activeBranch && hasBranchDefs
553
+ const branchMode = target === 'branch' && canTargetBranch
554
+ // `visible_when` (kernel Setting.visible_when) is evaluated against the live values.
555
+ const shownDefs = (branchMode ? definitions.filter((d) => d.scope === 'branch') : definitions).filter(
556
+ (d) => evaluateVisibleWhen(getVisibleWhen(d), settingsValues),
557
+ )
558
+ const setSetting = (key: string, value: unknown) => {
559
+ setSettingsValues((prev) => ({ ...prev, [key]: value }))
560
+ setTouched((prev) => new Set(prev).add(key))
561
+ setCleared((prev) => {
562
+ if (!prev.has(key)) return prev
563
+ const next = new Set(prev)
564
+ next.delete(key)
565
+ return next
566
+ })
567
+ }
568
+
569
+ // Seed connector defaults (e.g. environment = sandbox, first select option,
570
+ // or a value the backend prefilled from the org) so selects open on their
571
+ // default, then overlay the STORED non-secret values (GET …/values). Without
572
+ // the overlay a configured connector reopened empty, and re-saving sent the
573
+ // select defaults over what was stored (PIT-035: régimen reset to 601).
574
+ // Secrets are never returned; their inputs stay blank = "keep as is".
575
+ useEffect(() => {
576
+ if (!open) return
577
+ const seed: Record<string, string> = {}
578
+ for (const f of credFields) {
579
+ if (f.default != null && f.default !== '') seed[f.key] = String(f.default)
580
+ else if (f.type === 'select' && f.options?.length) seed[f.key] = f.options[0].value
581
+ }
582
+ setCredValues(seed)
583
+ setCurrentStep(0)
584
+ stepMoved.current = false
585
+ setFormError(null)
586
+ setFieldErrors({})
587
+ setBlockResults({})
588
+ setCredDirty(false)
589
+ if (!canManageIssuer || !connector?.provider || credFields.length === 0) return
590
+ let cancelled = false
591
+ api
592
+ .get(`/integrations/${connector.provider}/values`)
593
+ .then((res) => {
594
+ const stored = (res.data?.data?.values ?? {}) as Record<string, string>
595
+ if (cancelled) return
596
+ // Only fields the user has not touched yet.
597
+ setCredValues((prev) => {
598
+ const next = { ...prev }
599
+ for (const [k, v] of Object.entries(stored)) {
600
+ // Write-only: a secret is never prefilled, even if a host echoes it.
601
+ const def = credFields.find((f) => f.key === k)
602
+ if (def && isSecretCredential(def)) continue
603
+ if (v !== '' && prev[k] === seed[k]) next[k] = v
604
+ }
605
+ return next
606
+ })
607
+ })
608
+ .catch(() => {
609
+ /* older backend or no stored config: keep the defaults */
610
+ })
611
+ return () => {
612
+ cancelled = true
613
+ }
614
+ // eslint-disable-next-line react-hooks/exhaustive-deps
615
+ }, [open, connector?.provider, canManageIssuer])
616
+
617
+ // Load stored settings values + definitions. The backend returns the
618
+ // manifest's setting definitions alongside the stored values; fall back to
619
+ // the manifest we already have so custom (declarative) addons whose lifecycle
620
+ // isn't registered still render.
621
+ useEffect(() => {
622
+ if (!open) return
623
+ setLoading(true)
624
+ setTouched(new Set())
625
+ setCleared(new Set())
626
+ const branchQuery =
627
+ target === 'branch' && activeBranch ? `?branch_id=${encodeURIComponent(activeBranchId)}` : ''
628
+ api
629
+ .get(`/addons/${addon.addon_key}/settings${branchQuery}`)
630
+ .then((res) => {
631
+ setSettingsValues(res.data?.data || {})
632
+ setOverrides(res.data?.overrides || {})
633
+ const defs: AddonSettingDef[] =
634
+ res.data?.definitions?.length > 0
635
+ ? res.data.definitions
636
+ : (addon.manifest.settings_defs ?? [])
637
+ setDefinitions(defs)
638
+ })
639
+ .catch(() => {
640
+ setSettingsValues({})
641
+ setDefinitions(addon.manifest.settings_defs ?? [])
642
+ })
643
+ .finally(() => setLoading(false))
644
+ }, [open, addon.addon_key, target, activeBranchId])
645
+
646
+ // The addon's texts can arrive after this dialog (installed a moment ago, or
647
+ // the org bundle still in flight): when its labels do not resolve yet, pull
648
+ // the addon's own bundle so the form never paints raw keys.
649
+ useEffect(() => {
650
+ if (!open || !connector || !ensureAddonBundle) return
651
+ const keys = [
652
+ ...credFields.flatMap((f) => [f.label, f.description]),
653
+ ...layoutSections.flatMap((sec) => [sec.title, sec.description]),
654
+ ...layoutSections.flatMap((sec) => (sec.blocks ?? []).flatMap((b) => [b.title, b.description, b.label])),
655
+ ].filter((k): k is string => !!k)
656
+ if (keys.length === 0 || keys.every((k) => i18n.exists(k))) return
657
+ void ensureAddonBundle?.(connector.addon_key, i18n)
658
+ // eslint-disable-next-line react-hooks/exhaustive-deps
659
+ }, [open, connector?.addon_key, credFields.length])
660
+
661
+ // Section/step help: an i18n key or a literal sentence (never a raw key).
662
+ const addonText = (key?: string) => {
663
+ if (!key) return ''
664
+ const out = textOrFallback(t(key, { defaultValue: '' }), key, '')
665
+ return out || (/\s/.test(key) ? key : '')
666
+ }
667
+
668
+ const credLabel = (f: ConnectorCredentialField) => {
669
+ const fallback = humanizeKey(f.key)
670
+ return f.label ? textOrFallback(t(f.label, { defaultValue: fallback }), f.label, fallback) : fallback
671
+ }
672
+
673
+ const saveMutation = useMutation({
674
+ mutationFn: async () => {
675
+ if (connector && canManageIssuer) {
676
+ // Only send non-empty values so re-saving without retyping a stored
677
+ // secret leaves it untouched (server merges).
678
+ const payload: Record<string, string> = {}
679
+ for (const [k, v] of Object.entries(credValues)) {
680
+ if (v != null && v !== '') payload[k] = v
681
+ }
682
+ await api.post(`/integrations/${connector.provider}`, payload)
683
+ }
684
+ if (branchMode) {
685
+ // Only what the operator touched: an untouched key keeps inheriting.
686
+ const payload: Record<string, unknown> = {}
687
+ for (const k of touched) {
688
+ const d = definitions.find((x) => x.key === k)
689
+ if (d?.write_only && isBlank(settingsValues[k])) continue
690
+ payload[k] = settingsValues[k]
691
+ }
692
+ for (const k of cleared) payload[k] = null
693
+ if (Object.keys(payload).length > 0) {
694
+ await api.put(
695
+ `/addons/${addon.addon_key}/settings?branch_id=${encodeURIComponent(activeBranchId)}`,
696
+ payload,
697
+ )
698
+ }
699
+ } else if (definitions.length > 0) {
700
+ // write_only settings are never read back: send them only when typed.
701
+ const payload: Record<string, unknown> = { ...settingsValues }
702
+ for (const d of definitions) {
703
+ if (d.write_only && (!touched.has(d.key) || isBlank(payload[d.key]))) delete payload[d.key]
704
+ }
705
+ await api.put(`/addons/${addon.addon_key}/settings`, payload)
706
+ }
707
+ },
708
+ onSuccess: () => {
709
+ setFormError(null)
710
+ setFieldErrors({})
711
+ setCredDirty(false)
712
+ notify.success(st('installed_addons.config_saved'))
713
+ onOpenChange(false)
714
+ onSaved?.()
715
+ },
716
+ onError: (err: unknown) => {
717
+ const { message, fieldKeys } = parseSaveError(err, st('installed_addons.settings_error'))
718
+ const known = new Set(credFields.map((f) => f.key))
719
+ const errs: Record<string, string> = {}
720
+ for (const k of fieldKeys) {
721
+ const f = credFields.find((c) => c.key === k)
722
+ if (known.has(k) && f) {
723
+ errs[k] = st('installed_addons.field_required', {
724
+ defaultValue: 'Falta completar este campo.',
725
+ })
726
+ }
727
+ }
728
+ setFieldErrors(errs)
729
+ setFormError(message)
730
+ focusFirstInvalid(Object.keys(errs))
731
+ },
732
+ })
733
+
734
+ // Brings the first failed field into view and focuses it; in a stepper it
735
+ // also jumps to the step that holds it.
736
+ const focusFirstInvalid = (keys: string[]) => {
737
+ const first = keys[0]
738
+ if (!first) {
739
+ window.setTimeout(() => errorRef.current?.scrollIntoView({ block: 'nearest' }), 0)
740
+ return
741
+ }
742
+ const sectionKey = credFields.find((f) => f.key === first)?.section
743
+ if (sectionKey) {
744
+ // Index among the WIZARD steps (sections without fields/blocks are not steps).
745
+ const idx = wizardSteps.findIndex((sec) => sec.key === sectionKey)
746
+ if (idx >= 0) goToStep(idx)
747
+ }
748
+ window.setTimeout(() => {
749
+ const el = document.getElementById(`${idPrefix}-cred-${first}`)
750
+ el?.closest('details')?.setAttribute('open', '')
751
+ el?.scrollIntoView({ block: 'center' })
752
+ el?.focus()
753
+ }, 50)
754
+ }
755
+
756
+ // Check what is certain before the round trip, so the operator sees WHICH
757
+ // field is missing instead of a generic failure.
758
+ const handleSave = () => {
759
+ setFormError(null)
760
+ if (connector && canManageIssuer) {
761
+ const miss = missingRequired(credFields, credValues, !!connector.connected)
762
+ if (miss.length > 0) {
763
+ const errs: Record<string, string> = {}
764
+ for (const k of miss) {
765
+ errs[k] = st('installed_addons.field_required', { defaultValue: 'Falta completar este campo.' })
766
+ }
767
+ setFieldErrors(errs)
768
+ setFormError(
769
+ st('installed_addons.missing_fields', {
770
+ fields: miss.map((k) => credLabel(credFields.find((f) => f.key === k)!)).join(', '),
771
+ defaultValue: 'Faltan campos obligatorios: {{fields}}.',
772
+ }),
773
+ )
774
+ focusFirstInvalid(miss)
775
+ return
776
+ }
777
+ }
778
+ setFieldErrors({})
779
+ saveMutation.mutate()
780
+ }
781
+
782
+ // Saves typed-but-unsaved credentials before an action runs: actions (and
783
+ // the connector test) read the STORED credentials, so testing what is on
784
+ // screen requires persisting it first. Returns an error message, or null.
785
+ const persistCredsIfDirty = async (): Promise<string | null> => {
786
+ if (!credDirty || !connector || !canManageIssuer) return null
787
+ const miss = missingRequired(credFields, credValues, !!connector.connected)
788
+ if (miss.length > 0) {
789
+ const errs: Record<string, string> = {}
790
+ for (const k of miss) errs[k] = st('installed_addons.field_required')
791
+ setFieldErrors(errs)
792
+ return st('installed_addons.missing_fields', {
793
+ fields: miss.map((k) => credLabel(credFields.find((f) => f.key === k)!)).join(', '),
794
+ })
795
+ }
796
+ const payload: Record<string, string> = {}
797
+ for (const [k, v] of Object.entries(credValues)) {
798
+ if (v != null && v !== '') payload[k] = v
799
+ }
800
+ await api.post(`/integrations/${connector.provider}`, payload)
801
+ setCredDirty(false)
802
+ onSaved?.()
803
+ return null
804
+ }
805
+
806
+ // Runs a step action: the implicit connection test (connector.test_export)
807
+ // or a declared action block (host route /blocks/:key/run). The result is
808
+ // shown inline (aria-live) with retry, never as a toast that disappears.
809
+ const runAction = async (block: ConnectorFormBlock): Promise<BlockResult> => {
810
+ const fail = st('blocks.failed')
811
+ try {
812
+ const pre = await persistCredsIfDirty()
813
+ if (pre) return { status: 'error', message: pre, details: [] }
814
+ if (block.key === SYNC_BLOCK_KEY) return await runSync()
815
+ const url =
816
+ block.key === TEST_BLOCK_KEY
817
+ ? `/integrations/${connector?.provider}/test`
818
+ : `/integrations/${connector?.provider}/blocks/${encodeURIComponent(block.key)}/run`
819
+ const res = await api.post(url, {})
820
+ return normalizeBlockResult(res.data, fail)
821
+ } catch (err) {
822
+ return { status: 'error', message: errorMessage(err, fail), details: [] }
823
+ }
824
+ }
825
+ const setResult = (key: string, r: BlockResult) => setBlockResults((prev) => ({ ...prev, [key]: r }))
826
+
827
+ // "Sincronizar ahora": ops-native connectors with a sync worker (hub →
828
+ // partner read-models) run one sync now and report the run summary.
829
+ const runSync = async (): Promise<BlockResult> => {
830
+ const res = await api.post(connector?.sync_endpoint ?? '', {})
831
+ const data = res.data?.data as
832
+ | {
833
+ status?: string
834
+ message?: string
835
+ licenses?: { fetched?: number }
836
+ instances?: { fetched?: number }
837
+ accounts?: { fetched?: number }
838
+ errors?: string[]
839
+ }
840
+ | undefined
841
+ if (data?.status === 'skipped') {
842
+ return { status: 'warn', message: data.message || st('installed_addons.sync_skipped'), details: [] }
843
+ }
844
+ const summary = st('installed_addons.sync_done', {
845
+ licenses: data?.licenses?.fetched ?? 0,
846
+ instances: data?.instances?.fetched ?? 0,
847
+ accounts: data?.accounts?.fetched ?? 0,
848
+ })
849
+ if (data?.status === 'partial') {
850
+ return { status: 'warn', message: `${summary} · ${(data.errors ?? []).join('; ')}`, details: [] }
851
+ }
852
+ return { status: 'ok', message: summary, details: [] }
853
+ }
854
+
855
+ const hasCredentials = credFields.length > 0
856
+ const hasSettings = definitions.length > 0
857
+ const canTest = !!connector?.test_export && canManageIssuer
858
+ const issuerAdminNote = (
859
+ <p className='text-sm text-muted-foreground'>
860
+ {st('installed_addons.issuer_admin_only', {
861
+ defaultValue:
862
+ 'Solo un administrador de la organización puede ver y guardar los datos del emisor y el certificado. Pide a un administrador que los configure.',
863
+ })}
864
+ </p>
865
+ )
866
+ const canSync = !!connector?.sync_endpoint && !!connector?.connected
867
+
868
+ const renderCred = (f: ConnectorCredentialField) => (
869
+ <ConnectorCredentialFieldControl
870
+ key={f.key}
871
+ field={f}
872
+ connected={!!connector?.connected}
873
+ provider={connector?.provider ?? ''}
874
+ value={credValues[f.key] ?? ''}
875
+ onChange={(val) => setCred(f.key, val)}
876
+ />
877
+ )
878
+
879
+ // One setting control, shared by the flat layout and the wizard's last step.
880
+ const renderSetting = (def: AddonSettingDef) => {
881
+ const id = `${idPrefix}-setting-${def.key}`
882
+ const value = settingsValues[def.key] ?? def.default_value
883
+ const isCleared = cleared.has(def.key)
884
+ const overridden = branchMode && def.key in overrides && !isCleared
885
+ return (
886
+ <div key={def.key} className='flex flex-col gap-2'>
887
+ <div className='flex items-center gap-2'>
888
+ <Label htmlFor={id}>{def.label || def.key}</Label>
889
+ {def.scope === 'branch' && !branchMode && (
890
+ <Badge variant='outline' className='text-[10px]'>
891
+ {st('installed_addons.per_branch')}
892
+ </Badge>
893
+ )}
894
+ {branchMode && (
895
+ <span className='text-muted-foreground text-xs'>
896
+ {isCleared
897
+ ? st('installed_addons.inherit_pending')
898
+ : overridden || touched.has(def.key)
899
+ ? st('installed_addons.branch_own')
900
+ : st('installed_addons.branch_inherited')}
901
+ </span>
902
+ )}
903
+ {branchMode && (overridden || touched.has(def.key)) && !isCleared && (
904
+ <Button
905
+ type='button'
906
+ variant='link'
907
+ size='sm'
908
+ className='h-auto p-0 text-xs'
909
+ onClick={() => setCleared((prev) => new Set(prev).add(def.key))}
910
+ >
911
+ {st('installed_addons.inherit')}
912
+ </Button>
913
+ )}
914
+ </div>
915
+ {def.type === 'boolean' ? (
916
+ <Switch
917
+ id={id}
918
+ checked={!!value}
919
+ onCheckedChange={(checked) => setSetting(def.key, checked)}
920
+ />
921
+ ) : def.type === 'select' && (def.options?.length ?? 0) > 0 ? (
922
+ <Select value={String(value ?? '')} onValueChange={(v) => setSetting(def.key, v)}>
923
+ <SelectTrigger id={id}>
924
+ <SelectValue />
925
+ </SelectTrigger>
926
+ <SelectContent>
927
+ {def.options!.map((o) => (
928
+ <SelectItem key={String(o.value)} value={String(o.value)}>
929
+ {o.label}
930
+ </SelectItem>
931
+ ))}
932
+ </SelectContent>
933
+ </Select>
934
+ ) : def.write_only ? (
935
+ <>
936
+ <Input
937
+ id={id}
938
+ type='password'
939
+ autoComplete='new-password'
940
+ data-1p-ignore
941
+ data-lpignore='true'
942
+ spellCheck={false}
943
+ placeholder={def.stored ? '••••••••' : ''}
944
+ value={touched.has(def.key) ? String(settingsValues[def.key] ?? '') : ''}
945
+ onChange={(e) => setSetting(def.key, e.target.value)}
946
+ />
947
+ {def.stored ? (
948
+ <p className='text-xs text-muted-foreground'>{st('installed_addons.secret_stored')}</p>
949
+ ) : null}
950
+ </>
951
+ ) : (
952
+ <Input
953
+ id={id}
954
+ type={def.type === 'number' ? 'number' : 'text'}
955
+ value={String(value ?? '')}
956
+ onChange={(e) =>
957
+ setSetting(
958
+ def.key,
959
+ def.type === 'number'
960
+ ? e.target.value === ''
961
+ ? undefined
962
+ : Number(e.target.value)
963
+ : e.target.value,
964
+ )
965
+ }
966
+ />
967
+ )}
968
+ </div>
969
+ )
970
+ }
971
+
972
+ // Which level the settings form edits (only offered when the addon has
973
+ // branch-scoped settings and a specific branch is active).
974
+ const targetPicker = canTargetBranch ? (
975
+ <div className='flex flex-wrap items-center gap-2 rounded-md border p-2 text-sm'>
976
+ <span className='text-muted-foreground'>
977
+ {st('installed_addons.applies_to')}
978
+ </span>
979
+ <Button
980
+ type='button'
981
+ size='sm'
982
+ variant={branchMode ? 'outline' : 'default'}
983
+ onClick={() => setTarget('org')}
984
+ >
985
+ {st('installed_addons.whole_org')}
986
+ </Button>
987
+ <Button
988
+ type='button'
989
+ size='sm'
990
+ variant={branchMode ? 'default' : 'outline'}
991
+ onClick={() => setTarget('branch')}
992
+ >
993
+ {st('installed_addons.only_branch', { name: activeBranch?.name, defaultValue: 'Solo {{name}}' })}
994
+ </Button>
995
+ </div>
996
+ ) : null
997
+
998
+ // Settings (Ajustes) body, reused by the flat layout and the wizard's last step.
999
+ const settingsBody = (
1000
+ <div className='flex flex-col gap-3'>
1001
+ {targetPicker}
1002
+ {shownDefs.map(renderSetting)}
1003
+ </div>
1004
+ )
1005
+
1006
+ // OAuth connectors have no credential form: the surface shows their state and
1007
+ // hands "Conectar cuenta" to the host (its OAuth redirect flow).
1008
+ const isOAuth = !!connector && !!connector.auth && connector.auth !== 'token'
1009
+ const oauthPanel = isOAuth ? (
1010
+ <section className='flex flex-col gap-3 rounded-lg border border-border/70 p-3'>
1011
+ <div className='flex flex-wrap items-center justify-between gap-2'>
1012
+ <h4 className='flex items-center gap-2 text-sm font-medium'>
1013
+ <Link2 aria-hidden='true' className='h-4 w-4 text-muted-foreground' />
1014
+ {st('oauth.title')}
1015
+ </h4>
1016
+ <StepStatusBadge
1017
+ status={connector!.connected ? 'ok' : 'pending'}
1018
+ label={connector!.connected ? st('oauth.connected') : st('oauth.not_connected')}
1019
+ />
1020
+ </div>
1021
+ <HelpText text={st('oauth.help')} />
1022
+ {onConnectOAuth ? (
1023
+ <Button
1024
+ type='button'
1025
+ variant={connector!.connected ? 'outline' : 'default'}
1026
+ className='h-auto min-h-11 w-full sm:w-fit'
1027
+ onClick={() => onConnectOAuth(connector!)}
1028
+ >
1029
+ {connector!.connected ? st('oauth.reconnect') : st('oauth.connect')}
1030
+ </Button>
1031
+ ) : null}
1032
+ </section>
1033
+ ) : null
1034
+
1035
+ // Wizard steps: form_layout sections with fields OR blocks, + a final
1036
+ // "Ajustes" step when the addon also ships settings.
1037
+ const wizardSteps = stepMode
1038
+ ? buildWizardSteps(
1039
+ layoutSections,
1040
+ credFields.map((f) => f.section),
1041
+ hasSettings,
1042
+ )
1043
+ : []
1044
+ const totalSteps = wizardSteps.length
1045
+ const useStepper = stepMode && totalSteps > 1
1046
+ const stepIdx = Math.min(currentStep, Math.max(0, totalSteps - 1))
1047
+ const activeStep = wizardSteps[stepIdx]
1048
+ const isLastStep = stepIdx >= totalSteps - 1
1049
+
1050
+ // "Probar conexión" (connector.test_export) is a verification INSIDE the
1051
+ // flow (last credentials step / end of the credentials), not a footer
1052
+ // button — unless the addon already declares an action block for it.
1053
+ const implicitTest: ConnectorFormBlock | null =
1054
+ canTest && !hasExplicitTest(layoutSections, connector?.test_export)
1055
+ ? {
1056
+ key: TEST_BLOCK_KEY,
1057
+ kind: 'action',
1058
+ title: st('blocks.test_title'),
1059
+ description: st('blocks.test_help'),
1060
+ label: st('installed_addons.test_connection'),
1061
+ }
1062
+ : null
1063
+ const syncBlock: ConnectorFormBlock | null = canSync
1064
+ ? { key: SYNC_BLOCK_KEY, kind: 'action', title: st('blocks.sync_title'), label: st('installed_addons.sync_now') }
1065
+ : null
1066
+ const lastCredStep = (() => {
1067
+ for (let i = wizardSteps.length - 1; i >= 0; i--) if (wizardSteps[i].kind === 'creds') return wizardSteps[i].key
1068
+ return undefined
1069
+ })()
1070
+ const extraBlocks = [implicitTest, syncBlock].filter((b): b is ConnectorFormBlock => !!b)
1071
+ const blocksFor = (sectionKey: string, declared: ConnectorFormBlock[] = []) =>
1072
+ sectionKey === lastCredStep ? [...declared, ...extraBlocks] : declared
1073
+
1074
+ // Reading order inside a step: what the operator needs BEFORE typing
1075
+ // (instructions, the URL to paste in the provider's panel) goes above the
1076
+ // fields; verifications (actions) go below them.
1077
+ const leadBlocks = (blocks: ConnectorFormBlock[] = []) => blocks.filter((b) => b.kind !== 'action')
1078
+ const trailBlocks = (blocks: ConnectorFormBlock[] = []) => blocks.filter((b) => b.kind === 'action')
1079
+
1080
+ const renderBlocks = (blocks: ConnectorFormBlock[]) => (
1081
+ <ConnectorBlocks
1082
+ blocks={blocks}
1083
+ runAction={runAction}
1084
+ results={blockResults}
1085
+ onResult={setResult}
1086
+ actionsDisabled={!canManageIssuer}
1087
+ actionNote={credDirty ? st('blocks.save_first') : undefined}
1088
+ />
1089
+ )
1090
+
1091
+ const stepState = (i: number) => {
1092
+ const s = wizardSteps[i]
1093
+ return stepStatus({
1094
+ index: i,
1095
+ current: stepIdx,
1096
+ fieldKeys: s.kind === 'creds' ? credFields.filter((f) => f.section === s.key).map((f) => f.key) : [],
1097
+ fieldErrors,
1098
+ blockKeys: blocksFor(s.key, s.blocks).map((b) => b.key),
1099
+ results: blockResults,
1100
+ })
1101
+ }
1102
+
1103
+ // Moving between steps puts focus on the new step's heading (keyboard and
1104
+ // screen-reader users land on the content, not on the footer).
1105
+ const goToStep = (i: number) => {
1106
+ stepMoved.current = true
1107
+ setCurrentStep(i)
1108
+ }
1109
+ useEffect(() => {
1110
+ if (stepMoved.current) stepHeadingRef.current?.focus()
1111
+ }, [stepIdx])
1112
+
1113
+ // "Siguiente" checks the current step's required credentials first, so the
1114
+ // operator learns what is missing where it is, not at the end.
1115
+ const handleNext = () => {
1116
+ if (activeStep?.kind === 'creds' && connector && canManageIssuer) {
1117
+ const stepFields = credFields.filter((f) => f.section === activeStep.key)
1118
+ const miss = missingRequired(stepFields, credValues, !!connector.connected)
1119
+ if (miss.length > 0) {
1120
+ const errs: Record<string, string> = {}
1121
+ for (const k of miss) errs[k] = st('installed_addons.field_required')
1122
+ setFieldErrors(errs)
1123
+ setFormError(
1124
+ st('installed_addons.missing_fields', {
1125
+ fields: miss.map((k) => credLabel(credFields.find((f) => f.key === k)!)).join(', '),
1126
+ }),
1127
+ )
1128
+ focusFirstInvalid(miss)
1129
+ return
1130
+ }
1131
+ }
1132
+ setFormError(null)
1133
+ goToStep(stepIdx + 1)
1134
+ }
1135
+
1136
+ const hasAnyBlocks = layoutSections.some((s) => (s.blocks?.length ?? 0) > 0) || extraBlocks.length > 0
1137
+ const nothingToConfigure = !hasCredentials && !hasSettings && !isOAuth && !hasAnyBlocks
1138
+ const nothingToSave = !hasCredentials && !hasSettings
1139
+
1140
+ return (
1141
+ <Dialog open={open} onOpenChange={onOpenChange}>
1142
+ <DialogContent className='flex max-h-[85vh] flex-col max-sm:max-h-[calc(100dvh-1rem)] max-sm:gap-3 max-sm:p-4'>
1143
+ <ConnectorFormStateContext.Provider
1144
+ value={{ fields: credFields, errors: fieldErrors, idPrefix, client: api, expectedOptionKinds }}
1145
+ >
1146
+ <DialogHeader className='shrink-0 pe-8 text-start'>
1147
+ <DialogTitle className='leading-snug'>
1148
+ {st('installed_addons.configure_title', { name: displayName ?? addon.manifest.display_name ?? addon.manifest.name })}
1149
+ </DialogTitle>
1150
+ <DialogDescription>
1151
+ {st('installed_addons.configure_description')}
1152
+ </DialogDescription>
1153
+ </DialogHeader>
1154
+
1155
+ <div className='-mr-2 flex min-h-0 flex-col gap-6 overflow-y-auto py-2 pr-2'>
1156
+ {loading ? (
1157
+ <div className='flex justify-center py-8'>
1158
+ <Loader2 className='h-5 w-5 animate-spin text-muted-foreground' />
1159
+ </div>
1160
+ ) : useStepper ? (
1161
+ /* WIZARD por pasos: indicador + un paso a la vez (sin card-in-card). */
1162
+ <div className='flex flex-col gap-5'>
1163
+ {/* Stepper: 44px targets, a check on done steps, an alert on a
1164
+ step with errors; the step title wraps (never truncated). */}
1165
+ <nav aria-label={st('wizard.steps')} className='flex flex-col gap-2'>
1166
+ <ol className='flex items-center'>
1167
+ {wizardSteps.map((s, i) => {
1168
+ const status = stepState(i)
1169
+ const active = i === stepIdx
1170
+ const title = t(s.title ?? '', { defaultValue: humanizeKey(s.title) })
1171
+ return (
1172
+ <li
1173
+ key={s.key}
1174
+ className={cn('flex items-center', i < wizardSteps.length - 1 && 'flex-1')}
1175
+ >
1176
+ <button
1177
+ type='button'
1178
+ onClick={() => goToStep(i)}
1179
+ aria-current={active ? 'step' : undefined}
1180
+ aria-label={st('wizard.step_label', {
1181
+ n: i + 1,
1182
+ total: totalSteps,
1183
+ title,
1184
+ status: st(`status.${status}`),
1185
+ })}
1186
+ data-step-status={status}
1187
+ className='flex h-11 w-11 shrink-0 items-center justify-center rounded-full focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring'
1188
+ >
1189
+ <span
1190
+ aria-hidden='true'
1191
+ className={cn(
1192
+ 'flex h-8 w-8 items-center justify-center rounded-full border text-xs font-semibold transition-all',
1193
+ active
1194
+ ? 'border-primary bg-primary text-primary-foreground ring-4 ring-primary/15'
1195
+ : status === 'error'
1196
+ ? 'border-destructive bg-destructive/10 text-destructive'
1197
+ : status === 'ok'
1198
+ ? 'border-primary bg-primary/10 text-primary'
1199
+ : 'border-border text-muted-foreground',
1200
+ )}
1201
+ >
1202
+ {!active && status === 'error' ? (
1203
+ <AlertCircle className='h-4 w-4' />
1204
+ ) : !active && status === 'ok' ? (
1205
+ <Check className='h-4 w-4' />
1206
+ ) : (
1207
+ i + 1
1208
+ )}
1209
+ </span>
1210
+ </button>
1211
+ {i < wizardSteps.length - 1 && (
1212
+ <span
1213
+ aria-hidden='true'
1214
+ className={cn(
1215
+ 'mx-1 h-0.5 flex-1 rounded-full transition-colors',
1216
+ i < stepIdx ? 'bg-primary' : 'bg-border',
1217
+ )}
1218
+ />
1219
+ )}
1220
+ </li>
1221
+ )
1222
+ })}
1223
+ </ol>
1224
+ <div className='flex items-start justify-between gap-3'>
1225
+ <h3
1226
+ ref={stepHeadingRef}
1227
+ tabIndex={-1}
1228
+ className='min-w-0 text-base leading-snug font-semibold break-words outline-none'
1229
+ >
1230
+ {t(activeStep?.title ?? '', {
1231
+ defaultValue: humanizeKey(activeStep?.title),
1232
+ })}
1233
+ </h3>
1234
+ <span className='mt-0.5 shrink-0 text-xs font-medium tabular-nums text-muted-foreground'>
1235
+ {st('flow.step_of', { n: stepIdx + 1, total: totalSteps })}
1236
+ </span>
1237
+ </div>
1238
+ </nav>
1239
+
1240
+ <div className='flex flex-col gap-4'>
1241
+ {activeStep?.description && (
1242
+ <HelpText text={addonText(activeStep.description)} />
1243
+ )}
1244
+ {activeStep?.kind === 'settings' ? (
1245
+ settingsBody
1246
+ ) : !canManageIssuer ? (
1247
+ <>
1248
+ {issuerAdminNote}
1249
+ {renderBlocks(blocksFor(activeStep?.key ?? '', activeStep?.blocks))}
1250
+ </>
1251
+ ) : (
1252
+ <>
1253
+ {renderBlocks(leadBlocks(blocksFor(activeStep?.key ?? '', activeStep?.blocks)))}
1254
+ {credFields.filter((f) => f.section === activeStep?.key).map(renderCred)}
1255
+ {renderBlocks(trailBlocks(blocksFor(activeStep?.key ?? '', activeStep?.blocks)))}
1256
+ </>
1257
+ )}
1258
+ </div>
1259
+ </div>
1260
+ ) : (
1261
+ <>
1262
+ {oauthPanel}
1263
+ {/* Credenciales */}
1264
+ {hasCredentials && (
1265
+ <section className='flex flex-col gap-3'>
1266
+ <div className='flex items-center gap-2'>
1267
+ <Cable className='h-4 w-4 text-muted-foreground' />
1268
+ <h3 className='text-sm font-semibold'>
1269
+ {st('installed_addons.section_credentials')}
1270
+ </h3>
1271
+ </div>
1272
+ {!canManageIssuer ? (
1273
+ issuerAdminNote
1274
+ ) : useLayout ? (
1275
+ // form_layout: one titled group per section, in declared order.
1276
+ layoutSections.map((sec) => {
1277
+ const fields = credFields.filter((f) => f.section === sec.key)
1278
+ if (fields.length === 0 && (sec.blocks?.length ?? 0) === 0) return null
1279
+ return (
1280
+ <div
1281
+ key={sec.key}
1282
+ className='flex flex-col gap-3 rounded-md border border-border/60 px-3 py-3'
1283
+ >
1284
+ {sec.title && (
1285
+ <div className='flex flex-col gap-1'>
1286
+ <h4 className='text-sm font-medium'>
1287
+ {t(sec.title, { defaultValue: sec.title })}
1288
+ </h4>
1289
+ {sec.description && (
1290
+ <HelpText text={addonText(sec.description)} />
1291
+ )}
1292
+ </div>
1293
+ )}
1294
+ {renderBlocks(leadBlocks(sec.blocks))}
1295
+ {fields.map((f) => (
1296
+ <ConnectorCredentialFieldControl
1297
+ key={f.key}
1298
+ field={f}
1299
+ connected={!!connector?.connected}
1300
+ provider={connector?.provider ?? ''}
1301
+ value={credValues[f.key] ?? ''}
1302
+ onChange={(val) => setCred(f.key, val)}
1303
+ />
1304
+ ))}
1305
+ {renderBlocks(trailBlocks(sec.blocks))}
1306
+ </div>
1307
+ )
1308
+ })
1309
+ ) : (
1310
+ <>
1311
+ {requiredFields.map((f) => (
1312
+ <ConnectorCredentialFieldControl
1313
+ key={f.key}
1314
+ field={f}
1315
+ connected={!!connector?.connected}
1316
+ provider={connector?.provider ?? ''}
1317
+ value={credValues[f.key] ?? ''}
1318
+ onChange={(val) => setCred(f.key, val)}
1319
+ />
1320
+ ))}
1321
+ {advancedFields.length > 0 && (
1322
+ <details
1323
+ className='rounded-md border border-border/60 px-3 py-2'
1324
+ open={advancedFields.some((f) => !!fieldErrors[f.key]) || undefined}
1325
+ >
1326
+ <summary className='flex min-h-11 cursor-pointer items-center text-sm font-medium text-muted-foreground select-none sm:min-h-8'>
1327
+ {st('installed_addons.advanced')}
1328
+ </summary>
1329
+ <div className='flex flex-col gap-3 pt-3'>
1330
+ {advancedFields.map((f) => (
1331
+ <ConnectorCredentialFieldControl
1332
+ key={f.key}
1333
+ field={f}
1334
+ connected={!!connector?.connected}
1335
+ provider={connector?.provider ?? ''}
1336
+ value={credValues[f.key] ?? ''}
1337
+ onChange={(val) => setCred(f.key, val)}
1338
+ />
1339
+ ))}
1340
+ </div>
1341
+ </details>
1342
+ )}
1343
+ </>
1344
+ )}
1345
+ </section>
1346
+ )}
1347
+
1348
+ {/* Verificación (probar conexión / sincronizar) al final de las credenciales. */}
1349
+ {extraBlocks.length > 0 && renderBlocks(extraBlocks)}
1350
+
1351
+ {/* Ajustes */}
1352
+ {hasSettings && (
1353
+ <section className='flex flex-col gap-3'>
1354
+ <div className='flex items-center gap-2'>
1355
+ <Settings className='h-4 w-4 text-muted-foreground' />
1356
+ <h3 className='text-sm font-semibold'>
1357
+ {st('installed_addons.section_settings')}
1358
+ </h3>
1359
+ </div>
1360
+ {targetPicker}
1361
+ {shownDefs.map(renderSetting)}
1362
+ </section>
1363
+ )}
1364
+
1365
+ {nothingToConfigure && (
1366
+ <div className='flex flex-col items-start gap-1 rounded-lg border border-dashed p-4'>
1367
+ <p className='text-sm font-medium'>{st('empty.title')}</p>
1368
+ <HelpText text={st('empty.help')} />
1369
+ </div>
1370
+ )}
1371
+ </>
1372
+ )}
1373
+ </div>
1374
+
1375
+ {formError ? (
1376
+ <div
1377
+ ref={errorRef}
1378
+ role='alert'
1379
+ className='max-h-40 shrink-0 overflow-y-auto whitespace-pre-wrap break-words rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive'
1380
+ >
1381
+ {formError}
1382
+ </div>
1383
+ ) : null}
1384
+
1385
+ {/* Footer: always visible (outside the scroll). ONE primary action
1386
+ (Siguiente / Guardar) full width on phones, Atrás + Cancelar
1387
+ sharing the row below; a single right-aligned row from sm up.
1388
+ Verifications live inside the steps, not here. */}
1389
+ <DialogFooter
1390
+ data-wizard-footer=''
1391
+ className='grid shrink-0 grid-cols-2 gap-2 border-t pt-3 sm:flex sm:flex-row sm:justify-end sm:border-t-0 sm:pt-0'
1392
+ >
1393
+ {nothingToSave ? (
1394
+ <Button className='col-span-2 h-11 sm:h-9' onClick={() => onOpenChange(false)}>
1395
+ {st('common.close')}
1396
+ </Button>
1397
+ ) : (
1398
+ <>
1399
+ <Button
1400
+ className='order-first col-span-2 h-11 sm:order-last sm:h-9'
1401
+ onClick={useStepper && !isLastStep ? handleNext : handleSave}
1402
+ disabled={!(useStepper && !isLastStep) && (saveMutation.isPending || loading)}
1403
+ >
1404
+ {saveMutation.isPending && <Loader2 className='mr-2 h-4 w-4 animate-spin' />}
1405
+ {useStepper && !isLastStep ? st('common.next') : st('common.save')}
1406
+ </Button>
1407
+ {useStepper && stepIdx > 0 && (
1408
+ <Button variant='outline' className='h-11 sm:h-9' onClick={() => goToStep(Math.max(0, stepIdx - 1))}>
1409
+ {st('common.back')}
1410
+ </Button>
1411
+ )}
1412
+ <Button
1413
+ variant='ghost'
1414
+ className={cn('h-11 sm:order-first sm:h-9', !(useStepper && stepIdx > 0) && 'col-span-2')}
1415
+ onClick={() => onOpenChange(false)}
1416
+ >
1417
+ {st('common.cancel')}
1418
+ </Button>
1419
+ </>
1420
+ )}
1421
+ </DialogFooter>
1422
+ </ConnectorFormStateContext.Provider>
1423
+ </DialogContent>
1424
+ </Dialog>
1425
+ )
1426
+ }