@asteby/metacore-runtime-react 53.21.1 → 53.22.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 +6 -0
- package/dist/business/line-items.d.ts +1 -1
- package/dist/business/line-items.d.ts.map +1 -1
- package/dist/business/line-items.js +3 -4
- package/dist/dialogs/dynamic-record.d.ts.map +1 -1
- package/dist/dialogs/dynamic-record.js +76 -6
- package/dist/dialogs/inline-relation-rows.d.ts +26 -0
- package/dist/dialogs/inline-relation-rows.d.ts.map +1 -0
- package/dist/dialogs/inline-relation-rows.js +99 -0
- package/dist/dialogs/inline-relations.d.ts +46 -0
- package/dist/dialogs/inline-relations.d.ts.map +1 -0
- package/dist/dialogs/inline-relations.js +79 -0
- package/dist/dialogs/normalize-submit.d.ts +1 -1
- package/dist/dialogs/normalize-submit.d.ts.map +1 -1
- package/dist/dialogs/normalize-submit.js +3 -0
- package/dist/dialogs/use-inline-relations.d.ts +18 -0
- package/dist/dialogs/use-inline-relations.d.ts.map +1 -0
- package/dist/dialogs/use-inline-relations.js +69 -0
- package/dist/draft-rows.d.ts +44 -0
- package/dist/draft-rows.d.ts.map +1 -0
- package/dist/draft-rows.js +70 -0
- package/dist/types.d.ts +11 -0
- package/dist/types.d.ts.map +1 -1
- package/docs/relations.md +17 -0
- package/package.json +5 -5
- package/src/__tests__/draft-rows.test.ts +117 -0
- package/src/__tests__/dynamic-record-edit-payload-upload.test.tsx +8 -6
- package/src/__tests__/dynamic-record-inline-relations.test.tsx +184 -0
- package/src/business/line-items.ts +3 -4
- package/src/dialogs/dynamic-record.tsx +111 -5
- package/src/dialogs/inline-relation-rows.tsx +257 -0
- package/src/dialogs/inline-relations.ts +129 -0
- package/src/dialogs/normalize-submit.ts +4 -0
- package/src/dialogs/use-inline-relations.ts +79 -0
- package/src/draft-rows.ts +113 -0
- package/src/types.ts +11 -0
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// Relaciones hijas capturadas al CREAR el padre (`RelationMeta.create_inline`).
|
|
2
|
+
// Puro (sin React): qué relaciones aplican, qué columnas tiene cada fila,
|
|
3
|
+
// cómo viaja `_children` y cómo se reparten los errores 422
|
|
4
|
+
// `_children.<relación>.<i>.<campo>`.
|
|
5
|
+
import { isManagedRelationColumn } from '../dynamic-relation-helpers'
|
|
6
|
+
import {
|
|
7
|
+
serializeDraftRows,
|
|
8
|
+
type DraftColumn,
|
|
9
|
+
type DraftRow,
|
|
10
|
+
} from '../draft-rows'
|
|
11
|
+
import { localizeFieldIssue, type FieldIssue, type Translate } from '../server-error'
|
|
12
|
+
import type { RelationMeta } from '../types'
|
|
13
|
+
|
|
14
|
+
export const CHILDREN_KEY = '_children'
|
|
15
|
+
|
|
16
|
+
/** ¿Se captura al crear? Solo `create_inline === true` (ausente = no). */
|
|
17
|
+
export const isCreateInline = (rel: Pick<RelationMeta, 'create_inline'>): boolean => rel.create_inline === true
|
|
18
|
+
|
|
19
|
+
/** Mínimo de filas (entero >= 0) servido por el kernel; basura = 0. */
|
|
20
|
+
export function relationMin(rel: Pick<RelationMeta, 'min'>): number {
|
|
21
|
+
const m = Number(rel.min)
|
|
22
|
+
return Number.isFinite(m) && m > 0 ? Math.floor(m) : 0
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Forma mínima del campo hijo que lee el editor (compatible con `FieldDef`). */
|
|
26
|
+
export interface InlineFieldMeta extends DraftColumn {
|
|
27
|
+
[k: string]: any
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Campos capturables de la fila: los del modelo hijo menos la FK al padre y las
|
|
32
|
+
* columnas `scope` (las pone el servidor), auditoría, ocultos y de solo lectura.
|
|
33
|
+
*/
|
|
34
|
+
export function deriveInlineRowFields<T extends { key: string; hidden?: boolean; readonly?: boolean; type?: string }>(
|
|
35
|
+
fields: T[] | undefined,
|
|
36
|
+
relation: Pick<RelationMeta, 'foreign_key' | 'scope'>,
|
|
37
|
+
): T[] {
|
|
38
|
+
const fixed = new Set([relation.foreign_key, ...Object.keys(relation.scope ?? {})])
|
|
39
|
+
return (fields ?? []).filter(
|
|
40
|
+
(f) =>
|
|
41
|
+
!fixed.has(f.key) &&
|
|
42
|
+
!f.hidden &&
|
|
43
|
+
!f.readonly &&
|
|
44
|
+
f.type !== 'hidden' &&
|
|
45
|
+
!isManagedRelationColumn(f.key),
|
|
46
|
+
)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface InlineChildrenInput {
|
|
50
|
+
relation: string
|
|
51
|
+
rows: DraftRow[]
|
|
52
|
+
columns: DraftColumn[]
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Agrega `_children: { [relación]: filas }` al cuerpo. Sin relaciones inline
|
|
57
|
+
* devuelve el MISMO objeto: el cuerpo es idéntico al de siempre.
|
|
58
|
+
*/
|
|
59
|
+
export function withInlineChildren<P extends Record<string, any>>(
|
|
60
|
+
payload: P,
|
|
61
|
+
inline: InlineChildrenInput[],
|
|
62
|
+
): P | (P & { _children: Record<string, Array<Record<string, unknown>>> }) {
|
|
63
|
+
if (inline.length === 0) return payload
|
|
64
|
+
const children: Record<string, Array<Record<string, unknown>>> = {}
|
|
65
|
+
for (const i of inline) children[i.relation] = serializeDraftRows(i.rows, i.columns)
|
|
66
|
+
return { ...payload, [CHILDREN_KEY]: children }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface SplitChildErrors {
|
|
70
|
+
/** Errores que no son de `_children` (campos del padre), tal cual. */
|
|
71
|
+
parent: Record<string, FieldIssue[]>
|
|
72
|
+
/**
|
|
73
|
+
* Errores de hijas ya localizados, con la ruta `"<relación>.<i>.<campo>"`,
|
|
74
|
+
* `"<relación>.<i>"` (fila) o `"<relación>"` (conjunto, p. ej. `min`).
|
|
75
|
+
*/
|
|
76
|
+
children: Record<string, string>
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Separa un mapa 422 en errores del padre y errores de filas hijas. */
|
|
80
|
+
export function splitChildErrors(
|
|
81
|
+
map: Record<string, FieldIssue[]>,
|
|
82
|
+
relations: Array<Pick<RelationMeta, 'name' | 'label'>>,
|
|
83
|
+
fieldLabel: (relation: string, field: string) => string,
|
|
84
|
+
t: Translate,
|
|
85
|
+
language?: string,
|
|
86
|
+
): SplitChildErrors {
|
|
87
|
+
const parent: Record<string, FieldIssue[]> = {}
|
|
88
|
+
const children: Record<string, string> = {}
|
|
89
|
+
// Nombres más largos primero: «a.b» gana sobre «a» si ambos existen.
|
|
90
|
+
const names = [...relations].sort((a, b) => b.name.length - a.name.length)
|
|
91
|
+
const prefix = `${CHILDREN_KEY}.`
|
|
92
|
+
for (const [path, issues] of Object.entries(map)) {
|
|
93
|
+
if (!path.startsWith(prefix)) {
|
|
94
|
+
parent[path] = issues
|
|
95
|
+
continue
|
|
96
|
+
}
|
|
97
|
+
const rest = path.slice(prefix.length)
|
|
98
|
+
const rel = names.find((r) => rest === r.name || rest.startsWith(`${r.name}.`))
|
|
99
|
+
if (!rel) {
|
|
100
|
+
// Relación desconocida: no se pierde, queda como error de conjunto.
|
|
101
|
+
children[rest] = localizeFieldIssue(issues[0]!, rest, t, language)
|
|
102
|
+
continue
|
|
103
|
+
}
|
|
104
|
+
const tail = rest.slice(rel.name.length + 1) // "" | "<i>" | "<i>.<campo>"
|
|
105
|
+
const issue = issues[0]!
|
|
106
|
+
const relLabel = rel.label || rel.name
|
|
107
|
+
if (!tail) {
|
|
108
|
+
children[rel.name] =
|
|
109
|
+
issue.code === 'min' && issue.params?.min != null
|
|
110
|
+
? t('inlineRelation.min', {
|
|
111
|
+
defaultValue: 'Agrega al menos {{min}} {{label}} (hay {{count}})',
|
|
112
|
+
label: relLabel,
|
|
113
|
+
min: issue.params.min,
|
|
114
|
+
count: issue.params.count ?? 0,
|
|
115
|
+
})
|
|
116
|
+
: localizeFieldIssue(issue, relLabel, t, language)
|
|
117
|
+
continue
|
|
118
|
+
}
|
|
119
|
+
const dot = tail.indexOf('.')
|
|
120
|
+
const field = dot === -1 ? '' : tail.slice(dot + 1)
|
|
121
|
+
children[`${rel.name}.${tail}`] = localizeFieldIssue(
|
|
122
|
+
issue,
|
|
123
|
+
field ? fieldLabel(rel.name, field) : relLabel,
|
|
124
|
+
t,
|
|
125
|
+
language,
|
|
126
|
+
)
|
|
127
|
+
}
|
|
128
|
+
return { parent, children }
|
|
129
|
+
}
|
|
@@ -76,3 +76,7 @@ export function normalizeRefFieldsForSubmit(
|
|
|
76
76
|
}
|
|
77
77
|
return out
|
|
78
78
|
}
|
|
79
|
+
|
|
80
|
+
// Relaciones hijas capturadas al crear (`create_inline`): `_children` viaja con
|
|
81
|
+
// el padre; sin ellas el cuerpo no cambia. Ver `inline-relations.ts`.
|
|
82
|
+
export { withInlineChildren } from './inline-relations'
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// Carga las relaciones `create_inline` del modelo y los campos de su modelo
|
|
2
|
+
// hijo (`through`) para el modal en modo crear.
|
|
3
|
+
//
|
|
4
|
+
// Relaciones: `/metadata/table/<modelo>` (donde el kernel sirve `relations[]`,
|
|
5
|
+
// igual que ver/editar). Campos de la fila: `/metadata/modal/<through>` — el
|
|
6
|
+
// mismo contrato que usa el modal del hijo (requeridos, opciones, `ref`);
|
|
7
|
+
// si no responde, las columnas de `/metadata/table/<through>` pasan por
|
|
8
|
+
// `deriveRelationFormFields`, el mecanismo que ya usa `<DynamicRelation>`.
|
|
9
|
+
import { useEffect, useState } from 'react'
|
|
10
|
+
import { useApi } from '../api-context'
|
|
11
|
+
import { deriveRelationFormFields } from '../dynamic-relation-helpers'
|
|
12
|
+
import { deriveInlineRowFields, isCreateInline } from './inline-relations'
|
|
13
|
+
import type { RelationMeta } from '../types'
|
|
14
|
+
|
|
15
|
+
export interface InlineRelationsState<F> {
|
|
16
|
+
relations: RelationMeta[]
|
|
17
|
+
fields: Record<string, F[]>
|
|
18
|
+
/** true mientras se cargan relaciones/campos. */
|
|
19
|
+
loading: boolean
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const unwrap = (res: any) => res?.data?.data ?? res?.data
|
|
23
|
+
|
|
24
|
+
export function useInlineRelations<F extends { key: string; hidden?: boolean; readonly?: boolean; type?: string }>(
|
|
25
|
+
opts: { enabled: boolean; model: string; localizeLabel: (label: string) => string },
|
|
26
|
+
): InlineRelationsState<F> {
|
|
27
|
+
const api = useApi()
|
|
28
|
+
const { enabled, model } = opts
|
|
29
|
+
const [state, setState] = useState<InlineRelationsState<F>>({ relations: [], fields: {}, loading: false })
|
|
30
|
+
// `localizeLabel` cambia de identidad en cada render (viene de `t`); se lee por ref.
|
|
31
|
+
const [localize] = useState(() => ({ fn: opts.localizeLabel }))
|
|
32
|
+
localize.fn = opts.localizeLabel
|
|
33
|
+
|
|
34
|
+
useEffect(() => {
|
|
35
|
+
if (!enabled) {
|
|
36
|
+
setState({ relations: [], fields: {}, loading: false })
|
|
37
|
+
return
|
|
38
|
+
}
|
|
39
|
+
let cancelled = false
|
|
40
|
+
setState((s) => ({ ...s, loading: true }))
|
|
41
|
+
;(async () => {
|
|
42
|
+
try {
|
|
43
|
+
const meta = unwrap(await api.get(`/metadata/table/${model}`))
|
|
44
|
+
const rels: RelationMeta[] = (Array.isArray(meta?.relations) ? meta.relations : [])
|
|
45
|
+
.filter(isCreateInline)
|
|
46
|
+
.map((rel: RelationMeta) => ({ ...rel, label: rel.label ? localize.fn(rel.label) : rel.name }))
|
|
47
|
+
const fields: Record<string, F[]> = {}
|
|
48
|
+
await Promise.all(
|
|
49
|
+
rels.map(async (rel) => {
|
|
50
|
+
let raw: any[] | undefined
|
|
51
|
+
try {
|
|
52
|
+
const m = unwrap(await api.get(`/metadata/modal/${rel.through}`))
|
|
53
|
+
if (Array.isArray(m?.fields)) raw = m.fields
|
|
54
|
+
} catch {
|
|
55
|
+
/* cae a la metadata de tabla */
|
|
56
|
+
}
|
|
57
|
+
if (!raw) {
|
|
58
|
+
try {
|
|
59
|
+
const m = unwrap(await api.get(`/metadata/table/${rel.through}`))
|
|
60
|
+
raw = deriveRelationFormFields(m, rel.foreign_key) as any[]
|
|
61
|
+
} catch {
|
|
62
|
+
raw = []
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
fields[rel.name] = deriveInlineRowFields(raw as F[], rel)
|
|
66
|
+
}),
|
|
67
|
+
)
|
|
68
|
+
if (!cancelled) setState({ relations: rels, fields, loading: false })
|
|
69
|
+
} catch {
|
|
70
|
+
if (!cancelled) setState({ relations: [], fields: {}, loading: false })
|
|
71
|
+
}
|
|
72
|
+
})()
|
|
73
|
+
return () => {
|
|
74
|
+
cancelled = true
|
|
75
|
+
}
|
|
76
|
+
}, [api, enabled, model, localize])
|
|
77
|
+
|
|
78
|
+
return state
|
|
79
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// Núcleo genérico de «filas borrador»: filas capturadas en el cliente que aún
|
|
2
|
+
// no existen en el servidor. Lo comparten el editor de renglones de documento
|
|
3
|
+
// (`business/line-items.ts`: claves de UI) y las relaciones hijas capturadas
|
|
4
|
+
// al crear (`dialogs/inline-relation-rows.tsx`). Puro y sin React.
|
|
5
|
+
//
|
|
6
|
+
// Convenciones compartidas:
|
|
7
|
+
// - Clave de UI estable por fila (`key`), nunca se envía al backend.
|
|
8
|
+
// - Errores por celda con la ruta `"<índice>.<campo>"` (mismo formato que
|
|
9
|
+
// `validateLineItems` y `lineItemErrorsFor`).
|
|
10
|
+
|
|
11
|
+
export interface DraftRow {
|
|
12
|
+
/** Clave estable de UI (sobrevive a reordenar/quitar); no se envía. */
|
|
13
|
+
key: string
|
|
14
|
+
values: Record<string, any>
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
let seq = 0
|
|
18
|
+
/** Clave de UI única en el proceso. `prefix` solo ayuda a depurar. */
|
|
19
|
+
export function newDraftKey(prefix = 'row'): string {
|
|
20
|
+
seq += 1
|
|
21
|
+
return `${prefix}_${Date.now().toString(36)}_${seq}`
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function makeDraftRow(values: Record<string, any> = {}, key?: string): DraftRow {
|
|
25
|
+
return { key: key ?? newDraftKey(), values }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Agrega al final (orden de captura = orden de envío). */
|
|
29
|
+
export function appendDraftRow(rows: DraftRow[], row: DraftRow): DraftRow[] {
|
|
30
|
+
return [...rows, row]
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function removeDraftRow(rows: DraftRow[], key: string): DraftRow[] {
|
|
34
|
+
return rows.filter((r) => r.key !== key)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function updateDraftCell(rows: DraftRow[], key: string, field: string, value: unknown): DraftRow[] {
|
|
38
|
+
return rows.map((r) => (r.key === key ? { ...r, values: { ...r.values, [field]: value } } : r))
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Ruta de error de una celda: `"<índice>.<campo>"`. */
|
|
42
|
+
export const cellErrorKey = (index: number, field: string): string => `${index}.${field}`
|
|
43
|
+
|
|
44
|
+
export const isBlankValue = (v: unknown): boolean =>
|
|
45
|
+
v === undefined || v === null || (typeof v === 'string' && v.trim() === '')
|
|
46
|
+
|
|
47
|
+
export interface DraftColumn {
|
|
48
|
+
key: string
|
|
49
|
+
label: string
|
|
50
|
+
required?: boolean
|
|
51
|
+
type?: string
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface DraftRowsPolicy {
|
|
55
|
+
/** Mínimo de filas (`RelationMeta.min`). Default 0. */
|
|
56
|
+
min?: number
|
|
57
|
+
messages?: {
|
|
58
|
+
required?: (label: string) => string
|
|
59
|
+
min?: (min: number, count: number) => string
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface DraftRowsValidation {
|
|
64
|
+
/** Errores por celda `"<índice>.<campo>"`. */
|
|
65
|
+
errors: Record<string, string>
|
|
66
|
+
/** Error de conjunto (menos filas que el mínimo). */
|
|
67
|
+
form?: string
|
|
68
|
+
valid: boolean
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Requeridos por celda + mínimo de filas. */
|
|
72
|
+
export function validateDraftRows(
|
|
73
|
+
rows: DraftRow[],
|
|
74
|
+
columns: DraftColumn[],
|
|
75
|
+
policy: DraftRowsPolicy = {},
|
|
76
|
+
): DraftRowsValidation {
|
|
77
|
+
const min = policy.min ?? 0
|
|
78
|
+
const requiredMsg = policy.messages?.required ?? ((label: string) => `El campo ${label} es obligatorio`)
|
|
79
|
+
const minMsg =
|
|
80
|
+
policy.messages?.min ??
|
|
81
|
+
((m: number) => `Agrega al menos ${m} ${m === 1 ? 'fila' : 'filas'}`)
|
|
82
|
+
const errors: Record<string, string> = {}
|
|
83
|
+
rows.forEach((row, i) => {
|
|
84
|
+
for (const col of columns) {
|
|
85
|
+
if (col.required && isBlankValue(row.values[col.key])) {
|
|
86
|
+
errors[cellErrorKey(i, col.key)] = requiredMsg(col.label)
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
})
|
|
90
|
+
const form = min > 0 && rows.length < min ? minMsg(min, rows.length) : undefined
|
|
91
|
+
return { errors, form, valid: !form && Object.keys(errors).length === 0 }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Valores listos para el backend: solo las columnas conocidas, opcionales
|
|
96
|
+
* vacíos omitidos (nunca `""`), números reales y booleanos tal cual.
|
|
97
|
+
*/
|
|
98
|
+
export function serializeDraftRows(rows: DraftRow[], columns: DraftColumn[]): Array<Record<string, unknown>> {
|
|
99
|
+
return rows.map((row) => {
|
|
100
|
+
const out: Record<string, unknown> = {}
|
|
101
|
+
for (const col of columns) {
|
|
102
|
+
const v = row.values[col.key]
|
|
103
|
+
if (isBlankValue(v)) continue
|
|
104
|
+
if (col.type === 'number' || col.type === 'integer' || col.type === 'decimal') {
|
|
105
|
+
const n = typeof v === 'number' ? v : Number(String(v).replace(',', '.'))
|
|
106
|
+
out[col.key] = Number.isFinite(n) ? n : v
|
|
107
|
+
} else {
|
|
108
|
+
out[col.key] = typeof v === 'string' ? v.trim() : v
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return out
|
|
112
|
+
})
|
|
113
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -415,6 +415,17 @@ export interface RelationMeta {
|
|
|
415
415
|
* kernels) = not embedded.
|
|
416
416
|
*/
|
|
417
417
|
embed?: boolean
|
|
418
|
+
/**
|
|
419
|
+
* Capturable al CREAR el padre: el modal de registro en modo crear pinta
|
|
420
|
+
* esta relación como una tabla editable de filas borrador y las envía con
|
|
421
|
+
* el padre en `_children.<name>`. Aditivo; ausente = no se captura al crear.
|
|
422
|
+
*/
|
|
423
|
+
create_inline?: boolean
|
|
424
|
+
/**
|
|
425
|
+
* Mínimo de filas hijas que el servidor exige al crear (422 `min` en
|
|
426
|
+
* `_children.<name>`). El cliente lo muestra y bloquea el envío por debajo.
|
|
427
|
+
*/
|
|
428
|
+
min?: number
|
|
418
429
|
}
|
|
419
430
|
|
|
420
431
|
export interface FilterDefinition {
|