@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.
@@ -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
@@ -79,6 +79,9 @@ export type RelationDerive = 'image_width' | 'image_height' | 'next_position'
79
79
  * ("Para todas las variantes").
80
80
  * - `gallery: true` (on the image column) → the relation renders as a
81
81
  * thumbnail gallery instead of a table.
82
+ * - `main_from_parent: <k>` (on the image column) → the parent's `<k>` image
83
+ * is the gallery's main photo; while no gallery row holds it, it shows as a
84
+ * read-only first tile.
82
85
  * A column with none of them behaves exactly as before.
83
86
  */
84
87
  export interface RelationColumnUi {
@@ -87,6 +90,8 @@ export interface RelationColumnUi {
87
90
  defaultFromParent?: string
88
91
  emptyLabel?: string
89
92
  gallery?: boolean
93
+ /** Campo del padre cuya imagen es la principal de la galería (p. ej. `image`). */
94
+ mainFromParent?: string
90
95
  }
91
96
 
92
97
  const DERIVES = new Set<RelationDerive>(['image_width', 'image_height', 'next_position'])
@@ -103,6 +108,8 @@ export function relationColumnUi(col: ColumnDefinition): RelationColumnUi {
103
108
  const empty = sc.empty_label ?? sc.emptyLabel
104
109
  if (typeof empty === 'string' && empty.trim() !== '') out.emptyLabel = empty
105
110
  if (sc.gallery === true) out.gallery = true
111
+ const mfp = sc.main_from_parent ?? sc.mainFromParent
112
+ if (typeof mfp === 'string' && mfp.trim() !== '') out.mainFromParent = mfp.trim()
106
113
  return out
107
114
  }
108
115
 
@@ -193,6 +200,45 @@ export function nextRelationPosition(rows: Record<string, any>[], positionKey =
193
200
  return max + 1
194
201
  }
195
202
 
203
+ /**
204
+ * Renumbers a gallery contiguously (0..n-1). Order: current `position`
205
+ * ascending (empty/invalid last); ties — the duplicated positions an older
206
+ * client could leave — go oldest first (`created_at`, then `id`), so a
207
+ * product's original photo stays ahead of the ones uploaded later.
208
+ * `updates` holds only the rows whose stored position differs.
209
+ */
210
+ export function contiguousPositionUpdates(
211
+ rows: Record<string, any>[],
212
+ positionKey = 'position',
213
+ ): { ordered: Record<string, any>[]; updates: Array<{ id: string | number; position: number }> } {
214
+ const pos = (r: Record<string, any>) => {
215
+ const raw = r?.[positionKey]
216
+ const n = Number(raw)
217
+ return raw === null || raw === undefined || raw === '' || !Number.isFinite(n) ? Infinity : n
218
+ }
219
+ const ordered = rows
220
+ .map((r, i) => ({ r, i }))
221
+ .sort((a, b) => {
222
+ const pa = pos(a.r)
223
+ const pb = pos(b.r)
224
+ if (pa !== pb) return pa < pb ? -1 : 1
225
+ const ca = String(a.r?.created_at ?? '')
226
+ const cb = String(b.r?.created_at ?? '')
227
+ if (ca && cb && ca !== cb) return ca < cb ? -1 : 1
228
+ // Last resort: the id, so two tabs (or two runs) agree on the order.
229
+ const ia = String(a.r?.id ?? '')
230
+ const ib = String(b.r?.id ?? '')
231
+ if (ia !== ib) return ia < ib ? -1 : 1
232
+ return a.i - b.i
233
+ })
234
+ .map((x) => x.r)
235
+ const updates: Array<{ id: string | number; position: number }> = []
236
+ ordered.forEach((r, i) => {
237
+ if (pos(r) !== i && r?.id !== undefined && r?.id !== null) updates.push({ id: r.id, position: i })
238
+ })
239
+ return { ordered, updates }
240
+ }
241
+
196
242
  // Pulls a human label off a resolved relation/user object a backend serves:
197
243
  // `{ value, label }` (FK sibling), `{ name, … }` (user object such as
198
244
  // created_by) or `{ title }`. Returns undefined for plain/empty objects so the
@@ -513,3 +559,23 @@ export function pickOptionLabel(
513
559
  if (row.id !== undefined && row.id !== null && row.id !== '') return String(row.id)
514
560
  return '—'
515
561
  }
562
+
563
+ /**
564
+ * The parent's own image (e.g. `Product.image`) when it is the one the store
565
+ * serves first: the image column declares `main_from_parent`, the parent has
566
+ * that image and the gallery has NO rows at all (variant photos included). With
567
+ * any row, the store serves the gallery first, so the first photo is the main
568
+ * one and showing the parent's image as «Principal» would be wrong.
569
+ */
570
+ export function galleryLeadImage(
571
+ imageColumn: ColumnDefinition | undefined,
572
+ parent: Record<string, unknown> | null | undefined,
573
+ rows: Array<Record<string, any>>,
574
+ ): string | undefined {
575
+ if (!imageColumn || !parent || rows.length > 0) return undefined
576
+ const field = relationColumnUi(imageColumn).mainFromParent
577
+ if (!field) return undefined
578
+ const raw = parent[field]
579
+ const url = typeof raw === 'string' ? raw.trim() : ''
580
+ return url || undefined
581
+ }