@asteby/metacore-runtime-react 53.13.0 → 53.14.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 (69) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/action-modal-dispatcher.d.ts +1 -1
  3. package/dist/action-modal-dispatcher.d.ts.map +1 -1
  4. package/dist/action-modal-dispatcher.js +31 -6
  5. package/dist/bulk-image-dialog.d.ts +0 -13
  6. package/dist/bulk-image-dialog.d.ts.map +1 -1
  7. package/dist/bulk-image-dialog.js +9 -280
  8. package/dist/bulk-image-import.d.ts +2 -24
  9. package/dist/bulk-image-import.d.ts.map +1 -1
  10. package/dist/bulk-image-import.js +11 -30
  11. package/dist/bulk-image-target.d.ts +25 -0
  12. package/dist/bulk-image-target.d.ts.map +1 -0
  13. package/dist/bulk-image-target.js +30 -0
  14. package/dist/bulk-image-wizard.d.ts +15 -0
  15. package/dist/bulk-image-wizard.d.ts.map +1 -0
  16. package/dist/bulk-image-wizard.js +282 -0
  17. package/dist/dialogs/dynamic-record.d.ts +8 -1
  18. package/dist/dialogs/dynamic-record.d.ts.map +1 -1
  19. package/dist/dialogs/dynamic-record.js +34 -4
  20. package/dist/dynamic-columns.d.ts.map +1 -1
  21. package/dist/dynamic-columns.js +4 -0
  22. package/dist/dynamic-form-schema.d.ts.map +1 -1
  23. package/dist/dynamic-form-schema.js +5 -1
  24. package/dist/dynamic-form.d.ts.map +1 -1
  25. package/dist/dynamic-form.js +28 -3
  26. package/dist/dynamic-kanban.d.ts.map +1 -1
  27. package/dist/dynamic-kanban.js +33 -1
  28. package/dist/dynamic-line-items.d.ts.map +1 -1
  29. package/dist/dynamic-line-items.js +9 -1
  30. package/dist/dynamic-table.d.ts.map +1 -1
  31. package/dist/dynamic-table.js +7 -0
  32. package/dist/field-grid.d.ts +3 -1
  33. package/dist/field-grid.d.ts.map +1 -1
  34. package/dist/field-grid.js +2 -2
  35. package/dist/index.d.ts +3 -2
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +1 -2
  38. package/dist/nullable-boolean.d.ts +48 -0
  39. package/dist/nullable-boolean.d.ts.map +1 -0
  40. package/dist/nullable-boolean.js +80 -0
  41. package/dist/tri-state-boolean-impl.d.ts +24 -0
  42. package/dist/tri-state-boolean-impl.d.ts.map +1 -0
  43. package/dist/tri-state-boolean-impl.js +35 -0
  44. package/dist/tri-state-boolean.d.ts +15 -0
  45. package/dist/tri-state-boolean.d.ts.map +1 -0
  46. package/dist/tri-state-boolean.js +24 -0
  47. package/dist/use-dynamic-filters.d.ts.map +1 -1
  48. package/dist/use-dynamic-filters.js +10 -0
  49. package/package.json +3 -3
  50. package/src/__tests__/bulk-image-dialog.test.tsx +3 -3
  51. package/src/__tests__/nullable-boolean.test.tsx +458 -0
  52. package/src/action-modal-dispatcher.tsx +32 -6
  53. package/src/bulk-image-dialog.tsx +21 -496
  54. package/src/bulk-image-import.ts +2 -51
  55. package/src/bulk-image-target.ts +55 -0
  56. package/src/bulk-image-wizard.tsx +494 -0
  57. package/src/dialogs/dynamic-record.tsx +53 -5
  58. package/src/dynamic-columns.tsx +3 -0
  59. package/src/dynamic-form-schema.ts +4 -1
  60. package/src/dynamic-form.tsx +31 -2
  61. package/src/dynamic-kanban.tsx +6 -1
  62. package/src/dynamic-line-items.tsx +9 -1
  63. package/src/dynamic-table.tsx +5 -0
  64. package/src/field-grid.tsx +4 -0
  65. package/src/index.ts +2 -8
  66. package/src/nullable-boolean.ts +96 -0
  67. package/src/tri-state-boolean-impl.tsx +71 -0
  68. package/src/tri-state-boolean.tsx +39 -0
  69. package/src/use-dynamic-filters.ts +8 -0
