@asteby/metacore-runtime-react 53.4.1 → 53.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +73 -0
  3. package/dist/index.d.ts +2 -0
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +4 -0
  6. package/dist/setup/addon-config-surface.d.ts +119 -0
  7. package/dist/setup/addon-config-surface.d.ts.map +1 -0
  8. package/dist/setup/addon-config-surface.js +662 -0
  9. package/dist/setup/connector-blocks-model.d.ts +79 -0
  10. package/dist/setup/connector-blocks-model.d.ts.map +1 -0
  11. package/dist/setup/connector-blocks-model.js +96 -0
  12. package/dist/setup/connector-blocks.d.ts +48 -0
  13. package/dist/setup/connector-blocks.d.ts.map +1 -0
  14. package/dist/setup/connector-blocks.js +132 -0
  15. package/dist/setup/connector-form-model.d.ts +40 -0
  16. package/dist/setup/connector-form-model.d.ts.map +1 -0
  17. package/dist/setup/connector-form-model.js +76 -0
  18. package/dist/setup/flow-model.d.ts +49 -0
  19. package/dist/setup/flow-model.d.ts.map +1 -0
  20. package/dist/setup/flow-model.js +124 -0
  21. package/dist/setup/health-card.d.ts +25 -0
  22. package/dist/setup/health-card.d.ts.map +1 -0
  23. package/dist/setup/health-card.js +21 -0
  24. package/dist/setup/index.d.ts +13 -0
  25. package/dist/setup/index.d.ts.map +1 -0
  26. package/dist/setup/index.js +15 -0
  27. package/dist/setup/messages.d.ts +15 -0
  28. package/dist/setup/messages.d.ts.map +1 -0
  29. package/dist/setup/messages.js +320 -0
  30. package/dist/setup/records-table.d.ts +24 -0
  31. package/dist/setup/records-table.d.ts.map +1 -0
  32. package/dist/setup/records-table.js +80 -0
  33. package/dist/setup/setup-flow.d.ts +30 -0
  34. package/dist/setup/setup-flow.d.ts.map +1 -0
  35. package/dist/setup/setup-flow.js +277 -0
  36. package/dist/setup/setup-form-step.d.ts +20 -0
  37. package/dist/setup/setup-form-step.d.ts.map +1 -0
  38. package/dist/setup/setup-form-step.js +173 -0
  39. package/dist/setup/step-status-badge.d.ts +12 -0
  40. package/dist/setup/step-status-badge.d.ts.map +1 -0
  41. package/dist/setup/step-status-badge.js +21 -0
  42. package/dist/setup/tone.d.ts +8 -0
  43. package/dist/setup/tone.d.ts.map +1 -0
  44. package/dist/setup/tone.js +33 -0
  45. package/dist/setup/types.d.ts +130 -0
  46. package/dist/setup/types.d.ts.map +1 -0
  47. package/dist/setup/types.js +1 -0
  48. package/package.json +9 -5
  49. package/src/__tests__/addon-config-surface.test.tsx +260 -0
  50. package/src/__tests__/connector-blocks.test.tsx +302 -0
  51. package/src/__tests__/setup-components.test.tsx +147 -0
  52. package/src/__tests__/setup-flow-model.test.ts +117 -0
  53. package/src/__tests__/setup-flow.test.tsx +424 -0
  54. package/src/index.ts +29 -0
  55. package/src/setup/addon-config-surface.tsx +1426 -0
  56. package/src/setup/connector-blocks-model.ts +163 -0
  57. package/src/setup/connector-blocks.tsx +341 -0
  58. package/src/setup/connector-form-model.ts +115 -0
  59. package/src/setup/flow-model.ts +156 -0
  60. package/src/setup/health-card.tsx +131 -0
  61. package/src/setup/index.ts +35 -0
  62. package/src/setup/messages.ts +334 -0
  63. package/src/setup/records-table.tsx +186 -0
  64. package/src/setup/setup-flow.tsx +562 -0
  65. package/src/setup/setup-form-step.tsx +342 -0
  66. package/src/setup/step-status-badge.tsx +47 -0
  67. package/src/setup/tone.ts +44 -0
  68. package/src/setup/types.ts +147 -0
