@asteby/metacore-runtime-react 53.13.1 → 53.15.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 +20 -0
- package/dist/action-modal-dispatcher.d.ts +1 -1
- package/dist/action-modal-dispatcher.d.ts.map +1 -1
- package/dist/action-modal-dispatcher.js +31 -6
- package/dist/dialogs/dynamic-record.d.ts +8 -1
- package/dist/dialogs/dynamic-record.d.ts.map +1 -1
- package/dist/dialogs/dynamic-record.js +34 -4
- package/dist/dynamic-columns.d.ts.map +1 -1
- package/dist/dynamic-columns.js +4 -0
- package/dist/dynamic-form-schema.d.ts.map +1 -1
- package/dist/dynamic-form-schema.js +5 -1
- package/dist/dynamic-form.d.ts.map +1 -1
- package/dist/dynamic-form.js +28 -3
- package/dist/dynamic-kanban.d.ts.map +1 -1
- package/dist/dynamic-kanban.js +33 -1
- package/dist/dynamic-line-items.d.ts.map +1 -1
- package/dist/dynamic-line-items.js +9 -1
- package/dist/dynamic-table.d.ts.map +1 -1
- package/dist/dynamic-table.js +7 -0
- package/dist/field-grid.d.ts +3 -1
- package/dist/field-grid.d.ts.map +1 -1
- package/dist/field-grid.js +2 -2
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/nullable-boolean.d.ts +48 -0
- package/dist/nullable-boolean.d.ts.map +1 -0
- package/dist/nullable-boolean.js +80 -0
- package/dist/slots/addon-slot.d.ts +91 -0
- package/dist/slots/addon-slot.d.ts.map +1 -0
- package/dist/slots/addon-slot.js +219 -0
- package/dist/slots/index.d.ts +3 -0
- package/dist/slots/index.d.ts.map +1 -0
- package/dist/slots/index.js +2 -0
- package/dist/slots/sdk-range.d.ts +6 -0
- package/dist/slots/sdk-range.d.ts.map +1 -0
- package/dist/slots/sdk-range.js +92 -0
- package/dist/tri-state-boolean-impl.d.ts +24 -0
- package/dist/tri-state-boolean-impl.d.ts.map +1 -0
- package/dist/tri-state-boolean-impl.js +35 -0
- package/dist/tri-state-boolean.d.ts +15 -0
- package/dist/tri-state-boolean.d.ts.map +1 -0
- package/dist/tri-state-boolean.js +24 -0
- package/dist/use-dynamic-filters.d.ts.map +1 -1
- package/dist/use-dynamic-filters.js +10 -0
- package/package.json +5 -5
- package/src/__tests__/addon-slot.test.tsx +280 -0
- package/src/__tests__/nullable-boolean.test.tsx +458 -0
- package/src/__tests__/slot-legacy.test.tsx +34 -0
- package/src/action-modal-dispatcher.tsx +32 -6
- package/src/dialogs/dynamic-record.tsx +53 -5
- package/src/dynamic-columns.tsx +3 -0
- package/src/dynamic-form-schema.ts +4 -1
- package/src/dynamic-form.tsx +31 -2
- package/src/dynamic-kanban.tsx +6 -1
- package/src/dynamic-line-items.tsx +9 -1
- package/src/dynamic-table.tsx +5 -0
- package/src/field-grid.tsx +4 -0
- package/src/index.ts +1 -0
- package/src/nullable-boolean.ts +96 -0
- package/src/slots/addon-slot.tsx +452 -0
- package/src/slots/index.ts +18 -0
- package/src/slots/sdk-range.ts +86 -0
- package/src/tri-state-boolean-impl.tsx +71 -0
- package/src/tri-state-boolean.tsx +39 -0
- package/src/use-dynamic-filters.ts +8 -0
|
@@ -0,0 +1,458 @@
|
|
|
1
|
+
// @vitest-environment happy-dom
|
|
2
|
+
//
|
|
3
|
+
// Booleanos opcionales con NULL (kernel >= v0.248.4 conserva NULL y Get/List lo
|
|
4
|
+
// devuelven). Ejemplo real: `mp_payments.sandbox` usa NULL para «modo
|
|
5
|
+
// desconocido». Si el panel convierte ese NULL en `false` al guardar, un pago de
|
|
6
|
+
// prueba pasa a parecer real. Cubre:
|
|
7
|
+
// - guardar sin tocar un booleano NULL no envía `false`;
|
|
8
|
+
// - tocarlo sí envía el valor elegido;
|
|
9
|
+
// - el control de tres estados (Sí / No / Sin definir);
|
|
10
|
+
// - celdas y vistas con NULL («—», no «No»);
|
|
11
|
+
// - el filtro booleano con «Sin definir» (`f_<col>=NULL`, OpNull del kernel);
|
|
12
|
+
// - un booleano `required` sigue igual (switch de dos estados, default false).
|
|
13
|
+
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
14
|
+
import { act, cleanup, fireEvent, render, renderHook, screen, waitFor } from '@testing-library/react'
|
|
15
|
+
|
|
16
|
+
vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn() } }))
|
|
17
|
+
const DICT: Record<string, string> = { 'payments.field.sandbox': 'Modo de prueba' }
|
|
18
|
+
const I18N = { t: (k: string, o?: { defaultValue?: string }) => DICT[k] ?? o?.defaultValue ?? k, i18n: { language: 'es' } }
|
|
19
|
+
vi.mock('react-i18next', () => ({ useTranslation: () => I18N }))
|
|
20
|
+
|
|
21
|
+
import { DynamicForm } from '../dynamic-form'
|
|
22
|
+
import { buildZodSchema } from '../dynamic-form-schema'
|
|
23
|
+
import { DynamicRecordDialog, pickDeclaredFieldValues } from '../dialogs/dynamic-record'
|
|
24
|
+
import { buildFieldDefaults, renderField } from '../action-modal-dispatcher'
|
|
25
|
+
import { makeDefaultGetDynamicColumns } from '../dynamic-columns'
|
|
26
|
+
import { cardMatchesLaneFunnel } from '../dynamic-kanban'
|
|
27
|
+
import { useDynamicFilters } from '../use-dynamic-filters'
|
|
28
|
+
import { ApiProvider, type ApiClient } from '../api-context'
|
|
29
|
+
import {
|
|
30
|
+
BOOLEAN_UNSET_FILTER_VALUE,
|
|
31
|
+
isNullableBooleanField,
|
|
32
|
+
omitUntouchedNullBooleans,
|
|
33
|
+
usesTriState,
|
|
34
|
+
withBooleanUnsetOption,
|
|
35
|
+
} from '../nullable-boolean'
|
|
36
|
+
import { TriStateBooleanField } from '../tri-state-boolean'
|
|
37
|
+
import { fromTriState, toTriState } from '../tri-state-boolean-impl'
|
|
38
|
+
import type { ActionFieldDef, TableMetadata } from '../types'
|
|
39
|
+
|
|
40
|
+
afterEach(cleanup)
|
|
41
|
+
|
|
42
|
+
const sandbox: ActionFieldDef = { key: 'sandbox', label: 'Sandbox', type: 'boolean', nullable: true }
|
|
43
|
+
const requiredFlag: ActionFieldDef = { key: 'active', label: 'Activo', type: 'boolean', required: true }
|
|
44
|
+
|
|
45
|
+
const radio = (name: string) => screen.findByRole('radio', { name })
|
|
46
|
+
|
|
47
|
+
describe('isNullableBooleanField / usesTriState', () => {
|
|
48
|
+
it('opcional admite NULL; required o nullable:false no', () => {
|
|
49
|
+
expect(isNullableBooleanField({ type: 'boolean' })).toBe(true)
|
|
50
|
+
expect(isNullableBooleanField({ type: 'boolean', nullable: true })).toBe(true)
|
|
51
|
+
expect(isNullableBooleanField({ type: 'boolean', required: true })).toBe(false)
|
|
52
|
+
expect(isNullableBooleanField({ type: 'boolean', nullable: false })).toBe(false)
|
|
53
|
+
expect(isNullableBooleanField({ type: 'text' })).toBe(false)
|
|
54
|
+
})
|
|
55
|
+
it('tres estados si el servidor lo declara nullable o el valor original es NULL', () => {
|
|
56
|
+
expect(usesTriState({ type: 'boolean', nullable: true }, false)).toBe(true)
|
|
57
|
+
expect(usesTriState({ type: 'boolean' }, null)).toBe(true)
|
|
58
|
+
// Flag opcional de una acción sin `nullable` ni NULL: switch de siempre.
|
|
59
|
+
expect(usesTriState({ type: 'boolean' }, undefined)).toBe(false)
|
|
60
|
+
expect(usesTriState({ type: 'boolean', required: true }, null)).toBe(false)
|
|
61
|
+
})
|
|
62
|
+
it('toTriState / fromTriState', () => {
|
|
63
|
+
expect([true, false, null, undefined, '', 'true', 'false'].map(toTriState)).toEqual([
|
|
64
|
+
'true', 'false', 'null', 'null', 'null', 'true', 'false',
|
|
65
|
+
])
|
|
66
|
+
expect([fromTriState('true'), fromTriState('false'), fromTriState('null')]).toEqual([true, false, null])
|
|
67
|
+
})
|
|
68
|
+
it('zod acepta null en el opcional y lo rechaza en el required', () => {
|
|
69
|
+
expect(buildZodSchema([sandbox]).safeParse({ sandbox: null }).success).toBe(true)
|
|
70
|
+
expect(buildZodSchema([requiredFlag]).safeParse({ active: null }).success).toBe(false)
|
|
71
|
+
})
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
describe('TriStateBooleanField', () => {
|
|
75
|
+
it('radiogroup accesible: NULL marca «Sin definir» y cada opción emite su valor', async () => {
|
|
76
|
+
const onChange = vi.fn()
|
|
77
|
+
render(<TriStateBooleanField value={null} onChange={onChange} label="Sandbox" />)
|
|
78
|
+
expect(await screen.findByRole('radiogroup', { name: 'Sandbox' })).toBeTruthy()
|
|
79
|
+
expect((await radio('Sin definir')).getAttribute('aria-checked')).toBe('true')
|
|
80
|
+
expect((await radio('No')).getAttribute('aria-checked')).toBe('false')
|
|
81
|
+
fireEvent.click(await radio('Sí'))
|
|
82
|
+
fireEvent.click(await radio('No'))
|
|
83
|
+
fireEvent.click(await radio('Sin definir'))
|
|
84
|
+
expect(onChange.mock.calls).toEqual([[true], [false], [null]])
|
|
85
|
+
})
|
|
86
|
+
it('flechas mueven y seleccionan', async () => {
|
|
87
|
+
const onChange = vi.fn()
|
|
88
|
+
render(<TriStateBooleanField value={false} onChange={onChange} label="Sandbox" />)
|
|
89
|
+
fireEvent.keyDown(await radio('No'), { key: 'ArrowRight' })
|
|
90
|
+
expect(onChange).toHaveBeenLastCalledWith(null)
|
|
91
|
+
})
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
describe('DynamicForm — booleano NULL', () => {
|
|
95
|
+
it('guardar sin tocarlo NO envía false (la llave no viaja)', async () => {
|
|
96
|
+
const onSubmit = vi.fn()
|
|
97
|
+
render(
|
|
98
|
+
<DynamicForm
|
|
99
|
+
fields={[{ key: 'ref', label: 'Ref', type: 'text' }, sandbox]}
|
|
100
|
+
initialValues={{ id: 'p1', ref: 'MP-1', sandbox: null }}
|
|
101
|
+
onSubmit={onSubmit}
|
|
102
|
+
/>,
|
|
103
|
+
)
|
|
104
|
+
expect((await radio('Sin definir')).getAttribute('aria-checked')).toBe('true')
|
|
105
|
+
await act(async () => {
|
|
106
|
+
screen.getByText('Guardar').click()
|
|
107
|
+
})
|
|
108
|
+
expect(onSubmit).toHaveBeenCalledTimes(1)
|
|
109
|
+
const payload = onSubmit.mock.calls[0][0]
|
|
110
|
+
expect(payload).not.toHaveProperty('sandbox')
|
|
111
|
+
expect(payload.ref).toBe('MP-1')
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
it('tocarlo sí lo envía', async () => {
|
|
115
|
+
const onSubmit = vi.fn()
|
|
116
|
+
render(<DynamicForm fields={[sandbox]} initialValues={{ id: 'p1', sandbox: null }} onSubmit={onSubmit} />)
|
|
117
|
+
fireEvent.click(await radio('No'))
|
|
118
|
+
await act(async () => {
|
|
119
|
+
screen.getByText('Guardar').click()
|
|
120
|
+
})
|
|
121
|
+
expect(onSubmit.mock.calls[0][0]).toEqual({ sandbox: false })
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
it('volver a «Sin definir» envía null', async () => {
|
|
125
|
+
const onSubmit = vi.fn()
|
|
126
|
+
render(<DynamicForm fields={[sandbox]} initialValues={{ id: 'p1', sandbox: true }} onSubmit={onSubmit} />)
|
|
127
|
+
fireEvent.click(await radio('Sin definir'))
|
|
128
|
+
await act(async () => {
|
|
129
|
+
screen.getByText('Guardar').click()
|
|
130
|
+
})
|
|
131
|
+
expect(onSubmit.mock.calls[0][0]).toEqual({ sandbox: null })
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
it('required: switch de dos estados y el NULL legado sigue cayendo a false (sin cambio)', async () => {
|
|
135
|
+
const onSubmit = vi.fn()
|
|
136
|
+
render(<DynamicForm fields={[requiredFlag]} initialValues={{ id: 'p1', active: null }} onSubmit={onSubmit} />)
|
|
137
|
+
expect(screen.getByRole('switch')).toBeTruthy()
|
|
138
|
+
expect(screen.queryByRole('radiogroup')).toBeNull()
|
|
139
|
+
await act(async () => {
|
|
140
|
+
screen.getByText('Guardar').click()
|
|
141
|
+
})
|
|
142
|
+
expect(onSubmit.mock.calls[0][0]).toEqual({ active: false })
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
it('alta: el default del manifest no cambia', async () => {
|
|
146
|
+
const onSubmit = vi.fn()
|
|
147
|
+
render(
|
|
148
|
+
<DynamicForm
|
|
149
|
+
fields={[{ ...sandbox, defaultValue: true }, { key: 'flag', label: 'Flag', type: 'boolean' }]}
|
|
150
|
+
onSubmit={onSubmit}
|
|
151
|
+
/>,
|
|
152
|
+
)
|
|
153
|
+
await act(async () => {
|
|
154
|
+
screen.getByText('Guardar').click()
|
|
155
|
+
})
|
|
156
|
+
expect(onSubmit.mock.calls[0][0]).toEqual({ sandbox: true, flag: false })
|
|
157
|
+
})
|
|
158
|
+
})
|
|
159
|
+
|
|
160
|
+
const api = (put = vi.fn(async () => ({ data: { success: true } }))) =>
|
|
161
|
+
({
|
|
162
|
+
get: vi.fn(async () => ({ data: { data: {} } })),
|
|
163
|
+
post: vi.fn(async () => ({ data: { success: true } })),
|
|
164
|
+
put,
|
|
165
|
+
delete: vi.fn(async () => ({ data: { success: true } })),
|
|
166
|
+
}) as unknown as ApiClient
|
|
167
|
+
|
|
168
|
+
function renderRecord(fields: unknown[], record: Record<string, unknown>, onUpdate: (...a: unknown[]) => unknown) {
|
|
169
|
+
return render(
|
|
170
|
+
<ApiProvider client={api()}>
|
|
171
|
+
<DynamicRecordDialog
|
|
172
|
+
open
|
|
173
|
+
onOpenChange={() => {}}
|
|
174
|
+
model="mp_payments"
|
|
175
|
+
mode="edit"
|
|
176
|
+
recordId={String(record.id)}
|
|
177
|
+
initialRecord={record}
|
|
178
|
+
onUpdate={onUpdate as never}
|
|
179
|
+
schema={{ title: 'Pago', fields } as never}
|
|
180
|
+
/>
|
|
181
|
+
</ApiProvider>,
|
|
182
|
+
)
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
describe('DynamicRecordDialog (CRUD) — booleano NULL', () => {
|
|
186
|
+
const fields = [
|
|
187
|
+
{ key: 'reference', label: 'Referencia', type: 'text' },
|
|
188
|
+
{ key: 'sandbox', label: 'Sandbox', type: 'boolean', nullable: true },
|
|
189
|
+
]
|
|
190
|
+
const record = { id: 9, reference: 'MP-9', sandbox: null }
|
|
191
|
+
|
|
192
|
+
it('guardar sin tocarlo omite la llave (nunca false, "" ni "null")', async () => {
|
|
193
|
+
const onUpdate = vi.fn(async () => undefined)
|
|
194
|
+
renderRecord(fields, record, onUpdate)
|
|
195
|
+
expect((await radio('Sin definir')).getAttribute('aria-checked')).toBe('true')
|
|
196
|
+
fireEvent.click(screen.getByRole('button', { name: /Guardar|Actualizar/ }))
|
|
197
|
+
await waitFor(() => expect(onUpdate).toHaveBeenCalled())
|
|
198
|
+
const payload = (onUpdate.mock.calls[0] as unknown[])[1] as Record<string, unknown>
|
|
199
|
+
expect(payload).not.toHaveProperty('sandbox')
|
|
200
|
+
expect(payload.reference).toBe('MP-9')
|
|
201
|
+
})
|
|
202
|
+
|
|
203
|
+
it('elegir «Sin definir» sobre un valor guardado envía null JSON', async () => {
|
|
204
|
+
const onUpdate = vi.fn(async () => undefined)
|
|
205
|
+
renderRecord(fields, { ...record, sandbox: true }, onUpdate)
|
|
206
|
+
fireEvent.click(await radio('Sin definir'))
|
|
207
|
+
fireEvent.click(screen.getByRole('button', { name: /Guardar|Actualizar/ }))
|
|
208
|
+
await waitFor(() => expect(onUpdate).toHaveBeenCalled())
|
|
209
|
+
const payload = (onUpdate.mock.calls[0] as unknown[])[1] as Record<string, unknown>
|
|
210
|
+
expect(payload).toHaveProperty('sandbox', null)
|
|
211
|
+
expect(JSON.stringify(payload)).toContain('"sandbox":null')
|
|
212
|
+
})
|
|
213
|
+
|
|
214
|
+
it('tocarlo envía el valor elegido', async () => {
|
|
215
|
+
const onUpdate = vi.fn(async () => undefined)
|
|
216
|
+
renderRecord(fields, record, onUpdate)
|
|
217
|
+
fireEvent.click(await radio('Sí'))
|
|
218
|
+
fireEvent.click(screen.getByRole('button', { name: /Guardar|Actualizar/ }))
|
|
219
|
+
await waitFor(() => expect(onUpdate).toHaveBeenCalled())
|
|
220
|
+
const payload = (onUpdate.mock.calls[0] as unknown[])[1] as Record<string, unknown>
|
|
221
|
+
expect(payload.sandbox).toBe(true)
|
|
222
|
+
})
|
|
223
|
+
|
|
224
|
+
it('required: switch de dos estados, sin control de tres estados', async () => {
|
|
225
|
+
const onUpdate = vi.fn(async () => undefined)
|
|
226
|
+
renderRecord(
|
|
227
|
+
[{ key: 'active', label: 'Activo', type: 'boolean', required: true }],
|
|
228
|
+
{ id: 3, active: true },
|
|
229
|
+
onUpdate,
|
|
230
|
+
)
|
|
231
|
+
await waitFor(() => expect(screen.getByRole('switch')).toBeTruthy())
|
|
232
|
+
expect(screen.queryByRole('radiogroup')).toBeNull()
|
|
233
|
+
})
|
|
234
|
+
|
|
235
|
+
it("editPayload 'declared' conserva null en el booleano opcional (no '')", () => {
|
|
236
|
+
expect(
|
|
237
|
+
pickDeclaredFieldValues({ sandbox: null, note: null }, [
|
|
238
|
+
{ key: 'sandbox', label: 'S', type: 'boolean', nullable: true },
|
|
239
|
+
{ key: 'note', label: 'N', type: 'text' },
|
|
240
|
+
]),
|
|
241
|
+
).toEqual({ sandbox: null, note: '' })
|
|
242
|
+
})
|
|
243
|
+
|
|
244
|
+
it('vista: NULL se pinta «—», no «No»', async () => {
|
|
245
|
+
render(
|
|
246
|
+
<ApiProvider client={api()}>
|
|
247
|
+
<DynamicRecordDialog
|
|
248
|
+
open
|
|
249
|
+
onOpenChange={() => {}}
|
|
250
|
+
model="mp_payments"
|
|
251
|
+
mode="view"
|
|
252
|
+
recordId="9"
|
|
253
|
+
initialRecord={record}
|
|
254
|
+
schema={{ title: 'Pago', fields } as never}
|
|
255
|
+
/>
|
|
256
|
+
</ApiProvider>,
|
|
257
|
+
)
|
|
258
|
+
const mark = await screen.findByLabelText('Sin definir')
|
|
259
|
+
expect(mark.textContent).toBe('—')
|
|
260
|
+
expect(screen.queryByText('No')).toBeNull()
|
|
261
|
+
})
|
|
262
|
+
})
|
|
263
|
+
|
|
264
|
+
describe('omitUntouchedNullBooleans (contrato del payload)', () => {
|
|
265
|
+
const fs = [
|
|
266
|
+
{ key: 'sandbox', type: 'boolean' },
|
|
267
|
+
{ key: 'active', type: 'boolean', required: true },
|
|
268
|
+
{ key: 'note', type: 'text' },
|
|
269
|
+
]
|
|
270
|
+
it('omite el NULL no tocado; deja true/false, el null elegido y los no booleanos', () => {
|
|
271
|
+
const orig: Record<string, unknown> = { sandbox: null, active: true, note: null }
|
|
272
|
+
expect(omitUntouchedNullBooleans({ sandbox: null, active: true, note: null }, fs, (k) => orig[k])).toEqual({
|
|
273
|
+
active: true,
|
|
274
|
+
note: null,
|
|
275
|
+
})
|
|
276
|
+
expect(omitUntouchedNullBooleans({ sandbox: false }, fs, (k) => orig[k])).toEqual({ sandbox: false })
|
|
277
|
+
expect(omitUntouchedNullBooleans({ sandbox: null }, fs, () => true)).toEqual({ sandbox: null })
|
|
278
|
+
})
|
|
279
|
+
})
|
|
280
|
+
|
|
281
|
+
describe('modales de acción — buildFieldDefaults', () => {
|
|
282
|
+
it('booleano opcional NULL en el registro se siembra null; required y alta sin cambio', () => {
|
|
283
|
+
const fields: ActionFieldDef[] = [
|
|
284
|
+
{ key: 'sandbox', label: 'S', type: 'boolean' },
|
|
285
|
+
{ key: 'active', label: 'A', type: 'boolean', required: true },
|
|
286
|
+
{ key: 'notify', label: 'N', type: 'boolean' },
|
|
287
|
+
]
|
|
288
|
+
expect(buildFieldDefaults(fields, { id: 1, sandbox: null, active: null })).toEqual({
|
|
289
|
+
sandbox: null,
|
|
290
|
+
active: false,
|
|
291
|
+
notify: false,
|
|
292
|
+
})
|
|
293
|
+
// Alta (sin registro): el default del manifest manda.
|
|
294
|
+
expect(buildFieldDefaults([{ ...fields[0], defaultValue: true }, fields[1]], undefined)).toEqual({
|
|
295
|
+
sandbox: true,
|
|
296
|
+
active: false,
|
|
297
|
+
})
|
|
298
|
+
})
|
|
299
|
+
})
|
|
300
|
+
|
|
301
|
+
function renderBoolCell(value: unknown) {
|
|
302
|
+
const meta = {
|
|
303
|
+
title: 't',
|
|
304
|
+
endpoint: '/x',
|
|
305
|
+
columns: [{ key: 'sandbox', label: 'Sandbox', type: 'boolean' }],
|
|
306
|
+
actions: [],
|
|
307
|
+
perPageOptions: [10],
|
|
308
|
+
defaultPerPage: 10,
|
|
309
|
+
searchPlaceholder: '',
|
|
310
|
+
enableCRUDActions: false,
|
|
311
|
+
hasActions: false,
|
|
312
|
+
} as unknown as TableMetadata
|
|
313
|
+
const cols = makeDefaultGetDynamicColumns({ getImageUrl: (p: string) => p })(meta, undefined, undefined, 'es')
|
|
314
|
+
const c = cols.find((x) => (x as { accessorKey?: string }).accessorKey === 'sandbox' || x.id === 'sandbox')
|
|
315
|
+
if (!c || typeof c.cell !== 'function') throw new Error('columna no encontrada')
|
|
316
|
+
const row = { sandbox: value }
|
|
317
|
+
const node = (c.cell as (ctx: unknown) => React.ReactNode)({ row: { original: row }, getValue: () => value })
|
|
318
|
+
return render(<>{node}</>).container
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
describe('celda booleana', () => {
|
|
322
|
+
it('NULL pinta «—» (Sin definir), no «No»', () => {
|
|
323
|
+
const el = renderBoolCell(null)
|
|
324
|
+
expect(el.textContent).toBe('—')
|
|
325
|
+
expect(el.querySelector('[aria-label="Sin definir"]')).toBeTruthy()
|
|
326
|
+
})
|
|
327
|
+
it('false sigue siendo «No» y true «Sí»', () => {
|
|
328
|
+
expect(renderBoolCell(false).textContent).toContain('No')
|
|
329
|
+
cleanup()
|
|
330
|
+
expect(renderBoolCell(true).textContent).toContain('Sí')
|
|
331
|
+
})
|
|
332
|
+
})
|
|
333
|
+
|
|
334
|
+
describe('filtro booleano con NULL', () => {
|
|
335
|
+
it('withBooleanUnsetOption agrega «Sin definir» una sola vez y no inventa opciones', () => {
|
|
336
|
+
const yesNo = [
|
|
337
|
+
{ value: 'true', label: 'Sí' },
|
|
338
|
+
{ value: 'false', label: 'No' },
|
|
339
|
+
]
|
|
340
|
+
const out = withBooleanUnsetOption(yesNo, 'Sin definir')
|
|
341
|
+
expect(out.map((o) => o.value)).toEqual(['true', 'false', BOOLEAN_UNSET_FILTER_VALUE])
|
|
342
|
+
expect(withBooleanUnsetOption(out, 'Sin definir')).toHaveLength(3)
|
|
343
|
+
expect(withBooleanUnsetOption([], 'Sin definir')).toEqual([])
|
|
344
|
+
})
|
|
345
|
+
|
|
346
|
+
it('el filtro ofrece Sí / No / Sin definir y «Sin definir» viaja como f_<col>=NULL', async () => {
|
|
347
|
+
const metadata = {
|
|
348
|
+
title: 'Pagos',
|
|
349
|
+
endpoint: '/data/mp_payments',
|
|
350
|
+
columns: [{ key: 'sandbox', label: 'Sandbox', type: 'boolean', filterable: true }],
|
|
351
|
+
filters: [
|
|
352
|
+
{
|
|
353
|
+
key: 'sandbox',
|
|
354
|
+
label: 'Sandbox',
|
|
355
|
+
type: 'boolean',
|
|
356
|
+
options: [
|
|
357
|
+
{ value: 'true', label: 'Sí' },
|
|
358
|
+
{ value: 'false', label: 'No' },
|
|
359
|
+
],
|
|
360
|
+
},
|
|
361
|
+
],
|
|
362
|
+
actions: [],
|
|
363
|
+
perPageOptions: [10],
|
|
364
|
+
defaultPerPage: 10,
|
|
365
|
+
searchPlaceholder: '',
|
|
366
|
+
enableCRUDActions: false,
|
|
367
|
+
hasActions: false,
|
|
368
|
+
} as unknown as TableMetadata
|
|
369
|
+
const { result } = renderHook(() => useDynamicFilters(metadata, { model: 'mp_payments' }), {
|
|
370
|
+
wrapper: ({ children }) => <ApiProvider client={api()}>{children}</ApiProvider>,
|
|
371
|
+
})
|
|
372
|
+
const cfg = result.current.columnFilterConfigs.get('sandbox')
|
|
373
|
+
expect(cfg?.options?.map((o) => [o.value, o.label])).toEqual([
|
|
374
|
+
['true', 'Sí'],
|
|
375
|
+
['false', 'No'],
|
|
376
|
+
['NULL', 'Sin definir'],
|
|
377
|
+
])
|
|
378
|
+
act(() => result.current.handleDynamicFilterChange('sandbox', ['NULL']))
|
|
379
|
+
expect(result.current.filterParams.f_sandbox).toBe('NULL')
|
|
380
|
+
// «No» sigue siendo `= false`: excluye NULL a propósito (opción aparte).
|
|
381
|
+
act(() => result.current.handleDynamicFilterChange('sandbox', ['false']))
|
|
382
|
+
expect(result.current.filterParams.f_sandbox).toBe('false')
|
|
383
|
+
})
|
|
384
|
+
})
|
|
385
|
+
|
|
386
|
+
describe('carril del kanban con NULL', () => {
|
|
387
|
+
it('«Sin definir» (NULL) casa sólo con null explícito; No sigue siendo false', () => {
|
|
388
|
+
const f = { field: 'sandbox', values: ['NULL'] }
|
|
389
|
+
expect(cardMatchesLaneFunnel({ sandbox: null }, f)).toBe(true)
|
|
390
|
+
// Sin la columna (undefined) o con '' no es «Sin definir».
|
|
391
|
+
expect(cardMatchesLaneFunnel({}, f)).toBe(false)
|
|
392
|
+
expect(cardMatchesLaneFunnel({ sandbox: undefined }, f)).toBe(false)
|
|
393
|
+
expect(cardMatchesLaneFunnel({ sandbox: '' }, f)).toBe(false)
|
|
394
|
+
expect(cardMatchesLaneFunnel({ sandbox: false }, f)).toBe(false)
|
|
395
|
+
expect(cardMatchesLaneFunnel({ sandbox: null }, { field: 'sandbox', values: ['false'] })).toBe(false)
|
|
396
|
+
expect(cardMatchesLaneFunnel({ sandbox: false }, { field: 'sandbox', values: ['false'] })).toBe(true)
|
|
397
|
+
})
|
|
398
|
+
})
|
|
399
|
+
|
|
400
|
+
describe('accesibilidad del control de tres estados', () => {
|
|
401
|
+
it('CRUD: el radiogroup toma la etiqueta traducida por aria-labelledby', async () => {
|
|
402
|
+
renderRecord(
|
|
403
|
+
[{ key: 'sandbox', label: 'payments.field.sandbox', type: 'boolean', nullable: true }],
|
|
404
|
+
{ id: 9, sandbox: null },
|
|
405
|
+
vi.fn(),
|
|
406
|
+
)
|
|
407
|
+
const group = await screen.findByRole('radiogroup', { name: 'Modo de prueba' })
|
|
408
|
+
const labelId = group.getAttribute('aria-labelledby')
|
|
409
|
+
expect(labelId).toBeTruthy()
|
|
410
|
+
expect(document.getElementById(labelId!)?.textContent).toContain('Modo de prueba')
|
|
411
|
+
})
|
|
412
|
+
|
|
413
|
+
it('DynamicForm: el <Label> visible nombra al radiogroup', async () => {
|
|
414
|
+
render(<DynamicForm fields={[sandbox]} initialValues={{ id: 'p1', sandbox: null }} onSubmit={vi.fn()} />)
|
|
415
|
+
const group = await screen.findByRole('radiogroup', { name: 'Sandbox' })
|
|
416
|
+
expect(document.getElementById(group.getAttribute('aria-labelledby')!)?.tagName).toBe('LABEL')
|
|
417
|
+
})
|
|
418
|
+
|
|
419
|
+
it('dos formularios a la vez con el mismo campo: ids distintos, cada uno a su etiqueta', async () => {
|
|
420
|
+
render(
|
|
421
|
+
<>
|
|
422
|
+
<div data-testid="a">
|
|
423
|
+
<DynamicForm fields={[{ ...sandbox, label: 'Sandbox A' }]} initialValues={{ id: 'a', sandbox: null }} onSubmit={vi.fn()} />
|
|
424
|
+
</div>
|
|
425
|
+
<div data-testid="b">
|
|
426
|
+
<DynamicForm fields={[{ ...sandbox, label: 'Sandbox B' }]} initialValues={{ id: 'b', sandbox: null }} onSubmit={vi.fn()} />
|
|
427
|
+
</div>
|
|
428
|
+
</>,
|
|
429
|
+
)
|
|
430
|
+
const a = await screen.findByRole('radiogroup', { name: 'Sandbox A' })
|
|
431
|
+
const b = await screen.findByRole('radiogroup', { name: 'Sandbox B' })
|
|
432
|
+
const ida = a.getAttribute('aria-labelledby')!
|
|
433
|
+
const idb = b.getAttribute('aria-labelledby')!
|
|
434
|
+
expect(ida).not.toBe(idb)
|
|
435
|
+
expect(document.querySelectorAll(`[id="${ida}"]`)).toHaveLength(1)
|
|
436
|
+
expect(screen.getByTestId('a').contains(document.getElementById(ida))).toBe(true)
|
|
437
|
+
expect(screen.getByTestId('b').contains(document.getElementById(idb))).toBe(true)
|
|
438
|
+
})
|
|
439
|
+
|
|
440
|
+
it('modal de acción: renderField usa el id de etiqueta que le da su modal', async () => {
|
|
441
|
+
const field: ActionFieldDef = { key: 'sandbox', label: 'Sandbox', type: 'boolean', nullable: true }
|
|
442
|
+
render(
|
|
443
|
+
<>
|
|
444
|
+
<span id=":r1:sandbox-label">Modal 1</span>
|
|
445
|
+
{renderField(field, null, vi.fn(), {}, { sandbox: null }, undefined, ':r1:sandbox-label')}
|
|
446
|
+
<span id=":r2:sandbox-label">Modal 2</span>
|
|
447
|
+
{renderField(field, null, vi.fn(), {}, { sandbox: null }, undefined, ':r2:sandbox-label')}
|
|
448
|
+
</>,
|
|
449
|
+
)
|
|
450
|
+
expect(await screen.findByRole('radiogroup', { name: 'Modal 1' })).toBeTruthy()
|
|
451
|
+
expect(await screen.findByRole('radiogroup', { name: 'Modal 2' })).toBeTruthy()
|
|
452
|
+
})
|
|
453
|
+
|
|
454
|
+
it('sin <label> (celda de renglón): aria-label traducido', async () => {
|
|
455
|
+
render(<TriStateBooleanField value={null} onChange={vi.fn()} label="payments.field.sandbox" />)
|
|
456
|
+
expect(await screen.findByRole('radiogroup', { name: 'Modo de prueba' })).toBeTruthy()
|
|
457
|
+
})
|
|
458
|
+
})
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// @vitest-environment happy-dom
|
|
2
|
+
// Regresion de <Slot> (API historica): no cambia al existir <AddonSlot>.
|
|
3
|
+
import { describe, expect, it, vi } from 'vitest'
|
|
4
|
+
import { render, screen } from '@testing-library/react'
|
|
5
|
+
import { Slot, slotRegistry } from '../slot'
|
|
6
|
+
|
|
7
|
+
describe('<Slot> legacy', () => {
|
|
8
|
+
it('esparce props tal cual, incluso una clave llamada "props", sin wrapper', () => {
|
|
9
|
+
const name = `legacy.props.${Math.random()}`
|
|
10
|
+
const C = (p: any) => <b data-testid="c">{String(p.props)}|{String(p.x)}</b>
|
|
11
|
+
const off = slotRegistry.register(name, C)
|
|
12
|
+
const { container } = render(<Slot name={name} props={{ props: 'a', x: 1 }} />)
|
|
13
|
+
expect(screen.getByTestId('c').textContent).toBe('a|1')
|
|
14
|
+
expect(container.firstElementChild?.tagName).toBe('B')
|
|
15
|
+
off()
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
it('un error de render NO se traga (se propaga como siempre)', () => {
|
|
19
|
+
const name = `legacy.err.${Math.random()}`
|
|
20
|
+
const Boom = () => {
|
|
21
|
+
throw new Error('boom')
|
|
22
|
+
}
|
|
23
|
+
const off = slotRegistry.register(name, Boom)
|
|
24
|
+
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
|
25
|
+
expect(() => render(<Slot name={name} />)).toThrow('boom')
|
|
26
|
+
spy.mockRestore()
|
|
27
|
+
off()
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
it('sin contribuciones pinta el fallback', () => {
|
|
31
|
+
render(<Slot name={`legacy.none.${Math.random()}`} fallback={<i data-testid="fb" />} />)
|
|
32
|
+
expect(screen.getByTestId('fb')).toBeTruthy()
|
|
33
|
+
})
|
|
34
|
+
})
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
// The host injects its axios-like client via <ApiProvider>; we no longer
|
|
16
16
|
// depend on a bundler alias to `@/lib/api`.
|
|
17
17
|
import { emitRecordMutationSettled } from './record-mutation-events'
|
|
18
|
-
import { Suspense, useState, useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from 'react'
|
|
18
|
+
import { Suspense, useState, useCallback, useEffect, useId, useMemo, useRef, useSyncExternalStore } from 'react'
|
|
19
19
|
import { useTranslation } from 'react-i18next'
|
|
20
20
|
import {
|
|
21
21
|
Dialog,
|
|
@@ -96,6 +96,8 @@ import { federatedModalComponent, resolveFederatedModal } from './primitives/con
|
|
|
96
96
|
import { installedPredicate, useContributionsVersion } from './primitives/use-contributions'
|
|
97
97
|
import { isTodayToken, todayInZone } from './calendar-date'
|
|
98
98
|
import { useTimeZone } from './org-runtime-context'
|
|
99
|
+
import { isNullableBooleanField, omitUntouchedNullBooleans, usesTriState } from './nullable-boolean'
|
|
100
|
+
import { TriStateBooleanField } from './tri-state-boolean'
|
|
99
101
|
|
|
100
102
|
export type { ActionMetadata, ActionModalProps }
|
|
101
103
|
|
|
@@ -1088,6 +1090,8 @@ export function focusFirstInvalid(root: HTMLElement | null): HTMLElement | null
|
|
|
1088
1090
|
|
|
1089
1091
|
function GenericActionModal({ open, onOpenChange, action, model, record, endpoint, onSuccess }: ActionModalProps) {
|
|
1090
1092
|
const { t, i18n } = useTranslation()
|
|
1093
|
+
// Prefijo único por instancia para los ids de las etiquetas (aria-labelledby).
|
|
1094
|
+
const formUid = useId()
|
|
1091
1095
|
// Addon-contributed labels (action + fields) are i18n keys whose locale
|
|
1092
1096
|
// bundle loads asynchronously; translate at render so they don't render raw.
|
|
1093
1097
|
// defaultValue keeps an already-localized string unchanged.
|
|
@@ -1285,7 +1289,10 @@ function GenericActionModal({ open, onOpenChange, action, model, record, endpoin
|
|
|
1285
1289
|
setFormError(undefined)
|
|
1286
1290
|
setExecuting(true)
|
|
1287
1291
|
try {
|
|
1288
|
-
|
|
1292
|
+
// Un booleano NULL del registro que nadie tocó no viaja.
|
|
1293
|
+
let payload: Record<string, any> = record
|
|
1294
|
+
? omitUntouchedNullBooleans({ ...formData }, action.fields, (k) => readRecordPath(record, k))
|
|
1295
|
+
: { ...formData }
|
|
1289
1296
|
// Create-placement actions (and any create with no record) may need a
|
|
1290
1297
|
// host branch stamp when the sidebar is on "Todas". Skip when the
|
|
1291
1298
|
// form already collected branch_id, or the host has no gate.
|
|
@@ -1405,7 +1412,7 @@ function GenericActionModal({ open, onOpenChange, action, model, record, endpoin
|
|
|
1405
1412
|
resolveWidget(field) === 'richtext'
|
|
1406
1413
|
return (
|
|
1407
1414
|
<FieldCell key={field.key} fullWidth={fullWidth}>
|
|
1408
|
-
<FieldLabel htmlFor={field.key} required={field.required}>
|
|
1415
|
+
<FieldLabel id={`${formUid}${field.key}-label`} htmlFor={field.key} required={field.required}>
|
|
1409
1416
|
{tl(field.label)}
|
|
1410
1417
|
</FieldLabel>
|
|
1411
1418
|
{renderField(
|
|
@@ -1415,6 +1422,7 @@ function GenericActionModal({ open, onOpenChange, action, model, record, endpoin
|
|
|
1415
1422
|
formData,
|
|
1416
1423
|
record,
|
|
1417
1424
|
fieldErrors,
|
|
1425
|
+
`${formUid}${field.key}-label`,
|
|
1418
1426
|
)}
|
|
1419
1427
|
{fieldErrors[field.key] && (
|
|
1420
1428
|
<p id={`${field.key}-error`} className="text-destructive text-xs mt-1" data-field-error={field.key}>
|
|
@@ -1506,6 +1514,13 @@ export function buildFieldDefaults(
|
|
|
1506
1514
|
defaults[field.key] = fromRecord
|
|
1507
1515
|
continue
|
|
1508
1516
|
}
|
|
1517
|
+
// Booleano opcional en NULL en el registro: se siembra null («Sin
|
|
1518
|
+
// definir»), no el default ni `false`. Si el usuario no lo toca, la
|
|
1519
|
+
// llave no viaja (omitUntouchedNullBooleans) y el NULL se conserva.
|
|
1520
|
+
if (record && isNullableBooleanField(field) && readRecordPath(record, field.key) === null) {
|
|
1521
|
+
defaults[field.key] = null
|
|
1522
|
+
continue
|
|
1523
|
+
}
|
|
1509
1524
|
defaults[field.key] = resolveFieldDefault(field, ctx) ?? (field.type === 'boolean' ? false : '')
|
|
1510
1525
|
}
|
|
1511
1526
|
return defaults
|
|
@@ -1533,6 +1548,7 @@ function wizardStepErrors(
|
|
|
1533
1548
|
// single-page action form — no widget is duplicated.
|
|
1534
1549
|
function WizardActionModal({ open, onOpenChange, action, model, record, endpoint, onSuccess }: ActionModalProps) {
|
|
1535
1550
|
const { t, i18n } = useTranslation()
|
|
1551
|
+
const formUid = useId()
|
|
1536
1552
|
const tl = (s: string) => t(s, { defaultValue: s })
|
|
1537
1553
|
const api = useApi()
|
|
1538
1554
|
const reasonPrompt = useReasonPrompt()
|
|
@@ -1611,7 +1627,12 @@ function WizardActionModal({ open, onOpenChange, action, model, record, endpoint
|
|
|
1611
1627
|
const res = await reasonPrompt.run({
|
|
1612
1628
|
title: tl(action.label),
|
|
1613
1629
|
description: t('actions.reason_desc', { defaultValue: 'Esta acción pide el motivo. Queda en la bitácora del documento.' }),
|
|
1614
|
-
request: (reason) =>
|
|
1630
|
+
request: (reason) => {
|
|
1631
|
+
const data = record
|
|
1632
|
+
? omitUntouchedNullBooleans(formData, steps.flatMap((s) => s.fields ?? []), (k) => readRecordPath(record, k))
|
|
1633
|
+
: formData
|
|
1634
|
+
return api.post(url, withApproval(reason ? { ...data, reason } : data, auth))
|
|
1635
|
+
},
|
|
1615
1636
|
})
|
|
1616
1637
|
if (!res) return
|
|
1617
1638
|
const allFields = steps.flatMap(s => s.fields ?? [])
|
|
@@ -1697,10 +1718,10 @@ function WizardActionModal({ open, onOpenChange, action, model, record, endpoint
|
|
|
1697
1718
|
resolveWidget(field) === 'richtext'
|
|
1698
1719
|
return (
|
|
1699
1720
|
<FieldCell key={field.key} fullWidth={fullWidth}>
|
|
1700
|
-
<FieldLabel htmlFor={field.key} required={field.required}>
|
|
1721
|
+
<FieldLabel id={`${formUid}${field.key}-label`} htmlFor={field.key} required={field.required}>
|
|
1701
1722
|
{tl(field.label)}
|
|
1702
1723
|
</FieldLabel>
|
|
1703
|
-
{renderField(field, formData[field.key], (v: any) => updateField(field.key, v), formData, record)}
|
|
1724
|
+
{renderField(field, formData[field.key], (v: any) => updateField(field.key, v), formData, record, undefined, `${formUid}${field.key}-label`)}
|
|
1704
1725
|
</FieldCell>
|
|
1705
1726
|
)
|
|
1706
1727
|
})}
|
|
@@ -1804,6 +1825,8 @@ export function renderField(
|
|
|
1804
1825
|
formValues?: Record<string, any>,
|
|
1805
1826
|
record?: Record<string, any>,
|
|
1806
1827
|
fieldErrors?: Record<string, string>,
|
|
1828
|
+
// id único de la etiqueta visible: el control de tres estados la referencia.
|
|
1829
|
+
labelId?: string,
|
|
1807
1830
|
) {
|
|
1808
1831
|
// Repeatable line-items group → row grid (value is an array of row objects).
|
|
1809
1832
|
// The header form values flow in so a cell can depend on a header field.
|
|
@@ -1871,6 +1894,9 @@ export function renderField(
|
|
|
1871
1894
|
)
|
|
1872
1895
|
}
|
|
1873
1896
|
case 'switch':
|
|
1897
|
+
if (usesTriState(field, record ? readRecordPath(record, field.key) : undefined)) {
|
|
1898
|
+
return <TriStateBooleanField id={field.key} value={value} onChange={onChange} label={field.label} labelledBy={labelId} invalid={invalid} />
|
|
1899
|
+
}
|
|
1874
1900
|
return <Switch id={field.key} checked={!!value} onCheckedChange={onChange} />
|
|
1875
1901
|
case 'number':
|
|
1876
1902
|
return <Input id={field.key} type="number" value={value ?? ''} onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
|