@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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
  # @asteby/metacore-runtime-react
2
2
 
3
+ ## 53.13.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 68effb9: Galería: la imagen original del padre como «Principal» cuando la galería está vacía. Si la columna de imagen declara `display_config.main_from_parent: "<campo>"` (p. ej. `image` en el producto) y la galería no tiene ninguna foto, el panel muestra esa imagen como tarjeta «Principal» de solo lectura, con la leyenda «Imagen original del producto»: es la que la tienda sirve cuando no hay galería. Con una o más fotos la tienda sirve primero la galería, así que no hay tarjeta extra y la primera foto es la principal (la imagen original entra a la galería cuando el addon la siembra al crear la primera foto). Sin el hint no cambia nada.
8
+
9
+ ## 53.12.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 56a5f71: Carga masiva de imágenes a nivel catálogo. Nuevo `BulkImageImportButton` (y `BulkImageDialog`), montado en `DynamicCRUDPage` para cualquier modelo con galería (relación 1:N cuya columna de imagen declara `display_config.gallery: true`) y una columna `sku`. Asistente en cuatro pasos:
14
+
15
+ - Elegir un ZIP, una carpeta o imágenes sueltas con nombres `SKU.ext`, `SKU_2.ext`… (el ZIP se descomprime en el navegador).
16
+ - Vista previa: qué foto va a qué producto y en qué posición, SKU no encontrados, duplicados, baja resolución (lado largo < 600 px, configurable), archivos que no son imagen; cada fila importable se puede excluir.
17
+ - Importar con progreso por archivo (3 en paralelo); un error no detiene el resto. Una fila hija por foto, con posición a continuación de las existentes y ancho/alto medidos en el navegador.
18
+ - «Deshacer lote»: borra solo las filas creadas por ese lote. Los ids se guardan en un registro (localStorage, últimos 10 lotes) que también se puede descargar como JSON.
19
+
20
+ Solo usa contratos existentes (`GET /metadata/table`, `GET /data/<modelo>?f_<col>=in:`, `POST /upload`, `POST`/`DELETE /data/<hijo>`); no requiere cambios en el kernel. Nueva dependencia: `fflate`, cargada solo al elegir un ZIP.
21
+
22
+ ### Patch Changes
23
+
24
+ - 89168aa: Galería de una relación 1:N:
25
+
26
+ - Los botones de cada tarjeta ya no se recortan: la barra de acciones envuelve a otra línea cuando la tarjeta es angosta (140 px o móvil) y el botón de eliminar siempre es visible.
27
+ - Posiciones sin repetir. Dos subidas seguidas ya no leen el mismo máximo de una lista que aún no se refrescó. Al terminar una subida y al eliminar una foto, el panel lee las filas del servidor y las renumera de forma contigua (0..n-1); las filas que un cliente anterior dejó con la misma posición se ordenan por antigüedad, así la original queda primero. Solo se escriben las filas cuya posición cambia.
28
+
3
29
  ## 53.11.0
4
30
 
5
31
  ### Minor Changes