@@ -0,0 +1,35 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ // Control de tres estados para booleanos opcionales (ver nullable-boolean.ts).
3
+ // Se carga diferido desde tri-state-boolean.tsx para no pesar en el shell.
4
+ import { useTranslation } from 'react-i18next';
5
+ import { SegmentedControl } from '@asteby/metacore-ui/primitives';
6
+ /** Valor de formulario → estado del control. `''`/null/undefined son «Sin definir». */
7
+ export function toTriState(value) {
8
+ if (value === true || value === 'true')
9
+ return 'true';
10
+ if (value === false || value === 'false')
11
+ return 'false';
12
+ return 'null';
13
+ }
14
+ /** Estado del control → valor que viaja al servidor. */
15
+ export function fromTriState(state) {
16
+ if (state === 'true')
17
+ return true;
18
+ if (state === 'false')
19
+ return false;
20
+ return null;
21
+ }
22
+ /**
23
+ * Control de tres estados para un booleano opcional. Es un `radiogroup`
24
+ * (SegmentedControl de metacore-ui): flechas para moverse, el estado elegido
25
+ * se marca con relleno y `aria-checked`. «Sin definir» envía `null`.
26
+ */
27
+ export function TriStateBooleanField({ id, value, onChange, disabled, label, labelledBy, size = 'sm', invalid, }) {
28
+ const { t } = useTranslation();
29
+ const items = [
30
+ { value: 'true', label: t('common.yes', { defaultValue: 'Sí' }), disabled },
31
+ { value: 'false', label: t('common.no', { defaultValue: 'No' }), disabled },
32
+ { value: 'null', label: t('common.unset', { defaultValue: 'Sin definir' }), disabled },
33
+ ];
34
+ return (_jsx(SegmentedControl, { id: id, items: items, value: toTriState(value), onValueChange: (s) => onChange(fromTriState(s)), "aria-label": label ? t(label, { defaultValue: label }) : t('common.unset', { defaultValue: 'Sin definir' }), "aria-labelledby": labelledBy, "aria-invalid": invalid || undefined, "aria-disabled": disabled || undefined, "data-tri-state": "", size: size, className: "w-fit" }));
35
+ }
@@ -0,0 +1,15 @@
1
+ import type { TriStateBooleanFieldProps } from './tri-state-boolean-impl';
2
+ export type { TriStateBooleanFieldProps } from './tri-state-boolean-impl';
3
+ /**
4
+ * Control Sí / No / Sin definir para un booleano opcional. «Sin definir»
5
+ * envía `null`. Accesible (radiogroup con flechas) y con i18n es/en.
6
+ */
7
+ export declare function TriStateBooleanField(props: TriStateBooleanFieldProps): import("react").JSX.Element;
8
+ /**
9
+ * Celda/vista de solo lectura para un booleano NULL: «—» (misma convención que
10
+ * `formatDisplayValue`), con «Sin definir» como nombre accesible y tooltip.
11
+ */
12
+ export declare function NullBooleanMark({ className }: {
13
+ className?: string;
14
+ }): import("react").JSX.Element;
15
+ //# sourceMappingURL=tri-state-boolean.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tri-state-boolean.d.ts","sourceRoot":"","sources":["../src/tri-state-boolean.tsx"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,0BAA0B,CAAA;AAEzE,YAAY,EAAE,yBAAyB,EAAE,MAAM,0BAA0B,CAAA;AAMzE;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,yBAAyB,+BAMpE;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,EAAE,SAAS,EAAE,EAAE;IAAE,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,+BAQpE"}
@@ -0,0 +1,24 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ // Booleanos opcionales: control de tres estados (diferido) y marca de NULL.
3
+ // El control vive en tri-state-boolean-impl.tsx y se carga con React.lazy: sólo
4
+ // lo baja quien abre un formulario con un booleano opcional, así no suma al
5
+ // shell inicial de la app.
6
+ import { Suspense, lazy } from 'react';
7
+ import { useTranslation } from 'react-i18next';
8
+ const Impl = lazy(() => import('./tri-state-boolean-impl').then((m) => ({ default: m.TriStateBooleanField })));
9
+ /**
10
+ * Control Sí / No / Sin definir para un booleano opcional. «Sin definir»
11
+ * envía `null`. Accesible (radiogroup con flechas) y con i18n es/en.
12
+ */
13
+ export function TriStateBooleanField(props) {
14
+ return (_jsx(Suspense, { fallback: _jsx("span", { className: "inline-block h-8", "aria-busy": "true" }), children: _jsx(Impl, { ...props }) }));
15
+ }
16
+ /**
17
+ * Celda/vista de solo lectura para un booleano NULL: «—» (misma convención que
18
+ * `formatDisplayValue`), con «Sin definir» como nombre accesible y tooltip.
19
+ */
20
+ export function NullBooleanMark({ className }) {
21
+ const { t } = useTranslation();
22
+ const label = t('common.unset', { defaultValue: 'Sin definir' });
23
+ return (_jsx("span", { className: className ?? 'text-muted-foreground', title: label, "aria-label": label, "data-bool-null": "", children: "\u2014" }));
24
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"use-dynamic-filters.d.ts","sourceRoot":"","sources":["../src/use-dynamic-filters.ts"],"names":[],"mappings":"AAkBA,OAAO,KAAK,EAAE,kBAAkB,EAAgB,MAAM,wBAAwB,CAAA;AAC9E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAE5C,MAAM,WAAW,wBAAwB;IACvC;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IACpC;;;;OAIG;IACH,KAAK,CAAC,EAAE,MAAM,CAAA;IACd;;;;;;OAMG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,CAAA;CACxB;AAED,MAAM,WAAW,uBAAuB;IACtC,4EAA4E;IAC5E,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAA;IACxC,sDAAsD;IACtD,YAAY,EAAE,MAAM,CAAA;IACpB,eAAe,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,IAAI,CAAA;IACpC,iFAAiF;IACjF,mBAAmB,EAAE,GAAG,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAA;IACpD;;;;OAIG;IACH,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IACjC,uDAAuD;IACvD,yBAAyB,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,IAAI,CAAA;IACxE,kEAAkE;IAClE,iBAAiB,EAAE,MAAM,CAAA;IACzB,oDAAoD;IACpD,QAAQ,EAAE,MAAM,IAAI,CAAA;CACrB;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAC/B,QAAQ,EAAE,aAAa,GAAG,IAAI,EAC9B,IAAI,GAAE,wBAA6B,GAClC,uBAAuB,CA0TzB"}
1
+ {"version":3,"file":"use-dynamic-filters.d.ts","sourceRoot":"","sources":["../src/use-dynamic-filters.ts"],"names":[],"mappings":"AAoBA,OAAO,KAAK,EAAE,kBAAkB,EAAgB,MAAM,wBAAwB,CAAA;AAC9E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAE5C,MAAM,WAAW,wBAAwB;IACvC;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IACpC;;;;OAIG;IACH,KAAK,CAAC,EAAE,MAAM,CAAA;IACd;;;;;;OAMG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,CAAA;CACxB;AAED,MAAM,WAAW,uBAAuB;IACtC,4EAA4E;IAC5E,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAA;IACxC,sDAAsD;IACtD,YAAY,EAAE,MAAM,CAAA;IACpB,eAAe,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,IAAI,CAAA;IACpC,iFAAiF;IACjF,mBAAmB,EAAE,GAAG,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAA;IACpD;;;;OAIG;IACH,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IACjC,uDAAuD;IACvD,yBAAyB,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,IAAI,CAAA;IACxE,kEAAkE;IAClE,iBAAiB,EAAE,MAAM,CAAA;IACzB,oDAAoD;IACpD,QAAQ,EAAE,MAAM,IAAI,CAAA;CACrB;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAC/B,QAAQ,EAAE,aAAa,GAAG,IAAI,EAC9B,IAAI,GAAE,wBAA6B,GAClC,uBAAuB,CAgUzB"}
@@ -11,7 +11,9 @@
11
11
  // filtering (RFC: a board is just another view of the model), so the logic is
