@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,456 @@
|
|
|
1
|
+
// Carga masiva de imágenes a nivel catálogo — lógica pura (sin React).
|
|
2
|
+
//
|
|
3
|
+
// Genérica para cualquier modelo con una galería (relación 1:N cuya columna de
|
|
4
|
+
// imagen declara `display_config.gallery: true`): el archivo `SKU.ext`,
|
|
5
|
+
// `SKU_2.ext`… se asigna al registro padre cuyo campo SKU coincide, y cada
|
|
6
|
+
// archivo crea UNA fila hija. Nada aquí conoce productos, Protek ni el kernel:
|
|
7
|
+
// la unión con el SKU se resuelve contra la API de datos existente.
|
|
8
|
+
import type { ColumnDefinition, RelationMeta, TableMetadata } from './types'
|
|
9
|
+
import { relationColumnUi, relationGalleryColumn } from './dynamic-relation-helpers'
|
|
10
|
+
|
|
11
|
+
export const BULK_IMAGE_EXTENSIONS = ['jpg', 'jpeg', 'png', 'webp', 'gif', 'avif'] as const
|
|
12
|
+
/** Lado largo por debajo del cual la foto se avisa como «baja resolución». */
|
|
13
|
+
export const DEFAULT_MIN_LONG_SIDE = 600
|
|
14
|
+
/** Máximo de archivos por lote (la vista previa y la subida viven en memoria). */
|
|
15
|
+
export const MAX_BULK_FILES = 500
|
|
16
|
+
|
|
17
|
+
// ---------------------------------------------------------------------------
|
|
18
|
+
// Nombres de archivo
|
|
19
|
+
// ---------------------------------------------------------------------------
|
|
20
|
+
|
|
21
|
+
/** Último segmento de una ruta (acepta `/` y `\`). */
|
|
22
|
+
export function baseName(path: string): string {
|
|
23
|
+
const parts = path.split(/[\\/]/)
|
|
24
|
+
return parts[parts.length - 1] ?? ''
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** ¿Es una entrada ignorable (carpetas de macOS, archivos ocultos, no-imagen)? */
|
|
28
|
+
export function isIgnoredEntry(path: string): boolean {
|
|
29
|
+
if (path.endsWith('/') || path.endsWith('\\')) return true
|
|
30
|
+
if (/(^|[\\/])__MACOSX([\\/]|$)/.test(path)) return true
|
|
31
|
+
const name = baseName(path)
|
|
32
|
+
if (name === '' || name.startsWith('.')) return true
|
|
33
|
+
return !isImageName(name)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function isImageName(name: string): boolean {
|
|
37
|
+
const ext = name.split('.').pop()?.toLowerCase() ?? ''
|
|
38
|
+
return (BULK_IMAGE_EXTENSIONS as readonly string[]).includes(ext)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface ParsedImageName {
|
|
42
|
+
/** Nombre sin extensión, tal cual. */
|
|
43
|
+
stem: string
|
|
44
|
+
/** Candidatos de SKU en orden de preferencia, con el número de orden de cada uno. */
|
|
45
|
+
candidates: Array<{ sku: string; order: number }>
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* `SKU.ext` → orden 1; `SKU_2.ext` → orden 2. Como un SKU real puede terminar
|
|
50
|
+
* en `_N`, se ofrecen los dos candidatos y gana el que exista en el catálogo
|
|
51
|
+
* (primero el nombre completo).
|
|
52
|
+
*/
|
|
53
|
+
export function parseImageName(path: string): ParsedImageName {
|
|
54
|
+
const name = baseName(path)
|
|
55
|
+
const dot = name.lastIndexOf('.')
|
|
56
|
+
const stem = (dot > 0 ? name.slice(0, dot) : name).trim()
|
|
57
|
+
const candidates: ParsedImageName['candidates'] = []
|
|
58
|
+
if (stem) candidates.push({ sku: stem, order: 1 })
|
|
59
|
+
const m = /^(.+?)_(\d{1,3})$/.exec(stem)
|
|
60
|
+
if (m) candidates.push({ sku: m[1].trim(), order: Math.max(1, parseInt(m[2], 10)) })
|
|
61
|
+
return { stem, candidates }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export const normalizeSku = (s: string) => s.trim().toLowerCase()
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* SKUs a consultar (todos los candidatos, sin repetir), para pedirlos por
|
|
68
|
+
* lotes. El `IN` del servidor distingue mayúsculas, así que se piden también
|
|
69
|
+
* las variantes en MAYÚSCULAS y minúsculas; el cruce local no distingue.
|
|
70
|
+
*/
|
|
71
|
+
export function collectCandidateSkus(names: string[]): string[] {
|
|
72
|
+
const seen = new Set<string>()
|
|
73
|
+
for (const n of names) {
|
|
74
|
+
for (const c of parseImageName(n).candidates) {
|
|
75
|
+
for (const v of [c.sku, c.sku.toUpperCase(), c.sku.toLowerCase()]) seen.add(v)
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return [...seen]
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function chunk<T>(arr: T[], size: number): T[][] {
|
|
82
|
+
const out: T[][] = []
|
|
83
|
+
for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size))
|
|
84
|
+
return out
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// ---------------------------------------------------------------------------
|
|
88
|
+
// Configuración (descubierta de la metadata, sin tocar el kernel)
|
|
89
|
+
// ---------------------------------------------------------------------------
|
|
90
|
+
|
|
91
|
+
export interface BulkImageTarget {
|
|
92
|
+
/** Modelo hijo (galería), p. ej. `product_images`. */
|
|
93
|
+
childModel: string
|
|
94
|
+
/** FK del hijo hacia el padre. */
|
|
95
|
+
foreignKey: string
|
|
96
|
+
/** Columna de imagen (la de `gallery: true`). */
|
|
97
|
+
imageKey: string
|
|
98
|
+
/** Columnas derivadas (si el modelo las tiene). */
|
|
99
|
+
widthKey?: string
|
|
100
|
+
heightKey?: string
|
|
101
|
+
positionKey?: string
|
|
102
|
+
/** Carpeta de almacenamiento (`storage_path` de la columna). */
|
|
103
|
+
storagePath?: string
|
|
104
|
+
accept: string
|
|
105
|
+
maxSize?: number
|
|
106
|
+
/** Filtros de alcance de la relación (polimórficos): se copian a cada fila. */
|
|
107
|
+
scope?: Record<string, string>
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Busca la relación 1:N con galería. Necesita la metadata del hijo (para saber
|
|
112
|
+
* cuál es su columna de imagen); `childMetadata` la resuelve el llamador.
|
|
113
|
+
*/
|
|
114
|
+
export function deriveBulkImageTarget(
|
|
115
|
+
relation: Pick<RelationMeta, 'through' | 'foreign_key' | 'scope' | 'kind'>,
|
|
116
|
+
childMetadata: Pick<TableMetadata, 'columns'> | null | undefined,
|
|
117
|
+
): BulkImageTarget | null {
|
|
118
|
+
if (relation.kind !== 'one_to_many') return null
|
|
119
|
+
const img: ColumnDefinition | undefined = relationGalleryColumn(childMetadata)
|
|
120
|
+
if (!img) return null
|
|
121
|
+
// Sin la FK declarada el listado ignoraría `f_<fk>=in:` en silencio y devolvería todo.
|
|
122
|
+
if (!(childMetadata?.columns ?? []).some((c) => c.key === relation.foreign_key)) return null
|
|
123
|
+
const sc = (img.styleConfig ?? {}) as Record<string, unknown>
|
|
124
|
+
const keyOf = (derive: string) =>
|
|
125
|
+
(childMetadata?.columns ?? []).find((c) => relationColumnUi(c).derive === derive)?.key
|
|
126
|
+
const storagePath = (sc.storage_path ?? sc.storagePath) as string | undefined
|
|
127
|
+
return {
|
|
128
|
+
childModel: relation.through,
|
|
129
|
+
foreignKey: relation.foreign_key,
|
|
130
|
+
imageKey: img.key,
|
|
131
|
+
widthKey: keyOf('image_width'),
|
|
132
|
+
heightKey: keyOf('image_height'),
|
|
133
|
+
positionKey: keyOf('next_position') ?? (childMetadata?.columns ?? []).find((c) => c.key === 'position')?.key,
|
|
134
|
+
storagePath: typeof storagePath === 'string' && storagePath ? storagePath : undefined,
|
|
135
|
+
accept: (img as { accept?: string }).accept || 'image/*',
|
|
136
|
+
maxSize: (img as { maxSize?: number; max_size?: number }).maxSize ?? (img as { max_size?: number }).max_size,
|
|
137
|
+
scope: relation.scope,
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// ---------------------------------------------------------------------------
|
|
142
|
+
// Vista previa
|
|
143
|
+
// ---------------------------------------------------------------------------
|
|
144
|
+
|
|
145
|
+
export interface ParentRef {
|
|
146
|
+
id: string
|
|
147
|
+
label: string
|
|
148
|
+
sku: string
|
|
149
|
+
/** Mayor `position` ya cargada en su galería (-1 si no tiene fotos: la galería es de base 0). */
|
|
150
|
+
existingMaxPosition: number
|
|
151
|
+
existingCount: number
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export type PreviewStatus =
|
|
155
|
+
| 'ok'
|
|
156
|
+
| 'low_res'
|
|
157
|
+
| 'sku_not_found'
|
|
158
|
+
| 'duplicate'
|
|
159
|
+
| 'invalid_image'
|
|
160
|
+
| 'too_large'
|
|
161
|
+
|
|
162
|
+
export interface PreviewInput {
|
|
163
|
+
/** Ruta completa (puede traer carpetas). */
|
|
164
|
+
path: string
|
|
165
|
+
size: number
|
|
166
|
+
width?: number
|
|
167
|
+
height?: number
|
|
168
|
+
/** `false` si el navegador no pudo decodificarla. */
|
|
169
|
+
decodable?: boolean
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export interface PreviewRow extends PreviewInput {
|
|
173
|
+
key: string
|
|
174
|
+
status: PreviewStatus
|
|
175
|
+
sku?: string
|
|
176
|
+
order?: number
|
|
177
|
+
parent?: ParentRef
|
|
178
|
+
/** Posición asignada en la galería del padre (solo filas importables). */
|
|
179
|
+
position?: number
|
|
180
|
+
/** Mensaje corto para la tabla. */
|
|
181
|
+
note?: string
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export interface PreviewOptions {
|
|
185
|
+
minLongSide?: number
|
|
186
|
+
maxSize?: number
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** ¿La fila se importa por defecto? (`low_res` sí, con aviso; el usuario puede excluirla). */
|
|
190
|
+
export const isImportable = (r: PreviewRow) => r.status === 'ok' || r.status === 'low_res'
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Cruza los archivos con el catálogo. Reglas:
|
|
194
|
+
* - gana el nombre completo; si no existe como SKU, se prueba quitando `_N`;
|
|
195
|
+
* - dos archivos para el mismo SKU y el mismo orden son duplicados (se
|
|
196
|
+
* conserva el primero por ruta; el resto se marca y no se importa);
|
|
197
|
+
* - las fotos de un producto se numeran a continuación de las que ya tiene,
|
|
198
|
+
* en orden de `_N` (y de ruta a igualdad).
|
|
199
|
+
*/
|
|
200
|
+
export function buildPreview(
|
|
201
|
+
inputs: PreviewInput[],
|
|
202
|
+
parentsBySku: Map<string, ParentRef>,
|
|
203
|
+
opts: PreviewOptions = {},
|
|
204
|
+
): PreviewRow[] {
|
|
205
|
+
const minLong = opts.minLongSide ?? DEFAULT_MIN_LONG_SIDE
|
|
206
|
+
const rows: PreviewRow[] = inputs
|
|
207
|
+
.slice()
|
|
208
|
+
.sort((a, b) => a.path.localeCompare(b.path, undefined, { numeric: true }))
|
|
209
|
+
.map((inp, i) => {
|
|
210
|
+
const base: PreviewRow = { ...inp, key: `${i}:${inp.path}`, status: 'ok' }
|
|
211
|
+
if (inp.decodable === false) return { ...base, status: 'invalid_image', note: 'No es una imagen válida' }
|
|
212
|
+
if (opts.maxSize && inp.size > opts.maxSize) return { ...base, status: 'too_large', note: 'Excede el tamaño máximo' }
|
|
213
|
+
const parsed = parseImageName(inp.path)
|
|
214
|
+
for (const c of parsed.candidates) {
|
|
215
|
+
const parent = parentsBySku.get(normalizeSku(c.sku))
|
|
216
|
+
if (parent) {
|
|
217
|
+
const long = Math.max(inp.width ?? 0, inp.height ?? 0)
|
|
218
|
+
const lowRes = long > 0 && long < minLong
|
|
219
|
+
return {
|
|
220
|
+
...base,
|
|
221
|
+
sku: parent.sku,
|
|
222
|
+
order: c.order,
|
|
223
|
+
parent,
|
|
224
|
+
status: lowRes ? 'low_res' : 'ok',
|
|
225
|
+
note: lowRes ? `Baja resolución (${inp.width}×${inp.height})` : undefined,
|
|
226
|
+
} as PreviewRow
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return { ...base, sku: parsed.stem, status: 'sku_not_found', note: 'SKU no encontrado' }
|
|
230
|
+
})
|
|
231
|
+
|
|
232
|
+
// Duplicados: mismo producto + mismo orden.
|
|
233
|
+
const seen = new Set<string>()
|
|
234
|
+
for (const r of rows) {
|
|
235
|
+
if (!r.parent) continue
|
|
236
|
+
const k = `${r.parent.id}#${r.order}`
|
|
237
|
+
if (seen.has(k)) {
|
|
238
|
+
r.status = 'duplicate'
|
|
239
|
+
r.note = `Duplicado: ya hay otra foto ${r.order === 1 ? 'principal' : `_${r.order}`} para ${r.parent.sku}`
|
|
240
|
+
} else {
|
|
241
|
+
seen.add(k)
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// Posiciones consecutivas por producto, a continuación de las existentes.
|
|
246
|
+
const byParent = new Map<string, PreviewRow[]>()
|
|
247
|
+
for (const r of rows) {
|
|
248
|
+
if (!r.parent || !isImportable(r)) continue
|
|
249
|
+
const list = byParent.get(r.parent.id) ?? []
|
|
250
|
+
list.push(r)
|
|
251
|
+
byParent.set(r.parent.id, list)
|
|
252
|
+
}
|
|
253
|
+
for (const list of byParent.values()) {
|
|
254
|
+
list.sort((a, b) => (a.order ?? 1) - (b.order ?? 1) || a.path.localeCompare(b.path, undefined, { numeric: true }))
|
|
255
|
+
list.forEach((r, i) => {
|
|
256
|
+
r.position = (r.parent?.existingMaxPosition ?? -1) + i + 1
|
|
257
|
+
})
|
|
258
|
+
}
|
|
259
|
+
return rows
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export interface PreviewSummary {
|
|
263
|
+
total: number
|
|
264
|
+
importable: number
|
|
265
|
+
products: number
|
|
266
|
+
ok: number
|
|
267
|
+
low_res: number
|
|
268
|
+
sku_not_found: number
|
|
269
|
+
duplicate: number
|
|
270
|
+
invalid_image: number
|
|
271
|
+
too_large: number
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
export function summarizePreview(rows: PreviewRow[], excluded?: ReadonlySet<string>): PreviewSummary {
|
|
275
|
+
const s: PreviewSummary = {
|
|
276
|
+
total: rows.length, importable: 0, products: 0, ok: 0, low_res: 0,
|
|
277
|
+
sku_not_found: 0, duplicate: 0, invalid_image: 0, too_large: 0,
|
|
278
|
+
}
|
|
279
|
+
const parents = new Set<string>()
|
|
280
|
+
for (const r of rows) {
|
|
281
|
+
s[r.status] += 1
|
|
282
|
+
if (isImportable(r) && !excluded?.has(r.key)) {
|
|
283
|
+
s.importable += 1
|
|
284
|
+
if (r.parent) parents.add(r.parent.id)
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
s.products = parents.size
|
|
288
|
+
return s
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Tras excluir filas a mano, las posiciones se recalculan para no dejar
|
|
293
|
+
* huecos (la 2.ª foto de un producto cuya 1.ª se excluyó pasa a ser la 1.ª).
|
|
294
|
+
*/
|
|
295
|
+
export function selectForImport(rows: PreviewRow[], excluded: ReadonlySet<string>): PreviewRow[] {
|
|
296
|
+
const byOrder = (a: PreviewRow, b: PreviewRow) =>
|
|
297
|
+
(a.order ?? 1) - (b.order ?? 1) || a.path.localeCompare(b.path, undefined, { numeric: true })
|
|
298
|
+
// Mismo criterio que buildPreview: dentro de cada producto manda `_N`, no la ruta.
|
|
299
|
+
const picked = rows.filter((r) => isImportable(r) && !excluded.has(r.key)).sort(byOrder)
|
|
300
|
+
const counter = new Map<string, number>()
|
|
301
|
+
return picked.map((r) => {
|
|
302
|
+
const n = (counter.get(r.parent!.id) ?? 0) + 1
|
|
303
|
+
counter.set(r.parent!.id, n)
|
|
304
|
+
return { ...r, position: r.parent!.existingMaxPosition + n }
|
|
305
|
+
})
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// ---------------------------------------------------------------------------
|
|
309
|
+
// Cuerpo de la fila hija
|
|
310
|
+
// ---------------------------------------------------------------------------
|
|
311
|
+
|
|
312
|
+
export function buildChildPayload(
|
|
313
|
+
target: BulkImageTarget,
|
|
314
|
+
row: Pick<PreviewRow, 'parent' | 'position' | 'width' | 'height'>,
|
|
315
|
+
url: string,
|
|
316
|
+
): Record<string, unknown> {
|
|
317
|
+
const out: Record<string, unknown> = {
|
|
318
|
+
...(target.scope || {}),
|
|
319
|
+
[target.imageKey]: url,
|
|
320
|
+
[target.foreignKey]: row.parent!.id,
|
|
321
|
+
}
|
|
322
|
+
if (target.positionKey && typeof row.position === 'number') out[target.positionKey] = row.position
|
|
323
|
+
if (target.widthKey && row.width) out[target.widthKey] = Math.round(row.width)
|
|
324
|
+
if (target.heightKey && row.height) out[target.heightKey] = Math.round(row.height)
|
|
325
|
+
return out
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// ---------------------------------------------------------------------------
|
|
329
|
+
// Registro de lote (deshacer)
|
|
330
|
+
// ---------------------------------------------------------------------------
|
|
331
|
+
|
|
332
|
+
export interface BatchLogItem {
|
|
333
|
+
rowId: string
|
|
334
|
+
path: string
|
|
335
|
+
sku: string
|
|
336
|
+
parentId: string
|
|
337
|
+
url: string
|
|
338
|
+
undone?: boolean
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
export interface BatchLog {
|
|
342
|
+
batchId: string
|
|
343
|
+
createdAt: string
|
|
344
|
+
childModel: string
|
|
345
|
+
/** Organización/usuario (cacheScope) en que se creó: otro alcance no lo ve ni lo deshace. */
|
|
346
|
+
scope?: string
|
|
347
|
+
items: BatchLogItem[]
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
const LOG_KEY = 'metacore.bulk-image-batches.v1'
|
|
351
|
+
const MAX_LOGS = 10
|
|
352
|
+
|
|
353
|
+
export function newBatchId(now: Date = new Date()): string {
|
|
354
|
+
return `bulk-${now.toISOString().replace(/[-:.TZ]/g, '').slice(0, 14)}-${Math.random().toString(36).slice(2, 6)}`
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
export function loadBatchLogs(storage: Pick<Storage, 'getItem'> | undefined = safeStorage(), scope?: string): BatchLog[] {
|
|
358
|
+
try {
|
|
359
|
+
const raw = storage?.getItem(LOG_KEY)
|
|
360
|
+
const parsed = raw ? JSON.parse(raw) : []
|
|
361
|
+
if (!Array.isArray(parsed)) return []
|
|
362
|
+
// Con `scope`, solo los lotes de esa organización/usuario.
|
|
363
|
+
return scope === undefined ? parsed : parsed.filter((l: BatchLog) => !!l.scope && l.scope === scope)
|
|
364
|
+
} catch {
|
|
365
|
+
return []
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
export function saveBatchLog(log: BatchLog, storage: Pick<Storage, 'getItem' | 'setItem'> | undefined = safeStorage()): void {
|
|
370
|
+
try {
|
|
371
|
+
const all = loadBatchLogs(storage).filter((l) => l.batchId !== log.batchId)
|
|
372
|
+
all.unshift(log)
|
|
373
|
+
storage?.setItem(LOG_KEY, JSON.stringify(all.slice(0, MAX_LOGS)))
|
|
374
|
+
} catch {
|
|
375
|
+
/* almacenamiento no disponible: el registro descargable sigue siendo válido */
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function safeStorage(): Storage | undefined {
|
|
380
|
+
try {
|
|
381
|
+
return typeof localStorage !== 'undefined' ? localStorage : undefined
|
|
382
|
+
} catch {
|
|
383
|
+
return undefined
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** Filas del lote que aún se pueden deshacer. */
|
|
388
|
+
export const pendingUndo = (log: BatchLog) => log.items.filter((i) => !i.undone)
|
|
389
|
+
|
|
390
|
+
// ---------------------------------------------------------------------------
|
|
391
|
+
// Entradas: ZIP y carpeta
|
|
392
|
+
// ---------------------------------------------------------------------------
|
|
393
|
+
|
|
394
|
+
export interface BulkFile {
|
|
395
|
+
path: string
|
|
396
|
+
file: File
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
const MIME_BY_EXT: Record<string, string> = {
|
|
400
|
+
jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', webp: 'image/webp', gif: 'image/gif', avif: 'image/avif',
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/** Máximo descomprimido aceptado por archivo de un ZIP (defensa ante zip-bombs). */
|
|
404
|
+
export const MAX_ENTRY_BYTES = 25 * 1024 * 1024
|
|
405
|
+
export const MAX_TOTAL_BYTES = 400 * 1024 * 1024
|
|
406
|
+
|
|
407
|
+
/** Descomprime un ZIP en el navegador y devuelve solo las imágenes. */
|
|
408
|
+
export async function readZipImages(zip: Blob): Promise<{ files: BulkFile[]; skipped: number }> {
|
|
409
|
+
const { unzipSync } = await import('fflate')
|
|
410
|
+
const data = new Uint8Array(await zip.arrayBuffer())
|
|
411
|
+
let total = 0
|
|
412
|
+
let skipped = 0
|
|
413
|
+
const files: BulkFile[] = []
|
|
414
|
+
const entries = unzipSync(data, {
|
|
415
|
+
filter: (f) => {
|
|
416
|
+
if (f.name.endsWith('/')) return false
|
|
417
|
+
// Solo almacenado (0) o deflate (8): deflate64/cifrado abortarían todo el ZIP.
|
|
418
|
+
if (isIgnoredEntry(f.name) || (f.compression !== 0 && f.compression !== 8)) {
|
|
419
|
+
skipped += 1
|
|
420
|
+
return false
|
|
421
|
+
}
|
|
422
|
+
total += f.originalSize
|
|
423
|
+
if (f.originalSize > MAX_ENTRY_BYTES || total > MAX_TOTAL_BYTES) {
|
|
424
|
+
skipped += 1
|
|
425
|
+
return false
|
|
426
|
+
}
|
|
427
|
+
return true
|
|
428
|
+
},
|
|
429
|
+
})
|
|
430
|
+
for (const [path, bytes] of Object.entries(entries)) {
|
|
431
|
+
const ext = path.split('.').pop()?.toLowerCase() ?? ''
|
|
432
|
+
files.push({ path, file: new File([bytes as BlobPart], baseName(path), { type: MIME_BY_EXT[ext] ?? '' }) })
|
|
433
|
+
}
|
|
434
|
+
return { files, skipped }
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/** Normaliza lo que entrega un `<input>` / drop: ZIP o imágenes sueltas/carpeta. */
|
|
438
|
+
export async function collectBulkFiles(list: File[]): Promise<{ files: BulkFile[]; skipped: number }> {
|
|
439
|
+
const files: BulkFile[] = []
|
|
440
|
+
let skipped = 0
|
|
441
|
+
for (const f of list) {
|
|
442
|
+
if (/\.zip$/i.test(f.name) || f.type === 'application/zip' || f.type === 'application/x-zip-compressed') {
|
|
443
|
+
const z = await readZipImages(f)
|
|
444
|
+
files.push(...z.files)
|
|
445
|
+
skipped += z.skipped
|
|
446
|
+
continue
|
|
447
|
+
}
|
|
448
|
+
const rel = (f as File & { webkitRelativePath?: string }).webkitRelativePath || f.name
|
|
449
|
+
if (isIgnoredEntry(rel)) {
|
|
450
|
+
skipped += 1
|
|
451
|
+
continue
|
|
452
|
+
}
|
|
453
|
+
files.push({ path: rel, file: f })
|
|
454
|
+
}
|
|
455
|
+
return { files, skipped }
|
|
456
|
+
}
|
|
@@ -44,6 +44,7 @@ import { ExportDialog } from './dialogs/export'
|
|
|
44
44
|
import { ImportDialog } from './dialogs/import'
|
|
45
45
|
import { getModelExtension } from './model-extension-registry'
|
|
46
46
|
import { ModelActionToolbar } from './model-action-toolbar'
|
|
47
|
+
import { BulkImageImportButton } from './bulk-image-dialog'
|
|
47
48
|
import { resolveListPrimaryAction } from './list-primary-action'
|
|
48
49
|
import { useCan, modelCapability } from './permissions-context'
|
|
49
50
|
import type { DocumentFormsManifest, TableMetadata } from './types'
|
|
@@ -291,6 +292,7 @@ export function DynamicCRUDPage(props: DynamicCRUDPageProps) {
|
|
|
291
292
|
{strings.import}
|
|
292
293
|
</button>
|
|
293
294
|
)}
|
|
295
|
+
{metadata && !scoped.hideCreate && can(modelCapability(model, 'create')) && <BulkImageImportButton model={model} metadata={metadata} onChange={handleRefresh} />}
|
|
294
296
|
{ext?.toolbarExtras && <ext.toolbarExtras model={model} onRefresh={handleRefresh} />}
|
|
295
297
|
{toolbarExtras}
|
|
296
298
|
<ModelActionToolbar
|
package/src/dynamic-form.tsx
CHANGED
|
@@ -73,6 +73,12 @@ export interface DynamicFormProps {
|
|
|
73
73
|
* debe ser flex-col con alto máximo (p.ej. `max-h-[90dvh]`).
|
|
74
74
|
*/
|
|
75
75
|
scrollableBody?: boolean
|
|
76
|
+
/**
|
|
77
|
+
* Side data an upload widget learned about the file it stored (an image's
|
|
78
|
+
* natural width/height). Lets the host fill derived columns that are not
|
|
79
|
+
* form inputs. Optional; forms without it behave as before.
|
|
80
|
+
*/
|
|
81
|
+
onFieldMeta?: (key: string, meta: { width?: number; height?: number }) => void
|
|
76
82
|
}
|
|
77
83
|
|
|
78
84
|
// Valores iniciales del formulario: el registro (edición) gana sobre el default
|
|
@@ -105,6 +111,7 @@ export function DynamicForm({
|
|
|
105
111
|
disabled = false,
|
|
106
112
|
formLayout,
|
|
107
113
|
scrollableBody = false,
|
|
114
|
+
onFieldMeta,
|
|
108
115
|
}: DynamicFormProps) {
|
|
109
116
|
const [errors, setErrors] = useState<Record<string, string>>({})
|
|
110
117
|
const [submitting, setSubmitting] = useState(false)
|
|
@@ -226,6 +233,7 @@ export function DynamicForm({
|
|
|
226
233
|
values={values}
|
|
227
234
|
error={errors[field.key]}
|
|
228
235
|
initialValues={initialValues}
|
|
236
|
+
onFieldMeta={onFieldMeta}
|
|
229
237
|
/>
|
|
230
238
|
))}
|
|
231
239
|
</div>
|
|
@@ -343,6 +351,7 @@ interface FieldRendererProps {
|
|
|
343
351
|
* gate its options by a sibling field's value (`applyOptionWhen`).
|
|
344
352
|
*/
|
|
345
353
|
values?: Record<string, any>
|
|
354
|
+
onFieldMeta?: (key: string, meta: { width?: number; height?: number }) => void
|
|
346
355
|
}
|
|
347
356
|
|
|
348
357
|
interface FieldRowProps extends FieldRendererProps {
|
|
@@ -353,7 +362,7 @@ interface FieldRowProps extends FieldRendererProps {
|
|
|
353
362
|
// component so a STATIC enum select whose options are all gated out by a sibling
|
|
354
363
|
// value (`when`) can hide the ENTIRE row (label included) and run its reset
|
|
355
364
|
// effect with valid hook ordering.
|
|
356
|
-
function FieldRow({ field, value, onChange, values, error, initialValues }: FieldRowProps) {
|
|
365
|
+
function FieldRow({ field, value, onChange, values, error, initialValues, onFieldMeta }: FieldRowProps) {
|
|
357
366
|
const isStaticSelect =
|
|
358
367
|
resolveWidget(field) === 'select' && !field.ref && Array.isArray(field.options)
|
|
359
368
|
const effectiveOptions = isStaticSelect
|
|
@@ -390,6 +399,7 @@ function FieldRow({ field, value, onChange, values, error, initialValues }: Fiel
|
|
|
390
399
|
values={values}
|
|
391
400
|
effectiveOptions={effectiveOptions}
|
|
392
401
|
error={error}
|
|
402
|
+
onFieldMeta={onFieldMeta}
|
|
393
403
|
/>
|
|
394
404
|
{error && <span className="text-red-500 text-sm" role="alert">{error}</span>}
|
|
395
405
|
</div>
|
|
@@ -431,6 +441,7 @@ function FieldRenderer({
|
|
|
431
441
|
values,
|
|
432
442
|
effectiveOptions,
|
|
433
443
|
error,
|
|
444
|
+
onFieldMeta,
|
|
434
445
|
}: FieldRendererProps & { effectiveOptions?: import('./types').OptionDef[]; error?: string }) {
|
|
435
446
|
// Host-registered widget (`widget: "<name>"`) wins over every built-in and
|
|
436
447
|
// type-based branch. Unregistered names fall through untouched.
|
|
@@ -461,7 +472,14 @@ function FieldRenderer({
|
|
|
461
472
|
// File upload → themed picker that POSTs to the host upload endpoint and
|
|
462
473
|
// stores the returned file url/path as the field value.
|
|
463
474
|
if (widget === 'upload') {
|
|
464
|
-
return
|
|
475
|
+
return (
|
|
476
|
+
<UploadField
|
|
477
|
+
field={field}
|
|
478
|
+
value={value}
|
|
479
|
+
onChange={onChange}
|
|
480
|
+
onFileMeta={onFieldMeta ? (meta) => onFieldMeta(field.key, meta) : undefined}
|
|
481
|
+
/>
|
|
482
|
+
)
|
|
465
483
|
}
|
|
466
484
|
// Icon picker → lucide glyph search grid, with an "Imagen" mode that
|
|
467
485
|
// delegates to the same UploadField as `upload`. Stores a plain string:
|