@@ -0,0 +1,8 @@
1
+ import type { MetricTone, RecordStatus, StepStatus } from './types';
2
+ export type Tone = 'neutral' | 'info' | 'good' | 'warn' | 'bad';
3
+ export declare const TONE_BADGE: Record<Tone, string>;
4
+ export declare const TONE_TEXT: Record<Tone, string>;
5
+ export declare const STEP_TONE: Record<StepStatus, Tone>;
6
+ export declare const RECORD_TONE: Record<RecordStatus, Tone>;
7
+ export declare function metricTone(t: MetricTone | undefined): Tone;
8
+ //# sourceMappingURL=tone.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tone.d.ts","sourceRoot":"","sources":["../../src/setup/tone.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAEnE,MAAM,MAAM,IAAI,GAAG,SAAS,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,KAAK,CAAA;AAE/D,eAAO,MAAM,UAAU,EAAE,MAAM,CAAC,IAAI,EAAE,MAAM,CAM3C,CAAA;AAED,eAAO,MAAM,SAAS,EAAE,MAAM,CAAC,IAAI,EAAE,MAAM,CAM1C,CAAA;AAED,eAAO,MAAM,SAAS,EAAE,MAAM,CAAC,UAAU,EAAE,IAAI,CAO9C,CAAA;AAED,eAAO,MAAM,WAAW,EAAE,MAAM,CAAC,YAAY,EAAE,IAAI,CAOlD,CAAA;AAED,wBAAgB,UAAU,CAAC,CAAC,EAAE,UAAU,GAAG,SAAS,GAAG,IAAI,CAE1D"}
@@ -0,0 +1,33 @@
1
+ export const TONE_BADGE = {
2
+ neutral: 'border-border bg-muted text-muted-foreground',
3
+ info: 'border-sky-500/30 bg-sky-500/10 text-sky-700 dark:text-sky-300',
4
+ good: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300',
5
+ warn: 'border-amber-500/40 bg-amber-500/10 text-amber-800 dark:text-amber-300',
6
+ bad: 'border-destructive/40 bg-destructive/10 text-destructive',
7
+ };
8
+ export const TONE_TEXT = {
9
+ neutral: 'text-foreground',
10
+ info: 'text-sky-700 dark:text-sky-300',
11
+ good: 'text-emerald-700 dark:text-emerald-300',
12
+ warn: 'text-amber-800 dark:text-amber-300',
13
+ bad: 'text-destructive',
14
+ };
15
+ export const STEP_TONE = {
16
+ pending: 'neutral',
17
+ running: 'info',
18
+ ok: 'good',
19
+ warn: 'warn',
20
+ error: 'bad',
21
+ blocked: 'neutral',
22
+ };
23
+ export const RECORD_TONE = {
24
+ ok: 'good',
25
+ missing: 'bad',
26
+ wrong_value: 'bad',
27
+ propagating: 'info',
28
+ pending: 'neutral',
29
+ error: 'bad',
30
+ };
31
+ export function metricTone(t) {
32
+ return t === 'good' ? 'good' : t === 'warn' ? 'warn' : t === 'bad' ? 'bad' : 'neutral';
33
+ }
@@ -0,0 +1,130 @@
1
+ import type { FormLayout } from '../form-layout';
2
+ import type { VisibleWhen } from '../types';
3
+ export type StepStatus = 'pending' | 'running' | 'ok' | 'warn' | 'error' | 'blocked';
4
+ export type SetupStepKind = 'check' | 'form' | 'action' | 'records' | 'custom';
5
+ /** What the "fix" button of a diagnostic does. Exactly one is expected. */
6
+ export interface SetupFix {
7
+ label?: string;
8
+ /** Runs a server action on the step (`runStep(step, { action })`). */
9
+ action?: string;
10
+ /** Opens a link (http(s) or an app-relative path). */
11
+ url?: string;
12
+ /** Jumps to another step of the flow. */
13
+ step?: string;
14
+ }
15
+ export type DiagnosticSeverity = 'info' | 'warn' | 'error';
16
+ export interface SetupDiagnostic {
17
+ code?: string;
18
+ severity?: DiagnosticSeverity;
19
+ message: string;
20
+ detail?: string;
21
+ fix?: SetupFix;
22
+ }
23
+ export type RecordStatus = 'ok' | 'missing' | 'wrong_value' | 'propagating' | 'pending' | 'error';
24
+ /** One row of a records step (typically a DNS record to publish). */
25
+ export interface SetupRecord {
26
+ id?: string;
27
+ type: string;
28
+ name: string;
29
+ value: string;
30
+ status?: RecordStatus;
31
+ /** Human explanation for the row's state. */
32
+ diagnostic?: string | SetupDiagnostic;
33
+ /** What the server actually found, when it differs. */
34
+ found?: string;
35
+ ttl?: number;
36
+ priority?: number;
37
+ }
38
+ export type SetupFieldType = 'text' | 'secret' | 'number' | 'boolean' | 'select' | 'textarea';
39
+ export interface SetupField {
40
+ key: string;
41
+ type?: SetupFieldType;
42
+ label?: string;
43
+ description?: string;
44
+ placeholder?: string;
45
+ required?: boolean;
46
+ /** Value is never read back from the server; empty input keeps the stored one. */
47
+ write_only?: boolean;
48
+ default?: unknown;
49
+ options?: {
50
+ value: string;
51
+ label: string;
52
+ }[];
53
+ /** `form_layout` section this field belongs to. */
54
+ section?: string;
55
+ visible_when?: VisibleWhen;
56
+ }
57
+ export interface SetupStepDef {
58
+ key: string;
59
+ kind: SetupStepKind;
60
+ title: string;
61
+ description?: string;
62
+ depends_on?: string[];
63
+ optional?: boolean;
64
+ /** kind=form */
65
+ fields?: SetupField[];
66
+ form_layout?: FormLayout;
67
+ /** kind=action / check / records: label of the main button. */
68
+ action_label?: string;
69
+ /** kind=custom: federated slot name (default `setup.<flow>.<step>`). */
70
+ slot?: string;
71
+ }
72
+ export interface SetupFlowDef {
73
+ key?: string;
74
+ title?: string;
75
+ description?: string;
76
+ steps: SetupStepDef[];
77
+ }
78
+ export interface SetupStepState {
79
+ key: string;
80
+ status: StepStatus;
81
+ message?: string;
82
+ diagnostics?: SetupDiagnostic[];
83
+ records?: SetupRecord[];
84
+ /** Non-secret saved values (kind=form). */
85
+ values?: Record<string, unknown>;
86
+ /** write_only fields that already hold a stored value. */
87
+ stored_keys?: string[];
88
+ /** Server hint: poll again after this many seconds. */
89
+ retry_after_s?: number;
90
+ skipped?: boolean;
91
+ updated_at?: string;
92
+ }
93
+ export interface SetupFlowState {
94
+ steps: SetupStepState[] | Record<string, SetupStepState>;
95
+ /** Server's own verdict; otherwise derived from the steps. */
96
+ completed?: boolean;
97
+ }
98
+ export interface RunStepInput {
99
+ values?: Record<string, unknown>;
100
+ action?: string;
101
+ }
102
+ /** What the host plugs in. The server owns the state; the UI is resumable. */
103
+ export interface SetupFlowClient {
104
+ getState(): Promise<SetupFlowState>;
105
+ /** May answer the new step state, the whole flow state, or nothing (then the state is re-read). */
106
+ runStep(key: string, input?: RunStepInput): Promise<SetupStepState | SetupFlowState | void>;
107
+ skipStep(key: string): Promise<SetupStepState | SetupFlowState | void>;
108
+ /** Autosave of a form step's draft (non-final). Absent → no autosave. */
109
+ saveStep?(key: string, values: Record<string, unknown>): Promise<void>;
110
+ /** Push channel (SSE/WS). Returns the unsubscribe. Polling still covers a missed push. */
111
+ subscribe?(onState: (state: SetupFlowState) => void): () => void;
112
+ }
113
+ export type HealthStatus = 'ok' | 'warn' | 'error' | 'unknown';
114
+ export type MetricTone = 'neutral' | 'good' | 'warn' | 'bad';
115
+ export interface HealthMetric {
116
+ key: string;
117
+ label: string;
118
+ value: string | number;
119
+ unit?: string;
120
+ tone?: MetricTone;
121
+ hint?: string;
122
+ }
123
+ export interface HealthIssue {
124
+ id?: string;
125
+ severity: DiagnosticSeverity;
126
+ message: string;
127
+ detail?: string;
128
+ fix?: SetupFix;
129
+ }
130
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/setup/types.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAA;AAChD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,UAAU,CAAA;AAE3C,MAAM,MAAM,UAAU,GAAG,SAAS,GAAG,SAAS,GAAG,IAAI,GAAG,MAAM,GAAG,OAAO,GAAG,SAAS,CAAA;AACpF,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG,MAAM,GAAG,QAAQ,GAAG,SAAS,GAAG,QAAQ,CAAA;AAE9E,2EAA2E;AAC3E,MAAM,WAAW,QAAQ;IACrB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,sEAAsE;IACtE,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,sDAAsD;IACtD,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,yCAAyC;IACzC,IAAI,CAAC,EAAE,MAAM,CAAA;CAChB;AAED,MAAM,MAAM,kBAAkB,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CAAA;AAE1D,MAAM,WAAW,eAAe;IAC5B,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,QAAQ,CAAC,EAAE,kBAAkB,CAAA;IAC7B,OAAO,E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,CAAC,EAAE,MAAM,CAAA;IACf,GAAG,CAAC,EAAE,QAAQ,CAAA;CACjB"}
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asteby/metacore-runtime-react",
3
- "version": "53.4.1",
3
+ "version": "53.6.0",
4
4
  "description": "React runtime for metacore hosts — renders addon contributions dynamically",