12
12
  // factored here to guarantee both surfaces filter identically.
13
13
  import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
14
+ import { useTranslation } from 'react-i18next';
14
15
  import { useApi } from './api-context';
16
+ import { withBooleanUnsetOption } from './nullable-boolean';
15
17
  import { DATE_CELL_TYPES } from './dynamic-columns';
16
18
  import { getSearchableColumnKeys } from './column-visibility';
17
19
  import { useDebouncedValue } from './use-debounced-value';
@@ -25,6 +27,9 @@ import { useFacetLoaders, isLongTextColumn } from './use-facet-loaders';
25
27
  export function useDynamicFilters(metadata, opts = {}) {
26
28
  const { defaultFilters, model, endpoint, facetsEndpoint } = opts;
27
29
  const api = useApi();
30
+ const { t } = useTranslation();
31
+ // «Sin definir» del filtro booleano (NULL), ver withBooleanUnsetOption.
32
+ const unsetLabel = t('common.unset', { defaultValue: 'Sin definir' });
28
33
  const [dynamicFilters, setDynamicFilters] = useState({});
29
34
  const [globalFilter, setGlobalFilter] = useState('');
30
35
  const debouncedGlobalFilter = useDebouncedValue(globalFilter);
@@ -161,6 +166,8 @@ export function useDynamicFilters(metadata, opts = {}) {
161
166
  }
162
167
  if (fType === 'select' && options.length === 0 && !f.searchEndpoint)
163
168
  continue;
169
+ if (fType === 'boolean')
170
+ options = withBooleanUnsetOption(options, unsetLabel);
164
171
  map.set(f.key, {
165
172
  filterType: fType,
166
173
  filterKey: f.column || f.key,
@@ -214,6 +221,8 @@ export function useDynamicFilters(metadata, opts = {}) {
214
221
  : [];
215
222
  if (isStageColumn)
216
223
  options = stageOptions;
224
+ if (filterType === 'boolean')
225
+ options = withBooleanUnsetOption(options, unsetLabel);
217
226
  // (B) Upgrade a plain text filter to a facet value-picker (unless it's a
218
227
  // long-text/body column — too many unique values to enumerate).
219
228
  let loadOptions;
@@ -246,6 +255,7 @@ export function useDynamicFilters(metadata, opts = {}) {
246
255
  facetsBase,
247
256
  getFacetLoader,
248
257
  facetOptions,
258
+ unsetLabel,
249
259
  ]);
250
260
  // Prewarm every facet field in one burst once the configs settle, so the
251
261
  // Sheet popover and the lane value-picker open instantly (values + counts)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asteby/metacore-runtime-react",
3
- "version": "53.13.0",
3
+ "version": "53.14.0",
4
4
  "description": "React runtime for metacore hosts — renders addon contributions dynamically",
5
5
  "repository": {
6
6
  "type": "git",
@@ -43,7 +43,7 @@
43
43
  },
44
44
  "peerDependencies": {
45
45
  "@asteby/metacore-sdk": "^3.18.1",
46
- "@asteby/metacore-ui": "^2.32.0",
46
+ "@asteby/metacore-ui": "^2.32.1",
47
47
  "@tanstack/react-query": ">=5",
48
48
  "@tanstack/react-router": ">=1.100",
49
49
  "@tanstack/react-table": ">=8",
@@ -75,7 +75,7 @@
75
75
  },
76
76
  "devDependencies": {
77
77
  "@asteby/metacore-sdk": "3.18.1",
78
- "@asteby/metacore-ui": "2.32.0",
78
+ "@asteby/metacore-ui": "2.32.1",
79
79
  "@tanstack/react-query": "^5.95.0",
80
80
  "@tanstack/react-router": "^1.168.0",
81
81
  "@tanstack/react-table": "^8.20.0",
@@ -69,7 +69,7 @@ function setup(api: ApiClient) {
69
69
  return render(<ApiProvider client={api}><BulkImageImportButton model="products" /></ApiProvider>)
70
70
  }
71
71
 
72
- describe('BulkImageImportButton', () => {
72
+ describe('BulkImageImportButton', { timeout: 30000 }, () => {
73
73
  it('no aparece sin galería', async () => {
74
74
  const api = mockApi(false)
75
75
  setup(api)
@@ -81,7 +81,7 @@ describe('BulkImageImportButton', () => {
81
81
  const api = mockApi()
82
82
  setup(api)
83
83
  fireEvent.click(await screen.findByTestId('bulk-image-open'))
84
- const input = await screen.findByTestId('bulk-image-input')
84
+ const input = await screen.findByTestId('bulk-image-input', {}, { timeout: 15000 })
85
85
  fireEvent.change(input, { target: { files: [img('A100.jpg'), img('A100_2.jpg'), img('B200.jpg'), img('NOPE.jpg'), img('LOWB200_9.jpg')] } })
86
86
 
87
87
  await waitFor(() => expect(screen.getByTestId('bulk-image-summary')).toBeTruthy())
@@ -117,7 +117,7 @@ describe('BulkImageImportButton', () => {
117
117
  }) as any
118
118
  setup(api)
119
119
  fireEvent.click(await screen.findByTestId('bulk-image-open'))
120
- fireEvent.change(await screen.findByTestId('bulk-image-input'), { target: { files: [img('A100.jpg'), img('B200.jpg')] } })
120
+ fireEvent.change(await screen.findByTestId('bulk-image-input', {}, { timeout: 15000 }), { target: { files: [img('A100.jpg'), img('B200.jpg')] } })
121
121
  await waitFor(() => screen.getByTestId('bulk-image-import'))
122
122
  fireEvent.click(screen.getByTestId('bulk-image-import'))
123
123
  await waitFor(() => expect(screen.getByTestId('bulk-image-progress').textContent).toContain('1 con error'))
@@ -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
+ })