@asteby/metacore-runtime-react 53.10.2 → 53.12.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 (44) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/dist/bulk-image-dialog.d.ts +31 -0
  3. package/dist/bulk-image-dialog.d.ts.map +1 -0
  4. package/dist/bulk-image-dialog.js +339 -0
  5. package/dist/bulk-image-import.d.ts +158 -0
  6. package/dist/bulk-image-import.d.ts.map +1 -0
  7. package/dist/bulk-image-import.js +310 -0
  8. package/dist/dynamic-crud-page.d.ts.map +1 -1
  9. package/dist/dynamic-crud-page.js +2 -1
  10. package/dist/dynamic-form.d.ts +10 -1
  11. package/dist/dynamic-form.d.ts.map +1 -1
  12. package/dist/dynamic-form.js +6 -6
  13. package/dist/dynamic-relation-helpers.d.ts +65 -0
  14. package/dist/dynamic-relation-helpers.d.ts.map +1 -1
  15. package/dist/dynamic-relation-helpers.js +178 -2
  16. package/dist/dynamic-relation.d.ts +16 -0
  17. package/dist/dynamic-relation.d.ts.map +1 -1
  18. package/dist/dynamic-relation.js +277 -13
  19. package/dist/dynamic-relations.d.ts.map +1 -1
  20. package/dist/dynamic-relations.js +1 -1
  21. package/dist/index.d.ts +2 -0
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +2 -0
  24. package/dist/relation-gallery.d.ts +31 -0
  25. package/dist/relation-gallery.d.ts.map +1 -0
  26. package/dist/relation-gallery.js +154 -0
  27. package/dist/upload-field.d.ts +19 -1
  28. package/dist/upload-field.d.ts.map +1 -1
  29. package/dist/upload-field.js +50 -3
  30. package/package.json +2 -1
  31. package/src/__tests__/bulk-image-dialog.test.tsx +127 -0
  32. package/src/__tests__/bulk-image-import.test.ts +129 -0
  33. package/src/__tests__/relation-gallery-helpers.test.ts +154 -0
  34. package/src/__tests__/relation-gallery.test.tsx +229 -0
  35. package/src/bulk-image-dialog.tsx +594 -0
  36. package/src/bulk-image-import.ts +456 -0
  37. package/src/dynamic-crud-page.tsx +2 -0
  38. package/src/dynamic-form.tsx +20 -2
  39. package/src/dynamic-relation-helpers.ts +210 -2
  40. package/src/dynamic-relation.tsx +329 -15
  41. package/src/dynamic-relations.tsx +1 -0
  42. package/src/index.ts +12 -0
  43. package/src/relation-gallery.tsx +489 -0
  44. package/src/upload-field.tsx +60 -2
