@asteby/metacore-runtime-react 53.11.0 → 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.
@@ -0,0 +1,594 @@
1
+ // BulkImageImportButton — carga masiva de imágenes a nivel catálogo.
2
+ //
3
+ // Botón + asistente (elegir ZIP/carpeta → vista previa → importar con
4
+ // progreso → deshacer lote) para cualquier modelo con una galería declarada
5
+ // (relación 1:N cuya columna de imagen trae `display_config.gallery: true`).
6
+ // No renderiza nada si el modelo no tiene galería. Usa solo contratos que ya
7
+ // existen: GET /metadata/table, GET /data/<modelo> (filtro `f_<col>=in:`),
8
+ // POST /upload, POST y DELETE /data/<hijo>.
9
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
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'
27
+ import { useApi } from './api-context'
28
+ import { useMetadataCache } from './metadata-cache'
29
+ import { cacheScope } from './cache-scope'
30
+ import { modelCapability, useCan } from './permissions-context'
31
+ import { Progress } from './dialogs/_primitives'
32
+ import { extractUploadedValue, readImageSize } from './upload-field'
33
+ 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'
56
+
57
+ export interface BulkImageImportButtonProps {
58
+ /** Modelo padre (catálogo), p. ej. `products`. */
59
+ model: string
60
+ /** Metadata del padre; si se omite se lee de la caché / `/metadata/table`. */
61
+ metadata?: TableMetadata | null
62
+ /** Columna del padre que identifica la foto en el nombre de archivo. Default `sku`. */
63
+ skuKey?: string
64
+ /** Prefijo del endpoint de datos. Default `/data`. */
65
+ dataBase?: string
66
+ /** Lado largo mínimo antes de avisar «baja resolución». Default 600. */
67
+ minLongSide?: number
68
+ className?: string
69
+ /** Tras importar o deshacer (refrescar la lista). */
70
+ onChange?: () => void
71
+ }
72
+
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
+ export function BulkImageImportButton({
111
+ model,
112
+ metadata,
113
+ skuKey = 'sku',
114
+ dataBase = '/data',
115
+ minLongSide,
116
+ className,
117
+ onChange,
118
+ }: BulkImageImportButtonProps) {
119
+ const { t } = useTranslation()
120
+ const api = useApi()
121
+ const [target, setTarget] = useState<BulkImageTarget | null>(null)
122
+ const [open, setOpen] = useState(false)
123
+ const can = useCan()
124
+
125
+ // Descubre la galería: relación 1:N cuyo hijo tiene una columna de imagen con gallery.
126
+ useEffect(() => {
127
+ let alive = true
128
+ ;(async () => {
129
+ try {
130
+ let meta = metadata ?? useMetadataCache.getState().getMetadata(model) ?? null
131
+ if (!meta) {
132
+ const res = (await api.get(`/metadata/table/${model}`)) as any
133
+ meta = res?.data?.data ?? null
134
+ }
135
+ // El padre debe tener la columna que identifica la foto (SKU).
136
+ if (!(meta?.columns ?? []).some((c) => c.key === skuKey)) return
137
+ for (const rel of meta?.relations ?? []) {
138
+ if (rel.kind !== 'one_to_many') continue
139
+ let child = useMetadataCache.getState().getMetadata(rel.through) ?? null
140
+ if (!child) {
141
+ const r = (await api.get(`/metadata/table/${rel.through}`)) as any
142
+ child = r?.data?.data ?? null
143
+ }
144
+ const found = deriveBulkImageTarget(rel, child)
145
+ if (found) {
146
+ if (alive) setTarget(found)
147
+ return
148
+ }
149
+ }
150
+ } catch {
151
+ /* sin galería detectable: el botón no aparece */
152
+ }
153
+ })()
154
+ return () => {
155
+ alive = false
156
+ }
157
+ }, [api, model, metadata, skuKey])
158
+
159
+ // El flujo crea y borra filas del HIJO: exige sus permisos, no solo los del padre.
160
+ if (!target || !can(modelCapability(target.childModel, 'create')) || !can(modelCapability(target.childModel, 'delete'))) return null
161
+ return (
162
+ <>
163
+ <button
164
+ type="button"
165
+ data-testid="bulk-image-open"
166
+ onClick={() => setOpen(true)}
167
+ className={
168
+ className ??
169
+ 'inline-flex items-center gap-2 h-9 px-3 rounded-md border border-border bg-background hover:bg-accent text-sm font-medium text-foreground'
170
+ }
171
+ >
172
+ <ImagePlus className="size-4" />
173
+ {t('bulk_images.open', { defaultValue: 'Cargar imágenes' })}
174
+ </button>
175
+ {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
+ />
186
+ )}
187
+ </>
188
+ )
189
+ }
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
+ }