5
5
  "repository": {
6
6
  "type": "git",
@@ -15,6 +15,10 @@
15
15
  "types": "./dist/index.d.ts",
16
16
  "import": "./dist/index.js"
17
17
  },
18
+ "./setup": {
19
+ "types": "./dist/setup/index.d.ts",
20
+ "import": "./dist/setup/index.js"
21
+ },
18
22
  "./charts": {
19
23
  "types": "./dist/widgets/charts.d.ts",
20
24
  "import": "./dist/widgets/charts.js"
@@ -37,8 +41,8 @@
37
41
  "zod": "^4.3.0"
38
42
  },
39
43
  "peerDependencies": {
40
- "@asteby/metacore-sdk": "^3.17.0",
41
- "@asteby/metacore-ui": "^2.29.0",
44
+ "@asteby/metacore-sdk": "^3.18.0",
45
+ "@asteby/metacore-ui": "^2.31.0",
42
46
  "@tanstack/react-query": ">=5",
43
47
  "@tanstack/react-router": ">=1.100",
44
48
  "@tanstack/react-table": ">=8",
@@ -69,8 +73,8 @@
69
73
  }
70
74
  },
71
75
  "devDependencies": {
72
- "@asteby/metacore-sdk": "3.17.0",
73
- "@asteby/metacore-ui": "2.29.0",
76
+ "@asteby/metacore-sdk": "3.18.0",
77
+ "@asteby/metacore-ui": "2.31.0",
74
78
  "@tanstack/react-query": "^5.95.0",
75
79
  "@tanstack/react-router": "^1.168.0",
76
80
  "@tanstack/react-table": "^8.20.0",
@@ -0,0 +1,260 @@
1
+ // @vitest-environment happy-dom
2
+ import { afterEach, describe, expect, it, vi } from 'vitest'
3
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
4
+ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
5
+
6
+ vi.mock('react-i18next', () => {
7
+ const dict: Record<string, string> = { 'pay.public_key': 'Llave pública', 'pay.token': 'Token', 'pay.serie_a': 'Serie A', 'pay.serie_b': 'Serie B' }
8
+ const t = (k: string, o?: { defaultValue?: string }) => dict[k] ?? o?.defaultValue ?? k
9
+ return { useTranslation: () => ({ t, i18n: { language: 'es', exists: () => true } }) }
10
+ })
11
+
12
+ import { ApiProvider } from '../api-context'
13
+ import { AddonConfigSurface, clearConnectorLookupCache, type ConnectorEntry } from '../setup/addon-config-surface'
14
+ import { shapeMismatch, missingRequired, credentialShape } from '../setup/connector-form-model'
15
+
16
+ afterEach(cleanup)
17
+
18
+ const addon = { addon_key: 'pay', manifest: { name: 'pay', display_name: 'Pagos', settings_defs: [] as any[] } }
19
+ const PUB = 'APP_USR-12345678-1234-1234-1234-123456789012'
20
+
21
+ function makeApi(routes: Record<string, any> = {}) {
22
+ const calls: { m: string; url: string; body?: any }[] = []
23
+ const handle = (m: string) => async (url: string, body?: any) => {
24
+ calls.push({ m, url, body })
25
+ const key = `${m} ${url}`
26
+ const r = routes[key]
27
+ if (r instanceof Error) throw r
28
+ return { data: typeof r === 'function' ? r(body) : (r ?? { data: {} }) }
29
+ }
30
+ return { client: { get: handle('GET'), post: handle('POST'), put: handle('PUT'), delete: handle('DELETE') }, calls }
31
+ }
32
+
33
+ function setup(props: Partial<React.ComponentProps<typeof AddonConfigSurface>>, routes: Record<string, any> = {}) {
34
+ const api = makeApi(routes)
35
+ const notify = { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() }
36
+ const qc = new QueryClient({ defaultOptions: { mutations: { retry: false }, queries: { retry: false } } })
37
+ const onOpenChange = vi.fn()
38
+ const onSaved = vi.fn()
39
+ render(
40
+ <QueryClientProvider client={qc}>
41
+ <ApiProvider client={api.client as any} batch={false}>
42
+ <AddonConfigSurface
43
+ addon={addon}
44
+ connector={null}
45
+ open
46
+ onOpenChange={onOpenChange}
47
+ onSaved={onSaved}
48
+ notify={notify}
49
+ {...props}
50
+ />
51
+ </ApiProvider>
52
+ </QueryClientProvider>,
53
+ )
54
+ return { ...api, notify, onOpenChange, onSaved }
55
+ }
56
+
57
+ const connector: ConnectorEntry = {
58
+ addon_key: 'pay',
59
+ provider: 'mp',
60
+ connected: true,
61
+ test_export: 'ping',
62
+ credentials: [
63
+ { key: 'public_key', label: 'pay.public_key', required: true },
64
+ { key: 'access_token', label: 'pay.token', secret: true, required: true },
65
+ { key: 'env', type: 'select', options: [{ value: 'sandbox', label: 'Pruebas' }, { value: 'prod', label: 'Producción' }], default: 'sandbox' },
66
+ ],
67
+ }
68
+
69
+ describe('connector-form-model', () => {
70
+ it('detects pasted key shapes and mismatches against sibling fields', () => {
71
+ expect(credentialShape(PUB)).toBe('public_key')
72
+ expect(shapeMismatch(connector.credentials![1], PUB, connector.credentials!)).toEqual({ shape: 'public_key', suggestedKey: 'public_key' })
73
+ expect(shapeMismatch(connector.credentials![0], PUB, connector.credentials!)).toBeNull()
74
+ })
75
+ it('a stored secret counts as filled', () => {
76
+ expect(missingRequired(connector.credentials!, {}, true)).toEqual(['public_key'])
77
+ expect(missingRequired(connector.credentials!, {}, false)).toEqual(['public_key', 'access_token'])
78
+ })
79
+ })
80
+
81
+ describe('AddonConfigSurface', () => {
82
+ it('keeps the header and footer outside the scrolling body', async () => {
83
+ setup({ connector })
84
+ const title = await screen.findByText('Configurar Pagos')
85
+ expect(title).toBeTruthy()
86
+ const content = document.querySelector('[data-slot="dialog-content"]') as HTMLElement
87
+ expect(content.className).toContain('flex')
88
+ expect(content.className).toContain('flex-col')
89
+ const body = document.querySelector('.overflow-y-auto') as HTMLElement
90
+ expect(body).toBeTruthy()
91
+ expect(body.contains(title)).toBe(false)
92
+ expect(body.contains(screen.getByText('Guardar'))).toBe(false)
93
+ })
94
+
95
+ it('secrets are write-only: password input, never prefilled, empty is not sent', async () => {
96
+ const { calls, notify, onSaved } = setup(
97
+ { connector },
98
+ { 'GET /integrations/mp/values': { data: { values: { public_key: 'APP_USR-x', access_token: 'LEAK', env: 'prod' } } } },
99
+ )
100
+ const secret = (await screen.findByLabelText(/Token/)) as HTMLInputElement
101
+ expect(secret.type).toBe('password')
102
+ expect(secret.autocomplete).toBe('new-password')
103
+ expect(secret.placeholder).toBe('••••••••')
104
+ await waitFor(() => expect((screen.getByLabelText(/Llave pública/) as HTMLInputElement).value).toBe('APP_USR-x'))
105
+ fireEvent.click(screen.getByText('Guardar'))
106
+ await waitFor(() => expect(notify.success).toHaveBeenCalledWith('Configuración guardada'))
107
+ const post = calls.find((c) => c.m === 'POST' && c.url === '/integrations/mp')!
108
+ expect(post.body.public_key).toBe('APP_USR-x')
109
+ expect(post.body.env).toBe('prod')
110
+ expect('access_token' in post.body).toBe(false) // empty secret = keep stored; an echoed value is never prefilled
111
+ expect(secret.value).toBe('')
112
+ expect(onSaved).toHaveBeenCalled()
113
+ })
114
+
115
+ it('does not fetch stored values for non-admins and explains why', async () => {
116
+ const { calls } = setup({ connector, canManageIssuer: false })
117
+ expect(await screen.findByText(/Solo un administrador de la organización/)).toBeTruthy()
118
+ expect(calls.some((c) => c.url === '/integrations/mp/values')).toBe(false)
119
+ expect(screen.queryByText('Probar conexión')).toBeNull()
120
+ })
121
+
122
+ it('blocks save on missing required fields and names them', async () => {
123
+ const { calls } = setup({ connector: { ...connector, connected: false } })
124
+ await screen.findByLabelText(/Token/)
125
+ fireEvent.click(screen.getByText('Guardar'))
126
+ expect((await screen.findByText(/Faltan campos obligatorios: Llave pública, Token/)).getAttribute('role')).toBe('alert')
127
+ expect(calls.some((c) => c.m === 'POST' && c.url === '/integrations/mp')).toBe(false)
128
+ })
129
+
130
+ it('warns when a public key is pasted in the secret field (without blocking)', async () => {
131
+ setup({ connector })
132
+ const secret = await screen.findByLabelText(/Token/)
133
+ fireEvent.change(secret, { target: { value: PUB } })
134
+ await waitFor(() =>
135
+ expect(screen.getAllByRole('status').some((w) => w.textContent?.includes('Llave pública'))).toBe(true),
136
+ )
137
+ })
138
+
139
+ it('Probar conexión runs inside the form (not the footer) and shows the result inline', async () => {
140
+ const { calls, notify } = setup(
141
+ { connector },
142
+ { 'POST /integrations/mp/test': { success: true, data: { ok: false, message: 'Credenciales inválidas' } } },
143
+ )
144
+ const btn = await screen.findByText('Probar conexión')
145
+ const footer = document.querySelector('[data-wizard-footer]') as HTMLElement
146
+ expect(footer.contains(btn)).toBe(false)
147
+ fireEvent.click(btn)
148
+ const msg = await screen.findByText('Credenciales inválidas')
149
+ expect(msg.closest('[data-result-status]')?.getAttribute('data-result-status')).toBe('error')
150
+ expect(msg.closest('[aria-live="polite"]')).toBeTruthy()
151
+ expect(calls.some((c) => c.m === 'POST' && c.url === '/integrations/mp/test')).toBe(true)
152
+ expect(notify.error).not.toHaveBeenCalled()
153
+ // The retry keeps the same action reachable.
154
+ expect(screen.getByText(/Reintentar: Probar conexión/)).toBeTruthy()
155
+ })
156
+
157
+ it('dynamic_select lists options from the host lookup once per export', async () => {
158
+ const dyn: ConnectorEntry = {
159
+ ...connector,
160
+ credentials: [
161
+ { key: 'serie_a', type: 'dynamic_select', options_source: 'list_series', label: 'pay.serie_a' },
162
+ { key: 'serie_b', type: 'dynamic_select', options_source: 'list_series', label: 'pay.serie_b' },
163
+ ],
164
+ }
165
+ const { calls } = setup({ connector: dyn }, { 'POST /integrations/mp/lookup': { data: { options: [{ value: 'A1', label: 'Serie A1' }] } } })
166
+ await screen.findByText('Serie A')
167
+ await waitFor(() => expect(calls.filter((c) => c.url === '/integrations/mp/lookup').length).toBe(1))
168
+ })
169
+
170
+ it('settings: visible_when hides, write_only is not sent unless typed', async () => {
171
+ const defs = [
172
+ { key: 'mode', label: 'Modo', type: 'select', options: [{ value: 'a', label: 'A' }, { value: 'b', label: 'B' }] },
173
+ { key: 'extra', label: 'Extra', type: 'text', visible_when: { field: 'mode', equals: 'b' } },
174
+ { key: 'token', label: 'Token de ajustes', type: 'text', write_only: true, stored: true },
175
+ ]
176
+ const { calls, notify } = setup(
177
+ { connector: null },
178
+ { 'GET /addons/pay/settings': { data: { mode: 'a', token: 'SHOULD_NOT_ECHO' }, definitions: defs } },
179
+ )
180
+ await screen.findByText('Modo')
181
+ expect(screen.queryByText('Extra')).toBeNull()
182
+ const tok = screen.getByLabelText('Token de ajustes') as HTMLInputElement
183
+ expect(tok.type).toBe('password')
184
+ expect(tok.value).toBe('')
185
+ fireEvent.click(screen.getByText('Guardar'))
186
+ await waitFor(() => expect(notify.success).toHaveBeenCalled())
187
+ const put = calls.find((c) => c.m === 'PUT')!
188
+ expect('token' in put.body).toBe(false)
189
+ expect(put.body.mode).toBe('a')
190
+ })
191
+
192
+ it('per-branch mode only sends what was touched', async () => {
193
+ const defs = [{ key: 'tip', label: 'Propina', type: 'text', scope: 'branch' }, { key: 'org', label: 'Org', type: 'text' }]
194
+ const { calls, notify } = setup(
195
+ { connector: null, activeBranch: { id: 'b1', name: 'Centro' } },
196
+ { 'GET /addons/pay/settings': { data: {}, definitions: defs }, 'GET /addons/pay/settings?branch_id=b1': { data: {}, definitions: defs } },
197
+ )
198
+ fireEvent.click(await screen.findByText('Solo Centro'))
199
+ const input = await screen.findByLabelText('Propina')
200
+ fireEvent.change(input, { target: { value: '10' } })
201
+ fireEvent.click(screen.getByText('Guardar'))
202
+ await waitFor(() => expect(notify.success).toHaveBeenCalled())
203
+ const put = calls.find((c) => c.m === 'PUT')!
204
+ expect(put.url).toBe('/addons/pay/settings?branch_id=b1')
205
+ expect(put.body).toEqual({ tip: '10' })
206
+ })
207
+
208
+ it('a write_only setting typed then erased does not send "" over the stored secret', async () => {
209
+ const defs = [
210
+ { key: 'token', label: 'Token de ajustes', type: 'text', write_only: true, stored: true },
211
+ { key: 'limit', label: 'Límite', type: 'number' },
212
+ ]
213
+ const { calls, notify } = setup({ connector: null }, { 'GET /addons/pay/settings': { data: {}, definitions: defs } })
214
+ const tok = (await screen.findByLabelText('Token de ajustes')) as HTMLInputElement
215
+ fireEvent.change(tok, { target: { value: 'abc' } })
216
+ fireEvent.change(tok, { target: { value: '' } })
217
+ const limit = screen.getByLabelText('Límite') as HTMLInputElement
218
+ fireEvent.change(limit, { target: { value: '5' } })
219
+ fireEvent.change(limit, { target: { value: '' } })
220
+ fireEvent.click(screen.getByText('Guardar'))
221
+ await waitFor(() => expect(notify.success).toHaveBeenCalled())
222
+ const put = calls.find((c) => c.m === 'PUT')!
223
+ expect('token' in put.body).toBe(false)
224
+ expect(put.body.limit).toBeUndefined() // empty number is not 0
225
+ })
226
+
227
+ it('dynamic_select uses the `client` prop and the injected expectedOptionKinds', async () => {
228
+ const dyn: ConnectorEntry = {
229
+ ...connector,
230
+ credentials: [{ key: 'serie_x', type: 'dynamic_select', options_source: 'list_series', label: 'pay.serie_x' }],
231
+ }
232
+ const opts = [
233
+ { value: 'F1', label: 'Serie F1', tipo: 'factura' },
234
+ { value: 'N1', label: 'Serie N1', tipo: 'nota' },
235
+ ]
236
+ clearConnectorLookupCache()
237
+ const prop = makeApi({ 'POST /integrations/mp/lookup': { data: { options: opts } } })
238
+ const host = makeApi()
239
+ const qc = new QueryClient()
240
+ render(
241
+ <QueryClientProvider client={qc}>
242
+ <ApiProvider client={host.client as any} batch={false}>
243
+ <AddonConfigSurface
244
+ addon={addon}
245
+ connector={dyn}
246
+ open
247
+ onOpenChange={() => {}}
248
+ client={prop.client as any}
249
+ expectedOptionKinds={{ serie_x: 'factura' }}
250
+ />
251
+ </ApiProvider>
252
+ </QueryClientProvider>,
253
+ )
254
+ await waitFor(() => expect(prop.calls.some((c) => c.url === '/integrations/mp/lookup')).toBe(true))
255
+ expect(host.calls.some((c) => c.url === '/integrations/mp/lookup')).toBe(false)
256
+ fireEvent.click(await screen.findByRole('combobox', { name: /Serie X/i }))
257
+ expect(await screen.findByText('Serie F1')).toBeTruthy()
258
+ expect(screen.queryByText('Serie N1')).toBeNull()
259
+ })
260
+ })