@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,184 @@
|
|
|
1
|
+
// @vitest-environment happy-dom
|
|
2
|
+
//
|
|
3
|
+
// Crear un padre con relaciones hijas `create_inline`: tabla de filas borrador,
|
|
4
|
+
// `_children` en el cuerpo, `min` que bloquea y errores 422 por fila.
|
|
5
|
+
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
6
|
+
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
|
|
7
|
+
import { I18nextProvider } from 'react-i18next'
|
|
8
|
+
import i18next from 'i18next'
|
|
9
|
+
|
|
10
|
+
import { DynamicRecordDialog } from '../dialogs/dynamic-record'
|
|
11
|
+
import { ApiProvider } from '../api-context'
|
|
12
|
+
|
|
13
|
+
afterEach(cleanup)
|
|
14
|
+
|
|
15
|
+
function makeI18n() {
|
|
16
|
+
const inst = i18next.createInstance()
|
|
17
|
+
void inst.init({ lng: 'es', fallbackLng: 'es', react: { useSuspense: false }, resources: { es: { translation: {} } } })
|
|
18
|
+
return inst
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const parentSchema = {
|
|
22
|
+
title: 'Regla de descuento',
|
|
23
|
+
fields: [{ key: 'name', label: 'Nombre', type: 'text', required: true }],
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const tierModal = {
|
|
27
|
+
fields: [
|
|
28
|
+
{ key: 'rule_id', label: 'Regla', type: 'text' },
|
|
29
|
+
{ key: 'min_amount', label: 'Monto mínimo', type: 'number', required: true },
|
|
30
|
+
{ key: 'discount_type', label: 'Tipo', type: 'text', required: true },
|
|
31
|
+
{ key: 'discount_value', label: 'Valor', type: 'number', required: true },
|
|
32
|
+
{ key: 'created_at', label: 'Creado', type: 'date' },
|
|
33
|
+
],
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function makeApi(relations: any[]) {
|
|
37
|
+
return {
|
|
38
|
+
get: vi.fn(async (url: string) => {
|
|
39
|
+
if (url === '/metadata/table/DiscountRule') return { data: { data: { relations } } }
|
|
40
|
+
if (url === '/metadata/modal/DiscountRuleTier') return { data: { data: tierModal } }
|
|
41
|
+
return { data: { data: {} } }
|
|
42
|
+
}),
|
|
43
|
+
post: vi.fn(async (_url: string, _body: unknown) => ({ data: { success: true, data: { id: '1' } } })),
|
|
44
|
+
put: async () => ({ data: { success: true } }),
|
|
45
|
+
delete: async () => ({ data: { success: true } }),
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const tiers = {
|
|
50
|
+
name: 'tiers',
|
|
51
|
+
kind: 'one_to_many',
|
|
52
|
+
through: 'DiscountRuleTier',
|
|
53
|
+
foreign_key: 'rule_id',
|
|
54
|
+
label: 'Escalones',
|
|
55
|
+
create_inline: true,
|
|
56
|
+
embed: true,
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function setup(api: any, onCreate?: any) {
|
|
60
|
+
render(
|
|
61
|
+
<I18nextProvider i18n={makeI18n()}>
|
|
62
|
+
<ApiProvider client={api as never}>
|
|
63
|
+
<DynamicRecordDialog
|
|
64
|
+
open
|
|
65
|
+
onOpenChange={() => {}}
|
|
66
|
+
mode="create"
|
|
67
|
+
model="DiscountRule"
|
|
68
|
+
schema={parentSchema as never}
|
|
69
|
+
onCreate={onCreate}
|
|
70
|
+
/>
|
|
71
|
+
</ApiProvider>
|
|
72
|
+
</I18nextProvider>,
|
|
73
|
+
)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const type = (el: HTMLElement, value: string) => fireEvent.change(el, { target: { value } })
|
|
77
|
+
const cell = (field: string, row: number) =>
|
|
78
|
+
within(screen.getByRole('group', { name: `${field}, fila ${row}` })).getByRole(
|
|
79
|
+
field === 'Tipo' ? 'textbox' : 'spinbutton',
|
|
80
|
+
)
|
|
81
|
+
const fillRow = (row: number, amount: string, kind: string, value: string) => {
|
|
82
|
+
type(cell('Monto mínimo', row), amount)
|
|
83
|
+
type(cell('Tipo', row), kind)
|
|
84
|
+
type(cell('Valor', row), value)
|
|
85
|
+
}
|
|
86
|
+
const submit = () => fireEvent.submit(document.querySelector('form') as HTMLFormElement)
|
|
87
|
+
const fillName = () => type(document.querySelector('[data-aby-field="name"] input') as HTMLElement, 'Mayoreo')
|
|
88
|
+
|
|
89
|
+
describe('DynamicRecordDialog create — relaciones create_inline', () => {
|
|
90
|
+
it('pinta la sección solo para relaciones create_inline y oculta FK/auditoría', async () => {
|
|
91
|
+
const other = { name: 'notes', kind: 'one_to_many', through: 'Note', foreign_key: 'rule_id', label: 'Notas', embed: true }
|
|
92
|
+
setup(makeApi([tiers, other]))
|
|
93
|
+
await screen.findByRole('heading', { name: 'Escalones' })
|
|
94
|
+
expect(screen.queryByText('Notas')).toBeNull()
|
|
95
|
+
fireEvent.click(screen.getByRole('button', { name: /Agregar/ }))
|
|
96
|
+
expect(screen.getByRole('columnheader', { name: /Monto mínimo/ })).toBeTruthy()
|
|
97
|
+
expect(screen.queryByRole('columnheader', { name: /Regla/ })).toBeNull()
|
|
98
|
+
expect(screen.queryByRole('columnheader', { name: /Creado/ })).toBeNull()
|
|
99
|
+
})
|
|
100
|
+
|
|
101
|
+
it('agrega, quita y envía _children con el padre en una sola llamada', async () => {
|
|
102
|
+
const api = makeApi([tiers])
|
|
103
|
+
const onCreate = vi.fn(async (_body: Record<string, unknown>) => ({ id: '1' }))
|
|
104
|
+
setup(api, onCreate)
|
|
105
|
+
const add = await screen.findByRole('button', { name: /Agregar/ })
|
|
106
|
+
fireEvent.click(add)
|
|
107
|
+
fireEvent.click(add)
|
|
108
|
+
fireEvent.click(add)
|
|
109
|
+
expect(screen.getAllByRole('button', { name: /Quitar fila/ })).toHaveLength(3)
|
|
110
|
+
fireEvent.click(screen.getByRole('button', { name: 'Quitar fila 3' }))
|
|
111
|
+
fillName()
|
|
112
|
+
fillRow(1, '1000', 'percent', '5')
|
|
113
|
+
fillRow(2, '5000', 'percent', '10')
|
|
114
|
+
submit()
|
|
115
|
+
await waitFor(() => expect(onCreate).toHaveBeenCalledTimes(1))
|
|
116
|
+
expect(onCreate.mock.calls[0][0]).toMatchObject({
|
|
117
|
+
name: 'Mayoreo',
|
|
118
|
+
_children: {
|
|
119
|
+
tiers: [
|
|
120
|
+
{ min_amount: 1000, discount_type: 'percent', discount_value: 5 },
|
|
121
|
+
{ min_amount: 5000, discount_type: 'percent', discount_value: 10 },
|
|
122
|
+
],
|
|
123
|
+
},
|
|
124
|
+
})
|
|
125
|
+
})
|
|
126
|
+
|
|
127
|
+
it('bloquea el envío con requeridos por fila y con min', async () => {
|
|
128
|
+
const api = makeApi([{ ...tiers, min: 2 }])
|
|
129
|
+
const onCreate = vi.fn()
|
|
130
|
+
setup(api, onCreate)
|
|
131
|
+
const add = await screen.findByRole('button', { name: /Agregar/ })
|
|
132
|
+
expect(screen.getByText(/0 de 2 como mínimo/)).toBeTruthy()
|
|
133
|
+
fillName()
|
|
134
|
+
fireEvent.click(add)
|
|
135
|
+
submit()
|
|
136
|
+
const alerts = await screen.findAllByRole('alert')
|
|
137
|
+
expect(alerts.some((a) => /al menos 2/.test(a.textContent ?? ''))).toBe(true)
|
|
138
|
+
expect(screen.getAllByText(/obligatorio/).length).toBeGreaterThan(0)
|
|
139
|
+
expect(onCreate).not.toHaveBeenCalled()
|
|
140
|
+
expect(add.getAttribute('class')).toMatch(/min-h-11/)
|
|
141
|
+
})
|
|
142
|
+
|
|
143
|
+
it('sin relaciones inline el cuerpo es idéntico al de hoy (sin _children)', async () => {
|
|
144
|
+
const api = makeApi([{ ...tiers, create_inline: undefined }])
|
|
145
|
+
const onCreate = vi.fn(async (_body: Record<string, unknown>) => ({}))
|
|
146
|
+
setup(api, onCreate)
|
|
147
|
+
await waitFor(() => expect(api.get).toHaveBeenCalledWith('/metadata/table/DiscountRule'))
|
|
148
|
+
fillName()
|
|
149
|
+
submit()
|
|
150
|
+
await waitFor(() => expect(onCreate).toHaveBeenCalledTimes(1))
|
|
151
|
+
expect(onCreate.mock.calls[0][0]).toEqual({ name: 'Mayoreo' })
|
|
152
|
+
expect(screen.queryByRole('heading', { name: 'Escalones' })).toBeNull()
|
|
153
|
+
})
|
|
154
|
+
|
|
155
|
+
it('pinta el 422 en la celda de la fila y conserva lo capturado', async () => {
|
|
156
|
+
const api = makeApi([tiers])
|
|
157
|
+
// `/q` (metadata en lote) también viaja por post: solo falla el create.
|
|
158
|
+
const base = api.post.getMockImplementation()!
|
|
159
|
+
api.post.mockImplementation(async (url: string, body: unknown) => {
|
|
160
|
+
if (url !== '/dynamic/DiscountRule') return base(url, body)
|
|
161
|
+
throw {
|
|
162
|
+
response: {
|
|
163
|
+
status: 422,
|
|
164
|
+
data: { errors: { '_children.tiers.1.discount_value': [{ code: 'invalid_type' }] } },
|
|
165
|
+
},
|
|
166
|
+
}
|
|
167
|
+
})
|
|
168
|
+
setup(api)
|
|
169
|
+
const add = await screen.findByRole('button', { name: /Agregar/ })
|
|
170
|
+
fireEvent.click(add)
|
|
171
|
+
fireEvent.click(add)
|
|
172
|
+
fillName()
|
|
173
|
+
fillRow(1, '100', 'percent', '1')
|
|
174
|
+
fillRow(2, '200', 'percent', '999')
|
|
175
|
+
submit()
|
|
176
|
+
await waitFor(() => expect(api.post.mock.calls.filter(c => c[0] === '/dynamic/DiscountRule')).toHaveLength(1))
|
|
177
|
+
await waitFor(() =>
|
|
178
|
+
expect(screen.getByRole('group', { name: 'Valor, fila 2' }).parentElement?.textContent).toMatch(/formato inválido/),
|
|
179
|
+
)
|
|
180
|
+
expect((cell('Valor', 2) as HTMLInputElement).value).toBe('999')
|
|
181
|
+
expect((cell('Monto mínimo', 1) as HTMLInputElement).value).toBe('100')
|
|
182
|
+
expect(screen.getByRole('group', { name: 'Valor, fila 1' }).parentElement?.textContent).not.toMatch(/inválido/)
|
|
183
|
+
})
|
|
184
|
+
})
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// Lógica pura del <LineItemsEditor>: cálculo, validación y serialización. El
|
|
3
3
|
// guardado de renglones fallaba (PIT-018) por mandar al API cadenas vacías y
|
|
4
4
|
// claves de UI; `serializeLineItems` es la única puerta de salida hacia el backend.
|
|
5
|
+
import { newDraftKey } from '../draft-rows'
|
|
5
6
|
import { roundMoney, toAmount } from './format'
|
|
6
7
|
import type { ProductVariant } from './product-search'
|
|
7
8
|
|
|
@@ -99,11 +100,9 @@ export interface LineItemsPolicy {
|
|
|
99
100
|
allowZeroQuantity?: boolean
|
|
100
101
|
}
|
|
101
102
|
|
|
102
|
-
|
|
103
|
-
/** Clave de UI única en el proceso. */
|
|
103
|
+
/** Clave de UI única en el proceso (núcleo compartido con las filas borrador). */
|
|
104
104
|
export function newLineKey(): string {
|
|
105
|
-
|
|
106
|
-
return `li_${Date.now().toString(36)}_${seq}`
|
|
105
|
+
return newDraftKey('li')
|
|
107
106
|
}
|
|
108
107
|
|
|
109
108
|
export function makeLine(partial: Partial<LineItem> = {}): LineItem {
|
|
@@ -71,7 +71,12 @@ 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 { InlineRelationRows } from './inline-relation-rows'
|
|
76
|
+
import { relationMin, splitChildErrors } from './inline-relations'
|
|
77
|
+
import { useInlineRelations } from './use-inline-relations'
|
|
78
|
+
import { validateDraftRows, type DraftRow } from '../draft-rows'
|
|
79
|
+
import { clearFieldErrorTree, lineItemErrorsFor } from '../field-validation-ui'
|
|
75
80
|
import { validateValues, bagHasErrors, exemptUnchangedRuleIssues } from '../validator'
|
|
76
81
|
import { DynamicIcon, Icon, isLucideIconName } from '../dynamic-icon'
|
|
77
82
|
import { IconPickerField } from '../icon-picker-field'
|
|
@@ -801,7 +806,7 @@ export function DynamicRecordDialog({
|
|
|
801
806
|
}: DynamicRecordDialogProps) {
|
|
802
807
|
const api = useApi()
|
|
803
808
|
const branchGate = useBranchCreateGate()
|
|
804
|
-
const { t } = useTranslation()
|
|
809
|
+
const { t, i18n } = useTranslation()
|
|
805
810
|
const [modalMeta, setModalMeta] = useState<ModalMetadata | null>(
|
|
806
811
|
schema ? (schema as ModalMetadata) : null,
|
|
807
812
|
)
|
|
@@ -828,6 +833,44 @@ export function DynamicRecordDialog({
|
|
|
828
833
|
const [stepIndex, setStepIndex] = useState(0)
|
|
829
834
|
|
|
830
835
|
const isCreate = mode === 'create'
|
|
836
|
+
|
|
837
|
+
// Relaciones hijas `create_inline`: se capturan como filas borrador y viajan
|
|
838
|
+
// con el padre en `_children`. Solo al crear; ver/editar no cambia.
|
|
839
|
+
const inline = useInlineRelations<FieldDef>({
|
|
840
|
+
enabled: open && isCreate,
|
|
841
|
+
model,
|
|
842
|
+
localizeLabel: (label) => (t(label) !== label ? t(label) : label),
|
|
843
|
+
})
|
|
844
|
+
const [inlineRows, setInlineRows] = useState<Record<string, DraftRow[]>>({})
|
|
845
|
+
// Errores de filas hijas, ya localizados: `"<relación>.<i>.<campo>"`.
|
|
846
|
+
const [inlineErrors, setInlineErrors] = useState<Record<string, string>>({})
|
|
847
|
+
const inlineLabel = (relation: string, key: string): string => {
|
|
848
|
+
const f = inline.fields[relation]?.find(x => x.key === key)
|
|
849
|
+
return f?.label ? localizeFieldLabel(f.label, t) : key
|
|
850
|
+
}
|
|
851
|
+
// Validación de las filas (requeridos + mínimo) con mensajes localizados.
|
|
852
|
+
const validateInline = () => {
|
|
853
|
+
const errors: Record<string, string> = {}
|
|
854
|
+
for (const rel of inline.relations) {
|
|
855
|
+
const v = validateDraftRows(inlineRows[rel.name] ?? [], inline.fields[rel.name] ?? [], {
|
|
856
|
+
min: relationMin(rel),
|
|
857
|
+
messages: {
|
|
858
|
+
required: label =>
|
|
859
|
+
localizeFieldIssue({ code: 'required' }, label, t),
|
|
860
|
+
min: (min, count) =>
|
|
861
|
+
t('inlineRelation.min', {
|
|
862
|
+
defaultValue: 'Agrega al menos {{min}} {{label}} (hay {{count}})',
|
|
863
|
+
label: rel.label || rel.name,
|
|
864
|
+
min,
|
|
865
|
+
count,
|
|
866
|
+
}),
|
|
867
|
+
},
|
|
868
|
+
})
|
|
869
|
+
for (const [k, msg] of Object.entries(v.errors)) errors[`${rel.name}.${k}`] = msg
|
|
870
|
+
if (v.form) errors[rel.name] = v.form
|
|
871
|
+
}
|
|
872
|
+
return errors
|
|
873
|
+
}
|
|
831
874
|
const isView = mode === 'view'
|
|
832
875
|
const isEditable = mode === 'create' || mode === 'edit'
|
|
833
876
|
// Claves que un ayudante de captura (RecordPrefillBar) puede escribir: sólo
|
|
@@ -968,6 +1011,8 @@ export function DynamicRecordDialog({
|
|
|
968
1011
|
setRelations([])
|
|
969
1012
|
setRecord(null)
|
|
970
1013
|
setFormValues({})
|
|
1014
|
+
setInlineRows({})
|
|
1015
|
+
setInlineErrors({})
|
|
971
1016
|
}
|
|
972
1017
|
}, [open])
|
|
973
1018
|
|
|
@@ -1052,8 +1097,16 @@ export function DynamicRecordDialog({
|
|
|
1052
1097
|
// inline field errors + a summary toast. When there is no field map, fall
|
|
1053
1098
|
// back to the existing single cause-carrying toast.
|
|
1054
1099
|
const handleSubmitError = (err: unknown) => {
|
|
1055
|
-
const
|
|
1056
|
-
|
|
1100
|
+
const rawMap = extractFieldErrors(err)
|
|
1101
|
+
// Errores de filas hijas (`_children.<relación>.<i>.<campo>`) van a su celda.
|
|
1102
|
+
const split = rawMap
|
|
1103
|
+
? splitChildErrors(rawMap, inline.relations, inlineLabel, t, i18n.language)
|
|
1104
|
+
: undefined
|
|
1105
|
+
const map = split?.parent
|
|
1106
|
+
const childMsgs = split?.children ?? {}
|
|
1107
|
+
const hasChildErrors = Object.keys(childMsgs).length > 0
|
|
1108
|
+
if (hasChildErrors) setInlineErrors(childMsgs)
|
|
1109
|
+
if (map && (Object.keys(map).length > 0 || hasChildErrors)) {
|
|
1057
1110
|
const next: Record<string, string> = {}
|
|
1058
1111
|
for (const [key, issues] of Object.entries(map)) {
|
|
1059
1112
|
next[key] = localizeFieldIssue(issues[0], labelForKey(key), t)
|
|
@@ -1065,7 +1118,9 @@ export function DynamicRecordDialog({
|
|
|
1065
1118
|
const orphans = Object.entries(next).filter(([k]) => !visibleKeys.has(k))
|
|
1066
1119
|
const description = orphans.length
|
|
1067
1120
|
? orphans.map(([k, msg]) => `${labelForKey(k)}: ${msg}`).join(' · ')
|
|
1068
|
-
:
|
|
1121
|
+
: hasChildErrors
|
|
1122
|
+
? Object.values(childMsgs).join(' · ')
|
|
1123
|
+
: undefined
|
|
1069
1124
|
toast.error(
|
|
1070
1125
|
t('dynamic.validation_failed', { defaultValue: 'Revisa los campos marcados' }),
|
|
1071
1126
|
description ? { description } : undefined,
|
|
@@ -1079,6 +1134,10 @@ export function DynamicRecordDialog({
|
|
|
1079
1134
|
e?.preventDefault()
|
|
1080
1135
|
if (!modalMeta) return
|
|
1081
1136
|
|
|
1137
|
+
// Filas hijas (solo crear): se validan junto al padre para marcar todo de una vez.
|
|
1138
|
+
const inlineIssues = isCreate && inline.relations.length > 0 ? validateInline() : {}
|
|
1139
|
+
setInlineErrors(inlineIssues)
|
|
1140
|
+
|
|
1082
1141
|
if (isEditable) {
|
|
1083
1142
|
// Laravel-style: collect every issue from the shared validator
|
|
1084
1143
|
// (required + rule strings / min/max / email…) on visible fields only.
|
|
@@ -1118,6 +1177,12 @@ export function DynamicRecordDialog({
|
|
|
1118
1177
|
// Required check passed → clear any prior validation errors.
|
|
1119
1178
|
setFieldErrors({})
|
|
1120
1179
|
|
|
1180
|
+
if (Object.keys(inlineIssues).length > 0) {
|
|
1181
|
+
const description = Object.values(inlineIssues).join(' · ')
|
|
1182
|
+
toast.error(t('dynamic.validation_failed', { defaultValue: 'Revisa los campos marcados' }), { description })
|
|
1183
|
+
return
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1121
1186
|
// Fields hidden by their `visible_when` predicate must not be POSTed:
|
|
1122
1187
|
// the render, the required-gate and the payload all drive off the same
|
|
1123
1188
|
// filter, so a DiscountRule with scope=category never submits the
|
|
@@ -1149,6 +1214,17 @@ export function DynamicRecordDialog({
|
|
|
1149
1214
|
if (branchId) payload = { ...payload, branch_id: branchId }
|
|
1150
1215
|
}
|
|
1151
1216
|
|
|
1217
|
+
if (isCreate) {
|
|
1218
|
+
payload = withInlineChildren(
|
|
1219
|
+
payload,
|
|
1220
|
+
inline.relations.map(rel => ({
|
|
1221
|
+
relation: rel.name,
|
|
1222
|
+
rows: inlineRows[rel.name] ?? [],
|
|
1223
|
+
columns: inline.fields[rel.name] ?? [],
|
|
1224
|
+
})),
|
|
1225
|
+
)
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1152
1228
|
setSaving(true)
|
|
1153
1229
|
try {
|
|
1154
1230
|
if (isCreate && onCreate) {
|
|
@@ -1425,6 +1501,36 @@ export function DynamicRecordDialog({
|
|
|
1425
1501
|
/>
|
|
1426
1502
|
</div>
|
|
1427
1503
|
)}
|
|
1504
|
+
{isCreate && inline.relations.length > 0 && (
|
|
1505
|
+
<div className="mt-6 space-y-6" data-slot="inline-relations">
|
|
1506
|
+
{inline.relations.map(rel => (
|
|
1507
|
+
<InlineRelationRows
|
|
1508
|
+
key={rel.name}
|
|
1509
|
+
relation={rel}
|
|
1510
|
+
fields={inline.fields[rel.name] ?? []}
|
|
1511
|
+
rows={inlineRows[rel.name] ?? []}
|
|
1512
|
+
onChange={rows => setInlineRows(prev => ({ ...prev, [rel.name]: rows }))}
|
|
1513
|
+
errors={lineItemErrorsFor(rel.name, inlineErrors)}
|
|
1514
|
+
formError={inlineErrors[rel.name]}
|
|
1515
|
+
onRowRemoved={() => setInlineErrors(prev => clearFieldErrorTree(prev, rel.name))}
|
|
1516
|
+
onCellEdited={(i, f) =>
|
|
1517
|
+
setInlineErrors(prev => clearFieldErrorTree(clearFieldErrorTree(prev, `${rel.name}.${i}.${f}`), rel.name))
|
|
1518
|
+
}
|
|
1519
|
+
disabled={saving}
|
|
1520
|
+
renderField={(field, value, onChange, state) => (
|
|
1521
|
+
<EditField
|
|
1522
|
+
field={field as FieldDef}
|
|
1523
|
+
value={value}
|
|
1524
|
+
onChange={onChange}
|
|
1525
|
+
record={null}
|
|
1526
|
+
invalid={state.invalid}
|
|
1527
|
+
error={state.error}
|
|
1528
|
+
/>
|
|
1529
|
+
)}
|
|
1530
|
+
/>
|
|
1531
|
+
))}
|
|
1532
|
+
</div>
|
|
1533
|
+
)}
|
|
1428
1534
|
{!isCreate && record && audit && (
|
|
1429
1535
|
<AuditInfo
|
|
1430
1536
|
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
|
+
}
|