@asteby/metacore-runtime-react 53.13.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.
@@ -0,0 +1,55 @@
1
+ // Descubrimiento de la galería de un modelo (ligero: lo importa el botón del catálogo,
2
+ // que vive en el JS inicial; el resto de la carga masiva se carga bajo demanda).
3
+ import type { ColumnDefinition, RelationMeta, TableMetadata } from './types'
4
+ import { relationColumnUi, relationGalleryColumn } from './dynamic-relation-helpers'
5
+
6
+ export interface BulkImageTarget {
7
+ /** Modelo hijo (galería), p. ej. `product_images`. */
8
+ childModel: string
9
+ /** FK del hijo hacia el padre. */
10
+ foreignKey: string
11
+ /** Columna de imagen (la de `gallery: true`). */
12
+ imageKey: string
13
+ /** Columnas derivadas (si el modelo las tiene). */
14
+ widthKey?: string
15
+ heightKey?: string
16
+ positionKey?: string
17
+ /** Carpeta de almacenamiento (`storage_path` de la columna). */
18
+ storagePath?: string
19
+ accept: string
20
+ maxSize?: number
21
+ /** Filtros de alcance de la relación (polimórficos): se copian a cada fila. */
22
+ scope?: Record<string, string>
23
+ }
24
+
25
+ /**
26
+ * Busca la relación 1:N con galería. Necesita la metadata del hijo (para saber
27
+ * cuál es su columna de imagen); `childMetadata` la resuelve el llamador.
28
+ */
29
+ export function deriveBulkImageTarget(
30
+ relation: Pick<RelationMeta, 'through' | 'foreign_key' | 'scope' | 'kind'>,
31
+ childMetadata: Pick<TableMetadata, 'columns'> | null | undefined,
32
+ ): BulkImageTarget | null {
33
+ if (relation.kind !== 'one_to_many') return null
34
+ const img: ColumnDefinition | undefined = relationGalleryColumn(childMetadata)
35
+ if (!img) return null
36
+ // Sin la FK declarada el listado ignoraría `f_<fk>=in:` en silencio y devolvería todo.
37
+ if (!(childMetadata?.columns ?? []).some((c) => c.key === relation.foreign_key)) return null
38
+ const sc = (img.styleConfig ?? {}) as Record<string, unknown>
39
+ const keyOf = (derive: string) =>
40
+ (childMetadata?.columns ?? []).find((c) => relationColumnUi(c).derive === derive)?.key
41
+ const storagePath = (sc.storage_path ?? sc.storagePath) as string | undefined
42
+ return {
43
+ childModel: relation.through,
44
+ foreignKey: relation.foreign_key,
45
+ imageKey: img.key,
46
+ widthKey: keyOf('image_width'),
47
+ heightKey: keyOf('image_height'),
48
+ positionKey: keyOf('next_position') ?? (childMetadata?.columns ?? []).find((c) => c.key === 'position')?.key,
49
+ storagePath: typeof storagePath === 'string' && storagePath ? storagePath : undefined,
50
+ accept: (img as { accept?: string }).accept || 'image/*',
51
+ maxSize: (img as { maxSize?: number; max_size?: number }).maxSize ?? (img as { max_size?: number }).max_size,
52
+ scope: relation.scope,
53
+ }
54
+ }
55
+
@@ -0,0 +1,494 @@
1
+ // Asistente de carga masiva (se carga bajo demanda desde bulk-image-dialog.tsx para no
2
+ // engordar el JS inicial del shell). Ver el encabezado de ese archivo.
3
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
4
+ import { useTranslation } from 'react-i18next'
5
+ import {
6
+ Button,
7
+ Dialog,
8
+ DialogContent,
9
+ DialogDescription,
10
+ DialogFooter,
11
+ DialogHeader,
12
+ DialogTitle,
13
+ Table,
14
+ TableBody,
15
+ TableCell,
16
+ TableHead,
17
+ TableHeader,
18
+ TableRow,
19
+ } from '@asteby/metacore-ui/primitives'
20
+ import { AlertCircle, Check, FolderUp, ImagePlus, Loader2, Undo2, Download } from 'lucide-react'
21
+ import { useApi } from './api-context'
22
+ import { useMetadataCache } from './metadata-cache'
23
+ import { cacheScope } from './cache-scope'
24
+ import { modelCapability, useCan } from './permissions-context'
25
+ import { Progress } from './dialogs/_primitives'
26
+ import { extractUploadedValue, readImageSize } from './upload-field'
27
+ import type { TableMetadata } from './types'
28
+ import {
29
+ buildChildPayload,
30
+ buildPreview,
31
+ chunk,
32
+ collectBulkFiles,
33
+ collectCandidateSkus,
34
+ deriveBulkImageTarget,
35
+ isImportable,
36
+ loadBatchLogs,
37
+ MAX_BULK_FILES,
38
+ newBatchId,
39
+ normalizeSku,
40
+ pendingUndo,
41
+ saveBatchLog,
42
+ selectForImport,
43
+ summarizePreview,
44
+ type BatchLog,
45
+ type BulkFile,
46
+ type BulkImageTarget,
47
+ type ParentRef,
48
+ type PreviewRow,
49
+ } from './bulk-image-import'
50
+
51
+
52
+ type Step = 'pick' | 'analyzing' | 'preview' | 'importing' | 'done'
53
+ type ItemState = { status: 'pending' | 'uploading' | 'done' | 'error'; progress: number; error?: string }
54
+
55
+ const LOOKUP_CHUNK = 40
56
+ const CONCURRENCY = 3
57
+ const PAGE_SIZE = 200
58
+
59
+ /**
60
+ * Alcance del registro de lotes: organización + usuario (sin el idioma de
61
+ * cacheScope, para que cambiar de idioma no esconda lotes). null = desconocido:
62
+ * no se ofrecen lotes anteriores.
63
+ */
64
+ function batchScope(): string | null {
65
+ const s = cacheScope()
66
+ return s ? s.split(':').slice(0, 2).join(':') : null
67
+ }
68
+
69
+ /** map con concurrencia acotada (decodificar cientos de bitmaps a la vez tumba la pestaña). */
70
+ async function mapPool<T, R>(items: T[], limit: number, fn: (x: T) => Promise<R>): Promise<R[]> {
71
+ const out = new Array<R>(items.length)
72
+ let i = 0
73
+ await Promise.all(
74
+ Array.from({ length: Math.min(limit, items.length) }, async () => {
75
+ while (i < items.length) {
76
+ const idx = i++
77
+ out[idx] = await fn(items[idx])
78
+ }
79
+ }),
80
+ )
81
+ return out
82
+ }
83
+
84
+ function asRows(res: any): any[] {
85
+ const d = res?.data?.data ?? res?.data
86
+ return Array.isArray(d) ? d : Array.isArray(d?.data) ? d.data : []
87
+ }
88
+
89
+ export type BulkImageDialogProps = DialogProps
90
+
91
+ interface DialogProps {
92
+ open: boolean
93
+ onOpenChange: (o: boolean) => void
94
+ model: string
95
+ target: BulkImageTarget
96
+ skuKey: string
97
+ dataBase: string
98
+ minLongSide?: number
99
+ onChange?: () => void
100
+ }
101
+
102
+ export function BulkImageDialog({ open, onOpenChange, model, target, skuKey, dataBase, minLongSide, onChange }: DialogProps) {
103
+ const { t } = useTranslation()
104
+ const api = useApi()
105
+ const [step, setStep] = useState<Step>('pick')
106
+ const [error, setError] = useState<string | null>(null)
107
+ const [note, setNote] = useState<string | null>(null)
108
+ const [rows, setRows] = useState<PreviewRow[]>([])
109
+ const [excluded, setExcluded] = useState<Set<string>>(new Set())
110
+ const [items, setItems] = useState<Record<string, ItemState>>({})
111
+ const [log, setLog] = useState<BatchLog | null>(null)
112
+ const [undoing, setUndoing] = useState<{ done: number; total: number } | null>(null)
113
+ const [previousLogs, setPreviousLogs] = useState<BatchLog[]>(() => { const sc = batchScope(); return sc === null ? [] : loadBatchLogs(undefined, sc).filter((l) => l.childModel === target.childModel && pendingUndo(l).length > 0) })
114
+ const filesRef = useRef<Map<string, File>>(new Map())
115
+ const urlsRef = useRef<Map<string, string>>(new Map())
116
+ const cancelRef = useRef(false)
117
+ const zipInput = useRef<HTMLInputElement>(null)
118
+ const dirInput = useRef<HTMLInputElement>(null)
119
+
120
+ const releaseUrls = () => {
121
+ urlsRef.current.forEach((u) => URL.revokeObjectURL?.(u))
122
+ urlsRef.current.clear()
123
+ }
124
+ useEffect(() => () => releaseUrls(), [])
125
+
126
+ const childEndpoint = `${dataBase}/${target.childModel}`
127
+ const parentEndpoint = `${dataBase}/${model}`
128
+
129
+ const analyze = useCallback(
130
+ async (picked: File[]) => {
131
+ if (picked.length === 0) return
132
+ setError(null)
133
+ setNote(null)
134
+ setStep('analyzing')
135
+ try {
136
+ const { files, skipped } = await collectBulkFiles(picked)
137
+ if (files.length === 0) throw new Error(t('bulk_images.no_images', { defaultValue: 'No se encontraron imágenes (jpg, png, webp, gif, avif).' }))
138
+ if (files.length > MAX_BULK_FILES) {
139
+ throw new Error(t('bulk_images.too_many', { defaultValue: 'Máximo {{n}} imágenes por lote; divide la carga.', n: MAX_BULK_FILES }))
140
+ }
141
+ if (skipped > 0) setNote(t('bulk_images.skipped', { defaultValue: '{{n}} archivos ignorados (no son imágenes o son demasiado grandes).', n: skipped }))
142
+
143
+ // Medir en el navegador (el servidor no mide nada).
144
+ releaseUrls()
145
+ filesRef.current = new Map()
146
+ const inputs = await mapPool(
147
+ files,
148
+ 4,
149
+ async (f: BulkFile) => {
150
+ const size = await readImageSize(f.file)
151
+ filesRef.current.set(f.path, f.file)
152
+ urlsRef.current.set(f.path, URL.createObjectURL(f.file))
153
+ const ok = !!(size.width && size.height)
154
+ return { path: f.path, size: f.file.size, width: size.width, height: size.height, decodable: ok }
155
+ },
156
+ )
157
+
158
+ // Resolver SKU contra la API de datos existente (por lotes).
159
+ const skus = collectCandidateSkus(inputs.map((i) => i.path)).filter((s) => !s.includes(','))
160
+ const parents = new Map<string, ParentRef>()
161
+ for (const part of chunk(skus, LOOKUP_CHUNK)) {
162
+ const res = await api.get(parentEndpoint, {
163
+ params: { [`f_${skuKey}`]: `in:${part.join(',')}`, per_page: Math.min(200, part.length + 20) },
164
+ })
165
+ for (const r of asRows(res)) {
166
+ const sku = String(r[skuKey] ?? '')
167
+ if (!sku || r.id === undefined || r.id === null) continue
168
+ parents.set(normalizeSku(sku), {
169
+ id: String(r.id),
170
+ sku,
171
+ label: String(r.name ?? r.title ?? r.label ?? sku),
172
+ existingMaxPosition: -1,
173
+ existingCount: 0,
174
+ })
175
+ }
176
+ }
177
+
178
+ // Fotos que ya tiene cada producto: las nuevas van a continuación.
179
+ if (target.positionKey) {
180
+ const byId = new Map([...parents.values()].map((p) => [p.id, p]))
181
+ // El kernel limita per_page a 200: se pagina hasta agotar.
182
+ for (const part of chunk([...byId.keys()], LOOKUP_CHUNK)) {
183
+ for (let page = 1; page <= 50; page++) {
184
+ const res = await api.get(childEndpoint, {
185
+ params: { [`f_${target.foreignKey}`]: `in:${part.join(',')}`, per_page: PAGE_SIZE, page },
186
+ })
187
+ const got = asRows(res)
188
+ for (const r of got) {
189
+ const p = byId.get(String(r[target.foreignKey]))
190
+ if (!p) continue
191
+ p.existingCount += 1
192
+ const n = Number(r[target.positionKey])
193
+ if (Number.isFinite(n) && n > p.existingMaxPosition) p.existingMaxPosition = n
194
+ }
195
+ if (got.length < PAGE_SIZE) break
196
+ }
197
+ }
198
+ // Fotos existentes sin posición: las nuevas van detrás, nunca delante.
199
+ for (const p of byId.values()) {
200
+ if (p.existingCount > 0 && p.existingMaxPosition < p.existingCount - 1) p.existingMaxPosition = p.existingCount - 1
201
+ }
202
+ }
203
+
204
+ setRows(buildPreview(inputs, parents, { minLongSide, maxSize: target.maxSize }))
205
+ setExcluded(new Set())
206
+ setStep('preview')
207
+ } catch (e: any) {
208
+ setError(e?.message || t('bulk_images.analyze_failed', { defaultValue: 'No se pudo analizar la selección.' }))
209
+ setStep('pick')
210
+ }
211
+ },
212
+ // eslint-disable-next-line react-hooks/exhaustive-deps
213
+ [api, childEndpoint, minLongSide, parentEndpoint, skuKey, target],
214
+ )
215
+
216
+ const summary = useMemo(() => summarizePreview(rows, excluded), [rows, excluded])
217
+
218
+ const runImport = useCallback(async () => {
219
+ const queue = selectForImport(rows, excluded)
220
+ if (queue.length === 0) return
221
+ cancelRef.current = false
222
+ setStep('importing')
223
+ setError(null)
224
+ const batch: BatchLog = { batchId: newBatchId(), createdAt: new Date().toISOString(), childModel: target.childModel, scope: batchScope() ?? undefined, items: [] }
225
+ setLog(batch)
226
+ setItems(Object.fromEntries(queue.map((r) => [r.key, { status: 'pending', progress: 0 } as ItemState])))
227
+ const patch = (key: string, s: Partial<ItemState>) =>
228
+ setItems((m) => ({ ...m, [key]: { ...m[key], ...s } as ItemState }))
229
+
230
+ let next = 0
231
+ const worker = async () => {
232
+ while (!cancelRef.current) {
233
+ const row = queue[next++]
234
+ if (!row) return
235
+ patch(row.key, { status: 'uploading', progress: 0 })
236
+ let url = ''
237
+ try {
238
+ const file = filesRef.current.get(row.path)
239
+ if (!file) throw new Error('archivo no disponible')
240
+ const form = new FormData()
241
+ form.append('file', file)
242
+ if (target.storagePath) {
243
+ form.append('folder', target.storagePath)
244
+ form.append('storage_path', target.storagePath)
245
+ }
246
+ const up = await api.post('/upload', form, {
247
+ headers: { 'Content-Type': 'multipart/form-data' },
248
+ onUploadProgress: (e: { loaded: number; total?: number }) => {
249
+ if (e.total) patch(row.key, { progress: (e.loaded / e.total) * 0.9 })
250
+ },
251
+ } as any)
252
+ const body = (up as { data?: any })?.data
253
+ if (body && body.success === false) throw new Error(body.message || 'upload failed')
254
+ url = extractUploadedValue(body)
255
+ if (!url) throw new Error('upload failed')
256
+ const res = (await api.post(childEndpoint, buildChildPayload(target, row, url))) as any
257
+ if (!res?.data?.success) throw new Error(res?.data?.message || 'create failed')
258
+ const created = res.data.data ?? res.data
259
+ const rowId = created?.id
260
+ // Sin id no hay deshacer fiable: se avisa en vez de callar.
261
+ if (rowId === undefined || rowId === null) throw new Error('el servidor no devolvió el id de la fila creada')
262
+ batch.items.push({ rowId: String(rowId), path: row.path, sku: row.sku ?? '', parentId: row.parent!.id, url })
263
+ saveBatchLog(batch)
264
+ patch(row.key, { status: 'done', progress: 1 })
265
+ } catch (e: any) {
266
+ patch(row.key, { status: 'error', progress: 0, error: e?.response?.data?.message || e?.message || 'error' })
267
+ }
268
+ }
269
+ }
270
+ await Promise.all(Array.from({ length: Math.min(CONCURRENCY, queue.length) }, worker))
271
+ setLog({ ...batch, items: [...batch.items] })
272
+ setStep('done')
273
+ if (batch.items.length) onChange?.()
274
+ }, [api, childEndpoint, excluded, onChange, rows, target])
275
+
276
+ const undo = useCallback(
277
+ async (l: BatchLog) => {
278
+ const todo = pendingUndo(l)
279
+ setUndoing({ done: 0, total: todo.length })
280
+ setError(null)
281
+ const failures: string[] = []
282
+ for (const it of todo) {
283
+ try {
284
+ const res = (await api.delete(`${childEndpoint}/${it.rowId}`)) as any
285
+ if (res?.data?.success === false) throw new Error(res.data.message || 'delete failed')
286
+ it.undone = true
287
+ } catch (e: any) {
288
+ // 404 = ya no existe: el objetivo (que no esté) está cumplido.
289
+ if (e?.response?.status === 404) it.undone = true
290
+ else failures.push(`${it.sku || it.path}`)
291
+ }
292
+ setUndoing((u) => (u ? { ...u, done: u.done + 1 } : u))
293
+ }
294
+ saveBatchLog(l)
295
+ setUndoing(null)
296
+ setLog((cur) => (cur && cur.batchId === l.batchId ? { ...l, items: [...l.items] } : cur))
297
+ setPreviousLogs((ls) => ls.map((x) => (x.batchId === l.batchId ? { ...l, items: [...l.items] } : x)).filter((x) => pendingUndo(x).length > 0))
298
+ if (failures.length) {
299
+ setError(t('bulk_images.undo_partial', { defaultValue: 'No se pudieron deshacer: {{list}}. Reintenta.', list: failures.slice(0, 10).join(', ') }))
300
+ }
301
+ onChange?.()
302
+ },
303
+ [api, childEndpoint, onChange, t],
304
+ )
305
+
306
+ const downloadLog = (l: BatchLog) => {
307
+ const blob = new Blob([JSON.stringify(l, null, 2)], { type: 'application/json' })
308
+ const a = document.createElement('a')
309
+ a.href = URL.createObjectURL(blob)
310
+ a.download = `${l.batchId}.json`
311
+ a.click()
312
+ setTimeout(() => URL.revokeObjectURL(a.href), 1000)
313
+ }
314
+
315
+ const statusLabel = (r: PreviewRow) => {
316
+ switch (r.status) {
317
+ case 'ok': return t('bulk_images.s_ok', { defaultValue: 'Listo' })
318
+ case 'low_res': return t('bulk_images.s_low', { defaultValue: 'Baja resolución' })
319
+ case 'sku_not_found': return t('bulk_images.s_nosku', { defaultValue: 'SKU no encontrado' })
320
+ case 'duplicate': return t('bulk_images.s_dup', { defaultValue: 'Duplicado' })
321
+ case 'invalid_image': return t('bulk_images.s_invalid', { defaultValue: 'No es imagen' })
322
+ case 'too_large': return t('bulk_images.s_large', { defaultValue: 'Muy pesada' })
323
+ }
324
+ }
325
+
326
+ const doneCount = Object.values(items).filter((i) => i.status === 'done').length
327
+ const errCount = Object.values(items).filter((i) => i.status === 'error').length
328
+ const total = Object.keys(items).length
329
+ const busy = step === 'importing' || step === 'analyzing' || !!undoing
330
+
331
+ return (
332
+ <Dialog open={open} onOpenChange={(o) => { if (!o && busy) return; if (!o) releaseUrls(); onOpenChange(o) }}>
333
+ <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto" data-testid="bulk-image-dialog">
334
+ <DialogHeader>
335
+ <DialogTitle>{t('bulk_images.title', { defaultValue: 'Carga masiva de imágenes' })}</DialogTitle>
336
+ <DialogDescription>
337
+ {t('bulk_images.help', {
338
+ 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.',
339
+ })}
340
+ </DialogDescription>
341
+ </DialogHeader>
342
+
343
+ {error && <div role="alert" className="text-sm text-destructive flex gap-2 items-start"><AlertCircle className="size-4 mt-0.5" />{error}</div>}
344
+ {note && <div className="text-xs text-muted-foreground">{note}</div>}
345
+
346
+ {step === 'pick' && (
347
+ <div className="space-y-4">
348
+ <div
349
+ className="border-2 border-dashed rounded-lg p-8 text-center text-sm text-muted-foreground"
350
+ onDragOver={(e) => e.preventDefault()}
351
+ onDrop={(e) => { e.preventDefault(); void analyze(Array.from(e.dataTransfer?.files ?? [])) }}
352
+ >
353
+ <p className="mb-3">{t('bulk_images.drop', { defaultValue: 'Arrastra aquí el ZIP o las imágenes' })}</p>
354
+ <div className="flex gap-2 justify-center">
355
+ <Button variant="outline" onClick={() => zipInput.current?.click()}>
356
+ <ImagePlus className="size-4 mr-1" />{t('bulk_images.pick_zip', { defaultValue: 'Elegir ZIP o imágenes' })}
357
+ </Button>
358
+ <Button variant="outline" onClick={() => dirInput.current?.click()}>
359
+ <FolderUp className="size-4 mr-1" />{t('bulk_images.pick_folder', { defaultValue: 'Elegir carpeta' })}
360
+ </Button>
361
+ </div>
362
+ <input
363
+ ref={zipInput} type="file" multiple className="hidden" data-testid="bulk-image-input"
364
+ accept=".zip,application/zip,image/*"
365
+ onChange={(e) => { void analyze(Array.from(e.target.files ?? [])); e.target.value = '' }}
366
+ />
367
+ <input
368
+ ref={dirInput} type="file" multiple className="hidden" data-testid="bulk-image-dir"
369
+ {...({ webkitdirectory: '' } as Record<string, string>)}
370
+ onChange={(e) => { void analyze(Array.from(e.target.files ?? [])); e.target.value = '' }}
371
+ />
372
+ </div>
373
+ {previousLogs.length > 0 && (
374
+ <div className="text-sm space-y-2">
375
+ <div className="font-medium">{t('bulk_images.previous', { defaultValue: 'Lotes anteriores' })}</div>
376
+ {previousLogs.map((l) => (
377
+ <div key={l.batchId} className="flex items-center justify-between gap-2 border rounded-md px-3 py-2">
378
+ <span>{new Date(l.createdAt).toLocaleString()} · {pendingUndo(l).length} {t('bulk_images.images', { defaultValue: 'imágenes' })}</span>
379
+ <span className="flex gap-2">
380
+ <Button size="sm" variant="ghost" onClick={() => downloadLog(l)}><Download className="size-4" /></Button>
381
+ <Button size="sm" variant="outline" disabled={!!undoing} onClick={() => void undo(l)}>
382
+ <Undo2 className="size-4 mr-1" />{t('bulk_images.undo', { defaultValue: 'Deshacer lote' })}
383
+ </Button>
384
+ </span>
385
+ </div>
386
+ ))}
387
+ {undoing && <Progress value={(undoing.done / Math.max(1, undoing.total)) * 100} />}
388
+ </div>
389
+ )}
390
+ </div>
391
+ )}
392
+
393
+ {step === 'analyzing' && (
394
+ <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>
395
+ )}
396
+
397
+ {(step === 'preview' || step === 'importing' || step === 'done') && (
398
+ <div className="space-y-3">
399
+ <div className="flex flex-wrap gap-3 text-sm" data-testid="bulk-image-summary">
400
+ <span>{t('bulk_images.sum_import', { defaultValue: '{{n}} fotos para {{p}} productos', n: summary.importable, p: summary.products })}</span>
401
+ {summary.sku_not_found > 0 && <span className="text-destructive">{summary.sku_not_found} {t('bulk_images.s_nosku', { defaultValue: 'SKU no encontrado' })}</span>}
402
+ {summary.duplicate > 0 && <span className="text-destructive">{summary.duplicate} {t('bulk_images.s_dup', { defaultValue: 'Duplicado' })}</span>}
403
+ {summary.low_res > 0 && <span className="text-amber-600">{summary.low_res} {t('bulk_images.s_low', { defaultValue: 'Baja resolución' })}</span>}
404
+ {(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>}
405
+ </div>
406
+ {step !== 'preview' && (
407
+ <div className="space-y-1">
408
+ <Progress value={(doneCount + errCount) / Math.max(1, total) * 100} />
409
+ <div className="text-xs text-muted-foreground" data-testid="bulk-image-progress">
410
+ {t('bulk_images.progress', { defaultValue: '{{done}} de {{total}} subidas · {{err}} con error', done: doneCount, total, err: errCount })}
411
+ </div>
412
+ </div>
413
+ )}
414
+ <div className="border rounded-md max-h-[45vh] overflow-auto">
415
+ <Table>
416
+ <TableHeader>
417
+ <TableRow>
418
+ {step === 'preview' && <TableHead className="w-8" />}
419
+ <TableHead className="w-14" />
420
+ <TableHead>{t('bulk_images.col_file', { defaultValue: 'Archivo' })}</TableHead>
421
+ <TableHead>{t('bulk_images.col_product', { defaultValue: 'Producto' })}</TableHead>
422
+ <TableHead>{t('bulk_images.col_pos', { defaultValue: 'Pos.' })}</TableHead>
423
+ <TableHead>{t('bulk_images.col_status', { defaultValue: 'Estado' })}</TableHead>
424
+ </TableRow>
425
+ </TableHeader>
426
+ <TableBody>
427
+ {rows.map((r) => {
428
+ const it = items[r.key]
429
+ const skip = excluded.has(r.key)
430
+ return (
431
+ <TableRow key={r.key} data-status={r.status} className={skip ? 'opacity-50' : undefined}>
432
+ {step === 'preview' && (
433
+ <TableCell>
434
+ {isImportable(r) && (
435
+ <input
436
+ type="checkbox" checked={!skip} aria-label={r.path}
437
+ onChange={() => setExcluded((s) => { const n = new Set(s); if (n.has(r.key)) n.delete(r.key); else n.add(r.key); return n })}
438
+ />
439
+ )}
440
+ </TableCell>
441
+ )}
442
+ <TableCell>
443
+ {urlsRef.current.get(r.path) && <img src={urlsRef.current.get(r.path)} alt="" className="size-10 object-contain rounded bg-muted" loading="lazy" />}
444
+ </TableCell>
445
+ <TableCell className="text-xs break-all">{r.path}<div className="text-muted-foreground">{r.width && r.height ? `${r.width}×${r.height}` : ''}</div></TableCell>
446
+ <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>
447
+ <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>
448
+ <TableCell className="text-xs">
449
+ {it ? (
450
+ 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>
451
+ : it.status === 'error' ? <span className="text-destructive" title={it.error}>{it.error}</span>
452
+ : <div className="w-24"><Progress value={it.progress * 100} /></div>
453
+ ) : (
454
+ <span className={r.status === 'ok' ? '' : r.status === 'low_res' ? 'text-amber-600' : 'text-destructive'} title={r.note}>{statusLabel(r)}</span>
455
+ )}
456
+ </TableCell>
457
+ </TableRow>
458
+ )
459
+ })}
460
+ </TableBody>
461
+ </Table>
462
+ </div>
463
+ </div>
464
+ )}
465
+
466
+ <DialogFooter className="gap-2">
467
+ {step === 'preview' && (
468
+ <>
469
+ <Button variant="outline" onClick={() => { releaseUrls(); setRows([]); setStep('pick') }}>{t('bulk_images.back', { defaultValue: 'Elegir otros' })}</Button>
470
+ <Button disabled={summary.importable === 0} onClick={() => void runImport()} data-testid="bulk-image-import">
471
+ {t('bulk_images.import', { defaultValue: 'Importar {{n}} fotos', n: summary.importable })}
472
+ </Button>
473
+ </>
474
+ )}
475
+ {step === 'importing' && (
476
+ <Button variant="outline" onClick={() => { cancelRef.current = true }}>{t('bulk_images.cancel', { defaultValue: 'Detener' })}</Button>
477
+ )}
478
+ {step === 'done' && log && (
479
+ <>
480
+ <Button variant="ghost" onClick={() => downloadLog(log)}><Download className="size-4 mr-1" />{t('bulk_images.download_log', { defaultValue: 'Descargar registro' })}</Button>
481
+ {pendingUndo(log).length > 0 && (
482
+ <Button variant="outline" disabled={!!undoing} onClick={() => void undo(log)} data-testid="bulk-image-undo">
483
+ <Undo2 className="size-4 mr-1" />
484
+ {undoing ? `${undoing.done}/${undoing.total}` : t('bulk_images.undo', { defaultValue: 'Deshacer lote' })}
485
+ </Button>
486
+ )}
487
+ <Button onClick={() => { releaseUrls(); onOpenChange(false) }}>{t('bulk_images.close', { defaultValue: 'Cerrar' })}</Button>
488
+ </>
489
+ )}
490
+ </DialogFooter>
491
+ </DialogContent>
492
+ </Dialog>
493
+ )
494
+ }
package/src/index.ts CHANGED
@@ -892,13 +892,7 @@ export {
892
892
  export * from './capability-providers'
893
893
  export {
894
894
  BulkImageImportButton,
895
- BulkImageDialog,
896
895
  type BulkImageImportButtonProps,
897
896
  } from './bulk-image-dialog'
898
- export {
899
- buildPreview as buildBulkImagePreview,
900
- parseImageName as parseBulkImageName,
901
- deriveBulkImageTarget,
902
- type BulkImageTarget,
903
- type BatchLog as BulkImageBatchLog,
904
- } from './bulk-image-import'
897
+ export type { BulkImageTarget } from './bulk-image-target'
898
+ export type { BatchLog as BulkImageBatchLog } from './bulk-image-import'