@@ -0,0 +1,31 @@
1
+ import type { TableMetadata } from './types';
2
+ import { type BulkImageTarget } from './bulk-image-import';
3
+ export interface BulkImageImportButtonProps {
4
+ /** Modelo padre (catálogo), p. ej. `products`. */
5
+ model: string;
6
+ /** Metadata del padre; si se omite se lee de la caché / `/metadata/table`. */
7
+ metadata?: TableMetadata | null;
8
+ /** Columna del padre que identifica la foto en el nombre de archivo. Default `sku`. */
9
+ skuKey?: string;
10
+ /** Prefijo del endpoint de datos. Default `/data`. */
11
+ dataBase?: string;
12
+ /** Lado largo mínimo antes de avisar «baja resolución». Default 600. */
13
+ minLongSide?: number;
14
+ className?: string;
15
+ /** Tras importar o deshacer (refrescar la lista). */
16
+ onChange?: () => void;
17
+ }
18
+ export declare function BulkImageImportButton({ model, metadata, skuKey, dataBase, minLongSide, className, onChange, }: BulkImageImportButtonProps): import("react").JSX.Element | null;
19
+ interface DialogProps {
20
+ open: boolean;
21
+ onOpenChange: (o: boolean) => void;
22
+ model: string;
23
+ target: BulkImageTarget;
24
+ skuKey: string;
25
+ dataBase: string;
26
+ minLongSide?: number;
27
+ onChange?: () => void;
28
+ }
29
+ export declare function BulkImageDialog({ open, onOpenChange, model, target, skuKey, dataBase, minLongSide, onChange }: DialogProps): import("react").JSX.Element;
30
+ export {};
31
+ //# s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AwY1H"}
@@ -0,0 +1,339 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ // BulkImageImportButton — carga masiva de imágenes a nivel catálogo.
3
+ //
4
+ // Botón + asistente (elegir ZIP/carpeta → vista previa → importar con
5
+ // progreso → deshacer lote) para cualquier modelo con una galería declarada
6
+ // (relación 1:N cuya columna de imagen trae `display_config.gallery: true`).
7
+ // No renderiza nada si el modelo no tiene galería. Usa solo contratos que ya
8
+ // existen: GET /metadata/table, GET /data/<modelo> (filtro `f_<col>=in:`),
9
+ // POST /upload, POST y DELETE /data/<hijo>.
10
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
11
+ import { useTranslation } from 'react-i18next';
12
+ import { Button, Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from '@asteby/metacore-ui/primitives';
13
+ import { AlertCircle, Check, FolderUp, ImagePlus, Loader2, Undo2, Download } from 'lucide-react';
14
+ import { useApi } from './api-context';
15
+ import { useMetadataCache } from './metadata-cache';
16
+ import { cacheScope } from './cache-scope';
17
+ import { modelCapability, useCan } from './permissions-context';
18
+ import { Progress } from './dialogs/_primitives';
19
+ import { extractUploadedValue, readImageSize } from './upload-field';
20
+ import { buildChildPayload, buildPreview, chunk, collectBulkFiles, collectCandidateSkus, deriveBulkImageTarget, isImportable, loadBatchLogs, MAX_BULK_FILES, newBatchId, normalizeSku, pendingUndo, saveBatchLog, selectForImport, summarizePreview, } from './bulk-image-import';
21
+ const LOOKUP_CHUNK = 40;
22
+ const CONCURRENCY = 3;
23
+ const PAGE_SIZE = 200;
24
+ /**
25
+ * Alcance del registro de lotes: organización + usuario (sin el idioma de
26
+ * cacheScope, para que cambiar de idioma no esconda lotes). null = desconocido:
27
+ * no se ofrecen lotes anteriores.
28
+ */
29
+ function batchScope() {
30
+ const s = cacheScope();
31
+ return s ? s.split(':').slice(0, 2).join(':') : null;
32
+ }
33
+ /** map con concurrencia acotada (decodificar cientos de bitmaps a la vez tumba la pestaña). */
34
+ async function mapPool(items, limit, fn) {
35
+ const out = new Array(items.length);
36
+ let i = 0;
37
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
38
+ while (i < items.length) {
39
+ const idx = i++;
40
+ out[idx] = await fn(items[idx]);
41
+ }
42
+ }));
43
+ return out;
44
+ }
45
+ function asRows(res) {
46
+ const d = res?.data?.data ?? res?.data;
47
+ return Array.isArray(d) ? d : Array.isArray(d?.data) ? d.data : [];
48
+ }
49
+ export function BulkImageImportButton({ model, metadata, skuKey = 'sku', dataBase = '/data', minLongSide, className, onChange, }) {
50
+ const { t } = useTranslation();
51
+ const api = useApi();
52
+ const [target, setTarget] = useState(null);
53
+ const [open, setOpen] = useState(false);
54
+ const can = useCan();
55
+ // Descubre la galería: relación 1:N cuyo hijo tiene una columna de imagen con gallery.
56
+ useEffect(() => {
57
+ let alive = true;
58
+ (async () => {
59
+ try {
60
+ let meta = metadata ?? useMetadataCache.getState().getMetadata(model) ?? null;
61
+ if (!meta) {
62
+ const res = (await api.get(`/metadata/table/${model}`));
63
+ meta = res?.data?.data ?? null;
64
+ }
65
+ // El padre debe tener la columna que identifica la foto (SKU).
66
+ if (!(meta?.columns ?? []).some((c) => c.key === skuKey))
67
+ return;
68
+ for (const rel of meta?.relations ?? []) {
69
+ if (rel.kind !== 'one_to_many')
70
+ continue;
71
+ let child = useMetadataCache.getState().getMetadata(rel.through) ?? null;
72
+ if (!child) {
73
+ const r = (await api.get(`/metadata/table/${rel.through}`));
74
+ child = r?.data?.data ?? null;
75
+ }
76
+ const found = deriveBulkImageTarget(rel, child);
77
+ if (found) {
78
+ if (alive)
79
+ setTarget(found);
80
+ return;
81
+ }
82
+ }
83
+ }
84
+ catch {
85
+ /* sin galería detectable: el botón no aparece */
86
+ }
87
+ })();
88
+ return () => {
89
+ alive = false;
90
+ };
91
+ }, [api, model, metadata, skuKey]);
92
+ // El flujo crea y borra filas del HIJO: exige sus permisos, no solo los del padre.
93
+ if (!target || !can(modelCapability(target.childModel, 'create')) || !can(modelCapability(target.childModel, 'delete')))
94
+ return null;
95
+ return (_jsxs(_Fragment, { children: [_jsxs("button", { type: "button", "data-testid": "bulk-image-open", onClick: () => setOpen(true), className: className ??
96
+ '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', children: [_jsx(ImagePlus, { className: "size-4" }), t('bulk_images.open', { defaultValue: 'Cargar imágenes' })] }), open && (_jsx(BulkImageDialog, { open: open, onOpenChange: setOpen, model: model, target: target, skuKey: skuKey, dataBase: dataBase, minLongSide: minLongSide, onChange: onChange }))] }));
97
+ }
98
+ export function BulkImageDialog({ open, onOpenChange, model, target, skuKey, dataBase, minLongSide, onChange }) {
99
+ const { t } = useTranslation();
100
+ const api = useApi();
101
+ const [step, setStep] = useState('pick');
102
+ const [error, setError] = useState(null);
103
+ const [note, setNote] = useState(null);
104
+ const [rows, setRows] = useState([]);
105
+ const [excluded, setExcluded] = useState(new Set());
106
+ const [items, setItems] = useState({});
107
+ const [log, setLog] = useState(null);
108
+ const [undoing, setUndoing] = useState(null);
109
+ const [previousLogs, setPreviousLogs] = useState(() => { const sc = batchScope(); return sc === null ? [] : loadBatchLogs(undefined, sc).filter((l) => l.childModel === target.childModel && pendingUndo(l).length > 0); });
110
+ const filesRef = useRef(new Map());
111
+ const urlsRef = useRef(new Map());
112
+ const cancelRef = useRef(false);
113
+ const zipInput = useRef(null);
114
+ const dirInput = useRef(null);
115
+ const releaseUrls = () => {
116
+ urlsRef.current.forEach((u) => URL.revokeObjectURL?.(u));
117
+ urlsRef.current.clear();
118
+ };
119
+ useEffect(() => () => releaseUrls(), []);
120
+ const childEndpoint = `${dataBase}/${target.childModel}`;
121
+ const parentEndpoint = `${dataBase}/${model}`;
122
+ const analyze = useCallback(async (picked) => {
123
+ if (picked.length === 0)
124
+ return;
125
+ setError(null);
126
+ setNote(null);
127
+ setStep('analyzing');
128
+ try {
129
+ const { files, skipped } = await collectBulkFiles(picked);
130
+ if (files.length === 0)
131
+ throw new Error(t('bulk_images.no_images', { defaultValue: 'No se encontraron imágenes (jpg, png, webp, gif, avif).' }));
132
+ if (files.length > MAX_BULK_FILES) {
133
+ throw new Error(t('bulk_images.too_many', { defaultValue: 'Máximo {{n}} imágenes por lote; divide la carga.', n: MAX_BULK_FILES }));
134
+ }
135
+ if (skipped > 0)
136
+ setNote(t('bulk_images.skipped', { defaultValue: '{{n}} archivos ignorados (no son imágenes o son demasiado grandes).', n: skipped }));
137
+ // Medir en el navegador (el servidor no mide nada).
138
+ releaseUrls();
139
+ filesRef.current = new Map();
140
+ const inputs = await mapPool(files, 4, async (f) => {
141
+ const size = await readImageSize(f.file);
142
+ filesRef.current.set(f.path, f.file);
143
+ urlsRef.current.set(f.path, URL.createObjectURL(f.file));
144
+ const ok = !!(size.width && size.height);
145
+ return { path: f.path, size: f.file.size, width: size.width, height: size.height, decodable: ok };
146
+ });
147
+ // Resolver SKU contra la API de datos existente (por lotes).
148
+ const skus = collectCandidateSkus(inputs.map((i) => i.path)).filter((s) => !s.includes(','));
149
+ const parents = new Map();
150
+ for (const part of chunk(skus, LOOKUP_CHUNK)) {
151
+ const res = await api.get(parentEndpoint, {
152
+ params: { [`f_${skuKey}`]: `in:${part.join(',')}`, per_page: Math.min(200, part.length + 20) },
153
+ });
154
+ for (const r of asRows(res)) {
155
+ const sku = String(r[skuKey] ?? '');
156
+ if (!sku || r.id === undefined || r.id === null)
157
+ continue;
158
+ parents.set(normalizeSku(sku), {
159
+ id: String(r.id),
160
+ sku,
161
+ label: String(r.name ?? r.title ?? r.label ?? sku),
162
+ existingMaxPosition: -1,
163
+ existingCount: 0,
164
+ });
165
+ }
166
+ }
167
+ // Fotos que ya tiene cada producto: las nuevas van a continuación.
168
+ if (target.positionKey) {
169
+ const byId = new Map([...parents.values()].map((p) => [p.id, p]));
170
+ // El kernel limita per_page a 200: se pagina hasta agotar.
171
+ for (const part of chunk([...byId.keys()], LOOKUP_CHUNK)) {
172
+ for (let page = 1; page <= 50; page++) {
173
+ const res = await api.get(childEndpoint, {
174
+ params: { [`f_${target.foreignKey}`]: `in:${part.join(',')}`, per_page: PAGE_SIZE, page },
175
+ });
176
+ const got = asRows(res);
177
+ for (const r of got) {
178
+ const p = byId.get(String(r[target.foreignKey]));
179
+ if (!p)
180
+ continue;
181
+ p.existingCount += 1;
182
+ const n = Number(r[target.positionKey]);
183
+ if (Number.isFinite(n) && n > p.existingMaxPosition)
184
+ p.existingMaxPosition = n;
185
+ }
186
+ if (got.length < PAGE_SIZE)
187
+ break;
188
+ }
189
+ }
190
+ // Fotos existentes sin posición: las nuevas van detrás, nunca delante.
191
+ for (const p of byId.values()) {
192
+ if (p.existingCount > 0 && p.existingMaxPosition < p.existingCount - 1)
193
+ p.existingMaxPosition = p.existingCount - 1;
194
+ }
195
+ }
196
+ setRows(buildPreview(inputs, parents, { minLongSide, maxSize: target.maxSize }));
197
+ setExcluded(new Set());
198
+ setStep('preview');
199
+ }
200
+ catch (e) {
201
+ setError(e?.message || t('bulk_images.analyze_failed', { defaultValue: 'No se pudo analizar la selección.' }));
202
+ setStep('pick');
203
+ }
204
+ },
205
+ // eslint-disable-next-line react-hooks/exhaustive-deps
206
+ [api, childEndpoint, minLongSide, parentEndpoint, skuKey, target]);
207
+ const summary = useMemo(() => summarizePreview(rows, excluded), [rows, excluded]);
208
+ const runImport = useCallback(async () => {
209
+ const queue = selectForImport(rows, excluded);
210
+ if (queue.length === 0)
211
+ return;
212
+ cancelRef.current = false;
213
+ setStep('importing');
214
+ setError(null);
215
+ const batch = { batchId: newBatchId(), createdAt: new Date().toISOString(), childModel: target.childModel, scope: batchScope() ?? undefined, items: [] };
216
+ setLog(batch);
217
+ setItems(Object.fromEntries(queue.map((r) => [r.key, { status: 'pending', progress: 0 }])));
218
+ const patch = (key, s) => setItems((m) => ({ ...m, [key]: { ...m[key], ...s } }));
219
+ let next = 0;
220
+ const worker = async () => {
221
+ while (!cancelRef.current) {
222
+ const row = queue[next++];
223
+ if (!row)
224
+ return;
225
+ patch(row.key, { status: 'uploading', progress: 0 });
226
+ let url = '';
227
+ try {
228
+ const file = filesRef.current.get(row.path);
229
+ if (!file)
230
+ throw new Error('archivo no disponible');
231
+ const form = new FormData();
232
+ form.append('file', file);
233
+ if (target.storagePath) {
234
+ form.append('folder', target.storagePath);
235
+ form.append('storage_path', target.storagePath);
236
+ }
237
+ const up = await api.post('/upload', form, {
238
+ headers: { 'Content-Type': 'multipart/form-data' },
239
+ onUploadProgress: (e) => {
240
+ if (e.total)
241
+ patch(row.key, { progress: (e.loaded / e.total) * 0.9 });
242
+ },
243
+ });
244
+ const body = up?.data;
245
+ if (body && body.success === false)
246
+ throw new Error(body.message || 'upload failed');
247
+ url = extractUploadedValue(body);
248
+ if (!url)
249
+ throw new Error('upload failed');
250
+ const res = (await api.post(childEndpoint, buildChildPayload(target, row, url)));
251
+ if (!res?.data?.success)
252
+ throw new Error(res?.data?.message || 'create failed');
253
+ const created = res.data.data ?? res.data;
254
+ const rowId = created?.id;
255
+ // Sin id no hay deshacer fiable: se avisa en vez de callar.
256
+ if (rowId === undefined || rowId === null)
257
+ throw new Error('el servidor no devolvió el id de la fila creada');
258
+ batch.items.push({ rowId: String(rowId), path: row.path, sku: row.sku ?? '', parentId: row.parent.id, url });
259
+ saveBatchLog(batch);
260
+ patch(row.key, { status: 'done', progress: 1 });
261
+ }
262
+ catch (e) {
263
+ patch(row.key, { status: 'error', progress: 0, error: e?.response?.data?.message || e?.message || 'error' });
264
+ }
265
+ }
266
+ };
267
+ await Promise.all(Array.from({ length: Math.min(CONCURRENCY, queue.length) }, worker));
268
+ setLog({ ...batch, items: [...batch.items] });
269
+ setStep('done');
270
+ if (batch.items.length)
271
+ onChange?.();
272
+ }, [api, childEndpoint, excluded, onChange, rows, target]);
273
+ const undo = useCallback(async (l) => {
274
+ const todo = pendingUndo(l);
275
+ setUndoing({ done: 0, total: todo.length });
276
+ setError(null);
277
+ const failures = [];
278
+ for (const it of todo) {
279
+ try {
280
+ const res = (await api.delete(`${childEndpoint}/${it.rowId}`));
281
+ if (res?.data?.success === false)
282
+ throw new Error(res.data.message || 'delete failed');
283
+ it.undone = true;
284
+ }
285
+ catch (e) {
286
+ // 404 = ya no existe: el objetivo (que no esté) está cumplido.
287
+ if (e?.response?.status === 404)
288
+ it.undone = true;
289
+ else
290
+ 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
+ }, [api, childEndpoint, onChange, t]);
303
+ const downloadLog = (l) => {
304
+ const blob = new Blob([JSON.stringify(l, null, 2)], { type: 'application/json' });
305
+ const a = document.createElement('a');
306
+ a.href = URL.createObjectURL(blob);
307
+ a.download = `${l.batchId}.json`;
308
+ a.click();
309
+ setTimeout(() => URL.revokeObjectURL(a.href), 1000);
310
+ };
311
+ const statusLabel = (r) => {
312
+ switch (r.status) {
313
+ case 'ok': return t('bulk_images.s_ok', { defaultValue: 'Listo' });
314
+ case 'low_res': return t('bulk_images.s_low', { defaultValue: 'Baja resolución' });
315
+ case 'sku_not_found': return t('bulk_images.s_nosku', { defaultValue: 'SKU no encontrado' });
316
+ case 'duplicate': return t('bulk_images.s_dup', { defaultValue: 'Duplicado' });
317
+ case 'invalid_image': return t('bulk_images.s_invalid', { defaultValue: 'No es imagen' });
318
+ case 'too_large': return t('bulk_images.s_large', { defaultValue: 'Muy pesada' });
319
+ }
320
+ };
321
+ const doneCount = Object.values(items).filter((i) => i.status === 'done').length;
322
+ const errCount = Object.values(items).filter((i) => i.status === 'error').length;
323
+ const total = Object.keys(items).length;
324
+ const busy = step === 'importing' || step === 'analyzing' || !!undoing;
325
+ return (_jsx(Dialog, { open: open, onOpenChange: (o) => { if (!o && busy)
326
+ return; if (!o)
327
+ releaseUrls(); onOpenChange(o); }, children: _jsxs(DialogContent, { className: "max-w-4xl max-h-[90vh] overflow-y-auto", "data-testid": "bulk-image-dialog", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { children: t('bulk_images.title', { defaultValue: 'Carga masiva de imágenes' }) }), _jsx(DialogDescription, { children: t('bulk_images.help', {
328
+ 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.',
329
+ }) })] }), error && _jsxs("div", { role: "alert", className: "text-sm text-destructive flex gap-2 items-start", children: [_jsx(AlertCircle, { className: "size-4 mt-0.5" }), error] }), note && _jsx("div", { className: "text-xs text-muted-foreground", children: note }), step === 'pick' && (_jsxs("div", { className: "space-y-4", children: [_jsxs("div", { className: "border-2 border-dashed rounded-lg p-8 text-center text-sm text-muted-foreground", onDragOver: (e) => e.preventDefault(), onDrop: (e) => { e.preventDefault(); void analyze(Array.from(e.dataTransfer?.files ?? [])); }, children: [_jsx("p", { className: "mb-3", children: t('bulk_images.drop', { defaultValue: 'Arrastra aquí el ZIP o las imágenes' }) }), _jsxs("div", { className: "flex gap-2 justify-center", children: [_jsxs(Button, { variant: "outline", onClick: () => zipInput.current?.click(), children: [_jsx(ImagePlus, { className: "size-4 mr-1" }), t('bulk_images.pick_zip', { defaultValue: 'Elegir ZIP o imágenes' })] }), _jsxs(Button, { variant: "outline", onClick: () => dirInput.current?.click(), children: [_jsx(FolderUp, { className: "size-4 mr-1" }), t('bulk_images.pick_folder', { defaultValue: 'Elegir carpeta' })] })] }), _jsx("input", { ref: zipInput, type: "file", multiple: true, className: "hidden", "data-testid": "bulk-image-input", accept: ".zip,application/zip,image/*", onChange: (e) => { void analyze(Array.from(e.target.files ?? [])); e.target.value = ''; } }), _jsx("input", { ref: dirInput, type: "file", multiple: true, className: "hidden", "data-testid": "bulk-image-dir", ...{ webkitdirectory: '' }, onChange: (e) => { void analyze(Array.from(e.target.files ?? [])); e.target.value = ''; } })] }), previousLogs.length > 0 && (_jsxs("div", { className: "text-sm space-y-2", children: [_jsx("div", { className: "font-medium", children: t('bulk_images.previous', { defaultValue: 'Lotes anteriores' }) }), previousLogs.map((l) => (_jsxs("div", { className: "flex items-center justify-between gap-2 border rounded-md px-3 py-2", children: [_jsxs("span", { children: [new Date(l.createdAt).toLocaleString(), " \u00B7 ", pendingUndo(l).length, " ", t('bulk_images.images', { defaultValue: 'imágenes' })] }), _jsxs("span", { className: "flex gap-2", children: [_jsx(Button, { size: "sm", variant: "ghost", onClick: () => downloadLog(l), children: _jsx(Download, { className: "size-4" }) }), _jsxs(Button, { size: "sm", variant: "outline", disabled: !!undoing, onClick: () => void undo(l), children: [_jsx(Undo2, { className: "size-4 mr-1" }), t('bulk_images.undo', { defaultValue: 'Deshacer lote' })] })] })] }, l.batchId))), undoing && _jsx(Progress, { value: (undoing.done / Math.max(1, undoing.total)) * 100 })] }))] })), step === 'analyzing' && (_jsxs("div", { className: "flex items-center gap-2 text-sm py-8 justify-center", children: [_jsx(Loader2, { className: "size-4 animate-spin" }), t('bulk_images.analyzing', { defaultValue: 'Analizando imágenes y buscando SKU…' })] })), (step === 'preview' || step === 'importing' || step === 'done') && (_jsxs("div", { className: "space-y-3", children: [_jsxs("div", { className: "flex flex-wrap gap-3 text-sm", "data-testid": "bulk-image-summary", children: [_jsx("span", { children: t('bulk_images.sum_import', { defaultValue: '{{n}} fotos para {{p}} productos', n: summary.importable, p: summary.products }) }), summary.sku_not_found > 0 && _jsxs("span", { className: "text-destructive", children: [summary.sku_not_found, " ", t('bulk_images.s_nosku', { defaultValue: 'SKU no encontrado' })] }), summary.duplicate > 0 && _jsxs("span", { className: "text-destructive", children: [summary.duplicate, " ", t('bulk_images.s_dup', { defaultValue: 'Duplicado' })] }), summary.low_res > 0 && _jsxs("span", { className: "text-amber-600", children: [summary.low_res, " ", t('bulk_images.s_low', { defaultValue: 'Baja resolución' })] }), (summary.invalid_image + summary.too_large) > 0 && _jsxs("span", { className: "text-destructive", children: [summary.invalid_image + summary.too_large, " ", t('bulk_images.s_invalid', { defaultValue: 'No es imagen' })] })] }), step !== 'preview' && (_jsxs("div", { className: "space-y-1", children: [_jsx(Progress, { value: (doneCount + errCount) / Math.max(1, total) * 100 }), _jsx("div", { className: "text-xs text-muted-foreground", "data-testid": "bulk-image-progress", children: t('bulk_images.progress', { defaultValue: '{{done}} de {{total}} subidas · {{err}} con error', done: doneCount, total, err: errCount }) })] })), _jsx("div", { className: "border rounded-md max-h-[45vh] overflow-auto", children: _jsxs(Table, { children: [_jsx(TableHeader, { children: _jsxs(TableRow, { children: [step === 'preview' && _jsx(TableHead, { className: "w-8" }), _jsx(TableHead, { className: "w-14" }), _jsx(TableHead, { children: t('bulk_images.col_file', { defaultValue: 'Archivo' }) }), _jsx(TableHead, { children: t('bulk_images.col_product', { defaultValue: 'Producto' }) }), _jsx(TableHead, { children: t('bulk_images.col_pos', { defaultValue: 'Pos.' }) }), _jsx(TableHead, { children: t('bulk_images.col_status', { defaultValue: 'Estado' }) })] }) }), _jsx(TableBody, { children: rows.map((r) => {
330
+ const it = items[r.key];
331
+ const skip = excluded.has(r.key);
332
+ return (_jsxs(TableRow, { "data-status": r.status, className: skip ? 'opacity-50' : undefined, children: [step === 'preview' && (_jsx(TableCell, { children: isImportable(r) && (_jsx("input", { type: "checkbox", checked: !skip, "aria-label": r.path, onChange: () => setExcluded((s) => { const n = new Set(s); if (n.has(r.key))
333
+ n.delete(r.key);
334
+ else
335
+ n.add(r.key); return n; }) })) })), _jsx(TableCell, { children: urlsRef.current.get(r.path) && _jsx("img", { src: urlsRef.current.get(r.path), alt: "", className: "size-10 object-contain rounded bg-muted", loading: "lazy" }) }), _jsxs(TableCell, { className: "text-xs break-all", children: [r.path, _jsx("div", { className: "text-muted-foreground", children: r.width && r.height ? `${r.width}×${r.height}` : '' })] }), _jsx(TableCell, { className: "text-xs", children: r.parent ? _jsxs(_Fragment, { children: [r.parent.label, _jsxs("div", { className: "text-muted-foreground", children: [r.sku, r.parent.existingCount ? ` · ${r.parent.existingCount} ${t('bulk_images.already', { defaultValue: 'ya tiene' })}` : ''] })] }) : '—' }), _jsx(TableCell, { className: "text-xs", children: isImportable(r) && !skip && typeof r.position === 'number' ? (r.position === 0 ? `1 · ${t('bulk_images.main', { defaultValue: 'Principal' })}` : r.position + 1) : '—' }), _jsx(TableCell, { className: "text-xs", children: it ? (it.status === 'done' ? _jsxs("span", { className: "text-emerald-600 inline-flex items-center gap-1", children: [_jsx(Check, { className: "size-3" }), t('bulk_images.uploaded', { defaultValue: 'Subida' })] })
336
+ : it.status === 'error' ? _jsx("span", { className: "text-destructive", title: it.error, children: it.error })
337
+ : _jsx("div", { className: "w-24", children: _jsx(Progress, { value: it.progress * 100 }) })) : (_jsx("span", { className: r.status === 'ok' ? '' : r.status === 'low_res' ? 'text-amber-600' : 'text-destructive', title: r.note, children: statusLabel(r) })) })] }, r.key));
338
+ }) })] }) })] })), _jsxs(DialogFooter, { className: "gap-2", children: [step === 'preview' && (_jsxs(_Fragment, { children: [_jsx(Button, { variant: "outline", onClick: () => { releaseUrls(); setRows([]); setStep('pick'); }, children: t('bulk_images.back', { defaultValue: 'Elegir otros' }) }), _jsx(Button, { disabled: summary.importable === 0, onClick: () => void runImport(), "data-testid": "bulk-image-import", children: t('bulk_images.import', { defaultValue: 'Importar {{n}} fotos', n: summary.importable }) })] })), step === 'importing' && (_jsx(Button, { variant: "outline", onClick: () => { cancelRef.current = true; }, children: t('bulk_images.cancel', { defaultValue: 'Detener' }) })), step === 'done' && log && (_jsxs(_Fragment, { children: [_jsxs(Button, { variant: "ghost", onClick: () => downloadLog(log), children: [_jsx(Download, { className: "size-4 mr-1" }), t('bulk_images.download_log', { defaultValue: 'Descargar registro' })] }), pendingUndo(log).length > 0 && (_jsxs(Button, { variant: "outline", disabled: !!undoing, onClick: () => void undo(log), "data-testid": "bulk-image-undo", children: [_jsx(Undo2, { className: "size-4 mr-1" }), undoing ? `${undoing.done}/${undoing.total}` : t('bulk_images.undo', { defaultValue: 'Deshacer lote' })] })), _jsx(Button, { onClick: () => { releaseUrls(); onOpenChange(false); }, children: t('bulk_images.close', { defaultValue: 'Cerrar' }) })] }))] })] }) }));
339
+ }
@@ -0,0 +1,158 @@
1
+ import type { RelationMeta, TableMetadata } from './types';
2
+ export declare const BULK_IMAGE_EXTENSIONS: readonly ["jpg", "jpeg", "png", "webp", "gif", "avif"];
3
+ /** Lado largo por debajo del cual la foto se avisa como «baja resolución». */
4
+ export declare const DEFAULT_MIN_LONG_SIDE = 600;
5
+ /** Máximo de archivos por lote (la vista previa y la subida viven en memoria). */
6
+ export declare const MAX_BULK_FILES = 500;
7
+ /** Último segmento de una ruta (acepta `/` y `\`). */
8
+ export declare function baseName(path: string): string;
9
+ /** ¿Es una entrada ignorable (carpetas de macOS, archivos ocultos, no-imagen)? */
10
+ export declare function isIgnoredEntry(path: string): boolean;
11
+ export declare function isImageName(name: string): boolean;
12
+ export interface ParsedImageName {
13
+ /** Nombre sin extensión, tal cual. */
14
+ stem: string;
15
+ /** Candidatos de SKU en orden de preferencia, con el número de orden de cada uno. */
16
+ candidates: Array<{
17
+ sku: string;
18
+ order: number;
19
+ }>;
20
+ }
21
+ /**
22
+ * `SKU.ext` → orden 1; `SKU_2.ext` → orden 2. Como un SKU real puede terminar
23
+ * en `_N`, se ofrecen los dos candidatos y gana el que exista en el catálogo
24
+ * (primero el nombre completo).
25
+ */
26
+ export declare function parseImageName(path: string): ParsedImageName;
27
+ export declare const normalizeSku: (s: string) => string;
28
+ /**
29
+ * SKUs a consultar (todos los candidatos, sin repetir), para pedirlos por
30
+ * lotes. El `IN` del servidor distingue mayúsculas, así que se piden también
31
+ * las variantes en MAYÚSCULAS y minúsculas; el cruce local no distingue.
32
+ */
33
+ export declare function collectCandidateSkus(names: string[]): string[];
34
+ export declare function chunk<T>(arr: T[], size: number): T[][];
35
+ export interface BulkImageTarget {
36
+ /** Modelo hijo (galería), p. ej. `product_images`. */
37
+ childModel: string;
38
+ /** FK del hijo hacia el padre. */
39
+ foreignKey: string;
40
+ /** Columna de imagen (la de `gallery: true`). */
41
+ imageKey: string;
42
+ /** Columnas derivadas (si el modelo las tiene). */
43
+ widthKey?: string;
44
+ heightKey?: string;
45
+ positionKey?: string;
46
+ /** Carpeta de almacenamiento (`storage_path` de la columna). */
47
+ storagePath?: string;
48
+ accept: string;
49
+ maxSize?: number;
50
+ /** Filtros de alcance de la relación (polimórficos): se copian a cada fila. */
51
+ scope?: Record<string, string>;
52
+ }
53
+ /**
54
+ * Busca la relación 1:N con galería. Necesita la metadata del hijo (para saber
55
+ * cuál es su columna de imagen); `childMetadata` la resuelve el llamador.
56
+ */
57
+ export declare function deriveBulkImageTarget(relation: Pick<RelationMeta, 'through' | 'foreign_key' | 'scope' | 'kind'>, childMetadata: Pick<TableMetadata, 'columns'> | null | undefined): BulkImageTarget | null;
58
+ export interface ParentRef {
59
+ id: string;
60
+ label: string;
61
+ sku: string;
62
+ /** Mayor `position` ya cargada en su galería (-1 si no tiene fotos: la galería es de base 0). */
63
+ existingMaxPosition: number;
64
+ existingCount: number;
65
+ }
66
+ export type PreviewStatus = 'ok' | 'low_res' | 'sku_not_found' | 'duplicate' | 'invalid_image' | 'too_large';
67
+ export interface PreviewInput {
68
+ /** Ruta completa (puede traer carpetas). */
69
+ path: string;
70
+ size: number;
71
+ width?: number;
72
+ height?: number;
73
+ /** `false` si el navegador no pudo decodificarla. */
74
+ decodable?: boolean;
75
+ }
76
+ export interface PreviewRow extends PreviewInput {
77
+ key: string;
78
+ status: PreviewStatus;
79
+ sku?: string;
80
+ order?: number;
81
+ parent?: ParentRef;
82
+ /** Posición asignada en la galería del padre (solo filas importables). */
83
+ position?: number;
84
+ /** Mensaje corto para la tabla. */
85
+ note?: string;
86
+ }
87
+ export interface PreviewOptions {
88
+ minLongSide?: number;
89
+ maxSize?: number;
90
+ }
91
+ /** ¿La fila se importa por defecto? (`low_res` sí, con aviso; el usuario puede excluirla). */
92
+ export declare const isImportable: (r: PreviewRow) => boolean;
93
+ /**
94
+ * Cruza los archivos con el catálogo. Reglas:
95
+ * - gana el nombre completo; si no existe como SKU, se prueba quitando `_N`;
96
+ * - dos archivos para el mismo SKU y el mismo orden son duplicados (se
97
+ * conserva el primero por ruta; el resto se marca y no se importa);
98
+ * - las fotos de un producto se numeran a continuación de las que ya tiene,
99
+ * en orden de `_N` (y de ruta a igualdad).
100
+ */
101
+ export declare function buildPreview(inputs: PreviewInput[], parentsBySku: Map<string, ParentRef>, opts?: PreviewOptions): PreviewRow[];
102
+ export interface PreviewSummary {
103
+ total: number;
104
+ importable: number;
105
+ products: number;
106
+ ok: number;
107
+ low_res: number;
108
+ sku_not_found: number;
109
+ duplicate: number;
110
+ invalid_image: number;
111
+ too_large: number;
112
+ }
113
+ export declare function summarizePreview(rows: PreviewRow[], excluded?: ReadonlySet<string>): PreviewSummary;
114
+ /**
115
+ * Tras excluir filas a mano, las posiciones se recalculan para no dejar
116
+ * huecos (la 2.ª foto de un producto cuya 1.ª se excluyó pasa a ser la 1.ª).
117
+ */
118
+ export declare function selectForImport(rows: PreviewRow[], excluded: ReadonlySet<string>): PreviewRow[];
119
+ export declare function buildChildPayload(target: BulkImageTarget, row: Pick<PreviewRow, 'parent' | 'position' | 'width' | 'height'>, url: string): Record<string, unknown>;
120
+ export interface BatchLogItem {
121
+ rowId: string;
122
+ path: string;
123
+ sku: string;
124
+ parentId: string;
125
+ url: string;
126
+ undone?: boolean;
127
+ }
128
+ export interface BatchLog {
129
+ batchId: string;
130
+ createdAt: string;
131
+ childModel: string;
132
+ /** Organización/usuario (cacheScope) en que se creó: otro alcance no lo ve ni lo deshace. */
133
+ scope?: string;
134
+ items: BatchLogItem[];
135
+ }
136
+ export declare function newBatchId(now?: Date): string;
137
+ export declare function loadBatchLogs(storage?: Pick<Storage, 'getItem'> | undefined, scope?: string): BatchLog[];
138
+ export declare function saveBatchLog(log: BatchLog, storage?: Pick<Storage, 'getItem' | 'setItem'> | undefined): void;
139
+ /** Filas del lote que aún se pueden deshacer. */
140
+ export declare const pendingUndo: (log: BatchLog) => BatchLogItem[];
141
+ export interface BulkFile {
142
+ path: string;
143
+ file: File;
144
+ }
145
+ /** Máximo descomprimido aceptado por archivo de un ZIP (defensa ante zip-bombs). */
146
+ export declare const MAX_ENTRY_BYTES: number;
147
+ export declare const MAX_TOTAL_BYTES: number;
148
+ /** Descomprime un ZIP en el navegador y devuelve solo las imágenes. */
149
+ export declare function readZipImages(zip: Blob): Promise<{
150
+ files: BulkFile[];
151
+ skipped: number;
152
+ }>;
153
+ /** Normaliza lo que entrega un `<input>` / drop: ZIP o imágenes sueltas/carpeta. */
154
+ export declare function collectBulkFiles(list: File[]): Promise<{
155
+ files: BulkFile[];
156
+ skipped: number;
157
+ }>;
158
+ //# sourceMappingURL=bulk-image-import.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bulk-image-import.d.ts","sourceRoot":"","sources":["../src/bulk-image-import.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAoB,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAG5E,eAAO,MAAM,qBAAqB,wDAAyD,CAAA;AAC3F,8EAA8E;AAC9E,eAAO,MAAM,qBAAqB,MAAM,CAAA;AACxC,kFAAkF;AAClF,eAAO,MAAM,cAAc,MAAM,CAAA;AAMjC,sDAAsD;AACtD,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAG7C;AAED,kFAAkF;AAClF,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAMpD;AAED,wBAAgB,WAAW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