@asteby/metacore-runtime-react 53.11.0 → 53.13.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.
@@ -0,0 +1,129 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { zipSync } from 'fflate'
3
+ import {
4
+ buildChildPayload, buildPreview, collectBulkFiles, collectCandidateSkus, deriveBulkImageTarget,
5
+ isIgnoredEntry, loadBatchLogs, parseImageName, pendingUndo, saveBatchLog, selectForImport,
6
+ summarizePreview, type ParentRef,
7
+ } from '../bulk-image-import'
8
+
9
+ const parent = (id: string, sku: string, max = -1, count = 0): ParentRef => ({ id, sku, label: sku, existingMaxPosition: max, existingCount: count })
10
+ const map = (...ps: ParentRef[]) => new Map(ps.map((p) => [p.sku.toLowerCase(), p]))
11
+ const inp = (path: string, w = 800, h = 800) => ({ path, size: 1000, width: w, height: h })
12
+
13
+ describe('parseImageName', () => {
14
+ it('SKU.ext y SKU_N.ext', () => {
15
+ expect(parseImageName('a/b/ABC123.jpg').candidates).toEqual([{ sku: 'ABC123', order: 1 }])
16
+ expect(parseImageName('ABC123_2.png').candidates).toEqual([{ sku: 'ABC123_2', order: 1 }, { sku: 'ABC123', order: 2 }])
17
+ })
18
+ it('ignora basura de zips', () => {
19
+ expect(isIgnoredEntry('__MACOSX/x.jpg')).toBe(true)
20
+ expect(isIgnoredEntry('.DS_Store')).toBe(true)
21
+ expect(isIgnoredEntry('fotos/')).toBe(true)
22
+ expect(isIgnoredEntry('notas.txt')).toBe(true)
23
+ expect(isIgnoredEntry('fotos/A.JPG')).toBe(false)
24
+ })
25
+ it('candidatos únicos', () => {
26
+ expect(collectCandidateSkus(['A.jpg', 'A_2.jpg', 'b.jpg']).sort()).toEqual(['A', 'A_2', 'B', 'a', 'a_2', 'b'].sort())
27
+ })
28
+ })
29
+
30
+ describe('buildPreview', () => {
31
+ const A = parent('1', 'A100', 2, 2)
32
+ const B = parent('2', 'B200')
33
+ it('asigna producto, orden y posición a continuación de las existentes', () => {
34
+ const rows = buildPreview([inp('A100_2.jpg'), inp('A100.jpg'), inp('B200.jpg')], map(A, B))
35
+ const a1 = rows.find((r) => r.path === 'A100.jpg')!
36
+ const a2 = rows.find((r) => r.path === 'A100_2.jpg')!
37
+ expect([a1.position, a2.position]).toEqual([3, 4])
38
+ expect(rows.find((r) => r.path === 'B200.jpg')!.position).toBe(0)
39
+ })
40
+ it('SKU no encontrado, baja resolución, duplicado e inválida', () => {
41
+ const rows = buildPreview(
42
+ [inp('ZZZ.jpg'), inp('B200.jpg', 100, 100), inp('x/A100.jpg'), inp('y/A100.jpg'), { path: 'C.png', size: 1, decodable: false }],
43
+ map(A, B),
44
+ )
45
+ const st = Object.fromEntries(rows.map((r) => [r.path, r.status]))
46
+ expect(st['ZZZ.jpg']).toBe('sku_not_found')
47
+ expect(st['B200.jpg']).toBe('low_res')
48
+ expect(st['x/A100.jpg']).toBe('ok')
49
+ expect(st['y/A100.jpg']).toBe('duplicate')
50
+ expect(st['C.png']).toBe('invalid_image')
51
+ const s = summarizePreview(rows)
52
+ expect(s).toMatchObject({ importable: 2, products: 2, duplicate: 1, sku_not_found: 1, low_res: 1, invalid_image: 1 })
53
+ })
54
+ it('SKU que termina en _N gana el nombre completo', () => {
55
+ const X = parent('9', 'KIT_2')
56
+ const rows = buildPreview([inp('KIT_2.jpg')], map(X, parent('8', 'KIT')))
57
+ expect(rows[0].parent?.id).toBe('9')
58
+ expect(rows[0].order).toBe(1)
59
+ })
60
+ it('SKU.jpg y SKU_2.jpg: la principal es la primera aunque la ruta ordene al revés', () => {
61
+ const rows = buildPreview([inp('B200_2.jpg'), inp('B200.jpg')], map(B))
62
+ const sel = selectForImport(rows, new Set())
63
+ const pos = Object.fromEntries(sel.map((r) => [r.path, r.position]))
64
+ expect(pos).toEqual({ 'B200.jpg': 0, 'B200_2.jpg': 1 })
65
+ expect(Object.fromEntries(rows.map((r) => [r.path, r.position]))).toEqual(pos)
66
+ })
67
+ it('SKU_0 y SKU_01 cuentan como orden 1 y chocan con SKU.jpg', () => {
68
+ const rows = buildPreview([inp('B200.jpg'), inp('B200_01.jpg')], map(B))
69
+ expect(rows.filter((r) => r.status === 'duplicate')).toHaveLength(1)
70
+ })
71
+ it('el cruce no distingue mayúsculas', () => {
72
+ const rows = buildPreview([inp('b200.jpg')], map(B))
73
+ expect(rows[0].parent?.id).toBe('2')
74
+ })
75
+ it('excluir a mano recompacta posiciones', () => {
76
+ const rows = buildPreview([inp('B200.jpg'), inp('B200_2.jpg')], map(B))
77
+ const first = rows.find((r) => r.path === 'B200.jpg')!
78
+ const sel = selectForImport(rows, new Set([first.key]))
79
+ expect(sel).toHaveLength(1)
80
+ expect(sel[0].position).toBe(0)
81
+ })
82
+ })
83
+
84
+ describe('buildChildPayload / deriveBulkImageTarget', () => {
85
+ const meta: any = {
86
+ columns: [
87
+ { key: 'product_id' },
88
+ { key: 'url', type: 'image', styleConfig: { gallery: true, storage_path: 'products' } },
89
+ { key: 'width', styleConfig: { derive: 'image_width' } },
90
+ { key: 'height', styleConfig: { derive: 'image_height' } },
91
+ { key: 'position', styleConfig: { derive: 'next_position' } },
92
+ ],
93
+ }
94
+ it('detecta la galería y arma la fila', () => {
95
+ const t = deriveBulkImageTarget({ kind: 'one_to_many', through: 'product_images', foreign_key: 'product_id' }, meta)!
96
+ expect(t).toMatchObject({ imageKey: 'url', widthKey: 'width', heightKey: 'height', positionKey: 'position', storagePath: 'products' })
97
+ const [row] = buildPreview([inp('A.jpg', 640, 480)], map(parent('1', 'A')))
98
+ expect(buildChildPayload(t, row, '/f/a.jpg')).toEqual({ url: '/f/a.jpg', product_id: '1', position: 0, width: 640, height: 480 })
99
+ })
100
+ it('sin la FK declarada en el hijo = null (el filtro in: se ignoraría)', () => {
101
+ expect(deriveBulkImageTarget({ kind: 'one_to_many', through: 'pi', foreign_key: 'nope' }, meta)).toBeNull()
102
+ })
103
+ it('sin galería = null', () => {
104
+ expect(deriveBulkImageTarget({ kind: 'one_to_many', through: 'x', foreign_key: 'p' }, { columns: [{ key: 'url' }] } as any)).toBeNull()
105
+ })
106
+ })
107
+
108
+ describe('registro de lote', () => {
109
+ it('persiste y filtra lo deshecho', () => {
110
+ const mem: Record<string, string> = {}
111
+ const st = { getItem: (k: string) => mem[k] ?? null, setItem: (k: string, v: string) => { mem[k] = v } }
112
+ const log = { batchId: 'b1', createdAt: 'x', childModel: 'pi', items: [{ rowId: '1', path: 'a', sku: 'A', parentId: '1', url: 'u' }, { rowId: '2', path: 'b', sku: 'B', parentId: '2', url: 'u', undone: true }] }
113
+ saveBatchLog(log, st)
114
+ const back = loadBatchLogs(st)
115
+ expect(back).toHaveLength(1)
116
+ expect(pendingUndo(back[0]).map((i) => i.rowId)).toEqual(['1'])
117
+ })
118
+ })
119
+
120
+ describe('collectBulkFiles', () => {
121
+ it('lee imágenes de un ZIP y descarta lo demás', async () => {
122
+ const zip = zipSync({ 'fotos/A.jpg': new Uint8Array([1, 2, 3]), 'fotos/leeme.txt': new Uint8Array([1]), '__MACOSX/fotos/._A.jpg': new Uint8Array([1]) })
123
+ const f = new File([zip as BlobPart], 'lote.zip', { type: 'application/zip' })
124
+ const { files, skipped } = await collectBulkFiles([f])
125
+ expect(files.map((x) => x.path)).toEqual(['fotos/A.jpg'])
126
+ expect(files[0].file.name).toBe('A.jpg')
127
+ expect(skipped).toBe(2)
128
+ })
129
+ })
@@ -123,3 +123,32 @@ describe('orden y modo galería', () => {
123
123
  expect(relationColumnUi(col({ key: 'x', styleConfig: { derive: 'otra' } }))).toEqual({})
124
124
  })
