@asteby/metacore-runtime-react 53.12.0 → 53.13.1

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.
@@ -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'))
@@ -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)
@@ -1,58 +1,23 @@
1
1
  // BulkImageImportButton — carga masiva de imágenes a nivel catálogo.
2
2
  //
3
- // Botón + asistente (elegir ZIP/carpeta → vista previa → importar con
4
- // progreso → deshacer lote) para cualquier modelo con una galería declarada
3
+ // Botón que abre el asistente (elegir ZIP/carpeta → vista previa → importar con
4
+ // progreso → deshacer lote, en bulk-image-wizard.tsx, cargado bajo demanda) para cualquier modelo con una galería declarada
5
5
  // (relación 1:N cuya columna de imagen trae `display_config.gallery: true`).
6
6
  // No renderiza nada si el modelo no tiene galería. Usa solo contratos que ya
7
7
  // existen: GET /metadata/table, GET /data/<modelo> (filtro `f_<col>=in:`),
8
8
  // POST /upload, POST y DELETE /data/<hijo>.
9
- import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
9
+ import { lazy, Suspense, useEffect, useState } from 'react'
10
10
  import { useTranslation } from 'react-i18next'
11
- import {
12
- Button,
13
- Dialog,
14
- DialogContent,
15
- DialogDescription,
16
- DialogFooter,
17
- DialogHeader,
18
- DialogTitle,
19
- Table,
20
- TableBody,
21
- TableCell,
22
- TableHead,
23
- TableHeader,
24
- TableRow,
25
- } from '@asteby/metacore-ui/primitives'
26
- import { AlertCircle, Check, FolderUp, ImagePlus, Loader2, Undo2, Download } from 'lucide-react'
11
+ import { ImagePlus } from 'lucide-react'
27
12
  import { useApi } from './api-context'
28
13
  import { useMetadataCache } from './metadata-cache'
29
- import { cacheScope } from './cache-scope'
30
14
  import { modelCapability, useCan } from './permissions-context'
31
- import { Progress } from './dialogs/_primitives'
32
- import { extractUploadedValue, readImageSize } from './upload-field'
33
15
  import type { TableMetadata } from './types'
34
- import {
35
- buildChildPayload,
36
- buildPreview,
37
- chunk,
38
- collectBulkFiles,
39
- collectCandidateSkus,
40
- deriveBulkImageTarget,
41
- isImportable,
42
- loadBatchLogs,
43
- MAX_BULK_FILES,
44
- newBatchId,
45
- normalizeSku,
46
- pendingUndo,
47
- saveBatchLog,
48
- selectForImport,
49
- summarizePreview,
50
- type BatchLog,
51
- type BulkFile,
52
- type BulkImageTarget,
53
- type ParentRef,
54
- type PreviewRow,
55
- } from './bulk-image-import'
16
+ import { deriveBulkImageTarget, type BulkImageTarget } from './bulk-image-target'
17
+
18
+ // El asistente (tabla de vista previa, progreso, deshacer) pesa bastante y solo se usa al
19
+ // pulsar el botón: se carga bajo demanda, fuera del JS inicial del shell.
20
+ const BulkImageDialog = lazy(() => import('./bulk-image-wizard').then((m) => ({ default: m.BulkImageDialog })))
56
21
 
