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