125
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
+ })
@@ -7,7 +7,7 @@
7
7
  // persistiendo solo las posiciones que cambiaron. Sin display_config la
8
8
  // relación sigue siendo la tabla de siempre.
9
9
  import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
10
- import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
10
+ import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
11
11
  import { DynamicRelation } from '../dynamic-relation'
12
12
  import { ApiProvider, type ApiClient } from '../api-context'
13
13
 
@@ -23,13 +23,13 @@ beforeEach(() => {
23
23
 
24
24
  const col = (c: Record<string, unknown>) => ({ label: c.key, type: 'text', sortable: false, filterable: false, ...c })
25
25
 
26
- function meta(gallery: boolean) {
26
+ function meta(gallery: boolean, mainFromParent = false) {
27
27
  return {
28
28
  name: 'product_images',
29
29
  columns: [
30
30
  col({ key: 'id', hidden: true }),
31
31
  col({ key: 'product_id', ref: 'products' }),
32
- col({ key: 'url', label: 'Imagen', cellStyle: 'image_stack', ...(gallery ? { styleConfig: { gallery: true, max_size: 1024 } } : {}) }),
32
+ col({ key: 'url', label: 'Imagen', cellStyle: 'image_stack', ...(gallery ? { styleConfig: { gallery: true, max_size: 1024, ...(mainFromParent ? { main_from_parent: 'image' } : {}) } } : {}) }),
33
33
  col({ key: 'alt', label: 'Texto alternativo', ...(gallery ? { styleConfig: { default_from_parent: 'name' } } : {}) }),
34
34
  col({ key: 'width', type: 'number', ...(gallery ? { styleConfig: { derive: 'image_width' } } : {}) }),
35
35
  col({ key: 'height', type: 'number', ...(gallery ? { styleConfig: { derive: 'image_height' } } : {}) }),
@@ -47,11 +47,11 @@ const BASE_ROWS = [
47
47
  { id: 'img_a', product_id: 'p1', url: '/storage/a.png', alt: 'Frente', position: 0 },
48
48
  ]
49
49
 
50
- function mockApi(gallery: boolean) {
50
+ function mockApi(gallery: boolean, mainFromParent = false) {
51
51
  let n = 0
52
52
  const api = {
53
53
  get: vi.fn((url: string) =>
54
- Promise.resolve({ data: url.startsWith('/metadata/table/') ? { success: true, data: meta(gallery) } : { success: true, data: ROWS } }),
54
+ Promise.resolve({ data: url.startsWith('/metadata/table/') ? { success: true, data: meta(gallery, mainFromParent) } : { success: true, data: ROWS } }),
55
55
  ),
56
56
  post: vi.fn((url: string, _body?: any, cfg?: any) => {
57
57
  if (url === '/upload') {
@@ -66,7 +66,7 @@ function mockApi(gallery: boolean) {
66
66
  return api as unknown as ApiClient & typeof api
67
67
  }
68
68
 
69
- function renderPanel(api: ApiClient, model = 'product_images') {
69
+ function renderPanel(api: ApiClient, model = 'product_images', parentRecord: Record<string, unknown> = { id: 'p1', name: 'BALATA DISCO' }) {
70
70
  return render(
71
71
  <ApiProvider client={api}>
72
72
  <DynamicRelation
@@ -74,7 +74,7 @@ function renderPanel(api: ApiClient, model = 'product_images') {
74
74
  model={model}
75
75
  foreignKey="product_id"
76
76
  parentId="p1"
77
- parentRecord={{ id: 'p1', name: 'BALATA DISCO' }}
77
+ parentRecord={parentRecord}
78
78
  />
79
79
  </ApiProvider>,
80
80
  )
@@ -94,6 +94,31 @@ describe('DynamicRelation — galería', () => {
94
94
  expect(screen.queryByRole('table')).toBeNull()
95
95
  })
96
96
 
97
+ it('galería vacía: la imagen original del producto se muestra como «Principal» de solo lectura', async () => {
98
+ ROWS = []
99
+ renderPanel(mockApi(true, true), 'product_images_lead', { id: 'p1', name: 'BALATA', image: '/storage/original.jpg' })
100
+ const lead = await screen.findByTestId('gallery-lead')
101
+ expect(lead.getAttribute('data-main')).toBe('true')
102
+ expect(lead.querySelector('img')?.getAttribute('src')).toContain('original.jpg')
103
+ expect(within(lead).getByText('Principal')).toBeTruthy()
104
+ expect(within(lead).queryByRole('button')).toBeNull()
105
+ })
106
+
107
+ it('con filas en la galería no hay tarjeta extra: la primera de la galería es la principal (como en la tienda)', async () => {
108
+ renderPanel(mockApi(true, true), 'product_images_lead2', { id: 'p1', name: 'BALATA', image: '/storage/original-que-no-esta.jpg' })
109
+ await waitFor(() => expect(screen.getAllByTestId('gallery-tile')).toHaveLength(2))
110
+ expect(screen.queryByTestId('gallery-lead')).toBeNull()
111
+ expect(screen.getAllByTestId('gallery-tile')[0].getAttribute('data-main')).toBe('true')
112
+ expect(screen.getByLabelText('Hacer principal')).toBeTruthy()
113
+ })
114
+
115
+ it('sin el hint main_from_parent no hay tarjeta de imagen original', async () => {
116
+ ROWS = []
117
+ renderPanel(mockApi(true), 'product_images_lead3', { id: 'p1', name: 'BALATA', image: '/storage/original.jpg' })
118
+ await screen.findByTestId('gallery-dropzone')
119
+ expect(screen.queryByTestId('gallery-lead')).toBeNull()
120
+ })
121
+
97
122
  it('sube varias fotos: una fila por foto con posición siguiente, tamaño y alt sugerido; rechaza la pesada', async () => {
98
123
  const api = mockApi(true)
99
124
  renderPanel(api)
@@ -112,6 +137,65 @@ describe('DynamicRelation — galería', () => {
112
137
  expect(await screen.findByText(/pesa más de/)).toBeTruthy()
113
138
  })
114
139
 
140
+ it('tras subir renumera 0..n-1 desde el servidor: filas con posición repetida quedan contiguas, la original primero', async () => {
141
+ ROWS = [
142
+ { id: 'n2', product_id: 'p1', url: '/storage/n2.png', alt: 'b', position: 1, created_at: '2026-11-01T12:00:00Z' },
143
+ { id: 'n1', product_id: 'p1', url: '/storage/n1.png', alt: 'a', position: 0, created_at: '2026-11-01T11:00:00Z' },
144
+ { id: 'orig', product_id: 'p1', url: '/storage/o.png', alt: 'o', position: 0, created_at: '2026-10-22T10:00:00Z' },
145
+ ]
146
+ const api = mockApi(true)
147
+ renderPanel(api)
148
+ await waitFor(() => expect(screen.getAllByTestId('gallery-tile')).toHaveLength(3))
149
+ fireEvent.change(screen.getByTestId('gallery-input'), { target: { files: [png('x.png')] } })
150
+ await waitFor(() => expect(api.put).toHaveBeenCalledTimes(2))
151
+ expect(api.put).toHaveBeenCalledWith('/data/product_images/n1', { position: 1 })
152
+ expect(api.put).toHaveBeenCalledWith('/data/product_images/n2', { position: 2 })
153
+ expect(api.put).not.toHaveBeenCalledWith('/data/product_images/orig', expect.anything())
154
+ })
155
+
156
+ it('un PUT fallido al renumerar no detiene a los demás', async () => {
157
+ ROWS = [
158
+ { id: 'c', product_id: 'p1', url: '/storage/c.png', position: 5 },
159
+ { id: 'b', product_id: 'p1', url: '/storage/b.png', position: 3 },
160
+ { id: 'a', product_id: 'p1', url: '/storage/a.png', position: 0 },
161
+ ]
162
+ const api = mockApi(true)
163
+ api.put = vi.fn((url: string) => (url.endsWith('/b') ? Promise.reject(new Error('boom')) : Promise.resolve({ data: { success: true } }))) as any
164
+ renderPanel(api)
165
+ await waitFor(() => expect(screen.getAllByTestId('gallery-tile')).toHaveLength(3))
166
+ fireEvent.change(screen.getByTestId('gallery-input'), { target: { files: [png('x.png')] } })
167
+ await waitFor(() => expect(api.put).toHaveBeenCalledWith('/data/product_images/c', { position: 2 }))
168
+ expect(api.put).toHaveBeenCalledWith('/data/product_images/b', { position: 1 })
169
+ })
170
+
171
+ it('dos subidas seguidas no repiten posición', async () => {
172
+ ROWS = []
173
+ const api = mockApi(true)
174
+ // El servidor guarda lo que se crea: la renumeración lee filas reales.
175
+ const post = api.post
176
+ api.post = vi.fn((url: string, body?: any, cfg?: any) => {
177
+ if (url === '/data/product_images') ROWS.push({ id: `r${ROWS.length}`, created_at: `2026-11-01T10:0${ROWS.length}:00Z`, ...body })
178
+ return post(url, body, cfg)
179
+ }) as any
180
+ renderPanel(api)
181
+ await screen.findByTestId('gallery-dropzone')
182
+ fireEvent.change(screen.getByTestId('gallery-input'), { target: { files: [png('a.png')] } })
183
+ await waitFor(() => expect(api.post.mock.calls.filter((c: any[]) => c[0] === '/data/product_images')).toHaveLength(1))
184
+ fireEvent.change(screen.getByTestId('gallery-input'), { target: { files: [png('b.png')] } })
185
+ await waitFor(() => expect(api.post.mock.calls.filter((c: any[]) => c[0] === '/data/product_images')).toHaveLength(2))
186
+ const pos = api.post.mock.calls.filter((c: any[]) => c[0] === '/data/product_images').map((c: any[]) => c[1].position)
187
+ expect(new Set(pos).size).toBe(2)
188
+ })
189
+
190
+ it('la barra de acciones de cada tarjeta envuelve en vez de recortarse', async () => {
191
+ renderPanel(mockApi(true))
192
+ await waitFor(() => expect(screen.getAllByTestId('gallery-tile')).toHaveLength(2))
193
+ const second = screen.getAllByTestId('gallery-tile')[1]
194
+ expect(second.querySelector('[data-testid="gallery-tile-actions"]')?.className).toContain('flex-wrap')
195
+ expect(second.className).toContain('min-w-0')
196
+ expect(within(second).getByLabelText('Eliminar foto')).toBeTruthy()
197
+ })
198
+
115
199
  it('hacer principal persiste solo las posiciones que cambian', async () => {
116
200
  const api = mockApi(true)
117
201
  renderPanel(api)