@asteby/metacore-runtime-react 53.10.2 → 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.
- package/CHANGELOG.md +42 -0
- package/dist/bulk-image-dialog.d.ts +31 -0
- package/dist/bulk-image-dialog.d.ts.map +1 -0
- package/dist/bulk-image-dialog.js +339 -0
- package/dist/bulk-image-import.d.ts +158 -0
- package/dist/bulk-image-import.d.ts.map +1 -0
- package/dist/bulk-image-import.js +310 -0
- package/dist/dynamic-crud-page.d.ts.map +1 -1
- package/dist/dynamic-crud-page.js +2 -1
- package/dist/dynamic-form.d.ts +10 -1
- package/dist/dynamic-form.d.ts.map +1 -1
- package/dist/dynamic-form.js +6 -6
- package/dist/dynamic-relation-helpers.d.ts +65 -0
- package/dist/dynamic-relation-helpers.d.ts.map +1 -1
- package/dist/dynamic-relation-helpers.js +178 -2
- package/dist/dynamic-relation.d.ts +16 -0
- package/dist/dynamic-relation.d.ts.map +1 -1
- package/dist/dynamic-relation.js +277 -13
- package/dist/dynamic-relations.d.ts.map +1 -1
- package/dist/dynamic-relations.js +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/relation-gallery.d.ts +31 -0
- package/dist/relation-gallery.d.ts.map +1 -0
- package/dist/relation-gallery.js +154 -0
- package/dist/upload-field.d.ts +19 -1
- package/dist/upload-field.d.ts.map +1 -1
- package/dist/upload-field.js +50 -3
- package/package.json +2 -1
- package/src/__tests__/bulk-image-dialog.test.tsx +127 -0
- package/src/__tests__/bulk-image-import.test.ts +129 -0
- package/src/__tests__/relation-gallery-helpers.test.ts +154 -0
- package/src/__tests__/relation-gallery.test.tsx +229 -0
- package/src/bulk-image-dialog.tsx +594 -0
- package/src/bulk-image-import.ts +456 -0
- package/src/dynamic-crud-page.tsx +2 -0
- package/src/dynamic-form.tsx +20 -2
- package/src/dynamic-relation-helpers.ts +210 -2
- package/src/dynamic-relation.tsx +329 -15
- package/src/dynamic-relations.tsx +1 -0
- package/src/index.ts +12 -0
- package/src/relation-gallery.tsx +489 -0
- package/src/upload-field.tsx +60 -2
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
2
|
+
// RelationGallery — the thumbnail-grid view of a one_to_many relation whose
|
|
3
|
+
// image column declares `display_config.gallery: true` (e.g. a product's
|
|
4
|
+
// ProductImage rows). Opt-in: DynamicRelation keeps its table for every other
|
|
5
|
+
// relation. Pure UI over callbacks — DynamicRelation owns the API calls, so the
|
|
6
|
+
// `/upload` and `/data` contracts are the ones the table already uses.
|
|
7
|
+
//
|
|
8
|
+
// - Add several photos at once (picker or drag & drop), one progress bar,
|
|
9
|
+
// preview, error and retry per file; type/size limits with clear messages.
|
|
10
|
+
// - Reorder by dragging (pointer or keyboard: Space to lift, arrows to move)
|
|
11
|
+
// or with the explicit move buttons; the first image is the main one.
|
|
12
|
+
// - Delete asks for confirmation, then offers «Deshacer» for a few seconds.
|
|
13
|
+
// - Theme tokens only (bg-card, border, muted…) so it follows dark mode.
|
|
14
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|
15
|
+
import { useTranslation } from 'react-i18next';
|
|
16
|
+
import { DndContext, KeyboardSensor, PointerSensor, closestCenter, useSensor, useSensors, } from '@dnd-kit/core';
|
|
17
|
+
import { SortableContext, arrayMove, rectSortingStrategy, sortableKeyboardCoordinates, useSortable, } from '@dnd-kit/sortable';
|
|
18
|
+
import { CSS } from '@dnd-kit/utilities';
|
|
19
|
+
import { cn } from '@asteby/metacore-ui/lib';
|
|
20
|
+
import { Button } from '@asteby/metacore-ui/primitives';
|
|
21
|
+
import { ArrowLeft, ArrowRight, ImagePlus, Loader2, Pencil, RotateCcw, Star, Trash2, X } from 'lucide-react';
|
|
22
|
+
import { validateUploadFile } from './upload-field';
|
|
23
|
+
let uploadSeq = 0;
|
|
24
|
+
export function RelationGallery({ rows, rowKey, imageKey, captionKey, getImageUrl, accept = 'image/*', maxSize, canCreate = true, canEdit = true, canReorder, canDelete = true, onUpload, onUploadsSettled, onReorder, onEdit, onDelete, hiddenKeys, }) {
|
|
25
|
+
const { t } = useTranslation();
|
|
26
|
+
const inputRef = useRef(null);
|
|
27
|
+
const [dragOver, setDragOver] = useState(false);
|
|
28
|
+
const [uploads, setUploads] = useState([]);
|
|
29
|
+
const reorderable = canReorder ?? canEdit;
|
|
30
|
+
// Every local preview is released when its item goes away or on unmount.
|
|
31
|
+
const uploadsRef = useRef([]);
|
|
32
|
+
uploadsRef.current = uploads;
|
|
33
|
+
const releasePreview = (u) => {
|
|
34
|
+
if (u.preview)
|
|
35
|
+
URL.revokeObjectURL?.(u.preview);
|
|
36
|
+
};
|
|
37
|
+
const keyed = useMemo(() => rows
|
|
38
|
+
.map((row, i) => ({ row, key: rowKey(row, i) }))
|
|
39
|
+
.filter((r) => !hiddenKeys?.has(r.key)), [rows, rowKey, hiddenKeys]);
|
|
40
|
+
const ids = useMemo(() => keyed.map((k) => k.key), [keyed]);
|
|
41
|
+
useEffect(() => () => uploadsRef.current.forEach(releasePreview), []);
|
|
42
|
+
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }), useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }));
|
|
43
|
+
const move = useCallback((from, to) => {
|
|
44
|
+
if (from === to || to < 0 || to >= keyed.length)
|
|
45
|
+
return;
|
|
46
|
+
void onReorder(arrayMove(keyed, from, to).map((k) => k.row));
|
|
47
|
+
}, [keyed, onReorder]);
|
|
48
|
+
const handleDragEnd = useCallback((e) => {
|
|
49
|
+
if (!e.over || e.active.id === e.over.id)
|
|
50
|
+
return;
|
|
51
|
+
move(ids.indexOf(String(e.active.id)), ids.indexOf(String(e.over.id)));
|
|
52
|
+
}, [ids, move]);
|
|
53
|
+
const runUpload = useCallback(async (item) => {
|
|
54
|
+
setUploads((list) => list.map((u) => (u.id === item.id ? { ...u, status: 'uploading', progress: 0, error: undefined } : u)));
|
|
55
|
+
try {
|
|
56
|
+
await onUpload(item.file, item.offset, (fraction) => setUploads((list) => list.map((u) => (u.id === item.id ? { ...u, progress: Math.max(0, Math.min(1, fraction)) } : u))), item.uploadedUrl);
|
|
57
|
+
setUploads((list) => list.map((u) => (u.id === item.id ? { ...u, status: 'done', progress: 1 } : u)));
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
catch (err) {
|
|
61
|
+
const msg = err?.response?.data?.message ||
|
|
62
|
+
err?.message ||
|
|
63
|
+
t('dynamic.gallery.upload_failed', { defaultValue: 'No se pudo subir la foto.' });
|
|
64
|
+
const stored = typeof err?.uploadedUrl === 'string' ? err.uploadedUrl : item.uploadedUrl;
|
|
65
|
+
setUploads((list) => list.map((u) => (u.id === item.id ? { ...u, status: 'error', error: String(msg), uploadedUrl: stored } : u)));
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
}, [onUpload, t]);
|
|
69
|
+
const addFiles = useCallback(async (files) => {
|
|
70
|
+
const picked = Array.from(files ?? []);
|
|
71
|
+
if (picked.length === 0)
|
|
72
|
+
return;
|
|
73
|
+
const accepted = [];
|
|
74
|
+
const rejected = [];
|
|
75
|
+
for (const file of picked) {
|
|
76
|
+
const item = {
|
|
77
|
+
id: `up-${++uploadSeq}`,
|
|
78
|
+
file,
|
|
79
|
+
preview: typeof URL !== 'undefined' && URL.createObjectURL ? URL.createObjectURL(file) : '',
|
|
80
|
+
progress: 0,
|
|
81
|
+
status: 'uploading',
|
|
82
|
+
offset: accepted.length,
|
|
83
|
+
};
|
|
84
|
+
const bad = validateUploadFile(file, { accept, maxSize });
|
|
85
|
+
if (bad === 'type') {
|
|
86
|
+
rejected.push({ ...item, status: 'error', error: t('dynamic.gallery.invalid_type', { defaultValue: 'Formato no permitido. Usa JPG, PNG o WebP.' }) });
|
|
87
|
+
}
|
|
88
|
+
else if (bad === 'size') {
|
|
89
|
+
const mb = ((maxSize ?? 0) / (1024 * 1024)).toFixed(1);
|
|
90
|
+
rejected.push({ ...item, status: 'error', error: t('dynamic.gallery.too_large', { mb, defaultValue: `La foto pesa más de ${mb} MB.` }) });
|
|
91
|
+
}
|
|
92
|
+
else {
|
|
93
|
+
accepted.push(item);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
setUploads((list) => {
|
|
97
|
+
list.filter((u) => u.status === 'done').forEach(releasePreview);
|
|
98
|
+
return [...list.filter((u) => u.status !== 'done'), ...accepted, ...rejected];
|
|
99
|
+
});
|
|
100
|
+
// Sequential: keeps positions in pick order and spares the server.
|
|
101
|
+
let any = false;
|
|
102
|
+
for (const item of accepted) {
|
|
103
|
+
if (await runUpload(item))
|
|
104
|
+
any = true;
|
|
105
|
+
}
|
|
106
|
+
if (any)
|
|
107
|
+
onUploadsSettled?.();
|
|
108
|
+
}, [accept, maxSize, runUpload, onUploadsSettled, t]);
|
|
109
|
+
const retry = useCallback(async (item) => {
|
|
110
|
+
if (await runUpload({ ...item, offset: 0 }))
|
|
111
|
+
onUploadsSettled?.();
|
|
112
|
+
}, [runUpload, onUploadsSettled]);
|
|
113
|
+
const dismiss = useCallback((id) => {
|
|
114
|
+
setUploads((list) => {
|
|
115
|
+
const gone = list.find((u) => u.id === id);
|
|
116
|
+
if (gone)
|
|
117
|
+
releasePreview(gone);
|
|
118
|
+
return list.filter((u) => u.id !== id);
|
|
119
|
+
});
|
|
120
|
+
}, []);
|
|
121
|
+
const pending = uploads.filter((u) => u.status !== 'done');
|
|
122
|
+
// A retry numbers its photo past the rows already refreshed; while a batch
|
|
123
|
+
// is still uploading that list is stale, so retry waits for it.
|
|
124
|
+
const busy = uploads.some((u) => u.status === 'uploading');
|
|
125
|
+
const hintId = useMemo(() => `gallery-hint-${++uploadSeq}`, []);
|
|
126
|
+
const mainLabel = t('dynamic.gallery.main', { defaultValue: 'Principal' });
|
|
127
|
+
return (_jsxs("div", { className: "grid gap-3", "data-relation-view": "gallery", children: [canCreate && (_jsxs("div", { role: "button", tabIndex: 0, "aria-label": t('dynamic.gallery.add', { defaultValue: 'Agregar fotos' }), "aria-describedby": hintId, onClick: () => inputRef.current?.click(), onKeyDown: (e) => {
|
|
128
|
+
if (e.key === 'Enter' || e.key === ' ') {
|
|
129
|
+
e.preventDefault();
|
|
130
|
+
inputRef.current?.click();
|
|
131
|
+
}
|
|
132
|
+
}, onDragOver: (e) => {
|
|
133
|
+
e.preventDefault();
|
|
134
|
+
setDragOver(true);
|
|
135
|
+
}, onDragLeave: () => setDragOver(false), onDrop: (e) => {
|
|
136
|
+
e.preventDefault();
|
|
137
|
+
setDragOver(false);
|
|
138
|
+
void addFiles(e.dataTransfer?.files);
|
|
139
|
+
}, className: cn('flex cursor-pointer flex-col items-center justify-center gap-1 rounded-lg border-2 border-dashed border-muted-foreground/30 px-4 py-6 text-center text-sm text-muted-foreground transition-colors hover:border-primary/50 hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring', dragOver && 'border-primary/60 bg-muted/50'), "data-testid": "gallery-dropzone", children: [_jsx(ImagePlus, { className: "h-6 w-6", "aria-hidden": true }), _jsx("span", { className: "font-medium text-foreground", children: t('dynamic.gallery.add', { defaultValue: 'Agregar fotos' }) }), _jsx("span", { className: "text-xs", id: hintId, children: maxSize
|
|
140
|
+
? t('dynamic.gallery.hint_size', {
|
|
141
|
+
mb: (maxSize / (1024 * 1024)).toFixed(0),
|
|
142
|
+
defaultValue: `Arrastra aquí o elige varias a la vez · JPG, PNG o WebP · hasta ${(maxSize / (1024 * 1024)).toFixed(0)} MB`,
|
|
143
|
+
})
|
|
144
|
+
: t('dynamic.gallery.hint', { defaultValue: 'Arrastra aquí o elige varias a la vez · JPG, PNG o WebP' }) }), _jsx("input", { ref: inputRef, type: "file", accept: accept, multiple: true, className: "hidden", "data-testid": "gallery-input", onChange: (e) => {
|
|
145
|
+
void addFiles(e.target.files);
|
|
146
|
+
e.target.value = '';
|
|
147
|
+
} })] })), pending.length > 0 && (_jsx("ul", { className: "grid gap-2", "aria-live": "polite", "data-testid": "gallery-uploads", children: pending.map((u) => (_jsxs("li", { className: "flex items-center gap-3 rounded-md border bg-card p-2", children: [u.preview ? (_jsx("img", { src: u.preview, alt: "", className: "h-12 w-12 shrink-0 rounded object-cover" })) : (_jsx("div", { className: "h-12 w-12 shrink-0 rounded bg-muted" })), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("div", { className: "truncate text-sm", children: u.file.name }), u.status === 'error' ? (_jsx("div", { className: "text-xs text-destructive", role: "alert", children: u.error })) : (_jsx("div", { className: "mt-1 h-1.5 w-full overflow-hidden rounded bg-muted", role: "progressbar", "aria-label": u.file.name, "aria-valuemin": 0, "aria-valuemax": 100, "aria-valuenow": Math.round(u.progress * 100), children: _jsx("div", { className: "h-full bg-primary transition-all", style: { width: `${Math.round(u.progress * 100)}%` } }) }))] }), u.status === 'uploading' && _jsx(Loader2, { className: "h-4 w-4 animate-spin text-muted-foreground", "aria-hidden": true }), u.status === 'error' && !validateUploadFile(u.file, { accept, maxSize }) && (_jsx(Button, { type: "button", size: "sm", variant: "ghost", disabled: busy, onClick: () => void retry(u), "aria-label": t('dynamic.gallery.retry', { defaultValue: 'Reintentar' }), children: _jsx(RotateCcw, { className: "h-4 w-4" }) })), u.status === 'error' && (_jsx(Button, { type: "button", size: "sm", variant: "ghost", onClick: () => dismiss(u.id), "aria-label": t('dynamic.gallery.dismiss', { defaultValue: 'Quitar' }), children: _jsx(X, { className: "h-4 w-4" }) }))] }, u.id))) })), keyed.length === 0 && !canCreate && pending.length === 0 && (_jsx("div", { className: "rounded-md border bg-muted/30 py-8 text-center text-sm text-muted-foreground", children: t('dynamic.gallery.empty', { defaultValue: 'Sin fotos.' }) })), keyed.length > 0 && (_jsx(DndContext, { sensors: sensors, collisionDetection: closestCenter, onDragEnd: handleDragEnd, children: _jsx(SortableContext, { items: ids, strategy: rectSortingStrategy, children: _jsx("ul", { className: "grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4", "data-testid": "gallery-grid", children: keyed.map(({ row, key }, index) => (_jsx(GalleryTile, { id: key, src: row[imageKey] ? getImageUrl(String(row[imageKey])) : '', caption: captionKey ? String(row[captionKey] ?? '') : '', index: index, total: keyed.length, isMain: index === 0, mainLabel: mainLabel, canEdit: canEdit, canReorder: reorderable, canDelete: canDelete, onMove: (to) => move(index, to), onEdit: onEdit ? () => onEdit(row) : undefined, onDelete: onDelete ? () => onDelete(row) : undefined }, key))) }) }) }))] }));
|
|
148
|
+
}
|
|
149
|
+
function GalleryTile({ id, src, caption, index, total, isMain, mainLabel, canEdit, canReorder, canDelete, onMove, onEdit, onDelete, }) {
|
|
150
|
+
const { t } = useTranslation();
|
|
151
|
+
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id, disabled: !canReorder });
|
|
152
|
+
const label = caption || t('dynamic.gallery.photo', { n: index + 1, defaultValue: `Foto ${index + 1}` });
|
|
153
|
+
return (_jsxs("li", { ref: setNodeRef, style: { transform: CSS.Transform.toString(transform), transition }, className: cn('group relative min-w-0 overflow-hidden rounded-lg border bg-card', isMain && 'ring-2 ring-primary', isDragging && 'z-10 opacity-80 shadow-lg'), "data-testid": "gallery-tile", "data-main": isMain ? 'true' : undefined, children: [_jsx("div", { className: "aspect-square w-full touch-none bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring", ...attributes, ...listeners, "aria-roledescription": t('dynamic.gallery.sortable', { defaultValue: 'foto reordenable' }), "aria-label": `${label}${isMain ? ` · ${mainLabel}` : ''}`, children: src ? (_jsx("img", { src: src, alt: caption, className: "h-full w-full min-h-24 object-cover", draggable: false })) : null }), isMain && (_jsxs("span", { className: "absolute start-2 top-2 inline-flex items-center gap-1 rounded-full bg-primary px-2 py-0.5 text-xs font-medium text-primary-foreground", children: [_jsx(Star, { className: "h-3 w-3", "aria-hidden": true }), mainLabel] })), _jsxs("div", { className: "flex flex-wrap items-center justify-between gap-x-1 border-t bg-card px-1 py-0.5", "data-testid": "gallery-tile-actions", children: [_jsx("div", { className: "flex flex-wrap items-center", children: canReorder && (_jsxs(_Fragment, { children: [_jsx(Button, { type: "button", size: "sm", variant: "ghost", className: "h-8 w-8 p-0", disabled: index === 0, onClick: () => onMove(index - 1), "aria-label": t('dynamic.gallery.move_before', { defaultValue: 'Mover antes' }), children: _jsx(ArrowLeft, { className: "h-4 w-4 rtl:rotate-180" }) }), _jsx(Button, { type: "button", size: "sm", variant: "ghost", className: "h-8 w-8 p-0", disabled: index === total - 1, onClick: () => onMove(index + 1), "aria-label": t('dynamic.gallery.move_after', { defaultValue: 'Mover después' }), children: _jsx(ArrowRight, { className: "h-4 w-4 rtl:rotate-180" }) }), !isMain && (_jsx(Button, { type: "button", size: "sm", variant: "ghost", className: "h-8 w-8 p-0", onClick: () => onMove(0), "aria-label": t('dynamic.gallery.make_main', { defaultValue: 'Hacer principal' }), title: t('dynamic.gallery.make_main', { defaultValue: 'Hacer principal' }), children: _jsx(Star, { className: "h-4 w-4" }) }))] })) }), _jsxs("div", { className: "flex flex-wrap items-center", children: [canEdit && onEdit && (_jsx(Button, { type: "button", size: "sm", variant: "ghost", className: "h-8 w-8 p-0", onClick: onEdit, "aria-label": t('dynamic.gallery.edit', { defaultValue: 'Editar foto' }), children: _jsx(Pencil, { className: "h-4 w-4" }) })), canDelete && onDelete && (_jsx(Button, { type: "button", size: "sm", variant: "ghost", className: "h-8 w-8 p-0 text-destructive", onClick: onDelete, "aria-label": t('dynamic.gallery.delete', { defaultValue: 'Eliminar foto' }), children: _jsx(Trash2, { className: "h-4 w-4" }) }))] })] })] }));
|
|
154
|
+
}
|
package/dist/upload-field.d.ts
CHANGED
|
@@ -3,7 +3,25 @@ export interface UploadFieldProps {
|
|
|
3
3
|
field: ActionFieldDef;
|
|
4
4
|
value: any;
|
|
5
5
|
onChange: (v: any) => void;
|
|
6
|
+
/**
|
|
7
|
+
* Called after a successful upload of an image with its natural size,
|
|
8
|
+
* measured in the browser (no server round-trip, `/upload` contract
|
|
9
|
+
* unchanged). Lets a form fill derived width/height columns.
|
|
10
|
+
*/
|
|
11
|
+
onFileMeta?: (meta: {
|
|
12
|
+
width?: number;
|
|
13
|
+
height?: number;
|
|
14
|
+
}) => void;
|
|
6
15
|
}
|
|
16
|
+
/**
|
|
17
|
+
* Natural pixel size of an image file, measured client-side. Resolves `{}` for
|
|
18
|
+
* a non-image or when the browser cannot decode it — never throws, never
|
|
19
|
+
* guesses.
|
|
20
|
+
*/
|
|
21
|
+
export declare function readImageSize(file: Blob): Promise<{
|
|
22
|
+
width?: number;
|
|
23
|
+
height?: number;
|
|
24
|
+
}>;
|
|
7
25
|
/**
|
|
8
26
|
* Pulls the stored file url/path out of an upload response envelope, tolerating
|
|
9
27
|
* the common key shapes a host might return. Pure — exported for tests.
|
|
@@ -32,5 +50,5 @@ export declare function validateUploadFile(file: {
|
|
|
32
50
|
accept?: string;
|
|
33
51
|
maxSize?: number;
|
|
34
52
|
}): 'type' | 'size' | null;
|
|
35
|
-
export declare function UploadField({ field, value, onChange }: UploadFieldProps): import("react").JSX.Element;
|
|
53
|
+
export declare function UploadField({ field, value, onChange, onFileMeta }: UploadFieldProps): import("react").JSX.Element;
|
|
36
54
|
//# sourceMappingURL=upload-field.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"upload-field.d.ts","sourceRoot":"","sources":["../src/upload-field.tsx"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"upload-field.d.ts","sourceRoot":"","sources":["../src/upload-field.tsx"],"names":[],"mappings":"AAkBA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAE7C,MAAM,WAAW,gBAAgB;IAC7B,KAAK,EAAE,cAAc,CAAA;IACrB,KAAK,EAAE,GAAG,CAAA;IACV,QAAQ,EAAE,CAAC,CAAC,EAAE,GAAG,KAAK,IAAI,CAAA;IAC1B;;;;OAIG;IACH,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI,CAAA;CACnE;AAED;;;;GAIG;AACH,wBAAsB,aAAa,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC;IAAE,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CA0B5F;AASD;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,GAAG,GAAG,MAAM,CAWzD;AAED,+EAA+E;AAC/E,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAK1D;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAahG;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAC9B,IAAI,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,EAClD,IAAI,EAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE,GAC5C,MAAM,GAAG,MAAM,GAAG,IAAI,CAIxB;AAED,wBAAgB,WAAW,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,UAAU,EAAE,EAAE,gBAAgB,+BA8HnF"}
|
package/dist/upload-field.js
CHANGED
|
@@ -16,6 +16,46 @@ import { useTranslation } from 'react-i18next';
|
|
|
16
16
|
import { getUploadConfig } from './dynamic-form-schema';
|
|
17
17
|
import { FilePickButton } from './file-pick-button';
|
|
18
18
|
import { useApi } from './api-context';
|
|
19
|
+
import { useImageUrl } from './image-url-context';
|
|
20
|
+
/**
|
|
21
|
+
* Natural pixel size of an image file, measured client-side. Resolves `{}` for
|
|
22
|
+
* a non-image or when the browser cannot decode it — never throws, never
|
|
23
|
+
* guesses.
|
|
24
|
+
*/
|
|
25
|
+
export async function readImageSize(file) {
|
|
26
|
+
if (!file || !String(file.type || '').startsWith('image/'))
|
|
27
|
+
return {};
|
|
28
|
+
try {
|
|
29
|
+
if (typeof createImageBitmap === 'function') {
|
|
30
|
+
const bmp = await createImageBitmap(file);
|
|
31
|
+
const out = { width: bmp.width, height: bmp.height };
|
|
32
|
+
bmp.close?.();
|
|
33
|
+
if (out.width > 0 && out.height > 0)
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
// fall through to <img>
|
|
39
|
+
}
|
|
40
|
+
if (typeof Image === 'undefined' || typeof URL === 'undefined' || !URL.createObjectURL)
|
|
41
|
+
return {};
|
|
42
|
+
return new Promise((resolve) => {
|
|
43
|
+
const url = URL.createObjectURL(file);
|
|
44
|
+
const img = new Image();
|
|
45
|
+
img.onload = () => {
|
|
46
|
+
URL.revokeObjectURL(url);
|
|
47
|
+
resolve(img.naturalWidth > 0 ? { width: img.naturalWidth, height: img.naturalHeight } : {});
|
|
48
|
+
};
|
|
49
|
+
img.onerror = () => {
|
|
50
|
+
URL.revokeObjectURL(url);
|
|
51
|
+
resolve({});
|
|
52
|
+
};
|
|
53
|
+
img.src = url;
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
function isImageField(field, accept) {
|
|
57
|
+
return field.type === 'image' || (accept ?? '').toLowerCase().split(',').some((t) => t.trim().startsWith('image/'));
|
|
58
|
+
}
|
|
19
59
|
/** Default host upload endpoint. Overridable per-field via `searchEndpoint`. */
|
|
20
60
|
const DEFAULT_UPLOAD_ENDPOINT = '/upload';
|
|
21
61
|
/**
|
|
@@ -78,9 +118,10 @@ export function validateUploadFile(file, opts) {
|
|
|
78
118
|
return 'size';
|
|
79
119
|
return null;
|
|
80
120
|
}
|
|
81
|
-
export function UploadField({ field, value, onChange }) {
|
|
121
|
+
export function UploadField({ field, value, onChange, onFileMeta }) {
|
|
82
122
|
const { t } = useTranslation();
|
|
83
123
|
const api = useApi();
|
|
124
|
+
const getImageUrl = useImageUrl();
|
|
84
125
|
const [uploading, setUploading] = useState(false);
|
|
85
126
|
const [error, setError] = useState(null);
|
|
86
127
|
const { accept, maxSize, storagePath } = getUploadConfig(field);
|
|
@@ -137,6 +178,12 @@ export function UploadField({ field, value, onChange }) {
|
|
|
137
178
|
return;
|
|
138
179
|
}
|
|
139
180
|
onChange(stored);
|
|
181
|
+
if (onFileMeta && isImageField(field, accept)) {
|
|
182
|
+
void readImageSize(file).then((meta) => {
|
|
183
|
+
if (meta.width && meta.height)
|
|
184
|
+
onFileMeta(meta);
|
|
185
|
+
});
|
|
186
|
+
}
|
|
140
187
|
}
|
|
141
188
|
catch (err) {
|
|
142
189
|
setError(err?.response?.data?.message ||
|
|
@@ -145,7 +192,7 @@ export function UploadField({ field, value, onChange }) {
|
|
|
145
192
|
finally {
|
|
146
193
|
setUploading(false);
|
|
147
194
|
}
|
|
148
|
-
}, [api, endpoint, accept, maxSize, storagePath, onChange, t]);
|
|
195
|
+
}, [api, endpoint, accept, maxSize, storagePath, onChange, onFileMeta, field, t]);
|
|
149
196
|
return (_jsxs("div", { className: "grid gap-1.5", "data-widget": "upload", onDragOver: (e) => {
|
|
150
197
|
e.preventDefault();
|
|
151
198
|
}, onDrop: (e) => {
|
|
@@ -154,5 +201,5 @@ export function UploadField({ field, value, onChange }) {
|
|
|
154
201
|
if (!dropped || uploading)
|
|
155
202
|
return;
|
|
156
203
|
void handleFile(dropped);
|
|
157
|
-
}, children: [_jsx(FilePickButton, { id: field.key, accept: accept, loading: uploading, hasFile: hasValue, fileName: hasValue ? uploadedDisplayName(value) : undefined, onFile: (f) => void handleFile(f), pickLabel: field.placeholder || undefined }), error && (_jsx("span", { className: "text-sm text-destructive", role: "alert", children: error }))] }));
|
|
204
|
+
}, children: [hasValue && isImageField(field, accept) && (_jsx("img", { src: getImageUrl(String(value)), alt: "", className: "h-24 w-24 rounded-md border bg-muted object-cover", "data-testid": "upload-preview" })), _jsx(FilePickButton, { id: field.key, accept: accept, loading: uploading, hasFile: hasValue, fileName: hasValue ? uploadedDisplayName(value) : undefined, onFile: (f) => void handleFile(f), pickLabel: field.placeholder || undefined }), error && (_jsx("span", { className: "text-sm text-destructive", role: "alert", children: error }))] }));
|
|
158
205
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@asteby/metacore-runtime-react",
|
|
3
|
-
"version": "53.
|
|
3
|
+
"version": "53.12.0",
|
|
4
4
|
"description": "React runtime for metacore hosts — renders addon contributions dynamically",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -38,6 +38,7 @@
|
|
|
38
38
|
"@dnd-kit/sortable": "^10.0.0",
|
|
39
39
|
"@dnd-kit/utilities": "^3.2.2",
|
|
40
40
|
"@tanstack/react-virtual": "^3.14.13",
|
|
41
|
+
"fflate": "0.8.3",
|
|
41
42
|
"zod": "^4.3.0"
|
|
42
43
|
},
|
|
43
44
|
"peerDependencies": {
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// @vitest-environment happy-dom
|
|
2
|
+
//
|
|
3
|
+
// Asistente de carga masiva: aparece solo si el modelo tiene galería; analiza
|
|
4
|
+
// archivos SKU[_N].ext contra la API de datos, muestra la vista previa (SKU
|
|
5
|
+
// desconocido, duplicado, baja resolución), importa con una fila por foto y
|
|
6
|
+
// deshace borrando solo las filas creadas por el lote.
|
|
7
|
+
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
8
|
+
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
|
9
|
+
import { BulkImageImportButton } from '../bulk-image-dialog'
|
|
10
|
+
import { ApiProvider, type ApiClient } from '../api-context'
|
|
11
|
+
|
|
12
|
+
vi.mock('react-i18next', () => ({
|
|
13
|
+
useTranslation: () => ({
|
|
14
|
+
i18n: { language: 'es' },
|
|
15
|
+
t: (k: string, o?: Record<string, unknown>) =>
|
|
16
|
+
String(o?.defaultValue ?? k).replace(/\{\{(\w+)\}\}/g, (_, n) => String(o?.[n] ?? '')),
|
|
17
|
+
}),
|
|
18
|
+
}))
|
|
19
|
+
|
|
20
|
+
vi.mock('../upload-field', async (orig) => {
|
|
21
|
+
const real: any = await orig()
|
|
22
|
+
return {
|
|
23
|
+
...real,
|
|
24
|
+
readImageSize: vi.fn(async (f: File) => (f.name.startsWith('LOW') ? { width: 100, height: 100 } : { width: 1200, height: 900 })),
|
|
25
|
+
}
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
afterEach(() => { cleanup(); try { localStorage.clear() } catch { /* */ } })
|
|
29
|
+
|
|
30
|
+
const col = (c: Record<string, unknown>) => ({ label: c.key, type: 'text', sortable: false, filterable: false, ...c })
|
|
31
|
+
const parentMeta = (withRel = true) => ({
|
|
32
|
+
columns: [col({ key: 'id' }), col({ key: 'sku' })],
|
|
33
|
+
relations: withRel ? [{ name: 'images', kind: 'one_to_many', through: 'product_images', foreign_key: 'product_id' }] : [],
|
|
34
|
+
})
|
|
35
|
+
const childMeta = {
|
|
36
|
+
columns: [
|
|
37
|
+
col({ key: 'product_id' }),
|
|
38
|
+
col({ key: 'url', cellStyle: 'image_stack', styleConfig: { gallery: true } }),
|
|
39
|
+
col({ key: 'position', styleConfig: { derive: 'next_position' } }),
|
|
40
|
+
col({ key: 'width', styleConfig: { derive: 'image_width' } }),
|
|
41
|
+
col({ key: 'height', styleConfig: { derive: 'image_height' } }),
|
|
42
|
+
],
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function mockApi(withRel = true) {
|
|
46
|
+
let n = 0
|
|
47
|
+
return {
|
|
48
|
+
get: vi.fn((url: string, cfg?: any) => {
|
|
49
|
+
if (url === '/metadata/table/products') return Promise.resolve({ data: { success: true, data: parentMeta(withRel) } })
|
|
50
|
+
if (url === '/metadata/table/product_images') return Promise.resolve({ data: { success: true, data: childMeta } })
|
|
51
|
+
if (url === '/data/products') {
|
|
52
|
+
return Promise.resolve({ data: { success: true, data: [{ id: 'p1', sku: 'A100', name: 'Balata' }, { id: 'p2', sku: 'B200', name: 'Filtro' }] } })
|
|
53
|
+
}
|
|
54
|
+
if (url === '/data/product_images') return Promise.resolve({ data: { success: true, data: [{ id: 'x', product_id: 'p1', position: 4 }] } })
|
|
55
|
+
return Promise.resolve({ data: { success: true, data: [] } })
|
|
56
|
+
}),
|
|
57
|
+
post: vi.fn((url: string) => {
|
|
58
|
+
if (url === '/upload') return Promise.resolve({ data: { success: true, data: { url: `/storage/f${++n}.jpg` } } })
|
|
59
|
+
return Promise.resolve({ data: { success: true, data: { id: `row${++n}` } } })
|
|
60
|
+
}),
|
|
61
|
+
put: vi.fn(),
|
|
62
|
+
delete: vi.fn(() => Promise.resolve({ data: { success: true } })),
|
|
63
|
+
} as unknown as ApiClient & Record<string, any>
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const img = (name: string) => new File([new Uint8Array(10)], name, { type: 'image/jpeg' })
|
|
67
|
+
|
|
68
|
+
function setup(api: ApiClient) {
|
|
69
|
+
return render(<ApiProvider client={api}><BulkImageImportButton model="products" /></ApiProvider>)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
describe('BulkImageImportButton', () => {
|
|
73
|
+
it('no aparece sin galería', async () => {
|
|
74
|
+
const api = mockApi(false)
|
|
75
|
+
setup(api)
|
|
76
|
+
await waitFor(() => expect(api.get).toHaveBeenCalledWith('/metadata/table/products'))
|
|
77
|
+
expect(screen.queryByTestId('bulk-image-open')).toBeNull()
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
it('vista previa, importar con una fila por foto y deshacer solo ese lote', async () => {
|
|
81
|
+
const api = mockApi()
|
|
82
|
+
setup(api)
|
|
83
|
+
fireEvent.click(await screen.findByTestId('bulk-image-open'))
|
|
84
|
+
const input = await screen.findByTestId('bulk-image-input')
|
|
85
|
+
fireEvent.change(input, { target: { files: [img('A100.jpg'), img('A100_2.jpg'), img('B200.jpg'), img('NOPE.jpg'), img('LOWB200_9.jpg')] } })
|
|
86
|
+
|
|
87
|
+
await waitFor(() => expect(screen.getByTestId('bulk-image-summary')).toBeTruthy())
|
|
88
|
+
const summary = screen.getByTestId('bulk-image-summary').textContent!
|
|
89
|
+
expect(summary).toContain('3 fotos para 2 productos')
|
|
90
|
+
expect(summary).toContain('SKU no encontrado')
|
|
91
|
+
// filtro de SKU por la API de datos existente
|
|
92
|
+
const call = api.get.mock.calls.find((c: any[]) => c[0] === '/data/products')!
|
|
93
|
+
expect(call[1].params['f_sku']).toMatch(/^in:/)
|
|
94
|
+
|
|
95
|
+
fireEvent.click(screen.getByTestId('bulk-image-import'))
|
|
96
|
+
await waitFor(() => expect(screen.getByTestId('bulk-image-undo')).toBeTruthy())
|
|
97
|
+
const creates = api.post.mock.calls.filter((c: any[]) => c[0] === '/data/product_images').map((c: any[]) => c[1])
|
|
98
|
+
expect(creates).toHaveLength(3)
|
|
99
|
+
// A100 ya tenía hasta la posición 4: las nuevas van 5 y 6; medidas derivadas
|
|
100
|
+
expect(creates.filter((c: any) => c.product_id === 'p1').map((c: any) => c.position).sort()).toEqual([5, 6])
|
|
101
|
+
expect(creates[0]).toMatchObject({ width: 1200, height: 900 })
|
|
102
|
+
expect(screen.getByTestId('bulk-image-progress').textContent).toContain('3 de 3')
|
|
103
|
+
|
|
104
|
+
fireEvent.click(screen.getByTestId('bulk-image-undo'))
|
|
105
|
+
await waitFor(() => expect(api.delete).toHaveBeenCalledTimes(3))
|
|
106
|
+
const deleted = api.delete.mock.calls.map((c: any[]) => c[0])
|
|
107
|
+
expect(deleted.every((u: string) => /^\/data\/product_images\/row\d+$/.test(u))).toBe(true)
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
it('un error por archivo no tumba el resto', async () => {
|
|
111
|
+
const api = mockApi()
|
|
112
|
+
let k = 0
|
|
113
|
+
const orig = api.post
|
|
114
|
+
api.post = vi.fn((url: string, body?: any, cfg?: any) => {
|
|
115
|
+
if (url === '/upload' && ++k === 1) return Promise.reject(new Error('boom'))
|
|
116
|
+
return orig(url, body, cfg)
|
|
117
|
+
}) as any
|
|
118
|
+
setup(api)
|
|
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')] } })
|
|
121
|
+
await waitFor(() => screen.getByTestId('bulk-image-import'))
|
|
122
|
+
fireEvent.click(screen.getByTestId('bulk-image-import'))
|
|
123
|
+
await waitFor(() => expect(screen.getByTestId('bulk-image-progress').textContent).toContain('1 con error'))
|
|
124
|
+
const creates = (api.post as any).mock.calls.filter((c: any[]) => c[0] === '/data/product_images')
|
|
125
|
+
expect(creates).toHaveLength(1)
|
|
126
|
+
})
|
|
127
|
+
})
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { zipSync } from 'fflate'
|
|
3
|
+
import {
|
|
4
|
+
buildChildPayload, buildPreview, collectBulkFiles, collectCandidateSkus, deriveBulkImageTarget,
|
|
5
|
+
isIgnoredEntry, loadBatchLogs, parseImageName, pendingUndo, saveBatchLog, selectForImport,
|
|
6
|
+
summarizePreview, type ParentRef,
|
|
7
|
+
} from '../bulk-image-import'
|
|
8
|
+
|
|
9
|
+
const parent = (id: string, sku: string, max = -1, count = 0): ParentRef => ({ id, sku, label: sku, existingMaxPosition: max, existingCount: count })
|
|
10
|
+
const map = (...ps: ParentRef[]) => new Map(ps.map((p) => [p.sku.toLowerCase(), p]))
|
|
11
|
+
const inp = (path: string, w = 800, h = 800) => ({ path, size: 1000, width: w, height: h })
|
|
12
|
+
|
|
13
|
+
describe('parseImageName', () => {
|
|
14
|
+
it('SKU.ext y SKU_N.ext', () => {
|
|
15
|
+
expect(parseImageName('a/b/ABC123.jpg').candidates).toEqual([{ sku: 'ABC123', order: 1 }])
|
|
16
|
+
expect(parseImageName('ABC123_2.png').candidates).toEqual([{ sku: 'ABC123_2', order: 1 }, { sku: 'ABC123', order: 2 }])
|
|
17
|
+
})
|
|
18
|
+
it('ignora basura de zips', () => {
|
|
19
|
+
expect(isIgnoredEntry('__MACOSX/x.jpg')).toBe(true)
|
|
20
|
+
expect(isIgnoredEntry('.DS_Store')).toBe(true)
|
|
21
|
+
expect(isIgnoredEntry('fotos/')).toBe(true)
|
|
22
|
+
expect(isIgnoredEntry('notas.txt')).toBe(true)
|
|
23
|
+
expect(isIgnoredEntry('fotos/A.JPG')).toBe(false)
|
|
24
|
+
})
|
|
25
|
+
it('candidatos únicos', () => {
|
|
26
|
+
expect(collectCandidateSkus(['A.jpg', 'A_2.jpg', 'b.jpg']).sort()).toEqual(['A', 'A_2', 'B', 'a', 'a_2', 'b'].sort())
|
|
27
|
+
})
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
describe('buildPreview', () => {
|
|
31
|
+
const A = parent('1', 'A100', 2, 2)
|
|
32
|
+
const B = parent('2', 'B200')
|
|
33
|
+
it('asigna producto, orden y posición a continuación de las existentes', () => {
|
|
34
|
+
const rows = buildPreview([inp('A100_2.jpg'), inp('A100.jpg'), inp('B200.jpg')], map(A, B))
|
|
35
|
+
const a1 = rows.find((r) => r.path === 'A100.jpg')!
|
|
36
|
+
const a2 = rows.find((r) => r.path === 'A100_2.jpg')!
|
|
37
|
+
expect([a1.position, a2.position]).toEqual([3, 4])
|
|
38
|
+
expect(rows.find((r) => r.path === 'B200.jpg')!.position).toBe(0)
|
|
39
|
+
})
|
|
40
|
+
it('SKU no encontrado, baja resolución, duplicado e inválida', () => {
|
|
41
|
+
const rows = buildPreview(
|
|
42
|
+
[inp('ZZZ.jpg'), inp('B200.jpg', 100, 100), inp('x/A100.jpg'), inp('y/A100.jpg'), { path: 'C.png', size: 1, decodable: false }],
|
|
43
|
+
map(A, B),
|
|
44
|
+
)
|
|
45
|
+
const st = Object.fromEntries(rows.map((r) => [r.path, r.status]))
|
|
46
|
+
expect(st['ZZZ.jpg']).toBe('sku_not_found')
|
|
47
|
+
expect(st['B200.jpg']).toBe('low_res')
|
|
48
|
+
expect(st['x/A100.jpg']).toBe('ok')
|
|
49
|
+
expect(st['y/A100.jpg']).toBe('duplicate')
|
|
50
|
+
expect(st['C.png']).toBe('invalid_image')
|
|
51
|
+
const s = summarizePreview(rows)
|
|
52
|
+
expect(s).toMatchObject({ importable: 2, products: 2, duplicate: 1, sku_not_found: 1, low_res: 1, invalid_image: 1 })
|
|
53
|
+
})
|
|
54
|
+
it('SKU que termina en _N gana el nombre completo', () => {
|
|
55
|
+
const X = parent('9', 'KIT_2')
|
|
56
|
+
const rows = buildPreview([inp('KIT_2.jpg')], map(X, parent('8', 'KIT')))
|
|
57
|
+
expect(rows[0].parent?.id).toBe('9')
|
|
58
|
+
expect(rows[0].order).toBe(1)
|
|
59
|
+
})
|
|
60
|
+
it('SKU.jpg y SKU_2.jpg: la principal es la primera aunque la ruta ordene al revés', () => {
|
|
61
|
+
const rows = buildPreview([inp('B200_2.jpg'), inp('B200.jpg')], map(B))
|
|
62
|
+
const sel = selectForImport(rows, new Set())
|
|
63
|
+
const pos = Object.fromEntries(sel.map((r) => [r.path, r.position]))
|
|
64
|
+
expect(pos).toEqual({ 'B200.jpg': 0, 'B200_2.jpg': 1 })
|
|
65
|
+
expect(Object.fromEntries(rows.map((r) => [r.path, r.position]))).toEqual(pos)
|
|
66
|
+
})
|
|
67
|
+
it('SKU_0 y SKU_01 cuentan como orden 1 y chocan con SKU.jpg', () => {
|
|
68
|
+
const rows = buildPreview([inp('B200.jpg'), inp('B200_01.jpg')], map(B))
|
|
69
|
+
expect(rows.filter((r) => r.status === 'duplicate')).toHaveLength(1)
|
|
70
|
+
})
|
|
71
|
+
it('el cruce no distingue mayúsculas', () => {
|
|
72
|
+
const rows = buildPreview([inp('b200.jpg')], map(B))
|
|
73
|
+
expect(rows[0].parent?.id).toBe('2')
|
|
74
|
+
})
|
|
75
|
+
it('excluir a mano recompacta posiciones', () => {
|
|
76
|
+
const rows = buildPreview([inp('B200.jpg'), inp('B200_2.jpg')], map(B))
|
|
77
|
+
const first = rows.find((r) => r.path === 'B200.jpg')!
|
|
78
|
+
const sel = selectForImport(rows, new Set([first.key]))
|
|
79
|
+
expect(sel).toHaveLength(1)
|
|
80
|
+
expect(sel[0].position).toBe(0)
|
|
81
|
+
})
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
describe('buildChildPayload / deriveBulkImageTarget', () => {
|
|
85
|
+
const meta: any = {
|
|
86
|
+
columns: [
|
|
87
|
+
{ key: 'product_id' },
|
|
88
|
+
{ key: 'url', type: 'image', styleConfig: { gallery: true, storage_path: 'products' } },
|
|
89
|
+
{ key: 'width', styleConfig: { derive: 'image_width' } },
|
|
90
|
+
{ key: 'height', styleConfig: { derive: 'image_height' } },
|
|
91
|
+
{ key: 'position', styleConfig: { derive: 'next_position' } },
|
|
92
|
+
],
|
|
93
|
+
}
|
|
94
|
+
it('detecta la galería y arma la fila', () => {
|
|
95
|
+
const t = deriveBulkImageTarget({ kind: 'one_to_many', through: 'product_images', foreign_key: 'product_id' }, meta)!
|
|
96
|
+
expect(t).toMatchObject({ imageKey: 'url', widthKey: 'width', heightKey: 'height', positionKey: 'position', storagePath: 'products' })
|
|
97
|
+
const [row] = buildPreview([inp('A.jpg', 640, 480)], map(parent('1', 'A')))
|
|
98
|
+
expect(buildChildPayload(t, row, '/f/a.jpg')).toEqual({ url: '/f/a.jpg', product_id: '1', position: 0, width: 640, height: 480 })
|
|
99
|
+
})
|
|
100
|
+
it('sin la FK declarada en el hijo = null (el filtro in: se ignoraría)', () => {
|
|
101
|
+
expect(deriveBulkImageTarget({ kind: 'one_to_many', through: 'pi', foreign_key: 'nope' }, meta)).toBeNull()
|
|
102
|
+
})
|
|
103
|
+
it('sin galería = null', () => {
|
|
104
|
+
expect(deriveBulkImageTarget({ kind: 'one_to_many', through: 'x', foreign_key: 'p' }, { columns: [{ key: 'url' }] } as any)).toBeNull()
|
|
105
|
+
})
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
describe('registro de lote', () => {
|
|
109
|
+
it('persiste y filtra lo deshecho', () => {
|
|
110
|
+
const mem: Record<string, string> = {}
|
|
111
|
+
const st = { getItem: (k: string) => mem[k] ?? null, setItem: (k: string, v: string) => { mem[k] = v } }
|
|
112
|
+
const log = { batchId: 'b1', createdAt: 'x', childModel: 'pi', items: [{ rowId: '1', path: 'a', sku: 'A', parentId: '1', url: 'u' }, { rowId: '2', path: 'b', sku: 'B', parentId: '2', url: 'u', undone: true }] }
|
|
113
|
+
saveBatchLog(log, st)
|
|
114
|
+
const back = loadBatchLogs(st)
|
|
115
|
+
expect(back).toHaveLength(1)
|
|
116
|
+
expect(pendingUndo(back[0]).map((i) => i.rowId)).toEqual(['1'])
|
|
117
|
+
})
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
describe('collectBulkFiles', () => {
|
|
121
|
+
it('lee imágenes de un ZIP y descarta lo demás', async () => {
|
|
122
|
+
const zip = zipSync({ 'fotos/A.jpg': new Uint8Array([1, 2, 3]), 'fotos/leeme.txt': new Uint8Array([1]), '__MACOSX/fotos/._A.jpg': new Uint8Array([1]) })
|
|
123
|
+
const f = new File([zip as BlobPart], 'lote.zip', { type: 'application/zip' })
|
|
124
|
+
const { files, skipped } = await collectBulkFiles([f])
|
|
125
|
+
expect(files.map((x) => x.path)).toEqual(['fotos/A.jpg'])
|
|
126
|
+
expect(files[0].file.name).toBe('A.jpg')
|
|
127
|
+
expect(skipped).toBe(2)
|
|
128
|
+
})
|
|
129
|
+
})
|