@asteby/metacore-runtime-react 53.21.1 → 53.23.1
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 +24 -0
- package/dist/assist-interview.d.ts.map +1 -1
- package/dist/assist-interview.js +7 -10
- 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/custom-stages.d.ts.map +1 -1
- package/dist/custom-stages.js +2 -10
- package/dist/dialogs/dynamic-record.d.ts.map +1 -1
- package/dist/dialogs/dynamic-record.js +79 -7
- 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/genui/settings-block.d.ts.map +1 -1
- package/dist/genui/settings-block.js +7 -12
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/record-picker-dialog.d.ts.map +1 -1
- package/dist/record-picker-dialog.js +4 -3
- package/dist/setup/addon-config-surface.d.ts.map +1 -1
- package/dist/setup/addon-config-surface.js +14 -12
- package/dist/stage-automations.d.ts.map +1 -1
- package/dist/stage-automations.js +3 -12
- package/dist/stage-layout.d.ts.map +1 -1
- package/dist/stage-layout.js +2 -7
- package/dist/types.d.ts +11 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/use-addon-installed-probe.d.ts +8 -0
- package/dist/use-addon-installed-probe.d.ts.map +1 -0
- package/dist/use-addon-installed-probe.js +36 -0
- package/dist/use-addon-settings.d.ts +24 -0
- package/dist/use-addon-settings.d.ts.map +1 -1
- package/dist/use-addon-settings.js +39 -13
- package/dist/use-org-document-templates.d.ts.map +1 -1
- package/dist/use-org-document-templates.js +5 -9
- package/dist/views/data-source.d.ts.map +1 -1
- package/dist/views/data-source.js +9 -14
- package/docs/relations.md +17 -0
- package/package.json +8 -7
- 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/__tests__/genui-settings-block.test.tsx +6 -3
- package/src/__tests__/use-addon-settings-hooks.test.tsx +73 -0
- package/src/__tests__/use-addon-settings.test.ts +19 -3
- package/src/assist-interview.tsx +7 -11
- package/src/business/line-items.ts +3 -4
- package/src/custom-stages.tsx +2 -7
- package/src/dialogs/dynamic-record.tsx +117 -6
- 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 +78 -0
- package/src/draft-rows.ts +113 -0
- package/src/genui/settings-block.tsx +7 -13
- package/src/index.ts +1 -0
- package/src/record-picker-dialog.tsx +4 -3
- package/src/setup/addon-config-surface.tsx +16 -15
- package/src/stage-automations.tsx +3 -9
- package/src/stage-layout.ts +2 -7
- package/src/types.ts +11 -0
- package/src/use-addon-installed-probe.ts +39 -0
- package/src/use-addon-settings.ts +66 -12
- package/src/use-org-document-templates.ts +5 -10
- package/src/views/data-source.ts +6 -16
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
// the image-url resolver and the org IANA timezone — are passed as props so the
|
|
11
11
|
// SDK stays transport- and host-agnostic.
|
|
12
12
|
import { emitRecordMutation } from '../record-mutation-events'
|
|
13
|
-
import { createContext, useCallback, useContext, useEffect, useId, useMemo, useRef, useState } from 'react'
|
|
13
|
+
import { createContext, lazy, Suspense, useCallback, useContext, useEffect, useId, useMemo, useRef, useState } from 'react'
|
|
14
14
|
import { useTranslation } from 'react-i18next'
|
|
15
15
|
import type { ModelSchema } from './types'
|
|
16
16
|
|
|
@@ -71,7 +71,15 @@ import { FieldCell } from '../field-grid'
|
|
|
71
71
|
import { isNullableBooleanField, omitUntouchedNullBooleans, usesTriState } from '../nullable-boolean'
|
|
72
72
|
import { NullBooleanMark, TriStateBooleanField } from '../tri-state-boolean'
|
|
73
73
|
import { isNilUuid, normalizeNilUuid } from '../nil-uuid'
|
|
74
|
-
import { normalizeRefFieldsForSubmit } from './normalize-submit'
|
|
74
|
+
import { normalizeRefFieldsForSubmit, withInlineChildren } from './normalize-submit'
|
|
75
|
+
import { relationMin, splitChildErrors } from './inline-relations'
|
|
76
|
+
import { useInlineRelations } from './use-inline-relations'
|
|
77
|
+
|
|
78
|
+
// La tabla de filas hijas solo se usa al CREAR un registro cuyo modelo declara `create_inline`: se carga bajo demanda para no
|
|
79
|
+
// engordar el grafo inicial del panel (el shell de Ops tiene un techo de no-regresión).
|
|
80
|
+
const InlineRelationRows = lazy(() => import('./inline-relation-rows').then(m => ({ default: m.InlineRelationRows })))
|
|
81
|
+
import { validateDraftRows, type DraftRow } from '../draft-rows'
|
|
82
|
+
import { clearFieldErrorTree, lineItemErrorsFor } from '../field-validation-ui'
|
|
75
83
|
import { validateValues, bagHasErrors, exemptUnchangedRuleIssues } from '../validator'
|
|
76
84
|
import { DynamicIcon, Icon, isLucideIconName } from '../dynamic-icon'
|
|
77
85
|
import { IconPickerField } from '../icon-picker-field'
|
|
@@ -801,7 +809,7 @@ export function DynamicRecordDialog({
|
|
|
801
809
|
}: DynamicRecordDialogProps) {
|
|
802
810
|
const api = useApi()
|
|
803
811
|
const branchGate = useBranchCreateGate()
|
|
804
|
-
const { t } = useTranslation()
|
|
812
|
+
const { t, i18n } = useTranslation()
|
|
805
813
|
const [modalMeta, setModalMeta] = useState<ModalMetadata | null>(
|
|
806
814
|
schema ? (schema as ModalMetadata) : null,
|
|
807
815
|
)
|
|
@@ -828,6 +836,44 @@ export function DynamicRecordDialog({
|
|
|
828
836
|
const [stepIndex, setStepIndex] = useState(0)
|
|
829
837
|
|
|
830
838
|
const isCreate = mode === 'create'
|
|
839
|
+
|
|
840
|
+
// Relaciones hijas `create_inline`: se capturan como filas borrador y viajan
|
|
841
|
+
// con el padre en `_children`. Solo al crear; ver/editar no cambia.
|
|
842
|
+
const inline = useInlineRelations<FieldDef>({
|
|
843
|
+
enabled: open && isCreate,
|
|
844
|
+
model,
|
|
845
|
+
localizeLabel: (label) => (t(label) !== label ? t(label) : label),
|
|
846
|
+
})
|
|
847
|
+
const [inlineRows, setInlineRows] = useState<Record<string, DraftRow[]>>({})
|
|
848
|
+
// Errores de filas hijas, ya localizados: `"<relación>.<i>.<campo>"`.
|
|
849
|
+
const [inlineErrors, setInlineErrors] = useState<Record<string, string>>({})
|
|
850
|
+
const inlineLabel = (relation: string, key: string): string => {
|
|
851
|
+
const f = inline.fields[relation]?.find(x => x.key === key)
|
|
852
|
+
return f?.label ? localizeFieldLabel(f.label, t) : key
|
|
853
|
+
}
|
|
854
|
+
// Validación de las filas (requeridos + mínimo) con mensajes localizados.
|
|
855
|
+
const validateInline = () => {
|
|
856
|
+
const errors: Record<string, string> = {}
|
|
857
|
+
for (const rel of inline.relations) {
|
|
858
|
+
const v = validateDraftRows(inlineRows[rel.name] ?? [], inline.fields[rel.name] ?? [], {
|
|
859
|
+
min: relationMin(rel),
|
|
860
|
+
messages: {
|
|
861
|
+
required: label =>
|
|
862
|
+
localizeFieldIssue({ code: 'required' }, label, t),
|
|
863
|
+
min: (min, count) =>
|
|
864
|
+
t('inlineRelation.min', {
|
|
865
|
+
defaultValue: 'Agrega al menos {{min}} {{label}} (hay {{count}})',
|
|
866
|
+
label: rel.label || rel.name,
|
|
867
|
+
min,
|
|
868
|
+
count,
|
|
869
|
+
}),
|
|
870
|
+
},
|
|
871
|
+
})
|
|
872
|
+
for (const [k, msg] of Object.entries(v.errors)) errors[`${rel.name}.${k}`] = msg
|
|
873
|
+
if (v.form) errors[rel.name] = v.form
|
|
874
|
+
}
|
|
875
|
+
return errors
|
|
876
|
+
}
|
|
831
877
|
const isView = mode === 'view'
|
|
832
878
|
const isEditable = mode === 'create' || mode === 'edit'
|
|
833
879
|
// Claves que un ayudante de captura (RecordPrefillBar) puede escribir: sólo
|
|
@@ -968,6 +1014,8 @@ export function DynamicRecordDialog({
|
|
|
968
1014
|
setRelations([])
|
|
969
1015
|
setRecord(null)
|
|
970
1016
|
setFormValues({})
|
|
1017
|
+
setInlineRows({})
|
|
1018
|
+
setInlineErrors({})
|
|
971
1019
|
}
|
|
972
1020
|
}, [open])
|
|
973
1021
|
|
|
@@ -1052,8 +1100,16 @@ export function DynamicRecordDialog({
|
|
|
1052
1100
|
// inline field errors + a summary toast. When there is no field map, fall
|
|
1053
1101
|
// back to the existing single cause-carrying toast.
|
|
1054
1102
|
const handleSubmitError = (err: unknown) => {
|
|
1055
|
-
const
|
|
1056
|
-
|
|
1103
|
+
const rawMap = extractFieldErrors(err)
|
|
1104
|
+
// Errores de filas hijas (`_children.<relación>.<i>.<campo>`) van a su celda.
|
|
1105
|
+
const split = rawMap
|
|
1106
|
+
? splitChildErrors(rawMap, inline.relations, inlineLabel, t, i18n.language)
|
|
1107
|
+
: undefined
|
|
1108
|
+
const map = split?.parent
|
|
1109
|
+
const childMsgs = split?.children ?? {}
|
|
1110
|
+
const hasChildErrors = Object.keys(childMsgs).length > 0
|
|
1111
|
+
if (hasChildErrors) setInlineErrors(childMsgs)
|
|
1112
|
+
if (map && (Object.keys(map).length > 0 || hasChildErrors)) {
|
|
1057
1113
|
const next: Record<string, string> = {}
|
|
1058
1114
|
for (const [key, issues] of Object.entries(map)) {
|
|
1059
1115
|
next[key] = localizeFieldIssue(issues[0], labelForKey(key), t)
|
|
@@ -1065,7 +1121,9 @@ export function DynamicRecordDialog({
|
|
|
1065
1121
|
const orphans = Object.entries(next).filter(([k]) => !visibleKeys.has(k))
|
|
1066
1122
|
const description = orphans.length
|
|
1067
1123
|
? orphans.map(([k, msg]) => `${labelForKey(k)}: ${msg}`).join(' · ')
|
|
1068
|
-
:
|
|
1124
|
+
: hasChildErrors
|
|
1125
|
+
? Object.values(childMsgs).join(' · ')
|
|
1126
|
+
: undefined
|
|
1069
1127
|
toast.error(
|
|
1070
1128
|
t('dynamic.validation_failed', { defaultValue: 'Revisa los campos marcados' }),
|
|
1071
1129
|
description ? { description } : undefined,
|
|
@@ -1079,6 +1137,10 @@ export function DynamicRecordDialog({
|
|
|
1079
1137
|
e?.preventDefault()
|
|
1080
1138
|
if (!modalMeta) return
|
|
1081
1139
|
|
|
1140
|
+
// Filas hijas (solo crear): se validan junto al padre para marcar todo de una vez.
|
|
1141
|
+
const inlineIssues = isCreate && inline.relations.length > 0 ? validateInline() : {}
|
|
1142
|
+
setInlineErrors(inlineIssues)
|
|
1143
|
+
|
|
1082
1144
|
if (isEditable) {
|
|
1083
1145
|
// Laravel-style: collect every issue from the shared validator
|
|
1084
1146
|
// (required + rule strings / min/max / email…) on visible fields only.
|
|
@@ -1118,6 +1180,12 @@ export function DynamicRecordDialog({
|
|
|
1118
1180
|
// Required check passed → clear any prior validation errors.
|
|
1119
1181
|
setFieldErrors({})
|
|
1120
1182
|
|
|
1183
|
+
if (Object.keys(inlineIssues).length > 0) {
|
|
1184
|
+
const description = Object.values(inlineIssues).join(' · ')
|
|
1185
|
+
toast.error(t('dynamic.validation_failed', { defaultValue: 'Revisa los campos marcados' }), { description })
|
|
1186
|
+
return
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1121
1189
|
// Fields hidden by their `visible_when` predicate must not be POSTed:
|
|
1122
1190
|
// the render, the required-gate and the payload all drive off the same
|
|
1123
1191
|
// filter, so a DiscountRule with scope=category never submits the
|
|
@@ -1149,6 +1217,17 @@ export function DynamicRecordDialog({
|
|
|
1149
1217
|
if (branchId) payload = { ...payload, branch_id: branchId }
|
|
1150
1218
|
}
|
|
1151
1219
|
|
|
1220
|
+
if (isCreate) {
|
|
1221
|
+
payload = withInlineChildren(
|
|
1222
|
+
payload,
|
|
1223
|
+
inline.relations.map(rel => ({
|
|
1224
|
+
relation: rel.name,
|
|
1225
|
+
rows: inlineRows[rel.name] ?? [],
|
|
1226
|
+
columns: inline.fields[rel.name] ?? [],
|
|
1227
|
+
})),
|
|
1228
|
+
)
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1152
1231
|
setSaving(true)
|
|
1153
1232
|
try {
|
|
1154
1233
|
if (isCreate && onCreate) {
|
|
@@ -1425,6 +1504,38 @@ export function DynamicRecordDialog({
|
|
|
1425
1504
|
/>
|
|
1426
1505
|
</div>
|
|
1427
1506
|
)}
|
|
1507
|
+
{isCreate && inline.relations.length > 0 && (
|
|
1508
|
+
<div className="mt-6 space-y-6" data-slot="inline-relations">
|
|
1509
|
+
<Suspense fallback={<div role="status" aria-busy="true" className="h-24 animate-pulse rounded-md bg-muted" data-slot="inline-relations-loading" />}>
|
|
1510
|
+
{inline.relations.map(rel => (
|
|
1511
|
+
<InlineRelationRows
|
|
1512
|
+
key={rel.name}
|
|
1513
|
+
relation={rel}
|
|
1514
|
+
fields={inline.fields[rel.name] ?? []}
|
|
1515
|
+
rows={inlineRows[rel.name] ?? []}
|
|
1516
|
+
onChange={rows => setInlineRows(prev => ({ ...prev, [rel.name]: rows }))}
|
|
1517
|
+
errors={lineItemErrorsFor(rel.name, inlineErrors)}
|
|
1518
|
+
formError={inlineErrors[rel.name]}
|
|
1519
|
+
onRowRemoved={() => setInlineErrors(prev => clearFieldErrorTree(prev, rel.name))}
|
|
1520
|
+
onCellEdited={(i, f) =>
|
|
1521
|
+
setInlineErrors(prev => clearFieldErrorTree(clearFieldErrorTree(prev, `${rel.name}.${i}.${f}`), rel.name))
|
|
1522
|
+
}
|
|
1523
|
+
disabled={saving}
|
|
1524
|
+
renderField={(field, value, onChange, state) => (
|
|
1525
|
+
<EditField
|
|
1526
|
+
field={field as FieldDef}
|
|
1527
|
+
value={value}
|
|
1528
|
+
onChange={onChange}
|
|
1529
|
+
record={null}
|
|
1530
|
+
invalid={state.invalid}
|
|
1531
|
+
error={state.error}
|
|
1532
|
+
/>
|
|
1533
|
+
)}
|
|
1534
|
+
/>
|
|
1535
|
+
))}
|
|
1536
|
+
</Suspense>
|
|
1537
|
+
</div>
|
|
1538
|
+
)}
|
|
1428
1539
|
{!isCreate && record && audit && (
|
|
1429
1540
|
<AuditInfo
|
|
1430
1541
|
record={record}
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
// InlineRelationRows — tabla editable de filas borrador para UNA relación
|
|
2
|
+
// `create_inline` al crear el padre. Controlado: `rows`/`onChange`; el envío
|
|
3
|
+
// (`_children`) y la validación viven en el modal. Sobre el núcleo compartido
|
|
4
|
+
// con las partidas de documento: `draft-rows.ts` (claves, errores `"i.campo"`).
|
|
5
|
+
import { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode } from 'react'
|
|
6
|
+
import { useTranslation } from 'react-i18next'
|
|
7
|
+
import { Plus, Trash2 } from 'lucide-react'
|
|
8
|
+
import { Button } from '@asteby/metacore-ui/primitives'
|
|
9
|
+
import { localizeFieldLabel } from '../dynamic-columns-helpers'
|
|
10
|
+
import {
|
|
11
|
+
appendDraftRow,
|
|
12
|
+
cellErrorKey,
|
|
13
|
+
makeDraftRow,
|
|
14
|
+
removeDraftRow,
|
|
15
|
+
updateDraftCell,
|
|
16
|
+
type DraftRow,
|
|
17
|
+
} from '../draft-rows'
|
|
18
|
+
import { relationMin, type InlineFieldMeta } from './inline-relations'
|
|
19
|
+
import type { RelationMeta } from '../types'
|
|
20
|
+
|
|
21
|
+
export interface InlineRelationRowsProps {
|
|
22
|
+
relation: Pick<RelationMeta, 'name' | 'label' | 'min'>
|
|
23
|
+
fields: InlineFieldMeta[]
|
|
24
|
+
rows: DraftRow[]
|
|
25
|
+
onChange: (rows: DraftRow[]) => void
|
|
26
|
+
/** Errores por celda `"<i>.<campo>"` y por fila `"<i>"`. */
|
|
27
|
+
errors?: Record<string, string>
|
|
28
|
+
/** Error de conjunto (mínimo de filas, 422 `min`). */
|
|
29
|
+
formError?: string
|
|
30
|
+
/** Se avisa al quitar una fila: los índices de los errores del servidor ya no valen. */
|
|
31
|
+
onRowRemoved?: () => void
|
|
32
|
+
/** Se avisa al editar una celda (para limpiar su error). */
|
|
33
|
+
onCellEdited?: (index: number, field: string) => void
|
|
34
|
+
disabled?: boolean
|
|
35
|
+
/** Pinta el control de una celda (el modal inyecta su `EditField`). */
|
|
36
|
+
renderField: (
|
|
37
|
+
field: InlineFieldMeta,
|
|
38
|
+
value: any,
|
|
39
|
+
onChange: (v: any) => void,
|
|
40
|
+
state: { invalid: boolean; error?: string },
|
|
41
|
+
) => ReactNode
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const TOUCH = 'min-h-11 min-w-11'
|
|
45
|
+
const CONTROLS = 'input, select, textarea, button[role="combobox"]'
|
|
46
|
+
|
|
47
|
+
function blankValues(fields: InlineFieldMeta[]): Record<string, any> {
|
|
48
|
+
const v: Record<string, any> = {}
|
|
49
|
+
for (const f of fields) v[f.key] = f.defaultValue ?? ''
|
|
50
|
+
return v
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function InlineRelationRows({
|
|
54
|
+
relation,
|
|
55
|
+
fields,
|
|
56
|
+
rows,
|
|
57
|
+
onChange,
|
|
58
|
+
errors = {},
|
|
59
|
+
formError,
|
|
60
|
+
onRowRemoved,
|
|
61
|
+
onCellEdited,
|
|
62
|
+
disabled,
|
|
63
|
+
renderField,
|
|
64
|
+
}: InlineRelationRowsProps) {
|
|
65
|
+
const { t } = useTranslation()
|
|
66
|
+
const uid = useId()
|
|
67
|
+
const min = relationMin(relation)
|
|
68
|
+
const title = relation.label || relation.name
|
|
69
|
+
const tableRef = useRef<HTMLTableElement>(null)
|
|
70
|
+
const addRef = useRef<HTMLButtonElement>(null)
|
|
71
|
+
const [focusKey, setFocusKey] = useState<string | null>(null)
|
|
72
|
+
const [announce, setAnnounce] = useState('')
|
|
73
|
+
|
|
74
|
+
// Tras agregar: foco al primer control de la fila nueva.
|
|
75
|
+
useEffect(() => {
|
|
76
|
+
if (!focusKey) return
|
|
77
|
+
const row = tableRef.current?.querySelector<HTMLElement>(`tr[data-row-key="${focusKey}"]`)
|
|
78
|
+
row?.querySelector<HTMLElement>(CONTROLS)?.focus()
|
|
79
|
+
setFocusKey(null)
|
|
80
|
+
}, [focusKey, rows])
|
|
81
|
+
|
|
82
|
+
const addRow = () => {
|
|
83
|
+
const row = makeDraftRow(blankValues(fields))
|
|
84
|
+
onChange(appendDraftRow(rows, row))
|
|
85
|
+
setFocusKey(row.key)
|
|
86
|
+
setAnnounce(t('inlineRelation.added', { defaultValue: 'Fila agregada. {{count}} en total', count: rows.length + 1 }))
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const removeRow = (row: DraftRow, index: number) => {
|
|
90
|
+
onChange(removeDraftRow(rows, row.key))
|
|
91
|
+
onRowRemoved?.()
|
|
92
|
+
setAnnounce(
|
|
93
|
+
t('inlineRelation.removed', { defaultValue: 'Fila {{n}} eliminada. {{count}} en total', n: index + 1, count: rows.length - 1 }),
|
|
94
|
+
)
|
|
95
|
+
// La fila con el foco desaparece: el foco pasa al botón de agregar.
|
|
96
|
+
requestAnimationFrame(() => addRef.current?.focus())
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Enter en una celda nunca envía el padre: avanza al siguiente control y, al
|
|
100
|
+
// final de la última fila, agrega una fila (como el editor de partidas).
|
|
101
|
+
const onKeyDown = (e: KeyboardEvent<HTMLTableElement>) => {
|
|
102
|
+
if (e.key !== 'Enter' || e.defaultPrevented) return
|
|
103
|
+
const target = e.target as HTMLElement
|
|
104
|
+
if (target.tagName !== 'INPUT' || target.getAttribute('role') === 'combobox') return
|
|
105
|
+
e.preventDefault()
|
|
106
|
+
const controls = Array.from(tableRef.current?.querySelectorAll<HTMLElement>(CONTROLS) ?? []).filter(
|
|
107
|
+
(el) => !(el as HTMLInputElement).disabled,
|
|
108
|
+
)
|
|
109
|
+
const next = controls[controls.indexOf(target) + 1]
|
|
110
|
+
if (next) next.focus()
|
|
111
|
+
else if (!disabled) addRow()
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const headId = (key: string) => `${uid}-h-${key}`
|
|
115
|
+
const countText =
|
|
116
|
+
min > 0
|
|
117
|
+
? t('inlineRelation.countMin', {
|
|
118
|
+
defaultValue: '{{count}} de {{min}} como mínimo',
|
|
119
|
+
count: rows.length,
|
|
120
|
+
min,
|
|
121
|
+
})
|
|
122
|
+
: undefined
|
|
123
|
+
const formErrorId = `${uid}-err`
|
|
124
|
+
|
|
125
|
+
return (
|
|
126
|
+
<section
|
|
127
|
+
data-slot="inline-relation-rows"
|
|
128
|
+
data-relation={relation.name}
|
|
129
|
+
aria-labelledby={`${uid}-title`}
|
|
130
|
+
className="space-y-2"
|
|
131
|
+
>
|
|
132
|
+
<div className="flex flex-wrap items-center justify-between gap-2">
|
|
133
|
+
<div>
|
|
134
|
+
<h3 id={`${uid}-title`} className="text-sm font-semibold text-foreground">
|
|
135
|
+
{title}
|
|
136
|
+
</h3>
|
|
137
|
+
{countText && (
|
|
138
|
+
<p className={`text-xs ${formError ? 'text-destructive' : 'text-muted-foreground'}`}>{countText}</p>
|
|
139
|
+
)}
|
|
140
|
+
</div>
|
|
141
|
+
<Button
|
|
142
|
+
ref={addRef}
|
|
143
|
+
type="button"
|
|
144
|
+
variant="outline"
|
|
145
|
+
className={TOUCH}
|
|
146
|
+
onClick={addRow}
|
|
147
|
+
disabled={disabled}
|
|
148
|
+
>
|
|
149
|
+
<Plus className="size-4" aria-hidden />
|
|
150
|
+
{t('inlineRelation.add', { defaultValue: 'Agregar' })}
|
|
151
|
+
</Button>
|
|
152
|
+
</div>
|
|
153
|
+
|
|
154
|
+
{rows.length === 0 ? (
|
|
155
|
+
<div className="rounded-lg border border-dashed bg-muted/20 px-4 py-6 text-center text-sm text-muted-foreground">
|
|
156
|
+
{min > 0
|
|
157
|
+
? t('inlineRelation.emptyMin', {
|
|
158
|
+
defaultValue: 'Aún no hay filas. Agrega al menos {{min}}.',
|
|
159
|
+
min,
|
|
160
|
+
})
|
|
161
|
+
: t('inlineRelation.empty', { defaultValue: 'Aún no hay filas. Puedes agregarlas ahora o después.' })}
|
|
162
|
+
</div>
|
|
163
|
+
) : (
|
|
164
|
+
<div className="overflow-x-auto rounded-lg border bg-card/40">
|
|
165
|
+
<table
|
|
166
|
+
ref={tableRef}
|
|
167
|
+
onKeyDown={onKeyDown}
|
|
168
|
+
className="w-full border-collapse text-sm"
|
|
169
|
+
aria-label={title}
|
|
170
|
+
aria-describedby={formError ? formErrorId : undefined}
|
|
171
|
+
>
|
|
172
|
+
<thead className="border-b bg-muted/40 text-left text-xs font-medium text-muted-foreground">
|
|
173
|
+
<tr>
|
|
174
|
+
{fields.map((f) => (
|
|
175
|
+
<th key={f.key} id={headId(f.key)} scope="col" className="px-3 py-2 font-medium">
|
|
176
|
+
{localizeFieldLabel(f.label, t)}
|
|
177
|
+
{f.required && <span className="ml-0.5 text-destructive" aria-hidden>*</span>}
|
|
178
|
+
</th>
|
|
179
|
+
))}
|
|
180
|
+
<th scope="col" className="w-14 px-2 py-2">
|
|
181
|
+
<span className="sr-only">{t('inlineRelation.actions', { defaultValue: 'Acciones' })}</span>
|
|
182
|
+
</th>
|
|
183
|
+
</tr>
|
|
184
|
+
</thead>
|
|
185
|
+
<tbody>
|
|
186
|
+
{rows.map((row, i) => {
|
|
187
|
+
const rowError = errors[String(i)]
|
|
188
|
+
return (
|
|
189
|
+
<tr key={row.key} data-row-key={row.key} className="border-b last:border-b-0 align-top">
|
|
190
|
+
{fields.map((f) => {
|
|
191
|
+
const error = errors[cellErrorKey(i, f.key)]
|
|
192
|
+
const label = localizeFieldLabel(f.label, t)
|
|
193
|
+
return (
|
|
194
|
+
<td key={f.key} className="min-w-36 px-2 py-1.5">
|
|
195
|
+
<div
|
|
196
|
+
role="group"
|
|
197
|
+
aria-label={t('inlineRelation.cellLabel', {
|
|
198
|
+
defaultValue: '{{field}}, fila {{n}}',
|
|
199
|
+
field: label,
|
|
200
|
+
n: i + 1,
|
|
201
|
+
})}
|
|
202
|
+
data-aby-field={f.key}
|
|
203
|
+
>
|
|
204
|
+
{renderField(
|
|
205
|
+
f,
|
|
206
|
+
row.values[f.key] ?? '',
|
|
207
|
+
(v) => {
|
|
208
|
+
onChange(updateDraftCell(rows, row.key, f.key, v))
|
|
209
|
+
onCellEdited?.(i, f.key)
|
|
210
|
+
},
|
|
211
|
+
{ invalid: !!error, error },
|
|
212
|
+
)}
|
|
213
|
+
</div>
|
|
214
|
+
{error && <p className="mt-1 text-xs text-destructive">{error}</p>}
|
|
215
|
+
</td>
|
|
216
|
+
)
|
|
217
|
+
})}
|
|
218
|
+
<td className="px-2 py-1.5 text-right">
|
|
219
|
+
<Button
|
|
220
|
+
type="button"
|
|
221
|
+
variant="ghost"
|
|
222
|
+
size="icon"
|
|
223
|
+
className={`${TOUCH} text-muted-foreground hover:text-destructive`}
|
|
224
|
+
onClick={() => removeRow(row, i)}
|
|
225
|
+
disabled={disabled}
|
|
226
|
+
aria-label={t('inlineRelation.remove', {
|
|
227
|
+
defaultValue: 'Quitar fila {{n}}',
|
|
228
|
+
n: i + 1,
|
|
229
|
+
})}
|
|
230
|
+
>
|
|
231
|
+
<Trash2 className="size-4" aria-hidden />
|
|
232
|
+
</Button>
|
|
233
|
+
{rowError && (
|
|
234
|
+
<p className="mt-1 text-xs text-destructive" role="alert">
|
|
235
|
+
{rowError}
|
|
236
|
+
</p>
|
|
237
|
+
)}
|
|
238
|
+
</td>
|
|
239
|
+
</tr>
|
|
240
|
+
)
|
|
241
|
+
})}
|
|
242
|
+
</tbody>
|
|
243
|
+
</table>
|
|
244
|
+
</div>
|
|
245
|
+
)}
|
|
246
|
+
|
|
247
|
+
{formError && (
|
|
248
|
+
<p id={formErrorId} role="alert" className="text-xs text-destructive">
|
|
249
|
+
{formError}
|
|
250
|
+
</p>
|
|
251
|
+
)}
|
|
252
|
+
<p className="sr-only" role="status" aria-live="polite">
|
|
253
|
+
{announce}
|
|
254
|
+
</p>
|
|
255
|
+
</section>
|
|
256
|
+
)
|
|
257
|
+
}
|
|
@@ -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,78 @@
|
|
|
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 { unwrapResponse } from '@asteby/metacore-lib/envelope'
|
|
10
|
+
import { useEffect, useState } from 'react'
|
|
11
|
+
import { useApi } from '../api-context'
|
|
12
|
+
import { deriveRelationFormFields } from '../dynamic-relation-helpers'
|
|
13
|
+
import { deriveInlineRowFields, isCreateInline } from './inline-relations'
|
|
14
|
+
import type { RelationMeta } from '../types'
|
|
15
|
+
|
|
16
|
+
export interface InlineRelationsState<F> {
|
|
17
|
+
relations: RelationMeta[]
|
|
18
|
+
fields: Record<string, F[]>
|
|
19
|
+
/** true mientras se cargan relaciones/campos. */
|
|
20
|
+
loading: boolean
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function useInlineRelations<F extends { key: string; hidden?: boolean; readonly?: boolean; type?: string }>(
|
|
24
|
+
opts: { enabled: boolean; model: string; localizeLabel: (label: string) => string },
|
|
25
|
+
): InlineRelationsState<F> {
|
|
26
|
+
const api = useApi()
|
|
27
|
+
const { enabled, model } = opts
|
|
28
|
+
const [state, setState] = useState<InlineRelationsState<F>>({ relations: [], fields: {}, loading: false })
|
|
29
|
+
// `localizeLabel` cambia de identidad en cada render (viene de `t`); se lee por ref.
|
|
30
|
+
const [localize] = useState(() => ({ fn: opts.localizeLabel }))
|
|
31
|
+
localize.fn = opts.localizeLabel
|
|
32
|
+
|
|
33
|
+
useEffect(() => {
|
|
34
|
+
if (!enabled) {
|
|
35
|
+
setState({ relations: [], fields: {}, loading: false })
|
|
36
|
+
return
|
|
37
|
+
}
|
|
38
|
+
let cancelled = false
|
|
39
|
+
setState((s) => ({ ...s, loading: true }))
|
|
40
|
+
;(async () => {
|
|
41
|
+
try {
|
|
42
|
+
const meta = unwrapResponse<any>(await api.get(`/metadata/table/${model}`))
|
|
43
|
+
const rels: RelationMeta[] = (Array.isArray(meta?.relations) ? meta.relations : [])
|
|
44
|
+
.filter(isCreateInline)
|
|
45
|
+
.map((rel: RelationMeta) => ({ ...rel, label: rel.label ? localize.fn(rel.label) : rel.name }))
|
|
46
|
+
const fields: Record<string, F[]> = {}
|
|
47
|
+
await Promise.all(
|
|
48
|
+
rels.map(async (rel) => {
|
|
49
|
+
let raw: any[] | undefined
|
|
50
|
+
try {
|
|
51
|
+
const m = unwrapResponse<any>(await api.get(`/metadata/modal/${rel.through}`))
|
|
52
|
+
if (Array.isArray(m?.fields)) raw = m.fields
|
|
53
|
+
} catch {
|
|
54
|
+
/* cae a la metadata de tabla */
|
|
55
|
+
}
|
|
56
|
+
if (!raw) {
|
|
57
|
+
try {
|
|
58
|
+
const m = unwrapResponse<any>(await api.get(`/metadata/table/${rel.through}`))
|
|
59
|
+
raw = deriveRelationFormFields(m, rel.foreign_key) as any[]
|
|
60
|
+
} catch {
|
|
61
|
+
raw = []
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
fields[rel.name] = deriveInlineRowFields(raw as F[], rel)
|
|
65
|
+
}),
|
|
66
|
+
)
|
|
67
|
+
if (!cancelled) setState({ relations: rels, fields, loading: false })
|
|
68
|
+
} catch {
|
|
69
|
+
if (!cancelled) setState({ relations: [], fields: {}, loading: false })
|
|
70
|
+
}
|
|
71
|
+
})()
|
|
72
|
+
return () => {
|
|
73
|
+
cancelled = true
|
|
74
|
+
}
|
|
75
|
+
}, [api, enabled, model, localize])
|
|
76
|
+
|
|
77
|
+
return state
|
|
78
|
+
}
|