@@ -0,0 +1,154 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import {
3
+ deriveRelationFormFields,
4
+ isManagedRelationColumn,
5
+ nextRelationPosition,
6
+ relationColumnUi,
7
+ relationDerivedValues,
8
+ relationGalleryColumn,
9
+ relationInitialValues,
10
+ relationMediaKind,
11
+ relationPositionKey,
12
+ relationPositionSortable,
13
+ sortRelationRows,
14
+ } from '../dynamic-relation-helpers'
15
+ import { resolveWidget } from '../dynamic-form-schema'
16
+ import type { ColumnDefinition, TableMetadata } from '../types'
17
+
18
+ const col = (c: Partial<ColumnDefinition> & { key: string }): ColumnDefinition =>
19
+ ({ label: c.key, type: 'text', sortable: false, filterable: false, ...c }) as ColumnDefinition
20
+
21
+ // What /metadata/table serves for ProductImage (products 0.23.2) — the manifest
22
+ // `widget: image` does not travel to the table endpoint, `display: image_stack`
23
+ // does (as cellStyle), plus the creator avatar column every table gets.
24
+ const productImagesToday: Pick<TableMetadata, 'columns'> = {
25
+ columns: [
26
+ col({ key: 'product_id', ref: 'products' }),
27
+ col({ key: 'variant_id', ref: 'product_variants' }),
28
+ col({ key: 'url', cellStyle: 'image_stack' }),
29
+ col({ key: 'alt' }),
30
+ col({ key: 'width', type: 'number' }),
31
+ col({ key: 'height', type: 'number' }),
32
+ col({ key: 'position', type: 'number' }),
33
+ col({ key: 'created_by.avatar', type: 'avatar', cellStyle: 'creator' }),
34
+ ],
35
+ }
36
+
37
+ const productImagesDeclared: Pick<TableMetadata, 'columns'> = {
38
+ columns: [
39
+ col({ key: 'product_id', ref: 'products' }),
40
+ col({ key: 'variant_id', ref: 'product_variants', styleConfig: { empty_label: 'Para todas las variantes' } }),
41
+ col({ key: 'url', cellStyle: 'image_stack', styleConfig: { gallery: true, max_size: 5242880 } }),
42
+ col({ key: 'alt', styleConfig: { default_from_parent: 'name' } }),
43
+ col({ key: 'width', type: 'number', styleConfig: { derive: 'image_width' } }),
44
+ col({ key: 'height', type: 'number', styleConfig: { derive: 'image_height' } }),
45
+ col({ key: 'position', type: 'number', styleConfig: { derive: 'next_position' } }),
46
+ col({ key: 'created_by.avatar', type: 'avatar', cellStyle: 'creator' }),
47
+ ],
48
+ }
49
+
50
+ describe('deriveRelationFormFields: galería de producto', () => {
51
+ // Protek 01/11: «Imagen» salía como input de texto y «Creado por» editable.
52
+ it('la columna de imagen es el widget de subida y la auditoría no aparece', () => {
53
+ const fields = deriveRelationFormFields(productImagesToday, 'product_id')
54
+ const byKey = Object.fromEntries(fields.map((f) => [f.key, f]))
55
+ expect(byKey.url?.type).toBe('image')
56
+ expect(byKey.url?.accept).toBe('image/*')
57
+ expect(resolveWidget(byKey.url!)).toBe('upload')
58
+ expect(byKey['created_by.avatar']).toBeUndefined()
59
+ expect(byKey.variant_id && resolveWidget(byKey.variant_id)).toBe('dynamic_select')
60
+ })
61
+
62
+ it('sin display_config los campos numéricos siguen visibles (retrocompat)', () => {
63
+ const keys = deriveRelationFormFields(productImagesToday, 'product_id').map((f) => f.key)
64
+ expect(keys).toEqual(['variant_id', 'url', 'alt', 'width', 'height', 'position'])
65
+ })
66
+
67
+ it('derived/hidden fuera del formulario; empty_label como placeholder', () => {
68
+ const fields = deriveRelationFormFields(productImagesDeclared, 'product_id')
69
+ expect(fields.map((f) => f.key)).toEqual(['variant_id', 'url', 'alt'])
70
+ expect(fields[0].placeholder).toBe('Para todas las variantes')
71
+ })
72
+
73
+ it('una FK con display image_stack (logo de marca) sigue siendo picker, no subida', () => {
74
+ expect(relationMediaKind(col({ key: 'brand_id', ref: 'brands', cellStyle: 'image_stack' }))).toBeUndefined()
75
+ expect(relationMediaKind(col({ key: 'doc', widget: 'file' } as any))).toBe('file')
76
+ expect(relationMediaKind(col({ key: 'photo', type: 'image' }))).toBe('image')
77
+ expect(relationMediaKind(col({ key: 'sku' }))).toBeUndefined()
78
+ })
79
+
80
+ it('auditoría y proyecciones con punto nunca son editables', () => {
81
+ for (const k of ['created_by', 'created_by.avatar', 'updated_by_id', 'deleted_by', 'organization_id', 'product.name']) {
82
+ expect(isManagedRelationColumn(k)).toBe(true)
83
+ }
84
+ expect(isManagedRelationColumn('alt')).toBe(false)
85
+ })
86
+ })
87
+
88
+ describe('valores derivados de la fila', () => {
89
+ const rows = [{ position: 0 }, { position: 3 }, { position: null }]
90
+
91
+ it('posición siguiente solo al crear; tamaño solo si se midió', () => {
92
+ expect(relationDerivedValues(productImagesDeclared, { isCreate: true, rows, image: { width: 1200.4, height: 800 } }))
93
+ .toEqual({ width: 1200, height: 800, position: 4 })
94
+ expect(relationDerivedValues(productImagesDeclared, { isCreate: false, rows, image: null })).toEqual({})
95
+ expect(relationDerivedValues(productImagesToday, { isCreate: true, rows, image: { width: 1, height: 1 } })).toEqual({})
96
+ })
97
+
98
+ it('nextRelationPosition: 0 sin filas', () => {
99
+ expect(nextRelationPosition([])).toBe(0)
100
+ expect(nextRelationPosition([{ position: '2' }, { position: 'x' }])).toBe(3)
101
+ })
102
+
103
+ it('texto alternativo sugerido con el nombre del padre', () => {
104
+ expect(relationInitialValues(productImagesDeclared, { name: 'BALATA DISCO' })).toEqual({ alt: 'BALATA DISCO' })
105
+ expect(relationInitialValues(productImagesDeclared, null)).toEqual({})
106
+ expect(relationInitialValues(productImagesToday, { name: 'X' })).toEqual({})
107
+ })
108
+ })
109
+
110
+ describe('orden y modo galería', () => {
111
+ it('ordena por position, estable, sin posición al final', () => {
112
+ const rows = [{ id: 'a', position: 2 }, { id: 'b' }, { id: 'c', position: 0 }, { id: 'd', position: 2 }]
113
+ expect(sortRelationRows(rows, 'position').map((r) => r.id)).toEqual(['c', 'a', 'd', 'b'])
114
+ expect(sortRelationRows(rows, undefined)).toBe(rows)
115
+ expect(relationPositionKey(productImagesToday)).toBe('position')
116
+ expect(relationPositionSortable(productImagesToday)).toBe(false)
117
+ expect(relationPositionSortable({ columns: [col({ key: 'position', sortable: true })] })).toBe(true)
118
+ })
119
+
120
+ it('la galería es opt-in por display_config.gallery', () => {
121
+ expect(relationGalleryColumn(productImagesToday)).toBeUndefined()
122
+ expect(relationGalleryColumn(productImagesDeclared)?.key).toBe('url')
123
+ expect(relationColumnUi(col({ key: 'x', styleConfig: { derive: 'otra' } }))).toEqual({})
124
+ })
125
+ })
126
+
127
+ import { contiguousPositionUpdates } from '../dynamic-relation-helpers'
128
+
129
+ describe('contiguousPositionUpdates', () => {
130
+ it('caso U390556L: 0, 0, 1 pasa a 0, 1, 2 con la original (más vieja) primero', () => {
131
+ const rows = [
132
+ { id: 'n2', position: 1, created_at: '2026-11-01T12:00:00Z' },
133
+ { id: 'n1', position: 0, created_at: '2026-11-01T11:00:00Z' },
134
+ { id: 'orig', position: 0, created_at: '2026-10-22T10:00:00Z' },
135
+ ]
136
+ const { ordered, updates } = contiguousPositionUpdates(rows)
137
+ expect(ordered.map((r) => r.id)).toEqual(['orig', 'n1', 'n2'])
138
+ expect(updates).toEqual([{ id: 'n1', position: 1 }, { id: 'n2', position: 2 }])
139
+ })
140
+ it('cierra huecos y manda las sin posición al final', () => {
141
+ const { ordered, updates } = contiguousPositionUpdates([
142
+ { id: 'a', position: 3 }, { id: 'b', position: null }, { id: 'c', position: 7 },
143
+ ])
144
+ expect(ordered.map((r) => r.id)).toEqual(['a', 'c', 'b'])
145
+ expect(updates).toEqual([{ id: 'a', position: 0 }, { id: 'c', position: 1 }, { id: 'b', position: 2 }])
146
+ })
147
+ it('empate sin created_at se decide por id (estable entre pestañas)', () => {
148
+ const { ordered } = contiguousPositionUpdates([{ id: 'z', position: 0 }, { id: 'a', position: 0 }])
149
+ expect(ordered.map((r) => r.id)).toEqual(['a', 'z'])
150
+ })
151
+ it('ya contiguo = sin cambios', () => {
152
+ expect(contiguousPositionUpdates([{ id: 'a', position: 0 }, { id: 'b', position: 1 }]).updates).toEqual([])
153
+ })
154
+ })
@@ -0,0 +1,229 @@
1
+ // @vitest-environment happy-dom
2
+ //
3
+ // Galería de producto (display_config.gallery en la columna de imagen): la
4
+ // relación se ve como cuadrícula ordenada por position con la principal
5
+ // marcada, sube varias fotos de una vez (una fila por foto, posiciones en
6
+ // orden, tamaño medido, alt sugerido con el nombre del padre) y reordena
7
+ // persistiendo solo las posiciones que cambiaron. Sin display_config la
8
+ // relación sigue siendo la tabla de siempre.
9
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
10
+ import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
11
+ import { DynamicRelation } from '../dynamic-relation'
12
+ import { ApiProvider, type ApiClient } from '../api-context'
13
+
14
+ vi.mock('../upload-field', async (orig) => {
15
+ const real: any = await orig()
16
+ return { ...real, readImageSize: vi.fn(async () => ({ width: 1200, height: 900 })) }
17
+ })
18
+
19
+ afterEach(cleanup)
20
+ beforeEach(() => {
21
+ ROWS = BASE_ROWS.map((r) => ({ ...r }))
22
+ })
23
+
24
+ const col = (c: Record<string, unknown>) => ({ label: c.key, type: 'text', sortable: false, filterable: false, ...c })
25
+
26
+ function meta(gallery: boolean) {
27
+ return {
28
+ name: 'product_images',
29
+ columns: [
30
+ col({ key: 'id', hidden: true }),
31
+ col({ key: 'product_id', ref: 'products' }),
32
+ col({ key: 'url', label: 'Imagen', cellStyle: 'image_stack', ...(gallery ? { styleConfig: { gallery: true, max_size: 1024 } } : {}) }),
33
+ col({ key: 'alt', label: 'Texto alternativo', ...(gallery ? { styleConfig: { default_from_parent: 'name' } } : {}) }),
34
+ col({ key: 'width', type: 'number', ...(gallery ? { styleConfig: { derive: 'image_width' } } : {}) }),
35
+ col({ key: 'height', type: 'number', ...(gallery ? { styleConfig: { derive: 'image_height' } } : {}) }),
36
+ col({ key: 'position', type: 'number', sortable: true, ...(gallery ? { styleConfig: { derive: 'next_position' } } : {}) }),
37
+ ],
38
+ actions: [],
39
+ hasActions: false,
40
+ enableCRUDActions: false,
41
+ }
42
+ }
43
+
44
+ let ROWS: Record<string, unknown>[] = []
45
+ const BASE_ROWS = [
46
+ { id: 'img_b', product_id: 'p1', url: '/storage/b.png', alt: 'Trasera', position: 1 },
47
+ { id: 'img_a', product_id: 'p1', url: '/storage/a.png', alt: 'Frente', position: 0 },
48
+ ]
49
+
50
+ function mockApi(gallery: boolean) {
51
+ let n = 0
52
+ const api = {
53
+ get: vi.fn((url: string) =>
54
+ Promise.resolve({ data: url.startsWith('/metadata/table/') ? { success: true, data: meta(gallery) } : { success: true, data: ROWS } }),
55
+ ),
56
+ post: vi.fn((url: string, _body?: any, cfg?: any) => {
57
+ if (url === '/upload') {
58
+ cfg?.onUploadProgress?.({ loaded: 5, total: 10 })
59
+ return Promise.resolve({ data: { success: true, data: { url: `/storage/new-${++n}.webp` } } })
60
+ }
61
+ return Promise.resolve({ data: { success: true, data: {} } })
62
+ }),
63
+ put: vi.fn(() => Promise.resolve({ data: { success: true, data: {} } })),
64
+ delete: vi.fn(() => Promise.resolve({ data: { success: true, data: {} } })),
65
+ }
66
+ return api as unknown as ApiClient & typeof api
67
+ }
68
+
69
+ function renderPanel(api: ApiClient, model = 'product_images') {
70
+ return render(
71
+ <ApiProvider client={api}>
72
+ <DynamicRelation
73
+ kind="one_to_many"
74
+ model={model}
75
+ foreignKey="product_id"
76
+ parentId="p1"
77
+ parentRecord={{ id: 'p1', name: 'BALATA DISCO' }}
78
+ />
79
+ </ApiProvider>,
80
+ )
81
+ }
82
+
83
+ const png = (name: string, size = 10) => new File([new Uint8Array(size)], name, { type: 'image/png' })
84
+
85
+ describe('DynamicRelation — galería', () => {
86
+ it('cuadrícula ordenada por position, la primera es la principal', async () => {
87
+ renderPanel(mockApi(true))
88
+ await waitFor(() => expect(screen.getAllByTestId('gallery-tile')).toHaveLength(2))
89
+ const tiles = screen.getAllByTestId('gallery-tile')
90
+ expect(tiles[0].querySelector('img')?.getAttribute('alt')).toBe('Frente')
91
+ expect(tiles[0].getAttribute('data-main')).toBe('true')
92
+ expect(tiles[1].getAttribute('data-main')).toBeNull()
93
+ expect(screen.getByText('Principal')).toBeTruthy()
94
+ expect(screen.queryByRole('table')).toBeNull()
95
+ })
96
+
97
+ it('sube varias fotos: una fila por foto con posición siguiente, tamaño y alt sugerido; rechaza la pesada', async () => {
98
+ const api = mockApi(true)
99
+ renderPanel(api)
100
+ await waitFor(() => expect(screen.getAllByTestId('gallery-tile')).toHaveLength(2))
101
+ const input = screen.getByTestId('gallery-input') as HTMLInputElement
102
+ fireEvent.change(input, { target: { files: [png('uno.png'), png('dos.png'), png('pesada.png', 4096)] } })
103
+
104
+ await waitFor(() => {
105
+ const creates = api.post.mock.calls.filter((c: any[]) => c[0] === '/data/product_images')
106
+ expect(creates).toHaveLength(2)
107
+ })
108
+ const creates = api.post.mock.calls.filter((c: any[]) => c[0] === '/data/product_images').map((c: any[]) => c[1])
109
+ expect(creates[0]).toMatchObject({ product_id: 'p1', url: '/storage/new-1.webp', alt: 'BALATA DISCO', width: 1200, height: 900, position: 2 })
110
+ expect(creates[1]).toMatchObject({ url: '/storage/new-2.webp', position: 3 })
111
+ expect(api.post.mock.calls.filter((c: any[]) => c[0] === '/upload')).toHaveLength(2)
112
+ expect(await screen.findByText(/pesa más de/)).toBeTruthy()
113
+ })
114
+
115
+ it('tras subir renumera 0..n-1 desde el servidor: filas con posición repetida quedan contiguas, la original primero', async () => {
116
+ ROWS = [
117
+ { id: 'n2', product_id: 'p1', url: '/storage/n2.png', alt: 'b', position: 1, created_at: '2026-11-01T12:00:00Z' },
118
+ { id: 'n1', product_id: 'p1', url: '/storage/n1.png', alt: 'a', position: 0, created_at: '2026-11-01T11:00:00Z' },
119
+ { id: 'orig', product_id: 'p1', url: '/storage/o.png', alt: 'o', position: 0, created_at: '2026-10-22T10:00:00Z' },
120
+ ]
121
+ const api = mockApi(true)
122
+ renderPanel(api)
123
+ await waitFor(() => expect(screen.getAllByTestId('gallery-tile')).toHaveLength(3))
124
+ fireEvent.change(screen.getByTestId('gallery-input'), { target: { files: [png('x.png')] } })
125
+ await waitFor(() => expect(api.put).toHaveBeenCalledTimes(2))
126
+ expect(api.put).toHaveBeenCalledWith('/data/product_images/n1', { position: 1 })
127
+ expect(api.put).toHaveBeenCalledWith('/data/product_images/n2', { position: 2 })
128
+ expect(api.put).not.toHaveBeenCalledWith('/data/product_images/orig', expect.anything())
129
+ })
130
+
131
+ it('un PUT fallido al renumerar no detiene a los demás', async () => {
132
+ ROWS = [
133
+ { id: 'c', product_id: 'p1', url: '/storage/c.png', position: 5 },
134
+ { id: 'b', product_id: 'p1', url: '/storage/b.png', position: 3 },
135
+ { id: 'a', product_id: 'p1', url: '/storage/a.png', position: 0 },
136
+ ]
137
+ const api = mockApi(true)
138
+ api.put = vi.fn((url: string) => (url.endsWith('/b') ? Promise.reject(new Error('boom')) : Promise.resolve({ data: { success: true } }))) as any
139
+ renderPanel(api)
140
+ await waitFor(() => expect(screen.getAllByTestId('gallery-tile')).toHaveLength(3))
141
+ fireEvent.change(screen.getByTestId('gallery-input'), { target: { files: [png('x.png')] } })
142
+ await waitFor(() => expect(api.put).toHaveBeenCalledWith('/data/product_images/c', { position: 2 }))
143
+ expect(api.put).toHaveBeenCalledWith('/data/product_images/b', { position: 1 })
144
+ })
145
+
146
+ it('dos subidas seguidas no repiten posición', async () => {
147
+ ROWS = []
148
+ const api = mockApi(true)
149
+ // El servidor guarda lo que se crea: la renumeración lee filas reales.
150
+ const post = api.post
151
+ api.post = vi.fn((url: string, body?: any, cfg?: any) => {
152
+ if (url === '/data/product_images') ROWS.push({ id: `r${ROWS.length}`, created_at: `2026-11-01T10:0${ROWS.length}:00Z`, ...body })
153
+ return post(url, body, cfg)
154
+ }) as any
155
+ renderPanel(api)
156
+ await screen.findByTestId('gallery-dropzone')
157
+ fireEvent.change(screen.getByTestId('gallery-input'), { target: { files: [png('a.png')] } })
158
+ await waitFor(() => expect(api.post.mock.calls.filter((c: any[]) => c[0] === '/data/product_images')).toHaveLength(1))
159
+ fireEvent.change(screen.getByTestId('gallery-input'), { target: { files: [png('b.png')] } })
160
+ await waitFor(() => expect(api.post.mock.calls.filter((c: any[]) => c[0] === '/data/product_images')).toHaveLength(2))
161
+ const pos = api.post.mock.calls.filter((c: any[]) => c[0] === '/data/product_images').map((c: any[]) => c[1].position)
162
+ expect(new Set(pos).size).toBe(2)
163
+ })
164
+
165
+ it('la barra de acciones de cada tarjeta envuelve en vez de recortarse', async () => {
166
+ renderPanel(mockApi(true))
167
+ await waitFor(() => expect(screen.getAllByTestId('gallery-tile')).toHaveLength(2))
168
+ const second = screen.getAllByTestId('gallery-tile')[1]
169
+ expect(second.querySelector('[data-testid="gallery-tile-actions"]')?.className).toContain('flex-wrap')
170
+ expect(second.className).toContain('min-w-0')
171
+ expect(within(second).getByLabelText('Eliminar foto')).toBeTruthy()
172
+ })
173
+
174
+ it('hacer principal persiste solo las posiciones que cambian', async () => {
175
+ const api = mockApi(true)
176
+ renderPanel(api)
177
+ await waitFor(() => expect(screen.getAllByTestId('gallery-tile')).toHaveLength(2))
178
+ fireEvent.click(screen.getByLabelText('Hacer principal'))
179
+ await waitFor(() => expect(api.put).toHaveBeenCalledTimes(2))
180
+ expect(api.put).toHaveBeenCalledWith('/data/product_images/img_b', { position: 0 })
181
+ expect(api.put).toHaveBeenCalledWith('/data/product_images/img_a', { position: 1 })
182
+ })
183
+
184
+ it('una foto sin posición que pasa a principal sí se guarda (null no es 0)', async () => {
185
+ ROWS = [
186
+ { id: 'img_a', product_id: 'p1', url: '/storage/a.png', alt: 'Frente', position: 0 },
187
+ { id: 'img_n', product_id: 'p1', url: '/storage/n.png', alt: 'Vieja', position: null },
188
+ ]
189
+ const api = mockApi(true)
190
+ renderPanel(api)
191
+ await waitFor(() => expect(screen.getAllByTestId('gallery-tile')).toHaveLength(2))
192
+ fireEvent.click(screen.getByLabelText('Hacer principal'))
193
+ await waitFor(() => expect(api.put).toHaveBeenCalledTimes(2))
194
+ expect(api.put).toHaveBeenCalledWith('/data/product_images/img_n', { position: 0 })
195
+ expect(api.put).toHaveBeenCalledWith('/data/product_images/img_a', { position: 1 })
196
+ })
197
+
198
+ it('en frío, tras conocer la metadata, vuelve a pedir ordenado y completo', async () => {
199
+ const api = mockApi(true)
200
+ renderPanel(api, 'product_images_cold')
201
+ await waitFor(() => {
202
+ const lists = api.get.mock.calls.filter((c: any[]) => c[0] === '/data/product_images_cold')
203
+ expect(lists.length).toBe(2)
204
+ expect(lists[1][1].params).toMatchObject({ sortBy: 'position', per_page: 200 })
205
+ })
206
+ })
207
+
208
+ it('lista ordenada por position en el servidor una vez conocida la metadata', async () => {
209
+ const api = mockApi(true)
210
+ renderPanel(api)
211
+ await waitFor(() => expect(screen.getAllByTestId('gallery-tile')).toHaveLength(2))
212
+ fireEvent.click(screen.getByLabelText('Hacer principal'))
213
+ await waitFor(() => {
214
+ const lists = api.get.mock.calls.filter((c: any[]) => c[0] === '/data/product_images')
215
+ expect(lists.length).toBeGreaterThan(1)
216
+ expect(lists[lists.length - 1][1].params).toMatchObject({ sortBy: 'position', order: 'asc', per_page: 200 })
217
+ })
218
+ })
219
+
220
+ it('sin display_config sigue siendo tabla, «Imagen» es subida y sin «Creado por»', async () => {
221
+ renderPanel(mockApi(false), 'product_images_plain')
222
+ await waitFor(() => expect(screen.getByRole('table')).toBeTruthy())
223
+ expect(screen.queryByTestId('gallery-grid')).toBeNull()
224
+ fireEvent.click(screen.getByText('Agregar'))
225
+ await waitFor(() => expect(screen.getByRole('dialog')).toBeTruthy())
226
+ expect(document.querySelector('[data-widget="upload"]')).toBeTruthy()
227
+ expect(screen.queryByText('Creado por')).toBeNull()
228
+ })
229
+ })