@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.
- package/CHANGELOG.md +12 -0
- package/README.md +73 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -0
- package/dist/setup/addon-config-surface.d.ts +119 -0
- package/dist/setup/addon-config-surface.d.ts.map +1 -0
- package/dist/setup/addon-config-surface.js +662 -0
- package/dist/setup/connector-blocks-model.d.ts +79 -0
- package/dist/setup/connector-blocks-model.d.ts.map +1 -0
- package/dist/setup/connector-blocks-model.js +96 -0
- package/dist/setup/connector-blocks.d.ts +48 -0
- package/dist/setup/connector-blocks.d.ts.map +1 -0
- package/dist/setup/connector-blocks.js +132 -0
- package/dist/setup/connector-form-model.d.ts +40 -0
- package/dist/setup/connector-form-model.d.ts.map +1 -0
- package/dist/setup/connector-form-model.js +76 -0
- package/dist/setup/flow-model.d.ts +49 -0
- package/dist/setup/flow-model.d.ts.map +1 -0
- package/dist/setup/flow-model.js +124 -0
- package/dist/setup/health-card.d.ts +25 -0
- package/dist/setup/health-card.d.ts.map +1 -0
- package/dist/setup/health-card.js +21 -0
- package/dist/setup/index.d.ts +13 -0
- package/dist/setup/index.d.ts.map +1 -0
- package/dist/setup/index.js +15 -0
- package/dist/setup/messages.d.ts +15 -0
- package/dist/setup/messages.d.ts.map +1 -0
- package/dist/setup/messages.js +320 -0
- package/dist/setup/records-table.d.ts +24 -0
- package/dist/setup/records-table.d.ts.map +1 -0
- package/dist/setup/records-table.js +80 -0
- package/dist/setup/setup-flow.d.ts +30 -0
- package/dist/setup/setup-flow.d.ts.map +1 -0
- package/dist/setup/setup-flow.js +277 -0
- package/dist/setup/setup-form-step.d.ts +20 -0
- package/dist/setup/setup-form-step.d.ts.map +1 -0
- package/dist/setup/setup-form-step.js +173 -0
- package/dist/setup/step-status-badge.d.ts +12 -0
- package/dist/setup/step-status-badge.d.ts.map +1 -0
- package/dist/setup/step-status-badge.js +21 -0
- package/dist/setup/tone.d.ts +8 -0
- package/dist/setup/tone.d.ts.map +1 -0
- package/dist/setup/tone.js +33 -0
- package/dist/setup/types.d.ts +130 -0
- package/dist/setup/types.d.ts.map +1 -0
- package/dist/setup/types.js +1 -0
- package/package.json +9 -5
- package/src/__tests__/addon-config-surface.test.tsx +260 -0
- package/src/__tests__/connector-blocks.test.tsx +302 -0
- package/src/__tests__/setup-components.test.tsx +147 -0
- package/src/__tests__/setup-flow-model.test.ts +117 -0
- package/src/__tests__/setup-flow.test.tsx +424 -0
- package/src/index.ts +29 -0
- package/src/setup/addon-config-surface.tsx +1426 -0
- package/src/setup/connector-blocks-model.ts +163 -0
- package/src/setup/connector-blocks.tsx +341 -0
- package/src/setup/connector-form-model.ts +115 -0
- package/src/setup/flow-model.ts +156 -0
- package/src/setup/health-card.tsx +131 -0
- package/src/setup/index.ts +35 -0
- package/src/setup/messages.ts +334 -0
- package/src/setup/records-table.tsx +186 -0
- package/src/setup/setup-flow.tsx +562 -0
- package/src/setup/setup-form-step.tsx +342 -0
- package/src/setup/step-status-badge.tsx +47 -0
- package/src/setup/tone.ts +44 -0
- package/src/setup/types.ts +147 -0
|
@@ -0,0 +1,662 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
2
|
+
// AddonConfigSurface — the unified "Configurar addon" dialog, moved from the
|
|
3
|
+
// ops host (installed-addons) into the SDK so every host renders the same
|
|
4
|
+
// surface. It combines:
|
|
5
|
+
// • Credenciales — the addon's connector credential form (secrets are
|
|
6
|
+
// write-only: never read back, empty = keep the stored one). Required
|
|
7
|
+
// fields up top, optional under "Avanzado"; or grouped by `form_layout`
|
|
8
|
+
// (sections / steps). Saved via POST /integrations/:provider.
|
|
9
|
+
// • Ajustes — the addon's settings_defs (GET/PUT /addons/:key/settings),
|
|
10
|
+
// with per-branch overrides, `visible_when` and `write_only`.
|
|
11
|
+
// • Probar conexión (connector.test_export) and Sincronizar ahora.
|
|
12
|
+
// Fixed header + footer; only the body scrolls (a connector can declare many
|
|
13
|
+
// fields). Everything host-specific is injected: the API client (ApiProvider
|
|
14
|
+
// or `client`), the admin gate (`canManageIssuer`), the active branch, the
|
|
15
|
+
// addon i18n bundle loader and the notifier.
|
|
16
|
+
import { createContext, useContext, useEffect, useId, useRef, useState } from 'react';
|
|
17
|
+
import { useMutation } from '@tanstack/react-query';
|
|
18
|
+
import { useTranslation } from 'react-i18next';
|
|
19
|
+
import { toast } from 'sonner';
|
|
20
|
+
import { AlertCircle, Cable, Check, Link2, Loader2, RefreshCw, Settings } from 'lucide-react';
|
|
21
|
+
import { Badge, Button, Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, Input, Label, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, Switch, } from '@asteby/metacore-ui/primitives';
|
|
22
|
+
import { cn } from '@asteby/metacore-ui/lib';
|
|
23
|
+
import { useApi } from '../api-context';
|
|
24
|
+
import { evaluateVisibleWhen, getVisibleWhen } from '../dynamic-form-schema';
|
|
25
|
+
import { useSetupT } from './messages';
|
|
26
|
+
import { StepStatusBadge } from './step-status-badge';
|
|
27
|
+
import { ConnectorBlocks, HelpText } from './connector-blocks';
|
|
28
|
+
import { buildWizardSteps, errorMessage, hasExplicitTest, normalizeBlockResult, stepStatus, } from './connector-blocks-model';
|
|
29
|
+
import { isSecretCredential, missingRequired, parseSaveError, shapeMismatch, textOrFallback, } from './connector-form-model';
|
|
30
|
+
// Empty write_only value (typed then erased) must not overwrite the stored secret.
|
|
31
|
+
const isBlank = (v) => v == null || (typeof v === 'string' && v.trim() === '');
|
|
32
|
+
const NO_OPTION_KINDS = {};
|
|
33
|
+
/** Key of the implicit "Probar conexión" block (connector.test_export). */
|
|
34
|
+
const TEST_BLOCK_KEY = '__test_connection';
|
|
35
|
+
const SYNC_BLOCK_KEY = '__sync';
|
|
36
|
+
// ─── Connector credential field (reusable render) ───────────────────────────
|
|
37
|
+
// One connector credential field: label (i18n) + control (select|password|text)
|
|
38
|
+
// + optional help. Shared by the unified config dialog for both the essential
|
|
39
|
+
// and the advanced groups so the select/secret/label/help logic lives in a
|
|
40
|
+
// single place (DRY).
|
|
41
|
+
// Humanize an i18n key's last segment as a graceful fallback so a missing addon
|
|
42
|
+
// translation never surfaces the raw dotted key (e.g.
|
|
43
|
+
// "fiscal_mexico.connector.section.connection" → "Connection").
|
|
44
|
+
const humanizeKey = (k) => (k?.split('.').pop() ?? '')
|
|
45
|
+
.replace(/[_-]+/g, ' ')
|
|
46
|
+
.replace(/\b\w/g, (m) => m.toUpperCase());
|
|
47
|
+
const ConnectorFormStateContext = createContext({
|
|
48
|
+
fields: [],
|
|
49
|
+
errors: {},
|
|
50
|
+
idPrefix: 'addon-config',
|
|
51
|
+
expectedOptionKinds: {},
|
|
52
|
+
});
|
|
53
|
+
function ConnectorCredentialFieldControl({ field, value, connected, provider, onChange, }) {
|
|
54
|
+
const { t } = useTranslation();
|
|
55
|
+
const st = useSetupT();
|
|
56
|
+
const form = useContext(ConnectorFormStateContext);
|
|
57
|
+
// label/description are i18n keys (addon locales are loaded into i18next);
|
|
58
|
+
// never surface a raw dotted key: fall back to the humanized field key.
|
|
59
|
+
const humanize = (k) => k.replace(/[_-]+/g, ' ').replace(/\b\w/g, (m) => m.toUpperCase());
|
|
60
|
+
const labelOf = (f) => f.label ? textOrFallback(t(f.label, { defaultValue: humanize(f.key) }), f.label, humanize(f.key)) : humanize(f.key);
|
|
61
|
+
const label = labelOf(field);
|
|
62
|
+
const help = field.description
|
|
63
|
+
? textOrFallback(t(field.description, { defaultValue: '' }), field.description, '')
|
|
64
|
+
: '';
|
|
65
|
+
const isSecret = isSecretCredential(field);
|
|
66
|
+
const isDynamic = field.type === 'dynamic_select' || !!field.options_source;
|
|
67
|
+
const error = form.errors[field.key];
|
|
68
|
+
const mismatch = shapeMismatch(field, value, form.fields);
|
|
69
|
+
const target = mismatch?.suggestedKey
|
|
70
|
+
? form.fields.find((f) => f.key === mismatch.suggestedKey)
|
|
71
|
+
: undefined;
|
|
72
|
+
const warning = mismatch
|
|
73
|
+
? st(mismatch.shape === 'public_key'
|
|
74
|
+
? 'installed_addons.shape_public_key'
|
|
75
|
+
: 'installed_addons.shape_secret_key', { target: target ? labelOf(target) : '' })
|
|
76
|
+
: '';
|
|
77
|
+
return (_jsxs("div", { className: 'flex flex-col gap-1', "data-field": field.key, children: [_jsxs(Label, { htmlFor: `${form.idPrefix}-cred-${field.key}`, children: [label, field.required ? _jsx("span", { className: 'text-destructive', children: " *" }) : null] }), isDynamic ? (_jsx(DynamicConnectorSelect, { field: field, value: value, provider: provider, connected: connected, onChange: onChange })) : field.type === 'select' && field.options?.length ? (_jsxs(Select, { value: value, onValueChange: onChange, children: [_jsx(SelectTrigger, { id: `${form.idPrefix}-cred-${field.key}`, "aria-invalid": !!error || undefined, children: _jsx(SelectValue, {}) }), _jsx(SelectContent, { children: field.options.map((o) => (_jsx(SelectItem, { value: o.value, children: t(o.label, { defaultValue: o.value }) }, o.value))) })] })) : (_jsx(Input, { id: `${form.idPrefix}-cred-${field.key}`, type: isSecret ? 'password' : 'text',
|
|
78
|
+
// A secret must never be offered to (or filled by) the browser's
|
|
79
|
+
// password manager: "new-password" is the value browsers respect.
|
|
80
|
+
autoComplete: isSecret ? 'new-password' : 'off', "data-1p-ignore": isSecret ? true : undefined, "data-lpignore": isSecret ? 'true' : undefined, spellCheck: false, autoCapitalize: 'off', "aria-invalid": !!error || undefined, "aria-describedby": error ? `${form.idPrefix}-cred-${field.key}-error` : undefined, className: cn(error && 'border-destructive focus-visible:ring-destructive/40'), placeholder: connected && isSecret ? '••••••••' : '', value: value, onChange: (e) => onChange(e.target.value) })), error ? (_jsx("p", { id: `${form.idPrefix}-cred-${field.key}-error`, role: 'alert', className: 'text-xs text-destructive', children: error })) : null, warning ? (_jsx("p", { className: 'text-xs text-amber-600 dark:text-amber-400', role: 'status', children: warning })) : null, help ? _jsx(HelpText, { text: help }) : null] }));
|
|
81
|
+
}
|
|
82
|
+
// useApi() hands every component its own wrapper object, so the cache cannot be
|
|
83
|
+
// keyed by client: it is module-level, keyed by provider + export, and dropped
|
|
84
|
+
// whenever a config surface closes (a new org / credentials never reads stale).
|
|
85
|
+
const lookupCache = new Map();
|
|
86
|
+
/** Drops the shared option-lookup cache (called when the surface closes). */
|
|
87
|
+
export function clearConnectorLookupCache() {
|
|
88
|
+
lookupCache.clear();
|
|
89
|
+
}
|
|
90
|
+
function fetchLookupOptions(api, provider, field, force = false) {
|
|
91
|
+
const key = `${provider}:${field.options_source || field.key}`;
|
|
92
|
+
if (!force && lookupCache.has(key))
|
|
93
|
+
return lookupCache.get(key);
|
|
94
|
+
const p = api
|
|
95
|
+
.post(`/integrations/${provider}/lookup`, { credential: field.key })
|
|
96
|
+
.then((res) => (res.data?.data?.options ?? []))
|
|
97
|
+
.catch((err) => {
|
|
98
|
+
lookupCache.delete(key); // don't cache failures
|
|
99
|
+
throw err;
|
|
100
|
+
});
|
|
101
|
+
lookupCache.set(key, p);
|
|
102
|
+
return p;
|
|
103
|
+
}
|
|
104
|
+
// A dynamic_select connector credential: the option list is fetched from the
|
|
105
|
+
// host, which runs the addon's `options_source` WASM export org-scoped (it reads
|
|
106
|
+
// the org's SAVED credentials via connector_get, e.g. lists factura.com series).
|
|
107
|
+
// So options only resolve once the connector is configured+saved — until then we
|
|
108
|
+
// show a hint and a manual free-text fallback so the field is never a dead end.
|
|
109
|
+
function DynamicConnectorSelect({ field, value, provider, connected, onChange, }) {
|
|
110
|
+
const st = useSetupT();
|
|
111
|
+
const form = useContext(ConnectorFormStateContext);
|
|
112
|
+
const hostApi = useApi();
|
|
113
|
+
const api = form.client ?? hostApi;
|
|
114
|
+
const [options, setOptions] = useState([]);
|
|
115
|
+
const [state, setState] = useState('idle');
|
|
116
|
+
const [error, setError] = useState('');
|
|
117
|
+
const load = async (force = false) => {
|
|
118
|
+
setState('loading');
|
|
119
|
+
setError('');
|
|
120
|
+
try {
|
|
121
|
+
const opts = await fetchLookupOptions(api, provider, field, force);
|
|
122
|
+
setOptions(opts);
|
|
123
|
+
setState('done');
|
|
124
|
+
}
|
|
125
|
+
catch (err) {
|
|
126
|
+
setError(err.response?.data?.message ||
|
|
127
|
+
st('installed_addons.dynamic_select_error', {
|
|
128
|
+
defaultValue: 'No se pudieron listar las opciones. Guarda la conexión y vuelve a intentar.',
|
|
129
|
+
}));
|
|
130
|
+
setState('error');
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
// Auto-load once when the connector is already configured (editing an existing
|
|
134
|
+
// connection). Fresh configs load on demand via the refresh button.
|
|
135
|
+
useEffect(() => {
|
|
136
|
+
if (connected && state === 'idle')
|
|
137
|
+
void load();
|
|
138
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
139
|
+
}, [connected]);
|
|
140
|
+
// Scope the options to the kind (`tipo`) the host expects for this field,
|
|
141
|
+
// when the source reports one. The mapping is injected by the host
|
|
142
|
+
// (`expectedOptionKinds`); empty by default, so the SDK stays domain-agnostic.
|
|
143
|
+
const expected = form.expectedOptionKinds[field.key];
|
|
144
|
+
const filtered = expected && options.some((o) => o.tipo === expected)
|
|
145
|
+
? options.filter((o) => o.tipo === expected)
|
|
146
|
+
: options;
|
|
147
|
+
return (_jsxs("div", { className: 'flex flex-col gap-1', children: [_jsxs("div", { className: 'flex items-center gap-2', children: [filtered.length > 0 ? (_jsxs(Select, { value: value, onValueChange: onChange, children: [_jsx(SelectTrigger, { id: `${form.idPrefix}-cred-${field.key}`, className: 'flex-1', children: _jsx(SelectValue, { placeholder: st('installed_addons.dynamic_select_choose', {
|
|
148
|
+
defaultValue: 'Elige una opción',
|
|
149
|
+
}) }) }), _jsx(SelectContent, { children: filtered.map((o) => (_jsx(SelectItem, { value: o.value, children: o.label }, o.value))) })] })) : (_jsx(Input, { id: `${form.idPrefix}-cred-${field.key}`, value: value, placeholder: st('installed_addons.dynamic_select_placeholder', {
|
|
150
|
+
defaultValue: 'Guarda la conexión y actualiza para elegir',
|
|
151
|
+
}), onChange: (e) => onChange(e.target.value) })), _jsx(Button, { type: 'button', variant: 'outline', size: 'sm', onClick: () => void load(true), disabled: state === 'loading', title: st('installed_addons.dynamic_select_refresh', {
|
|
152
|
+
defaultValue: 'Actualizar opciones',
|
|
153
|
+
}), children: state === 'loading' ? (_jsx(Loader2, { className: 'h-4 w-4 animate-spin' })) : (_jsx(RefreshCw, { className: 'h-4 w-4' })) })] }), state === 'error' && _jsx("p", { className: 'text-xs text-destructive', children: error })] }));
|
|
154
|
+
}
|
|
155
|
+
// ─── Unified addon configuration dialog ─────────────────────────────────────
|
|
156
|
+
// One "Configuración del addon" surface per addon combining two sections:
|
|
157
|
+
// • Credenciales — the addon's `token` connector credential form. Essential
|
|
158
|
+
// (required) fields render up top; optional/advanced fields (base_url,
|
|
159
|
+
// stamp_path, …) collapse under an "Avanzado" <details>. Saved via
|
|
160
|
+
// POST /integrations/:provider (only non-empty values, so re-saving without
|
|
161
|
+
// retyping a stored secret doesn't wipe it).
|
|
162
|
+
// • Ajustes — the addon's settings_defs (GET/PUT /addons/:key/settings).
|
|
163
|
+
// Fixed header + footer, scrollable body — a connector can declare many fields
|
|
164
|
+
// (env, keys, RFC, régimen, CP, base_url, stamp/cancel path) that would
|
|
165
|
+
// otherwise overflow the viewport.
|
|
166
|
+
export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSaved, canManageIssuer = true, activeBranch = null, ensureAddonBundle, notify = toast, client, expectedOptionKinds = NO_OPTION_KINDS, displayName, onConnectOAuth, }) {
|
|
167
|
+
const idPrefix = useId();
|
|
168
|
+
const { t, i18n } = useTranslation();
|
|
169
|
+
const st = useSetupT();
|
|
170
|
+
const hostApi = useApi();
|
|
171
|
+
const api = client ?? hostApi;
|
|
172
|
+
const activeBranchId = activeBranch?.id ?? '';
|
|
173
|
+
useEffect(() => {
|
|
174
|
+
if (!open)
|
|
175
|
+
clearConnectorLookupCache();
|
|
176
|
+
}, [open]);
|
|
177
|
+
const credFields = connector?.credentials ?? [];
|
|
178
|
+
const requiredFields = credFields.filter((f) => f.required);
|
|
179
|
+
const advancedFields = credFields.filter((f) => !f.required);
|
|
180
|
+
// A connector with a form_layout groups its credentials into titled sections
|
|
181
|
+
// (a light wizard). Fall back to the required/advanced split when absent.
|
|
182
|
+
const layoutSections = connector?.form_layout?.sections ?? [];
|
|
183
|
+
const useLayout = layoutSections.length > 0 && credFields.some((f) => !!f.section);
|
|
184
|
+
// A form_layout with mode "steps" drives a real wizard (one section at a time
|
|
185
|
+
// with Atrás/Siguiente), instead of stacked cards.
|
|
186
|
+
const stepMode = useLayout && connector?.form_layout?.mode === 'steps';
|
|
187
|
+
const [credValues, setCredValues] = useState({});
|
|
188
|
+
const [settingsValues, setSettingsValues] = useState({});
|
|
189
|
+
const [definitions, setDefinitions] = useState([]);
|
|
190
|
+
const [loading, setLoading] = useState(false);
|
|
191
|
+
const [currentStep, setCurrentStep] = useState(0);
|
|
192
|
+
// Last failed save: the complete message (shown in full, not as a toast that
|
|
193
|
+
// cuts it) and the fields to highlight.
|
|
194
|
+
const [formError, setFormError] = useState(null);
|
|
195
|
+
const [fieldErrors, setFieldErrors] = useState({});
|
|
196
|
+
const errorRef = useRef(null);
|
|
197
|
+
// Results of the step actions (by block key) and whether the operator typed
|
|
198
|
+
// credentials not saved yet (an action tests what is STORED: it saves first).
|
|
199
|
+
const [blockResults, setBlockResults] = useState({});
|
|
200
|
+
const [credDirty, setCredDirty] = useState(false);
|
|
201
|
+
const stepHeadingRef = useRef(null);
|
|
202
|
+
const stepMoved = useRef(false);
|
|
203
|
+
const setCred = (key, val) => {
|
|
204
|
+
setCredValues((v) => ({ ...v, [key]: val }));
|
|
205
|
+
setCredDirty(true);
|
|
206
|
+
if (fieldErrors[key]) {
|
|
207
|
+
setFieldErrors((e) => {
|
|
208
|
+
const { [key]: _drop, ...rest } = e;
|
|
209
|
+
return rest;
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
// Per-branch settings (POS-1): a setting the manifest declares `scope: branch`
|
|
214
|
+
// can be overridden for the ACTIVE branch. `target` picks which level the form
|
|
215
|
+
// reads/writes; in "branch" mode only the branch-scoped settings show, only the
|
|
216
|
+
// ones the operator touched are saved (an untouched key keeps inheriting the org
|
|
217
|
+
// value) and «Heredar de la organización» clears an override.
|
|
218
|
+
const [target, setTarget] = useState('org');
|
|
219
|
+
const [overrides, setOverrides] = useState({});
|
|
220
|
+
const [touched, setTouched] = useState(new Set());
|
|
221
|
+
const [cleared, setCleared] = useState(new Set());
|
|
222
|
+
const hasBranchDefs = definitions.some((d) => d.scope === 'branch');
|
|
223
|
+
const canTargetBranch = !!activeBranch && hasBranchDefs;
|
|
224
|
+
const branchMode = target === 'branch' && canTargetBranch;
|
|
225
|
+
// `visible_when` (kernel Setting.visible_when) is evaluated against the live values.
|
|
226
|
+
const shownDefs = (branchMode ? definitions.filter((d) => d.scope === 'branch') : definitions).filter((d) => evaluateVisibleWhen(getVisibleWhen(d), settingsValues));
|
|
227
|
+
const setSetting = (key, value) => {
|
|
228
|
+
setSettingsValues((prev) => ({ ...prev, [key]: value }));
|
|
229
|
+
setTouched((prev) => new Set(prev).add(key));
|
|
230
|
+
setCleared((prev) => {
|
|
231
|
+
if (!prev.has(key))
|
|
232
|
+
return prev;
|
|
233
|
+
const next = new Set(prev);
|
|
234
|
+
next.delete(key);
|
|
235
|
+
return next;
|
|
236
|
+
});
|
|
237
|
+
};
|
|
238
|
+
// Seed connector defaults (e.g. environment = sandbox, first select option,
|
|
239
|
+
// or a value the backend prefilled from the org) so selects open on their
|
|
240
|
+
// default, then overlay the STORED non-secret values (GET …/values). Without
|
|
241
|
+
// the overlay a configured connector reopened empty, and re-saving sent the
|
|
242
|
+
// select defaults over what was stored (PIT-035: régimen reset to 601).
|
|
243
|
+
// Secrets are never returned; their inputs stay blank = "keep as is".
|
|
244
|
+
useEffect(() => {
|
|
245
|
+
if (!open)
|
|
246
|
+
return;
|
|
247
|
+
const seed = {};
|
|
248
|
+
for (const f of credFields) {
|
|
249
|
+
if (f.default != null && f.default !== '')
|
|
250
|
+
seed[f.key] = String(f.default);
|
|
251
|
+
else if (f.type === 'select' && f.options?.length)
|
|
252
|
+
seed[f.key] = f.options[0].value;
|
|
253
|
+
}
|
|
254
|
+
setCredValues(seed);
|
|
255
|
+
setCurrentStep(0);
|
|
256
|
+
stepMoved.current = false;
|
|
257
|
+
setFormError(null);
|
|
258
|
+
setFieldErrors({});
|
|
259
|
+
setBlockResults({});
|
|
260
|
+
setCredDirty(false);
|
|
261
|
+
if (!canManageIssuer || !connector?.provider || credFields.length === 0)
|
|
262
|
+
return;
|
|
263
|
+
let cancelled = false;
|
|
264
|
+
api
|
|
265
|
+
.get(`/integrations/${connector.provider}/values`)
|
|
266
|
+
.then((res) => {
|
|
267
|
+
const stored = (res.data?.data?.values ?? {});
|
|
268
|
+
if (cancelled)
|
|
269
|
+
return;
|
|
270
|
+
// Only fields the user has not touched yet.
|
|
271
|
+
setCredValues((prev) => {
|
|
272
|
+
const next = { ...prev };
|
|
273
|
+
for (const [k, v] of Object.entries(stored)) {
|
|
274
|
+
// Write-only: a secret is never prefilled, even if a host echoes it.
|
|
275
|
+
const def = credFields.find((f) => f.key === k);
|
|
276
|
+
if (def && isSecretCredential(def))
|
|
277
|
+
continue;
|
|
278
|
+
if (v !== '' && prev[k] === seed[k])
|
|
279
|
+
next[k] = v;
|
|
280
|
+
}
|
|
281
|
+
return next;
|
|
282
|
+
});
|
|
283
|
+
})
|
|
284
|
+
.catch(() => {
|
|
285
|
+
/* older backend or no stored config: keep the defaults */
|
|
286
|
+
});
|
|
287
|
+
return () => {
|
|
288
|
+
cancelled = true;
|
|
289
|
+
};
|
|
290
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
291
|
+
}, [open, connector?.provider, canManageIssuer]);
|
|
292
|
+
// Load stored settings values + definitions. The backend returns the
|
|
293
|
+
// manifest's setting definitions alongside the stored values; fall back to
|
|
294
|
+
// the manifest we already have so custom (declarative) addons whose lifecycle
|
|
295
|
+
// isn't registered still render.
|
|
296
|
+
useEffect(() => {
|
|
297
|
+
if (!open)
|
|
298
|
+
return;
|
|
299
|
+
setLoading(true);
|
|
300
|
+
setTouched(new Set());
|
|
301
|
+
setCleared(new Set());
|
|
302
|
+
const branchQuery = target === 'branch' && activeBranch ? `?branch_id=${encodeURIComponent(activeBranchId)}` : '';
|
|
303
|
+
api
|
|
304
|
+
.get(`/addons/${addon.addon_key}/settings${branchQuery}`)
|
|
305
|
+
.then((res) => {
|
|
306
|
+
setSettingsValues(res.data?.data || {});
|
|
307
|
+
setOverrides(res.data?.overrides || {});
|
|
308
|
+
const defs = res.data?.definitions?.length > 0
|
|
309
|
+
? res.data.definitions
|
|
310
|
+
: (addon.manifest.settings_defs ?? []);
|
|
311
|
+
setDefinitions(defs);
|
|
312
|
+
})
|
|
313
|
+
.catch(() => {
|
|
314
|
+
setSettingsValues({});
|
|
315
|
+
setDefinitions(addon.manifest.settings_defs ?? []);
|
|
316
|
+
})
|
|
317
|
+
.finally(() => setLoading(false));
|
|
318
|
+
}, [open, addon.addon_key, target, activeBranchId]);
|
|
319
|
+
// The addon's texts can arrive after this dialog (installed a moment ago, or
|
|
320
|
+
// the org bundle still in flight): when its labels do not resolve yet, pull
|
|
321
|
+
// the addon's own bundle so the form never paints raw keys.
|
|
322
|
+
useEffect(() => {
|
|
323
|
+
if (!open || !connector || !ensureAddonBundle)
|
|
324
|
+
return;
|
|
325
|
+
const keys = [
|
|
326
|
+
...credFields.flatMap((f) => [f.label, f.description]),
|
|
327
|
+
...layoutSections.flatMap((sec) => [sec.title, sec.description]),
|
|
328
|
+
...layoutSections.flatMap((sec) => (sec.blocks ?? []).flatMap((b) => [b.title, b.description, b.label])),
|
|
329
|
+
].filter((k) => !!k);
|
|
330
|
+
if (keys.length === 0 || keys.every((k) => i18n.exists(k)))
|
|
331
|
+
return;
|
|
332
|
+
void ensureAddonBundle?.(connector.addon_key, i18n);
|
|
333
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
334
|
+
}, [open, connector?.addon_key, credFields.length]);
|
|
335
|
+
// Section/step help: an i18n key or a literal sentence (never a raw key).
|
|
336
|
+
const addonText = (key) => {
|
|
337
|
+
if (!key)
|
|
338
|
+
return '';
|
|
339
|
+
const out = textOrFallback(t(key, { defaultValue: '' }), key, '');
|
|
340
|
+
return out || (/\s/.test(key) ? key : '');
|
|
341
|
+
};
|
|
342
|
+
const credLabel = (f) => {
|
|
343
|
+
const fallback = humanizeKey(f.key);
|
|
344
|
+
return f.label ? textOrFallback(t(f.label, { defaultValue: fallback }), f.label, fallback) : fallback;
|
|
345
|
+
};
|
|
346
|
+
const saveMutation = useMutation({
|
|
347
|
+
mutationFn: async () => {
|
|
348
|
+
if (connector && canManageIssuer) {
|
|
349
|
+
// Only send non-empty values so re-saving without retyping a stored
|
|
350
|
+
// secret leaves it untouched (server merges).
|
|
351
|
+
const payload = {};
|
|
352
|
+
for (const [k, v] of Object.entries(credValues)) {
|
|
353
|
+
if (v != null && v !== '')
|
|
354
|
+
payload[k] = v;
|
|
355
|
+
}
|
|
356
|
+
await api.post(`/integrations/${connector.provider}`, payload);
|
|
357
|
+
}
|
|
358
|
+
if (branchMode) {
|
|
359
|
+
// Only what the operator touched: an untouched key keeps inheriting.
|
|
360
|
+
const payload = {};
|
|
361
|
+
for (const k of touched) {
|
|
362
|
+
const d = definitions.find((x) => x.key === k);
|
|
363
|
+
if (d?.write_only && isBlank(settingsValues[k]))
|
|
364
|
+
continue;
|
|
365
|
+
payload[k] = settingsValues[k];
|
|
366
|
+
}
|
|
367
|
+
for (const k of cleared)
|
|
368
|
+
payload[k] = null;
|
|
369
|
+
if (Object.keys(payload).length > 0) {
|
|
370
|
+
await api.put(`/addons/${addon.addon_key}/settings?branch_id=${encodeURIComponent(activeBranchId)}`, payload);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
else if (definitions.length > 0) {
|
|
374
|
+
// write_only settings are never read back: send them only when typed.
|
|
375
|
+
const payload = { ...settingsValues };
|
|
376
|
+
for (const d of definitions) {
|
|
377
|
+
if (d.write_only && (!touched.has(d.key) || isBlank(payload[d.key])))
|
|
378
|
+
delete payload[d.key];
|
|
379
|
+
}
|
|
380
|
+
await api.put(`/addons/${addon.addon_key}/settings`, payload);
|
|
381
|
+
}
|
|
382
|
+
},
|
|
383
|
+
onSuccess: () => {
|
|
384
|
+
setFormError(null);
|
|
385
|
+
setFieldErrors({});
|
|
386
|
+
setCredDirty(false);
|
|
387
|
+
notify.success(st('installed_addons.config_saved'));
|
|
388
|
+
onOpenChange(false);
|
|
389
|
+
onSaved?.();
|
|
390
|
+
},
|
|
391
|
+
onError: (err) => {
|
|
392
|
+
const { message, fieldKeys } = parseSaveError(err, st('installed_addons.settings_error'));
|
|
393
|
+
const known = new Set(credFields.map((f) => f.key));
|
|
394
|
+
const errs = {};
|
|
395
|
+
for (const k of fieldKeys) {
|
|
396
|
+
const f = credFields.find((c) => c.key === k);
|
|
397
|
+
if (known.has(k) && f) {
|
|
398
|
+
errs[k] = st('installed_addons.field_required', {
|
|
399
|
+
defaultValue: 'Falta completar este campo.',
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
setFieldErrors(errs);
|
|
404
|
+
setFormError(message);
|
|
405
|
+
focusFirstInvalid(Object.keys(errs));
|
|
406
|
+
},
|
|
407
|
+
});
|
|
408
|
+
// Brings the first failed field into view and focuses it; in a stepper it
|
|
409
|
+
// also jumps to the step that holds it.
|
|
410
|
+
const focusFirstInvalid = (keys) => {
|
|
411
|
+
const first = keys[0];
|
|
412
|
+
if (!first) {
|
|
413
|
+
window.setTimeout(() => errorRef.current?.scrollIntoView({ block: 'nearest' }), 0);
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
const sectionKey = credFields.find((f) => f.key === first)?.section;
|
|
417
|
+
if (sectionKey) {
|
|
418
|
+
// Index among the WIZARD steps (sections without fields/blocks are not steps).
|
|
419
|
+
const idx = wizardSteps.findIndex((sec) => sec.key === sectionKey);
|
|
420
|
+
if (idx >= 0)
|
|
421
|
+
goToStep(idx);
|
|
422
|
+
}
|
|
423
|
+
window.setTimeout(() => {
|
|
424
|
+
const el = document.getElementById(`${idPrefix}-cred-${first}`);
|
|
425
|
+
el?.closest('details')?.setAttribute('open', '');
|
|
426
|
+
el?.scrollIntoView({ block: 'center' });
|
|
427
|
+
el?.focus();
|
|
428
|
+
}, 50);
|
|
429
|
+
};
|
|
430
|
+
// Check what is certain before the round trip, so the operator sees WHICH
|
|
431
|
+
// field is missing instead of a generic failure.
|
|
432
|
+
const handleSave = () => {
|
|
433
|
+
setFormError(null);
|
|
434
|
+
if (connector && canManageIssuer) {
|
|
435
|
+
const miss = missingRequired(credFields, credValues, !!connector.connected);
|
|
436
|
+
if (miss.length > 0) {
|
|
437
|
+
const errs = {};
|
|
438
|
+
for (const k of miss) {
|
|
439
|
+
errs[k] = st('installed_addons.field_required', { defaultValue: 'Falta completar este campo.' });
|
|
440
|
+
}
|
|
441
|
+
setFieldErrors(errs);
|
|
442
|
+
setFormError(st('installed_addons.missing_fields', {
|
|
443
|
+
fields: miss.map((k) => credLabel(credFields.find((f) => f.key === k))).join(', '),
|
|
444
|
+
defaultValue: 'Faltan campos obligatorios: {{fields}}.',
|
|
445
|
+
}));
|
|
446
|
+
focusFirstInvalid(miss);
|
|
447
|
+
return;
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
setFieldErrors({});
|
|
451
|
+
saveMutation.mutate();
|
|
452
|
+
};
|
|
453
|
+
// Saves typed-but-unsaved credentials before an action runs: actions (and
|
|
454
|
+
// the connector test) read the STORED credentials, so testing what is on
|
|
455
|
+
// screen requires persisting it first. Returns an error message, or null.
|
|
456
|
+
const persistCredsIfDirty = async () => {
|
|
457
|
+
if (!credDirty || !connector || !canManageIssuer)
|
|
458
|
+
return null;
|
|
459
|
+
const miss = missingRequired(credFields, credValues, !!connector.connected);
|
|
460
|
+
if (miss.length > 0) {
|
|
461
|
+
const errs = {};
|
|
462
|
+
for (const k of miss)
|
|
463
|
+
errs[k] = st('installed_addons.field_required');
|
|
464
|
+
setFieldErrors(errs);
|
|
465
|
+
return st('installed_addons.missing_fields', {
|
|
466
|
+
fields: miss.map((k) => credLabel(credFields.find((f) => f.key === k))).join(', '),
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
const payload = {};
|
|
470
|
+
for (const [k, v] of Object.entries(credValues)) {
|
|
471
|
+
if (v != null && v !== '')
|
|
472
|
+
payload[k] = v;
|
|
473
|
+
}
|
|
474
|
+
await api.post(`/integrations/${connector.provider}`, payload);
|
|
475
|
+
setCredDirty(false);
|
|
476
|
+
onSaved?.();
|
|
477
|
+
return null;
|
|
478
|
+
};
|
|
479
|
+
// Runs a step action: the implicit connection test (connector.test_export)
|
|
480
|
+
// or a declared action block (host route /blocks/:key/run). The result is
|
|
481
|
+
// shown inline (aria-live) with retry, never as a toast that disappears.
|
|
482
|
+
const runAction = async (block) => {
|
|
483
|
+
const fail = st('blocks.failed');
|
|
484
|
+
try {
|
|
485
|
+
const pre = await persistCredsIfDirty();
|
|
486
|
+
if (pre)
|
|
487
|
+
return { status: 'error', message: pre, details: [] };
|
|
488
|
+
if (block.key === SYNC_BLOCK_KEY)
|
|
489
|
+
return await runSync();
|
|
490
|
+
const url = block.key === TEST_BLOCK_KEY
|
|
491
|
+
? `/integrations/${connector?.provider}/test`
|
|
492
|
+
: `/integrations/${connector?.provider}/blocks/${encodeURIComponent(block.key)}/run`;
|
|
493
|
+
const res = await api.post(url, {});
|
|
494
|
+
return normalizeBlockResult(res.data, fail);
|
|
495
|
+
}
|
|
496
|
+
catch (err) {
|
|
497
|
+
return { status: 'error', message: errorMessage(err, fail), details: [] };
|
|
498
|
+
}
|
|
499
|
+
};
|
|
500
|
+
const setResult = (key, r) => setBlockResults((prev) => ({ ...prev, [key]: r }));
|
|
501
|
+
// "Sincronizar ahora": ops-native connectors with a sync worker (hub →
|
|
502
|
+
// partner read-models) run one sync now and report the run summary.
|
|
503
|
+
const runSync = async () => {
|
|
504
|
+
const res = await api.post(connector?.sync_endpoint ?? '', {});
|
|
505
|
+
const data = res.data?.data;
|
|
506
|
+
if (data?.status === 'skipped') {
|
|
507
|
+
return { status: 'warn', message: data.message || st('installed_addons.sync_skipped'), details: [] };
|
|
508
|
+
}
|
|
509
|
+
const summary = st('installed_addons.sync_done', {
|
|
510
|
+
licenses: data?.licenses?.fetched ?? 0,
|
|
511
|
+
instances: data?.instances?.fetched ?? 0,
|
|
512
|
+
accounts: data?.accounts?.fetched ?? 0,
|
|
513
|
+
});
|
|
514
|
+
if (data?.status === 'partial') {
|
|
515
|
+
return { status: 'warn', message: `${summary} · ${(data.errors ?? []).join('; ')}`, details: [] };
|
|
516
|
+
}
|
|
517
|
+
return { status: 'ok', message: summary, details: [] };
|
|
518
|
+
};
|
|
519
|
+
const hasCredentials = credFields.length > 0;
|
|
520
|
+
const hasSettings = definitions.length > 0;
|
|
521
|
+
const canTest = !!connector?.test_export && canManageIssuer;
|
|
522
|
+
const issuerAdminNote = (_jsx("p", { className: 'text-sm text-muted-foreground', children: st('installed_addons.issuer_admin_only', {
|
|
523
|
+
defaultValue: '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.',
|
|
524
|
+
}) }));
|
|
525
|
+
const canSync = !!connector?.sync_endpoint && !!connector?.connected;
|
|
526
|
+
const renderCred = (f) => (_jsx(ConnectorCredentialFieldControl, { field: f, connected: !!connector?.connected, provider: connector?.provider ?? '', value: credValues[f.key] ?? '', onChange: (val) => setCred(f.key, val) }, f.key));
|
|
527
|
+
// One setting control, shared by the flat layout and the wizard's last step.
|
|
528
|
+
const renderSetting = (def) => {
|
|
529
|
+
const id = `${idPrefix}-setting-${def.key}`;
|
|
530
|
+
const value = settingsValues[def.key] ?? def.default_value;
|
|
531
|
+
const isCleared = cleared.has(def.key);
|
|
532
|
+
const overridden = branchMode && def.key in overrides && !isCleared;
|
|
533
|
+
return (_jsxs("div", { className: 'flex flex-col gap-2', children: [_jsxs("div", { className: 'flex items-center gap-2', children: [_jsx(Label, { htmlFor: id, children: def.label || def.key }), def.scope === 'branch' && !branchMode && (_jsx(Badge, { variant: 'outline', className: 'text-[10px]', children: st('installed_addons.per_branch') })), branchMode && (_jsx("span", { className: 'text-muted-foreground text-xs', children: isCleared
|
|
534
|
+
? st('installed_addons.inherit_pending')
|
|
535
|
+
: overridden || touched.has(def.key)
|
|
536
|
+
? st('installed_addons.branch_own')
|
|
537
|
+
: st('installed_addons.branch_inherited') })), branchMode && (overridden || touched.has(def.key)) && !isCleared && (_jsx(Button, { type: 'button', variant: 'link', size: 'sm', className: 'h-auto p-0 text-xs', onClick: () => setCleared((prev) => new Set(prev).add(def.key)), children: st('installed_addons.inherit') }))] }), def.type === 'boolean' ? (_jsx(Switch, { id: id, checked: !!value, onCheckedChange: (checked) => setSetting(def.key, checked) })) : def.type === 'select' && (def.options?.length ?? 0) > 0 ? (_jsxs(Select, { value: String(value ?? ''), onValueChange: (v) => setSetting(def.key, v), children: [_jsx(SelectTrigger, { id: id, children: _jsx(SelectValue, {}) }), _jsx(SelectContent, { children: def.options.map((o) => (_jsx(SelectItem, { value: String(o.value), children: o.label }, String(o.value)))) })] })) : def.write_only ? (_jsxs(_Fragment, { children: [_jsx(Input, { id: id, type: 'password', autoComplete: 'new-password', "data-1p-ignore": true, "data-lpignore": 'true', spellCheck: false, placeholder: def.stored ? '••••••••' : '', value: touched.has(def.key) ? String(settingsValues[def.key] ?? '') : '', onChange: (e) => setSetting(def.key, e.target.value) }), def.stored ? (_jsx("p", { className: 'text-xs text-muted-foreground', children: st('installed_addons.secret_stored') })) : null] })) : (_jsx(Input, { id: id, type: def.type === 'number' ? 'number' : 'text', value: String(value ?? ''), onChange: (e) => setSetting(def.key, def.type === 'number'
|
|
538
|
+
? e.target.value === ''
|
|
539
|
+
? undefined
|
|
540
|
+
: Number(e.target.value)
|
|
541
|
+
: e.target.value) }))] }, def.key));
|
|
542
|
+
};
|
|
543
|
+
// Which level the settings form edits (only offered when the addon has
|
|
544
|
+
// branch-scoped settings and a specific branch is active).
|
|
545
|
+
const targetPicker = canTargetBranch ? (_jsxs("div", { className: 'flex flex-wrap items-center gap-2 rounded-md border p-2 text-sm', children: [_jsx("span", { className: 'text-muted-foreground', children: st('installed_addons.applies_to') }), _jsx(Button, { type: 'button', size: 'sm', variant: branchMode ? 'outline' : 'default', onClick: () => setTarget('org'), children: st('installed_addons.whole_org') }), _jsx(Button, { type: 'button', size: 'sm', variant: branchMode ? 'default' : 'outline', onClick: () => setTarget('branch'), children: st('installed_addons.only_branch', { name: activeBranch?.name, defaultValue: 'Solo {{name}}' }) })] })) : null;
|
|
546
|
+
// Settings (Ajustes) body, reused by the flat layout and the wizard's last step.
|
|
547
|
+
const settingsBody = (_jsxs("div", { className: 'flex flex-col gap-3', children: [targetPicker, shownDefs.map(renderSetting)] }));
|
|
548
|
+
// OAuth connectors have no credential form: the surface shows their state and
|
|
549
|
+
// hands "Conectar cuenta" to the host (its OAuth redirect flow).
|
|
550
|
+
const isOAuth = !!connector && !!connector.auth && connector.auth !== 'token';
|
|
551
|
+
const oauthPanel = isOAuth ? (_jsxs("section", { className: 'flex flex-col gap-3 rounded-lg border border-border/70 p-3', children: [_jsxs("div", { className: 'flex flex-wrap items-center justify-between gap-2', children: [_jsxs("h4", { className: 'flex items-center gap-2 text-sm font-medium', children: [_jsx(Link2, { "aria-hidden": 'true', className: 'h-4 w-4 text-muted-foreground' }), st('oauth.title')] }), _jsx(StepStatusBadge, { status: connector.connected ? 'ok' : 'pending', label: connector.connected ? st('oauth.connected') : st('oauth.not_connected') })] }), _jsx(HelpText, { text: st('oauth.help') }), onConnectOAuth ? (_jsx(Button, { type: 'button', variant: connector.connected ? 'outline' : 'default', className: 'h-auto min-h-11 w-full sm:w-fit', onClick: () => onConnectOAuth(connector), children: connector.connected ? st('oauth.reconnect') : st('oauth.connect') })) : null] })) : null;
|
|
552
|
+
// Wizard steps: form_layout sections with fields OR blocks, + a final
|
|
553
|
+
// "Ajustes" step when the addon also ships settings.
|
|
554
|
+
const wizardSteps = stepMode
|
|
555
|
+
? buildWizardSteps(layoutSections, credFields.map((f) => f.section), hasSettings)
|
|
556
|
+
: [];
|
|
557
|
+
const totalSteps = wizardSteps.length;
|
|
558
|
+
const useStepper = stepMode && totalSteps > 1;
|
|
559
|
+
const stepIdx = Math.min(currentStep, Math.max(0, totalSteps - 1));
|
|
560
|
+
const activeStep = wizardSteps[stepIdx];
|
|
561
|
+
const isLastStep = stepIdx >= totalSteps - 1;
|
|
562
|
+
// "Probar conexión" (connector.test_export) is a verification INSIDE the
|
|
563
|
+
// flow (last credentials step / end of the credentials), not a footer
|
|
564
|
+
// button — unless the addon already declares an action block for it.
|
|
565
|
+
const implicitTest = canTest && !hasExplicitTest(layoutSections, connector?.test_export)
|
|
566
|
+
? {
|
|
567
|
+
key: TEST_BLOCK_KEY,
|
|
568
|
+
kind: 'action',
|
|
569
|
+
title: st('blocks.test_title'),
|
|
570
|
+
description: st('blocks.test_help'),
|
|
571
|
+
label: st('installed_addons.test_connection'),
|
|
572
|
+
}
|
|
573
|
+
: null;
|
|
574
|
+
const syncBlock = canSync
|
|
575
|
+
? { key: SYNC_BLOCK_KEY, kind: 'action', title: st('blocks.sync_title'), label: st('installed_addons.sync_now') }
|
|
576
|
+
: null;
|
|
577
|
+
const lastCredStep = (() => {
|
|
578
|
+
for (let i = wizardSteps.length - 1; i >= 0; i--)
|
|
579
|
+
if (wizardSteps[i].kind === 'creds')
|
|
580
|
+
return wizardSteps[i].key;
|
|
581
|
+
return undefined;
|
|
582
|
+
})();
|
|
583
|
+
const extraBlocks = [implicitTest, syncBlock].filter((b) => !!b);
|
|
584
|
+
const blocksFor = (sectionKey, declared = []) => sectionKey === lastCredStep ? [...declared, ...extraBlocks] : declared;
|
|
585
|
+
// Reading order inside a step: what the operator needs BEFORE typing
|
|
586
|
+
// (instructions, the URL to paste in the provider's panel) goes above the
|
|
587
|
+
// fields; verifications (actions) go below them.
|
|
588
|
+
const leadBlocks = (blocks = []) => blocks.filter((b) => b.kind !== 'action');
|
|
589
|
+
const trailBlocks = (blocks = []) => blocks.filter((b) => b.kind === 'action');
|
|
590
|
+
const renderBlocks = (blocks) => (_jsx(ConnectorBlocks, { blocks: blocks, runAction: runAction, results: blockResults, onResult: setResult, actionsDisabled: !canManageIssuer, actionNote: credDirty ? st('blocks.save_first') : undefined }));
|
|
591
|
+
const stepState = (i) => {
|
|
592
|
+
const s = wizardSteps[i];
|
|
593
|
+
return stepStatus({
|
|
594
|
+
index: i,
|
|
595
|
+
current: stepIdx,
|
|
596
|
+
fieldKeys: s.kind === 'creds' ? credFields.filter((f) => f.section === s.key).map((f) => f.key) : [],
|
|
597
|
+
fieldErrors,
|
|
598
|
+
blockKeys: blocksFor(s.key, s.blocks).map((b) => b.key),
|
|
599
|
+
results: blockResults,
|
|
600
|
+
});
|
|
601
|
+
};
|
|
602
|
+
// Moving between steps puts focus on the new step's heading (keyboard and
|
|
603
|
+
// screen-reader users land on the content, not on the footer).
|
|
604
|
+
const goToStep = (i) => {
|
|
605
|
+
stepMoved.current = true;
|
|
606
|
+
setCurrentStep(i);
|
|
607
|
+
};
|
|
608
|
+
useEffect(() => {
|
|
609
|
+
if (stepMoved.current)
|
|
610
|
+
stepHeadingRef.current?.focus();
|
|
611
|
+
}, [stepIdx]);
|
|
612
|
+
// "Siguiente" checks the current step's required credentials first, so the
|
|
613
|
+
// operator learns what is missing where it is, not at the end.
|
|
614
|
+
const handleNext = () => {
|
|
615
|
+
if (activeStep?.kind === 'creds' && connector && canManageIssuer) {
|
|
616
|
+
const stepFields = credFields.filter((f) => f.section === activeStep.key);
|
|
617
|
+
const miss = missingRequired(stepFields, credValues, !!connector.connected);
|
|
618
|
+
if (miss.length > 0) {
|
|
619
|
+
const errs = {};
|
|
620
|
+
for (const k of miss)
|
|
621
|
+
errs[k] = st('installed_addons.field_required');
|
|
622
|
+
setFieldErrors(errs);
|
|
623
|
+
setFormError(st('installed_addons.missing_fields', {
|
|
624
|
+
fields: miss.map((k) => credLabel(credFields.find((f) => f.key === k))).join(', '),
|
|
625
|
+
}));
|
|
626
|
+
focusFirstInvalid(miss);
|
|
627
|
+
return;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
setFormError(null);
|
|
631
|
+
goToStep(stepIdx + 1);
|
|
632
|
+
};
|
|
633
|
+
const hasAnyBlocks = layoutSections.some((s) => (s.blocks?.length ?? 0) > 0) || extraBlocks.length > 0;
|
|
634
|
+
const nothingToConfigure = !hasCredentials && !hasSettings && !isOAuth && !hasAnyBlocks;
|
|
635
|
+
const nothingToSave = !hasCredentials && !hasSettings;
|
|
636
|
+
return (_jsx(Dialog, { open: open, onOpenChange: onOpenChange, children: _jsx(DialogContent, { className: 'flex max-h-[85vh] flex-col max-sm:max-h-[calc(100dvh-1rem)] max-sm:gap-3 max-sm:p-4', children: _jsxs(ConnectorFormStateContext.Provider, { value: { fields: credFields, errors: fieldErrors, idPrefix, client: api, expectedOptionKinds }, children: [_jsxs(DialogHeader, { className: 'shrink-0 pe-8 text-start', children: [_jsx(DialogTitle, { className: 'leading-snug', children: st('installed_addons.configure_title', { name: displayName ?? addon.manifest.display_name ?? addon.manifest.name }) }), _jsx(DialogDescription, { children: st('installed_addons.configure_description') })] }), _jsx("div", { className: '-mr-2 flex min-h-0 flex-col gap-6 overflow-y-auto py-2 pr-2', children: loading ? (_jsx("div", { className: 'flex justify-center py-8', children: _jsx(Loader2, { className: 'h-5 w-5 animate-spin text-muted-foreground' }) })) : useStepper ? (_jsxs("div", { className: 'flex flex-col gap-5', children: [_jsxs("nav", { "aria-label": st('wizard.steps'), className: 'flex flex-col gap-2', children: [_jsx("ol", { className: 'flex items-center', children: wizardSteps.map((s, i) => {
|
|
637
|
+
const status = stepState(i);
|
|
638
|
+
const active = i === stepIdx;
|
|
639
|
+
const title = t(s.title ?? '', { defaultValue: humanizeKey(s.title) });
|
|
640
|
+
return (_jsxs("li", { className: cn('flex items-center', i < wizardSteps.length - 1 && 'flex-1'), children: [_jsx("button", { type: 'button', onClick: () => goToStep(i), "aria-current": active ? 'step' : undefined, "aria-label": st('wizard.step_label', {
|
|
641
|
+
n: i + 1,
|
|
642
|
+
total: totalSteps,
|
|
643
|
+
title,
|
|
644
|
+
status: st(`status.${status}`),
|
|
645
|
+
}), "data-step-status": status, 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', children: _jsx("span", { "aria-hidden": 'true', className: cn('flex h-8 w-8 items-center justify-center rounded-full border text-xs font-semibold transition-all', active
|
|
646
|
+
? 'border-primary bg-primary text-primary-foreground ring-4 ring-primary/15'
|
|
647
|
+
: status === 'error'
|
|
648
|
+
? 'border-destructive bg-destructive/10 text-destructive'
|
|
649
|
+
: status === 'ok'
|
|
650
|
+
? 'border-primary bg-primary/10 text-primary'
|
|
651
|
+
: 'border-border text-muted-foreground'), children: !active && status === 'error' ? (_jsx(AlertCircle, { className: 'h-4 w-4' })) : !active && status === 'ok' ? (_jsx(Check, { className: 'h-4 w-4' })) : (i + 1) }) }), i < wizardSteps.length - 1 && (_jsx("span", { "aria-hidden": 'true', className: cn('mx-1 h-0.5 flex-1 rounded-full transition-colors', i < stepIdx ? 'bg-primary' : 'bg-border') }))] }, s.key));
|
|
652
|
+
}) }), _jsxs("div", { className: 'flex items-start justify-between gap-3', children: [_jsx("h3", { ref: stepHeadingRef, tabIndex: -1, className: 'min-w-0 text-base leading-snug font-semibold break-words outline-none', children: t(activeStep?.title ?? '', {
|
|
653
|
+
defaultValue: humanizeKey(activeStep?.title),
|
|
654
|
+
}) }), _jsx("span", { className: 'mt-0.5 shrink-0 text-xs font-medium tabular-nums text-muted-foreground', children: st('flow.step_of', { n: stepIdx + 1, total: totalSteps }) })] })] }), _jsxs("div", { className: 'flex flex-col gap-4', children: [activeStep?.description && (_jsx(HelpText, { text: addonText(activeStep.description) })), activeStep?.kind === 'settings' ? (settingsBody) : !canManageIssuer ? (_jsxs(_Fragment, { children: [issuerAdminNote, renderBlocks(blocksFor(activeStep?.key ?? '', activeStep?.blocks))] })) : (_jsxs(_Fragment, { children: [renderBlocks(leadBlocks(blocksFor(activeStep?.key ?? '', activeStep?.blocks))), credFields.filter((f) => f.section === activeStep?.key).map(renderCred), renderBlocks(trailBlocks(blocksFor(activeStep?.key ?? '', activeStep?.blocks)))] }))] })] })) : (_jsxs(_Fragment, { children: [oauthPanel, hasCredentials && (_jsxs("section", { className: 'flex flex-col gap-3', children: [_jsxs("div", { className: 'flex items-center gap-2', children: [_jsx(Cable, { className: 'h-4 w-4 text-muted-foreground' }), _jsx("h3", { className: 'text-sm font-semibold', children: st('installed_addons.section_credentials') })] }), !canManageIssuer ? (issuerAdminNote) : useLayout ? (
|
|
655
|
+
// form_layout: one titled group per section, in declared order.
|
|
656
|
+
layoutSections.map((sec) => {
|
|
657
|
+
const fields = credFields.filter((f) => f.section === sec.key);
|
|
658
|
+
if (fields.length === 0 && (sec.blocks?.length ?? 0) === 0)
|
|
659
|
+
return null;
|
|
660
|
+
return (_jsxs("div", { className: 'flex flex-col gap-3 rounded-md border border-border/60 px-3 py-3', children: [sec.title && (_jsxs("div", { className: 'flex flex-col gap-1', children: [_jsx("h4", { className: 'text-sm font-medium', children: t(sec.title, { defaultValue: sec.title }) }), sec.description && (_jsx(HelpText, { text: addonText(sec.description) }))] })), renderBlocks(leadBlocks(sec.blocks)), fields.map((f) => (_jsx(ConnectorCredentialFieldControl, { field: f, connected: !!connector?.connected, provider: connector?.provider ?? '', value: credValues[f.key] ?? '', onChange: (val) => setCred(f.key, val) }, f.key))), renderBlocks(trailBlocks(sec.blocks))] }, sec.key));
|
|
661
|
+
})) : (_jsxs(_Fragment, { children: [requiredFields.map((f) => (_jsx(ConnectorCredentialFieldControl, { field: f, connected: !!connector?.connected, provider: connector?.provider ?? '', value: credValues[f.key] ?? '', onChange: (val) => setCred(f.key, val) }, f.key))), advancedFields.length > 0 && (_jsxs("details", { className: 'rounded-md border border-border/60 px-3 py-2', open: advancedFields.some((f) => !!fieldErrors[f.key]) || undefined, children: [_jsx("summary", { className: 'flex min-h-11 cursor-pointer items-center text-sm font-medium text-muted-foreground select-none sm:min-h-8', children: st('installed_addons.advanced') }), _jsx("div", { className: 'flex flex-col gap-3 pt-3', children: advancedFields.map((f) => (_jsx(ConnectorCredentialFieldControl, { field: f, connected: !!connector?.connected, provider: connector?.provider ?? '', value: credValues[f.key] ?? '', onChange: (val) => setCred(f.key, val) }, f.key))) })] }))] }))] })), extraBlocks.length > 0 && renderBlocks(extraBlocks), hasSettings && (_jsxs("section", { className: 'flex flex-col gap-3', children: [_jsxs("div", { className: 'flex items-center gap-2', children: [_jsx(Settings, { className: 'h-4 w-4 text-muted-foreground' }), _jsx("h3", { className: 'text-sm font-semibold', children: st('installed_addons.section_settings') })] }), targetPicker, shownDefs.map(renderSetting)] })), nothingToConfigure && (_jsxs("div", { className: 'flex flex-col items-start gap-1 rounded-lg border border-dashed p-4', children: [_jsx("p", { className: 'text-sm font-medium', children: st('empty.title') }), _jsx(HelpText, { text: st('empty.help') })] }))] })) }), formError ? (_jsx("div", { ref: errorRef, role: 'alert', 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', children: formError })) : null, _jsx(DialogFooter, { "data-wizard-footer": '', 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', children: nothingToSave ? (_jsx(Button, { className: 'col-span-2 h-11 sm:h-9', onClick: () => onOpenChange(false), children: st('common.close') })) : (_jsxs(_Fragment, { children: [_jsxs(Button, { className: 'order-first col-span-2 h-11 sm:order-last sm:h-9', onClick: useStepper && !isLastStep ? handleNext : handleSave, disabled: !(useStepper && !isLastStep) && (saveMutation.isPending || loading), children: [saveMutation.isPending && _jsx(Loader2, { className: 'mr-2 h-4 w-4 animate-spin' }), useStepper && !isLastStep ? st('common.next') : st('common.save')] }), useStepper && stepIdx > 0 && (_jsx(Button, { variant: 'outline', className: 'h-11 sm:h-9', onClick: () => goToStep(Math.max(0, stepIdx - 1)), children: st('common.back') })), _jsx(Button, { variant: 'ghost', className: cn('h-11 sm:order-first sm:h-9', !(useStepper && stepIdx > 0) && 'col-span-2'), onClick: () => onOpenChange(false), children: st('common.cancel') })] })) })] }) }) }));
|
|
662
|
+
}
|