57
22
  export interface BulkImageImportButtonProps {
58
23
  /** Modelo padre (catálogo), p. ej. `products`. */
@@ -70,43 +35,6 @@ export interface BulkImageImportButtonProps {
70
35
  onChange?: () => void
71
36
  }
72
37
 
73
- type Step = 'pick' | 'analyzing' | 'preview' | 'importing' | 'done'
74
- type ItemState = { status: 'pending' | 'uploading' | 'done' | 'error'; progress: number; error?: string }
75
-
76
- const LOOKUP_CHUNK = 40
77
- const CONCURRENCY = 3
78
- const PAGE_SIZE = 200
79
-
80
- /**
81
- * Alcance del registro de lotes: organización + usuario (sin el idioma de
82
- * cacheScope, para que cambiar de idioma no esconda lotes). null = desconocido:
83
- * no se ofrecen lotes anteriores.
84
- */
85
- function batchScope(): string | null {
86
- const s = cacheScope()
87
- return s ? s.split(':').slice(0, 2).join(':') : null
88
- }
89
-
90
- /** map con concurrencia acotada (decodificar cientos de bitmaps a la vez tumba la pestaña). */
91
- async function mapPool<T, R>(items: T[], limit: number, fn: (x: T) => Promise<R>): Promise<R[]> {
92
- const out = new Array<R>(items.length)
93
- let i = 0
94
- await Promise.all(
95
- Array.from({ length: Math.min(limit, items.length) }, async () => {
96
- while (i < items.length) {
97
- const idx = i++
98
- out[idx] = await fn(items[idx])
99
- }
100
- }),
101
- )
102
- return out
103
- }
104
-
105
- function asRows(res: any): any[] {
106
- const d = res?.data?.data ?? res?.data
107
- return Array.isArray(d) ? d : Array.isArray(d?.data) ? d.data : []
108
- }
109
-
110
38
  export function BulkImageImportButton({
111
39
  model,
112
40
  metadata,
@@ -173,422 +101,19 @@ export function BulkImageImportButton({
173
101
  {t('bulk_images.open', { defaultValue: 'Cargar imágenes' })}
174
102
  </button>
175
103
  {open && (
176
- <BulkImageDialog
177
- open={open}
178
- onOpenChange={setOpen}
179
- model={model}
180
- target={target}
181
- skuKey={skuKey}
182
- dataBase={dataBase}
183
- minLongSide={minLongSide}
184
- onChange={onChange}
185
- />
104
+ <Suspense fallback={null}>
105
+ <BulkImageDialog
106
+ open={open}
107
+ onOpenChange={setOpen}
108
+ model={model}
109
+ target={target}
110
+ skuKey={skuKey}
111
+ dataBase={dataBase}
112
+ minLongSide={minLongSide}
113
+ onChange={onChange}
114
+ />
115
+ </Suspense>
186
116
  )}
187
117
  </>
188
118
  )
189
119
  }
190
-
191
- interface DialogProps {
192
- open: boolean
193
- onOpenChange: (o: boolean) => void
194
- model: string
195
- target: BulkImageTarget
196
- skuKey: string
197
- dataBase: string
198
- minLongSide?: number
199
- onChange?: () => void
200
- }
201
-
202
- export function BulkImageDialog({ open, onOpenChange, model, target, skuKey, dataBase, minLongSide, onChange }: DialogProps) {
203
- const { t } = useTranslation()
204
- const api = useApi()
205
- const [step, setStep] = useState<Step>('pick')
206
- const [error, setError] = useState<string | null>(null)
207
- const [note, setNote] = useState<string | null>(null)
208
- const [rows, setRows] = useState<PreviewRow[]>([])
209
- const [excluded, setExcluded] = useState<Set<string>>(new Set())
210
- const [items, setItems] = useState<Record<string, ItemState>>({})
211
- const [log, setLog] = useState<BatchLog | null>(null)
212
- const [undoing, setUndoing] = useState<{ done: number; total: number } | null>(null)
213
- const [previousLogs, setPreviousLogs] = useState<BatchLog[]>(() => { const sc = batchScope(); return sc === null ? [] : loadBatchLogs(undefined, sc).filter((l) => l.childModel === target.childModel && pendingUndo(l).length > 0) })
214
- const filesRef = useRef<Map<string, File>>(new Map())
215
- const urlsRef = useRef<Map<string, string>>(new Map())
216
- const cancelRef = useRef(false)
217
- const zipInput = useRef<HTMLInputElement>(null)
218
- const dirInput = useRef<HTMLInputElement>(null)
219
-
220
- const releaseUrls = () => {
221
- urlsRef.current.forEach((u) => URL.revokeObjectURL?.(u))
222
- urlsRef.current.clear()
223
- }
224
- useEffect(() => () => releaseUrls(), [])
225
-
226
- const childEndpoint = `${dataBase}/${target.childModel}`
227
- const parentEndpoint = `${dataBase}/${model}`
228
-
229
- const analyze = useCallback(
230
- async (picked: File[]) => {
231
- if (picked.length === 0) return
232
- setError(null)
233
- setNote(null)
234
- setStep('analyzing')
235
- try {
236
- const { files, skipped } = await collectBulkFiles(picked)
237
- if (files.length === 0) throw new Error(t('bulk_images.no_images', { defaultValue: 'No se encontraron imágenes (jpg, png, webp, gif, avif).' }))
238
- if (files.length > MAX_BULK_FILES) {
239
- throw new Error(t('bulk_images.too_many', { defaultValue: 'Máximo {{n}} imágenes por lote; divide la carga.', n: MAX_BULK_FILES }))
240
- }
241
- if (skipped > 0) setNote(t('bulk_images.skipped', { defaultValue: '{{n}} archivos ignorados (no son imágenes o son demasiado grandes).', n: skipped }))
242
-
243
- // Medir en el navegador (el servidor no mide nada).
244
- releaseUrls()
245
- filesRef.current = new Map()
246
- const inputs = await mapPool(
247
- files,
248
- 4,
249
- async (f: BulkFile) => {
250
- const size = await readImageSize(f.file)
251
- filesRef.current.set(f.path, f.file)
252
- urlsRef.current.set(f.path, URL.createObjectURL(f.file))
253
- const ok = !!(size.width && size.height)
254
- return { path: f.path, size: f.file.size, width: size.width, height: size.height, decodable: ok }
255
- },
256
- )
257
-
258
- // Resolver SKU contra la API de datos existente (por lotes).
259
- const skus = collectCandidateSkus(inputs.map((i) => i.path)).filter((s) => !s.includes(','))
260
- const parents = new Map<string, ParentRef>()
261
- for (const part of chunk(skus, LOOKUP_CHUNK)) {
262
- const res = await api.get(parentEndpoint, {
263
- params: { [`f_${skuKey}`]: `in:${part.join(',')}`, per_page: Math.min(200, part.length + 20) },
264
- })
265
- for (const r of asRows(res)) {
266
- const sku = String(r[skuKey] ?? '')
267
- if (!sku || r.id === undefined || r.id === null) continue
268
- parents.set(normalizeSku(sku), {
269
- id: String(r.id),
270
- sku,
271
- label: String(r.name ?? r.title ?? r.label ?? sku),
272
- existingMaxPosition: -1,
273
- existingCount: 0,
274
- })
275
- }
276
- }
277
-
278
- // Fotos que ya tiene cada producto: las nuevas van a continuación.
279
- if (target.positionKey) {
280
- const byId = new Map([...parents.values()].map((p) => [p.id, p]))
281
- // El kernel limita per_page a 200: se pagina hasta agotar.
282
- for (const part of chunk([...byId.keys()], LOOKUP_CHUNK)) {
283
- for (let page = 1; page <= 50; page++) {
284
- const res = await api.get(childEndpoint, {
285
- params: { [`f_${target.foreignKey}`]: `in:${part.join(',')}`, per_page: PAGE_SIZE, page },
286
- })
287
- const got = asRows(res)
288
- for (const r of got) {
289
- const p = byId.get(String(r[target.foreignKey]))
290
- if (!p) continue
291
- p.existingCount += 1
292
- const n = Number(r[target.positionKey])
293
- if (Number.isFinite(n) && n > p.existingMaxPosition) p.existingMaxPosition = n
294
- }
295
- if (got.length < PAGE_SIZE) break
296
- }
297
- }
298
- // Fotos existentes sin posición: las nuevas van detrás, nunca delante.
299
- for (const p of byId.values()) {
300
- if (p.existingCount > 0 && p.existingMaxPosition < p.existingCount - 1) p.existingMaxPosition = p.existingCount - 1
301
- }
302
- }
303
-
304
- setRows(buildPreview(inputs, parents, { minLongSide, maxSize: target.maxSize }))
305
- setExcluded(new Set())
306
- setStep('preview')
307
- } catch (e: any) {
308
- setError(e?.message || t('bulk_images.analyze_failed', { defaultValue: 'No se pudo analizar la selección.' }))
309
- setStep('pick')
310
- }
311
- },
312
- // eslint-disable-next-line react-hooks/exhaustive-deps
313
- [api, childEndpoint, minLongSide, parentEndpoint, skuKey, target],
314
- )
315
-
316
- const summary = useMemo(() => summarizePreview(rows, excluded), [rows, excluded])
317
-
318
- const runImport = useCallback(async () => {
319
- const queue = selectForImport(rows, excluded)
320
- if (queue.length === 0) return
321
- cancelRef.current = false
322
- setStep('importing')
323
- setError(null)
324
- const batch: BatchLog = { batchId: newBatchId(), createdAt: new Date().toISOString(), childModel: target.childModel, scope: batchScope() ?? undefined, items: [] }
325
- setLog(batch)
326
- setItems(Object.fromEntries(queue.map((r) => [r.key, { status: 'pending', progress: 0 } as ItemState])))
327
- const patch = (key: string, s: Partial<ItemState>) =>
328
- setItems((m) => ({ ...m, [key]: { ...m[key], ...s } as ItemState }))
329
-
330
- let next = 0
331
- const worker = async () => {
332
- while (!cancelRef.current) {
333
- const row = queue[next++]
334
- if (!row) return
335
- patch(row.key, { status: 'uploading', progress: 0 })
336
- let url = ''
337
- try {
338
- const file = filesRef.current.get(row.path)
339
- if (!file) throw new Error('archivo no disponible')
340
- const form = new FormData()
341
- form.append('file', file)
342
- if (target.storagePath) {
343
- form.append('folder', target.storagePath)
344
- form.append('storage_path', target.storagePath)
345
- }
346
- const up = await api.post('/upload', form, {
347
- headers: { 'Content-Type': 'multipart/form-data' },
348
- onUploadProgress: (e: { loaded: number; total?: number }) => {
349
- if (e.total) patch(row.key, { progress: (e.loaded / e.total) * 0.9 })
350
- },
351
- } as any)
352
- const body = (up as { data?: any })?.data
353
- if (body && body.success === false) throw new Error(body.message || 'upload failed')
354
- url = extractUploadedValue(body)
355
- if (!url) throw new Error('upload failed')
356
- const res = (await api.post(childEndpoint, buildChildPayload(target, row, url))) as any
357
- if (!res?.data?.success) throw new Error(res?.data?.message || 'create failed')
358
- const created = res.data.data ?? res.data
359
- const rowId = created?.id
360
- // Sin id no hay deshacer fiable: se avisa en vez de callar.
361
- if (rowId === undefined || rowId === null) throw new Error('el servidor no devolvió el id de la fila creada')
362
- batch.items.push({ rowId: String(rowId), path: row.path, sku: row.sku ?? '', parentId: row.parent!.id, url })
363
- saveBatchLog(batch)
364
- patch(row.key, { status: 'done', progress: 1 })
365
- } catch (e: any) {
366
- patch(row.key, { status: 'error', progress: 0, error: e?.response?.data?.message || e?.message || 'error' })
367
- }
368
- }
369
- }
370
- await Promise.all(Array.from({ length: Math.min(CONCURRENCY, queue.length) }, worker))
371
- setLog({ ...batch, items: [...batch.items] })
372
- setStep('done')
373
- if (batch.items.length) onChange?.()
374
- }, [api, childEndpoint, excluded, onChange, rows, target])
375
-
376
- const undo = useCallback(
377
- async (l: BatchLog) => {
378
- const todo = pendingUndo(l)
379
- setUndoing({ done: 0, total: todo.length })
380
- setError(null)
381
- const failures: string[] = []
382
- for (const it of todo) {
383
- try {
384
- const res = (await api.delete(`${childEndpoint}/${it.rowId}`)) as any
385
- if (res?.data?.success === false) throw new Error(res.data.message || 'delete failed')
386
- it.undone = true
387
- } catch (e: any) {
388
- // 404 = ya no existe: el objetivo (que no esté) está cumplido.
389
- if (e?.response?.status === 404) it.undone = true
390
- else failures.push(`${it.sku || it.path}`)
391
- }
392
- setUndoing((u) => (u ? { ...u, done: u.done + 1 } : u))
393
- }
394
- saveBatchLog(l)
395
- setUndoing(null)
396
- setLog((cur) => (cur && cur.batchId === l.batchId ? { ...l, items: [...l.items] } : cur))
397
- setPreviousLogs((ls) => ls.map((x) => (x.batchId === l.batchId ? { ...l, items: [...l.items] } : x)).filter((x) => pendingUndo(x).length > 0))
398
- if (failures.length) {
399
- setError(t('bulk_images.undo_partial', { defaultValue: 'No se pudieron deshacer: {{list}}. Reintenta.', list: failures.slice(0, 10).join(', ') }))
400
- }
401
- onChange?.()
402
- },
403
- [api, childEndpoint, onChange, t],
404
- )
405
-
406
- const downloadLog = (l: BatchLog) => {
407
- const blob = new Blob([JSON.stringify(l, null, 2)], { type: 'application/json' })
408
- const a = document.createElement('a')
409
- a.href = URL.createObjectURL(blob)
410
- a.download = `${l.batchId}.json`
411
- a.click()
412
- setTimeout(() => URL.revokeObjectURL(a.href), 1000)
413
- }
414
-
415
- const statusLabel = (r: PreviewRow) => {
416
- switch (r.status) {
417
- case 'ok': return t('bulk_images.s_ok', { defaultValue: 'Listo' })
418
- case 'low_res': return t('bulk_images.s_low', { defaultValue: 'Baja resolución' })
419
- case 'sku_not_found': return t('bulk_images.s_nosku', { defaultValue: 'SKU no encontrado' })
420
- case 'duplicate': return t('bulk_images.s_dup', { defaultValue: 'Duplicado' })
421
- case 'invalid_image': return t('bulk_images.s_invalid', { defaultValue: 'No es imagen' })
422
- case 'too_large': return t('bulk_images.s_large', { defaultValue: 'Muy pesada' })
423
- }
424
- }
425
-
426
- const doneCount = Object.values(items).filter((i) => i.status === 'done').length
427
- const errCount = Object.values(items).filter((i) => i.status === 'error').length
428
- const total = Object.keys(items).length
429
- const busy = step === 'importing' || step === 'analyzing' || !!undoing
430
-
431
- return (
432
- <Dialog open={open} onOpenChange={(o) => { if (!o && busy) return; if (!o) releaseUrls(); onOpenChange(o) }}>
433
- <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto" data-testid="bulk-image-dialog">
434
- <DialogHeader>
435
- <DialogTitle>{t('bulk_images.title', { defaultValue: 'Carga masiva de imágenes' })}</DialogTitle>
436
- <DialogDescription>
437
- {t('bulk_images.help', {
438
- defaultValue: 'Sube un ZIP o una carpeta con archivos nombrados SKU.jpg, SKU_2.jpg… Cada archivo se agrega a la galería del producto con ese SKU.',
439
- })}
440
- </DialogDescription>
441
- </DialogHeader>
442
-
443
- {error && <div role="alert" className="text-sm text-destructive flex gap-2 items-start"><AlertCircle className="size-4 mt-0.5" />{error}</div>}
444
- {note && <div className="text-xs text-muted-foreground">{note}</div>}
445
-
446
- {step === 'pick' && (
447
- <div className="space-y-4">
448
- <div
449
- className="border-2 border-dashed rounded-lg p-8 text-center text-sm text-muted-foreground"
450
- onDragOver={(e) => e.preventDefault()}
451
- onDrop={(e) => { e.preventDefault(); void analyze(Array.from(e.dataTransfer?.files ?? [])) }}
452
- >
453
- <p className="mb-3">{t('bulk_images.drop', { defaultValue: 'Arrastra aquí el ZIP o las imágenes' })}</p>
454
- <div className="flex gap-2 justify-center">
455
- <Button variant="outline" onClick={() => zipInput.current?.click()}>
456
- <ImagePlus className="size-4 mr-1" />{t('bulk_images.pick_zip', { defaultValue: 'Elegir ZIP o imágenes' })}
457
- </Button>
458
- <Button variant="outline" onClick={() => dirInput.current?.click()}>
459
- <FolderUp className="size-4 mr-1" />{t('bulk_images.pick_folder', { defaultValue: 'Elegir carpeta' })}
460
- </Button>
461
- </div>
462
- <input
463
- ref={zipInput} type="file" multiple className="hidden" data-testid="bulk-image-input"
464
- accept=".zip,application/zip,image/*"
465
- onChange={(e) => { void analyze(Array.from(e.target.files ?? [])); e.target.value = '' }}
466
- />
467
- <input
468
- ref={dirInput} type="file" multiple className="hidden" data-testid="bulk-image-dir"
469
- {...({ webkitdirectory: '' } as Record<string, string>)}
470
- onChange={(e) => { void analyze(Array.from(e.target.files ?? [])); e.target.value = '' }}
471
- />
472
- </div>
473
- {previousLogs.length > 0 && (
474
- <div className="text-sm space-y-2">
475
- <div className="font-medium">{t('bulk_images.previous', { defaultValue: 'Lotes anteriores' })}</div>
476
- {previousLogs.map((l) => (
477
- <div key={l.batchId} className="flex items-center justify-between gap-2 border rounded-md px-3 py-2">
478
- <span>{new Date(l.createdAt).toLocaleString()} · {pendingUndo(l).length} {t('bulk_images.images', { defaultValue: 'imágenes' })}</span>
479
- <span className="flex gap-2">
480
- <Button size="sm" variant="ghost" onClick={() => downloadLog(l)}><Download className="size-4" /></Button>
481
- <Button size="sm" variant="outline" disabled={!!undoing} onClick={() => void undo(l)}>
482
- <Undo2 className="size-4 mr-1" />{t('bulk_images.undo', { defaultValue: 'Deshacer lote' })}
483
- </Button>
484
- </span>
485
- </div>
486
- ))}
487
- {undoing && <Progress value={(undoing.done / Math.max(1, undoing.total)) * 100} />}
488
- </div>
489
- )}
490
- </div>
491
- )}
492
-
493
- {step === 'analyzing' && (
494
- <div className="flex items-center gap-2 text-sm py-8 justify-center"><Loader2 className="size-4 animate-spin" />{t('bulk_images.analyzing', { defaultValue: 'Analizando imágenes y buscando SKU…' })}</div>
495
- )}
496
-
497
- {(step === 'preview' || step === 'importing' || step === 'done') && (
498
- <div className="space-y-3">
499
- <div className="flex flex-wrap gap-3 text-sm" data-testid="bulk-image-summary">
500
- <span>{t('bulk_images.sum_import', { defaultValue: '{{n}} fotos para {{p}} productos', n: summary.importable, p: summary.products })}</span>
501
- {summary.sku_not_found > 0 && <span className="text-destructive">{summary.sku_not_found} {t('bulk_images.s_nosku', { defaultValue: 'SKU no encontrado' })}</span>}
502
- {summary.duplicate > 0 && <span className="text-destructive">{summary.duplicate} {t('bulk_images.s_dup', { defaultValue: 'Duplicado' })}</span>}
503
- {summary.low_res > 0 && <span className="text-amber-600">{summary.low_res} {t('bulk_images.s_low', { defaultValue: 'Baja resolución' })}</span>}
504
- {(summary.invalid_image + summary.too_large) > 0 && <span className="text-destructive">{summary.invalid_image + summary.too_large} {t('bulk_images.s_invalid', { defaultValue: 'No es imagen' })}</span>}
505
- </div>
506
- {step !== 'preview' && (
507
- <div className="space-y-1">
508
- <Progress value={(doneCount + errCount) / Math.max(1, total) * 100} />
509
- <div className="text-xs text-muted-foreground" data-testid="bulk-image-progress">
510
- {t('bulk_images.progress', { defaultValue: '{{done}} de {{total}} subidas · {{err}} con error', done: doneCount, total, err: errCount })}
511
- </div>
512
- </div>
513
- )}
514
- <div className="border rounded-md max-h-[45vh] overflow-auto">
515
- <Table>
516
- <TableHeader>
517
- <TableRow>
518
- {step === 'preview' && <TableHead className="w-8" />}
519
- <TableHead className="w-14" />
520
- <TableHead>{t('bulk_images.col_file', { defaultValue: 'Archivo' })}</TableHead>
521
- <TableHead>{t('bulk_images.col_product', { defaultValue: 'Producto' })}</TableHead>
522
- <TableHead>{t('bulk_images.col_pos', { defaultValue: 'Pos.' })}</TableHead>
523
- <TableHead>{t('bulk_images.col_status', { defaultValue: 'Estado' })}</TableHead>
524
- </TableRow>
525
- </TableHeader>
526
- <TableBody>
527
- {rows.map((r) => {
528
- const it = items[r.key]
529
- const skip = excluded.has(r.key)
530
- return (
531
- <TableRow key={r.key} data-status={r.status} className={skip ? 'opacity-50' : undefined}>
532
- {step === 'preview' && (
533
- <TableCell>
534
- {isImportable(r) && (
535
- <input
536
- type="checkbox" checked={!skip} aria-label={r.path}
537
- onChange={() => setExcluded((s) => { const n = new Set(s); if (n.has(r.key)) n.delete(r.key); else n.add(r.key); return n })}
538
- />
539
- )}
540
- </TableCell>
541
- )}
542
- <TableCell>
543
- {urlsRef.current.get(r.path) && <img src={urlsRef.current.get(r.path)} alt="" className="size-10 object-contain rounded bg-muted" loading="lazy" />}
544
- </TableCell>
545
- <TableCell className="text-xs break-all">{r.path}<div className="text-muted-foreground">{r.width && r.height ? `${r.width}×${r.height}` : ''}</div></TableCell>
546
- <TableCell className="text-xs">{r.parent ? <>{r.parent.label}<div className="text-muted-foreground">{r.sku}{r.parent.existingCount ? ` · ${r.parent.existingCount} ${t('bulk_images.already', { defaultValue: 'ya tiene' })}` : ''}</div></> : '—'}</TableCell>
547
- <TableCell className="text-xs">{isImportable(r) && !skip && typeof r.position === 'number' ? (r.position === 0 ? `1 · ${t('bulk_images.main', { defaultValue: 'Principal' })}` : r.position + 1) : '—'}</TableCell>
548
- <TableCell className="text-xs">
549
- {it ? (
550
- it.status === 'done' ? <span className="text-emerald-600 inline-flex items-center gap-1"><Check className="size-3" />{t('bulk_images.uploaded', { defaultValue: 'Subida' })}</span>
551
- : it.status === 'error' ? <span className="text-destructive" title={it.error}>{it.error}</span>
552
- : <div className="w-24"><Progress value={it.progress * 100} /></div>
553
- ) : (
554
- <span className={r.status === 'ok' ? '' : r.status === 'low_res' ? 'text-amber-600' : 'text-destructive'} title={r.note}>{statusLabel(r)}</span>
555
- )}
556
- </TableCell>
557
- </TableRow>
558
- )
559
- })}
560
- </TableBody>
561
- </Table>
562
- </div>
563
- </div>
564
- )}
565
-
566
- <DialogFooter className="gap-2">
567
- {step === 'preview' && (
568
- <>
569
- <Button variant="outline" onClick={() => { releaseUrls(); setRows([]); setStep('pick') }}>{t('bulk_images.back', { defaultValue: 'Elegir otros' })}</Button>
570
- <Button disabled={summary.importable === 0} onClick={() => void runImport()} data-testid="bulk-image-import">
571
- {t('bulk_images.import', { defaultValue: 'Importar {{n}} fotos', n: summary.importable })}
572
- </Button>
573
- </>
574
- )}
575
- {step === 'importing' && (
576
- <Button variant="outline" onClick={() => { cancelRef.current = true }}>{t('bulk_images.cancel', { defaultValue: 'Detener' })}</Button>
577
- )}
578
- {step === 'done' && log && (
579
- <>
580
- <Button variant="ghost" onClick={() => downloadLog(log)}><Download className="size-4 mr-1" />{t('bulk_images.download_log', { defaultValue: 'Descargar registro' })}</Button>
581
- {pendingUndo(log).length > 0 && (
582
- <Button variant="outline" disabled={!!undoing} onClick={() => void undo(log)} data-testid="bulk-image-undo">
583
- <Undo2 className="size-4 mr-1" />
584
- {undoing ? `${undoing.done}/${undoing.total}` : t('bulk_images.undo', { defaultValue: 'Deshacer lote' })}
585
- </Button>
586
- )}
587
- <Button onClick={() => { releaseUrls(); onOpenChange(false) }}>{t('bulk_images.close', { defaultValue: 'Cerrar' })}</Button>
588
- </>
589
- )}
590
- </DialogFooter>
591
- </DialogContent>
592
- </Dialog>
593
- )
594
- }