@asteby/metacore-runtime-react 49.12.0 → 50.0.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,224 @@
1
+ // @vitest-environment happy-dom
2
+ //
3
+ // DynamicTable bulk delete: the error toast keeps the count and adds the
4
+ // server's refusal reasons (grouped, truncated, as a string with line breaks) as `description`;
5
+ // `onBulkDeleteResult` reports the outcome per id.
6
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
7
+ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
8
+
9
+ const toastMock = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }))
10
+ vi.mock('sonner', () => ({ toast: toastMock }))
11
+ vi.mock('@tanstack/react-router', () => ({ useNavigate: () => () => {} }))
12
+ const I18N = {
13
+ t: (_k: string, o?: { defaultValue?: string; count?: number }) => {
14
+ if (o?.defaultValue && o.count != null) return o.defaultValue.replace('{{count}}', String(o.count))
15
+ return o?.defaultValue ?? _k
16
+ },
17
+ i18n: { language: 'es' },
18
+ }
19
+ vi.mock('react-i18next', () => ({ useTranslation: () => I18N }))
20
+
21
+ import { DynamicTable } from '../dynamic-table'
22
+ import { makeDefaultGetDynamicColumns } from '../dynamic-columns'
23
+ import { ApiProvider, type ApiClient } from '../api-context'
24
+ import { useMetadataCache } from '../metadata-cache'
25
+ import type { TableMetadata } from '../types'
26
+
27
+ afterEach(cleanup)
28
+ const getDynamicColumns = makeDefaultGetDynamicColumns()
29
+
30
+ function meta(): TableMetadata {
31
+ return {
32
+ title: 'Patients',
33
+ endpoint: '/data/patient',
34
+ columns: [{ key: 'title', label: 'Title', type: 'text', sortable: true, filterable: false, searchable: true }],
35
+ actions: [],
36
+ perPageOptions: [10],
37
+ defaultPerPage: 10,
38
+ searchPlaceholder: 'Buscar...',
39
+ enableCRUDActions: false,
40
+ hasActions: false,
41
+ }
42
+ }
43
+
44
+ type Outcome = { ok: true } | { status: number; message?: string } | { softFail: string }
45
+
46
+ function fakeApi(outcomes: Record<number, Outcome>): ApiClient {
47
+ const ok = (data: unknown) => ({ data: { success: true, data, meta: { total: 5 } } })
48
+ return {
49
+ get: vi.fn(async (url: string) => {
50
+ if (url.startsWith('/metadata/table/')) return ok(meta())
51
+ if (url.endsWith('/facets')) return ok([])
52
+ return ok([1, 2, 3, 4, 5].map((id) => ({ id, title: `Row ${id}` })))
53
+ }),
54
+ post: vi.fn(async () => ok(null)),
55
+ put: vi.fn(async () => ok(null)),
56
+ delete: vi.fn(async (url: string) => {
57
+ const id = Number(url.split('/').pop())
58
+ const o = outcomes[id] ?? { ok: true }
59
+ if ('softFail' in o) return { data: { success: false, message: o.softFail } }
60
+ if ('status' in o) {
61
+ throw Object.assign(new Error('Request failed'), {
62
+ response: { status: o.status, data: o.message ? { message: o.message } : {} },
63
+ })
64
+ }
65
+ return { data: { success: true } }
66
+ }),
67
+ }
68
+ }
69
+
70
+ async function runBulkDelete(api: ApiClient, onResult?: (r: any) => void) {
71
+ render(
72
+ <ApiProvider client={api}>
73
+ <DynamicTable model="patient" enableUrlSync={false} getDynamicColumns={getDynamicColumns} onBulkDeleteResult={onResult} />
74
+ </ApiProvider>,
75
+ )
76
+ await screen.findAllByText('Row 1')
77
+ fireEvent.click(screen.getAllByRole('checkbox')[0]) // select all
78
+ fireEvent.click(await screen.findByText('Eliminar'))
79
+ fireEvent.click(await screen.findByText('Eliminar todos'))
80
+ await waitFor(() => expect(toastMock.error.mock.calls.length + toastMock.success.mock.calls.length).toBeGreaterThan(0), { timeout: 5000 })
81
+ }
82
+
83
+ const MSG = 'El registro forma parte del expediente, que debe conservarse al menos 5 años'
84
+
85
+ describe('DynamicTable bulk delete reasons', () => {
86
+ beforeEach(() => {
87
+ localStorage.clear()
88
+ sessionStorage.clear()
89
+ toastMock.success.mockClear()
90
+ toastMock.error.mockClear()
91
+ useMetadataCache.getState().setMetadata('patient', meta())
92
+ })
93
+
94
+ it('groups the same reason with its count and keeps the success toast', async () => {
95
+ const onResult = vi.fn()
96
+ await runBulkDelete(fakeApi({ 2: { status: 409, message: MSG }, 4: { status: 409, message: MSG } }), onResult)
97
+ expect(toastMock.success).toHaveBeenCalledWith('3 registro(s) eliminado(s) correctamente')
98
+ expect(toastMock.error).toHaveBeenCalledTimes(1)
99
+ const [title, opts] = toastMock.error.mock.calls[0]
100
+ expect(title).toBe('2 registro(s) no pudieron ser eliminados')
101
+ expect(opts.description).toBe(`• ${MSG} (×2)`)
102
+ expect(onResult).toHaveBeenCalledTimes(1)
103
+ expect(onResult).toHaveBeenCalledWith({
104
+ succeeded: [1, 3, 5],
105
+ failed: [{ id: 2, message: MSG, status: 409 }, { id: 4, message: MSG, status: 409 }],
106
+ })
107
+ })
108
+
109
+ it('lists distinct reasons, including a soft failure message', async () => {
110
+ await runBulkDelete(fakeApi({ 1: { status: 409, message: 'Motivo A' }, 2: { softFail: 'Motivo B' } }))
111
+ expect(toastMock.error.mock.calls[0][1].description).toBe('• Motivo A\n• Motivo B')
112
+ })
113
+
114
+ it('shows "y N más" past three distinct reasons', async () => {
115
+ await runBulkDelete(fakeApi({
116
+ 1: { status: 409, message: 'R1' }, 2: { status: 409, message: 'R2' },
117
+ 3: { status: 409, message: 'R3' }, 4: { status: 409, message: 'R4' }, 5: { status: 409, message: 'R5' },
118
+ }))
119
+ expect(toastMock.error.mock.calls[0][1].description).toBe('• R1\n• R2\n• R3\ny 2 más')
120
+ })
121
+
122
+ it('truncates long reasons', async () => {
123
+ await runBulkDelete(fakeApi({ 1: { status: 409, message: 'x'.repeat(500) } }))
124
+ const d: string = toastMock.error.mock.calls[0][1].description
125
+ expect(d.length).toBeLessThanOrEqual(2 + 200)
126
+ expect(d.endsWith('…')).toBe(true)
127
+ })
128
+
129
+ it('leaves the toast exactly as before when the server gave no message', async () => {
130
+ const onResult = vi.fn()
131
+ const api = fakeApi({ 1: { status: 500 } })
132
+ ;(api.delete as any).mockImplementationOnce(async () => { throw new Error('') })
133
+ await runBulkDelete(api, onResult)
134
+ expect(toastMock.error).toHaveBeenCalledTimes(1)
135
+ expect(toastMock.error.mock.calls[0].length).toBe(2)
136
+ expect(toastMock.error.mock.calls[0][1]).toBeUndefined()
137
+ expect(onResult.mock.calls[0][0].failed[0]).toMatchObject({ id: 1 })
138
+ expect(onResult.mock.calls[0][0].failed[0].message).toBeUndefined()
139
+ })
140
+
141
+ it('works without onBulkDeleteResult', async () => {
142
+ await runBulkDelete(fakeApi({ 2: { status: 409, message: MSG } }))
143
+ expect(toastMock.error).toHaveBeenCalledTimes(1)
144
+ })
145
+
146
+ it('passes server HTML through as plain text', async () => {
147
+ const evil = '<img src=x onerror=alert(1)>'
148
+ await runBulkDelete(fakeApi({ 1: { status: 409, message: evil } }))
149
+ const d = toastMock.error.mock.calls[0][1].description
150
+ expect(typeof d).toBe('string')
151
+ expect(d).toBe(`• ${evil}`)
152
+ })
153
+
154
+ it('ignores generic axios messages as a reason', async () => {
155
+ const onResult = vi.fn()
156
+ const api = fakeApi({})
157
+ ;(api.delete as any).mockImplementationOnce(async () => { throw new Error('Request failed with status code 500') })
158
+ ;(api.delete as any).mockImplementationOnce(async () => { throw new Error('Network Error') })
159
+ ;(api.delete as any).mockImplementationOnce(async () => { throw new Error('timeout of 5000ms exceeded') })
160
+ await runBulkDelete(api, onResult)
161
+ expect(toastMock.error.mock.calls[0][1]).toBeUndefined()
162
+ for (const f of onResult.mock.calls[0][0].failed) expect(f.message).toBeUndefined()
163
+ })
164
+
165
+ it('prefers the server message over the generic axios one', async () => {
166
+ const api = fakeApi({})
167
+ ;(api.delete as any).mockImplementationOnce(async () => {
168
+ throw Object.assign(new Error('Request failed with status code 409'), { response: { status: 409, data: { message: 'Motivo real' } } })
169
+ })
170
+ await runBulkDelete(api)
171
+ expect(toastMock.error.mock.calls[0][1].description).toBe('• Motivo real')
172
+ })
173
+
174
+ it('counts a cancelled reason prompt as a failure without message or description', async () => {
175
+ const onResult = vi.fn()
176
+ const api = fakeApi({})
177
+ ;(api.delete as any).mockImplementationOnce(async () => {
178
+ throw Object.assign(new Error('x'), {
179
+ response: { status: 422, data: { errors: { reason: [{ code: 'required', params: { min: 3 } }] } } },
180
+ })
181
+ })
182
+ render(
183
+ <ApiProvider client={api}>
184
+ <DynamicTable model="patient" enableUrlSync={false} getDynamicColumns={getDynamicColumns} onBulkDeleteResult={onResult} />
185
+ </ApiProvider>,
186
+ )
187
+ await screen.findAllByText('Row 1')
188
+ fireEvent.click(screen.getAllByRole('checkbox')[0])
189
+ fireEvent.click(await screen.findByText('Eliminar'))
190
+ fireEvent.click(await screen.findByText('Eliminar todos'))
191
+ const cancel = await screen.findByPlaceholderText('Explica por qué. Queda en la bitácora.')
192
+ expect(cancel).toBeTruthy()
193
+ const dialog = cancel.closest('[role="dialog"]') as HTMLElement
194
+ fireEvent.click(Array.from(dialog.querySelectorAll('button')).find((b) => b.textContent === 'Cancelar')!)
195
+ await waitFor(() => expect(toastMock.error).toHaveBeenCalled(), { timeout: 5000 })
196
+ expect(toastMock.error.mock.calls[0][0]).toBe('5 registro(s) no pudieron ser eliminados')
197
+ expect(toastMock.error.mock.calls[0][1]).toBeUndefined()
198
+ const { succeeded, failed } = onResult.mock.calls[0][0]
199
+ expect(succeeded).toEqual([])
200
+ expect(failed.map((f: any) => f.id)).toEqual([1, 2, 3, 4, 5])
201
+ for (const f of failed) expect(f.message).toBeUndefined()
202
+ expect(api.delete).toHaveBeenCalledTimes(1)
203
+ })
204
+
205
+ it('still refreshes the table when onBulkDeleteResult throws, with no unhandled rejection', async () => {
206
+ const unhandled = vi.fn()
207
+ process.on('unhandledRejection', unhandled)
208
+ const api = fakeApi({ 2: { status: 409, message: MSG } })
209
+ const listCalls = () => (api.get as any).mock.calls.filter(([u]: [string]) => !u.startsWith('/metadata/') && !u.endsWith('/facets')).length
210
+ const err = vi.spyOn(console, 'error').mockImplementation(() => {})
211
+ try {
212
+ let before = -1
213
+ await runBulkDelete(api, () => { before = listCalls(); throw new Error('boom') })
214
+ expect(before).toBeGreaterThan(0)
215
+ await waitFor(() => expect(listCalls()).toBeGreaterThan(before), { timeout: 5000 })
216
+ await new Promise((r) => setTimeout(r, 50))
217
+ expect(unhandled).not.toHaveBeenCalled()
218
+ expect(err.mock.calls.some((c) => String(c[0]).includes('onBulkDeleteResult'))).toBe(true)
219
+ } finally {
220
+ process.off('unhandledRejection', unhandled)
221
+ err.mockRestore()
222
+ }
223
+ })
224
+ })
@@ -0,0 +1,49 @@
1
+ // @vitest-environment happy-dom
2
+ //
3
+ // IconPickerField `iconOnly`: hides the "Imagen" tab; stored value is always a
4
+ // lucide name; a pre-existing url/path is preserved until cleared/replaced.
5
+ import { afterEach, describe, expect, it, vi } from 'vitest'
6
+ import { cleanup, render, screen, fireEvent } from '@testing-library/react'
7
+
8
+ vi.mock('../upload-field', () => ({
9
+ UploadField: () => <div data-testid="upload-field" />,
10
+ }))
11
+
12
+ import { IconPickerField } from '../icon-picker-field'
13
+ import type { ActionFieldDef } from '../types'
14
+
15
+ afterEach(cleanup)
16
+
17
+ const field: ActionFieldDef = { key: 'icon', label: 'Ícono', type: 'text', widget: 'icon' }
18
+
19
+ describe('IconPickerField iconOnly', () => {
20
+ it('por defecto sigue mostrando la pestaña Imagen', () => {
21
+ render(<IconPickerField field={field} value="" onChange={() => {}} />)
22
+ expect(screen.getByRole('tab', { name: 'Imagen' })).toBeTruthy()
23
+ })
24
+
25
+ it.each([
26
+ ['prop', { iconOnly: true }, field],
27
+ ['field.iconOnly', {}, { ...field, iconOnly: true }],
28
+ ['field.icon_only', {}, { ...field, icon_only: true }],
29
+ ])('oculta la pestaña Imagen (%s) y guarda el nombre Lucide', (_n, props, f) => {
30
+ const onChange = vi.fn()
31
+ render(<IconPickerField field={f as ActionFieldDef} value="" onChange={onChange} {...props} />)
32
+ expect(screen.queryByRole('tab')).toBeNull()
33
+ fireEvent.click(screen.getByRole('combobox'))
34
+ fireEvent.change(screen.getByLabelText('Buscar ícono'), { target: { value: 'credit' } })
35
+ fireEvent.click(screen.getByRole('option', { name: 'CreditCard' }))
36
+ expect(onChange).toHaveBeenCalledWith('CreditCard')
37
+ expect(screen.queryByTestId('upload-field')).toBeNull()
38
+ })
39
+
40
+ it('un valor URL existente no se corrompe: se muestra y solo cambia al quitar', () => {
41
+ const onChange = vi.fn()
42
+ render(<IconPickerField field={field} iconOnly value="/uploads/logo.png" onChange={onChange} />)
43
+ expect(onChange).not.toHaveBeenCalled()
44
+ expect(screen.getByTestId('icon-legacy-value').textContent).toContain('/uploads/logo.png')
45
+ expect(screen.queryByTestId('upload-field')).toBeNull()
46
+ fireEvent.click(screen.getByRole('button', { name: 'Quitar' }))
47
+ expect(onChange).toHaveBeenCalledWith('')
48
+ })
49
+ })
@@ -55,12 +55,12 @@ import { toastServerError, extractFieldErrors, localizeFieldIssue, localizeField
55
55
  import { DynamicSelectField, OptionLead, OptionThumb } from '../dynamic-select-field'
56
56
  import { RecordPicker } from '../record-picker'
57
57
  import { DynamicMultiSelectField } from '../dynamic-multi-select-field'
58
- import { UploadField } from '../upload-field'
58
+ import { UploadField, validateUploadFile } from '../upload-field'
59
59
  import { DynamicRelations } from '../dynamic-relations'
60
60
  import { AuditInfo, readAuditMeta } from '../audit-info'
61
61
  import type { AuditMeta } from '../types'
62
62
  import { useOptionsResolver, type ResolvedOption } from '../use-options-resolver'
63
- import { getFieldRef, getVisibleWhen, evaluateVisibleWhen, ATTRIBUTE_CLASSES_KEY } from '../dynamic-form-schema'
63
+ import { getFieldRef, getVisibleWhen, evaluateVisibleWhen, getUploadConfig, ATTRIBUTE_CLASSES_KEY } from '../dynamic-form-schema'
64
64
  import { useAttributeClasses, type AttributeClass } from '../attribute-classes'
65
65
  import type { VisibleWhen } from '../types'
66
66
  import { groupFieldsBySection, type FormLayout } from '../form-layout'
@@ -181,6 +181,65 @@ export interface FieldDef {
181
181
  * `groupFieldsBySection`.
182
182
  */
183
183
  section?: string
184
+ /** `icon` widget: only lucide names (no "Imagen" tab). */
185
+ iconOnly?: boolean
186
+ /** snake_case alias for `iconOnly`. */
187
+ icon_only?: boolean
188
+ /**
189
+ * `file` / `image` upload: maximum size in bytes. A larger file is rejected
190
+ * client-side (error toast + inline message) and never POSTed to `/upload`.
191
+ * Absent → no limit (retrocompat).
192
+ */
193
+ maxSize?: number
194
+ /**
195
+ * `file` / `image` upload: accept list (`"image/*"`, `"image/png,.webp"`).
196
+ * Forwarded to the file input and also enforced on pick and drag-and-drop.
197
+ * Absent → `image/*` for `image`, anything for `file` (retrocompat).
198
+ */
199
+ accept?: string
200
+ /**
201
+ * Pre-fills this field from a sibling while the user has not edited it by
202
+ * hand: `{ field: 'name', transform: 'slug' }` keeps `slug` in sync with
203
+ * `name`. Once the user types in this field it is no longer derived.
204
+ */
205
+ deriveFrom?: { field: string; transform: 'slug' }
206
+ /** snake_case alias for `deriveFrom`. */
207
+ derive_from?: { field: string; transform: 'slug' }
208
+ }
209
+
210
+ /**
211
+ * Lowercase, accent-free, hyphenated slug ("Asociaciones Médicas" →
212
+ * "asociaciones-medicas"). Pure — used by `FieldDef.deriveFrom`.
213
+ */
214
+ export function slugify(input: unknown): string {
215
+ return String(input ?? '')
216
+ .normalize('NFD')
217
+ .replace(/[\u0300-\u036f]/g, '')
218
+ .toLowerCase()
219
+ .replace(/[^a-z0-9]+/g, '-')
220
+ .replace(/^-+|-+$/g, '')
221
+ }
222
+
223
+ const getDeriveFrom = (f: FieldDef) => f.deriveFrom ?? f.derive_from
224
+
225
+ /**
226
+ * `editPayload: 'declared'` — keeps only the keys of the fields declared in the
227
+ * modal metadata. A declared field with no value is sent as '' (so a value can
228
+ * be cleared); one hidden by `visible_when` (already stripped) stays out.
229
+ */
230
+ export function pickDeclaredFieldValues(
231
+ values: Record<string, any>,
232
+ fields: FieldDef[] | undefined,
233
+ ): Record<string, any> {
234
+ const out: Record<string, any> = {}
235
+ for (const f of fields ?? []) {
236
+ if (f.key in values) {
237
+ out[f.key] = values[f.key] ?? ''
238
+ } else if (!getVisibleWhen(f) && !f.hidden && f.type !== 'hidden' && !f.readonly) {
239
+ out[f.key] = ''
240
+ }
241
+ }
242
+ return out
184
243
  }
185
244
 
186
245
  // Permissive shape: the wire payload may omit some fields (e.g. `title` is
@@ -197,7 +256,30 @@ interface ModalMetadata {
197
256
  titleKey?: string
198
257
  createTitle?: string
199
258
  editTitle?: string
259
+ /**
260
+ * Optional per-model dialog texts. When present they replace the generic
261
+ * description / submit label of the mode; absent → the built-in texts.
262
+ * snake_case aliases accepted (wire format).
263
+ */
264
+ createDescription?: string
265
+ editDescription?: string
266
+ viewDescription?: string
267
+ createSubmitLabel?: string
268
+ editSubmitLabel?: string
269
+ create_description?: string
270
+ edit_description?: string
271
+ view_description?: string
272
+ create_submit_label?: string
273
+ edit_submit_label?: string
200
274
  fields?: FieldDef[]
275
+ /**
276
+ * Shape of the PUT payload in `mode='edit'`. `'all'` (default) sends every
277
+ * form value as before; `'declared'` sends only the keys of the fields
278
+ * declared in this metadata (a declared empty field goes as ''). Create is
279
+ * unaffected. Tolerates the snake_case alias `edit_payload`.
280
+ */
281
+ editPayload?: 'all' | 'declared'
282
+ edit_payload?: 'all' | 'declared'
201
283
  /**
202
284
  * Declarative form layout (kernel PR #230): groups the fields into named
203
285
  * sections rendered stacked (`mode:"sections"`) or as a wizard
@@ -501,6 +583,33 @@ function formatDisplayValue(rawValue: any, field: FieldDef): string {
501
583
  return String(value)
502
584
  }
503
585
 
586
+ // modeTexts resolves the per-model description / submit label for a mode,
587
+ // falling back to the generic MODE_CONFIG strings when metadata omits them.
588
+ function modeTexts(
589
+ meta: ModalMetadata | null | undefined,
590
+ mode: 'create' | 'edit' | 'view',
591
+ base: { description: string; submitLabel: string },
592
+ ): { description: string; submitLabel: string } {
593
+ const pick = (...v: Array<string | undefined>) => v.find((x) => typeof x === 'string' && x.trim() !== '')
594
+ if (!meta) return base
595
+ if (mode === 'create') {
596
+ return {
597
+ description: pick(meta.createDescription, meta.create_description) ?? base.description,
598
+ submitLabel: pick(meta.createSubmitLabel, meta.create_submit_label) ?? base.submitLabel,
599
+ }
600
+ }
601
+ if (mode === 'edit') {
602
+ return {
603
+ description: pick(meta.editDescription, meta.edit_description) ?? base.description,
604
+ submitLabel: pick(meta.editSubmitLabel, meta.edit_submit_label) ?? base.submitLabel,
605
+ }
606
+ }
607
+ return {
608
+ description: pick(meta.viewDescription, meta.view_description) ?? base.description,
609
+ submitLabel: base.submitLabel,
610
+ }
611
+ }
612
+
504
613
  const MODE_CONFIG = {
505
614
  create: {
506
615
  getTitle: (meta: ModalMetadata, t: TFn) => {
@@ -690,6 +799,8 @@ export function DynamicRecordDialog({
690
799
  const [audit, setAudit] = useState<AuditMeta | undefined>(undefined)
691
800
  const [record, setRecord] = useState<any | null>(null)
692
801
  const [formValues, setFormValues] = useState<Record<string, any>>({})
802
+ // Derived fields (`deriveFrom`) the user has typed in by hand: no longer derived.
803
+ const manualDerived = useRef<Set<string>>(new Set())
693
804
  // Classes of the record's category (plus those its saved data carries), for
694
805
  // `visible_when.class` fields.
695
806
  const attributeClasses = useAttributeClasses(api, modalMeta, formValues, record)
@@ -731,6 +842,7 @@ export function DynamicRecordDialog({
731
842
  // the wizard to its first step.
732
843
  setFieldErrors({})
733
844
  setStepIndex(0)
845
+ manualDerived.current.clear()
734
846
 
735
847
  let cancelled = false
736
848
 
@@ -747,6 +859,14 @@ export function DynamicRecordDialog({
747
859
  ? ''
748
860
  : resolvePath(rec, field.key) ?? field.defaultValue ?? ''
749
861
  }
862
+ // En edición, un destino derivado ya guardado no se pisa: cuenta como manual.
863
+ if (!isCreate) {
864
+ for (const field of meta.fields ?? []) {
865
+ if (getDeriveFrom(field) && initial[field.key] !== '' && initial[field.key] != null) {
866
+ manualDerived.current.add(field.key)
867
+ }
868
+ }
869
+ }
750
870
  setFormValues(initial)
751
871
  }
752
872
 
@@ -986,7 +1106,10 @@ export function DynamicRecordDialog({
986
1106
  // filter, so a DiscountRule with scope=category never submits the
987
1107
  // product_id / customer_id it isn't showing. Mirrors dynamic-form.tsx,
988
1108
  // which builds its Zod only over visibleFields.
989
- const submittedValues = stripHiddenFieldValues(formValues, modalMeta.fields, mode, attributeClasses)
1109
+ let submittedValues = stripHiddenFieldValues(formValues, modalMeta.fields, mode, attributeClasses)
1110
+ if (mode === 'edit' && (modalMeta.editPayload ?? modalMeta.edit_payload) === 'declared') {
1111
+ submittedValues = pickDeclaredFieldValues(submittedValues, modalMeta.fields)
1112
+ }
990
1113
 
991
1114
  // Empty reference pickers → null (not "" / nil-UUID) so nullable FK
992
1115
  // columns accept them instead of raising a 23503 FK violation.
@@ -1086,6 +1209,8 @@ export function DynamicRecordDialog({
1086
1209
  ? 'Editar registro'
1087
1210
  : 'Ver registro'
1088
1211
 
1212
+ const texts = modeTexts(modalMeta, mode, config)
1213
+
1089
1214
  const visibleFields = filterVisibleFields(modalMeta?.fields, mode, formValues, attributeClasses)
1090
1215
 
1091
1216
  // Declarative form layout: group the (already visibility-filtered) fields by
@@ -1115,7 +1240,23 @@ export function DynamicRecordDialog({
1115
1240
  locked={isCreate && !!lockedFields?.includes(field.key)}
1116
1241
  error={fieldErrors[field.key]}
1117
1242
  onChange={val => {
1118
- setFormValues((prev: Record<string, any>) => ({ ...prev, [field.key]: val }))
1243
+ if (getDeriveFrom(field)) {
1244
+ if (val === '' || val == null) manualDerived.current.delete(field.key)
1245
+ else manualDerived.current.add(field.key)
1246
+ }
1247
+ setFormValues((prev: Record<string, any>) => {
1248
+ const next = { ...prev, [field.key]: val }
1249
+ for (const target of modalMeta?.fields ?? []) {
1250
+ const d = getDeriveFrom(target)
1251
+ if (!d || d.field !== field.key || d.transform !== 'slug') continue
1252
+ if (manualDerived.current.has(target.key)) continue
1253
+ const current = prev[target.key] ?? ''
1254
+ if (current === '' || current === slugify(prev[field.key])) {
1255
+ next[target.key] = slugify(val)
1256
+ }
1257
+ }
1258
+ return next
1259
+ })
1119
1260
  setFieldErrors(prev => {
1120
1261
  if (!prev[field.key]) return prev
1121
1262
  const next = { ...prev }
@@ -1152,7 +1293,7 @@ export function DynamicRecordDialog({
1152
1293
  <DialogContent className="sm:max-w-2xl max-h-[90dvh] flex flex-col p-0 gap-0 overflow-hidden" style={{ maxHeight: '90dvh' }}>
1153
1294
  <DialogHeader className="p-6 pb-4 border-b shrink-0">
1154
1295
  <DialogTitle>{title}</DialogTitle>
1155
- <DialogDescription>{config.description}</DialogDescription>
1296
+ <DialogDescription>{texts.description}</DialogDescription>
1156
1297
  </DialogHeader>
1157
1298
 
1158
1299
  <div className="flex-1 overflow-y-auto p-6">
@@ -1332,7 +1473,7 @@ export function DynamicRecordDialog({
1332
1473
  disabled={saving || loading}
1333
1474
  >
1334
1475
  {saving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
1335
- {saving ? config.submittingLabel : config.submitLabel}
1476
+ {saving ? config.submittingLabel : texts.submitLabel}
1336
1477
  </Button>
1337
1478
  )}
1338
1479
  </div>
@@ -2435,18 +2576,34 @@ function ScannableRecordInput({
2435
2576
  )
2436
2577
  }
2437
2578
 
2438
- function ImageUploadField({ field: _field, value, onChange }: { field: FieldDef; value: any; onChange: (val: any) => void }) {
2579
+ function ImageUploadField({ field, value, onChange }: { field: FieldDef; value: any; onChange: (val: any) => void }) {
2439
2580
  const { t } = useTranslation()
2440
2581
  const api = useApi()
2441
2582
  const model = useContext(ModelContext)
2442
2583
  const getImageUrl = useContext(ImageUrlContext)
2443
2584
  const [uploading, setUploading] = useState(false)
2585
+ const [error, setError] = useState<string | null>(null)
2586
+ const [dragging, setDragging] = useState(false)
2444
2587
  const inputRef = useRef<HTMLInputElement>(null)
2445
-
2446
- async function handleFile(e: React.ChangeEvent<HTMLInputElement>) {
2447
- const file = e.target.files?.[0]
2448
- if (!file) return
2449
-
2588
+ const { accept: declaredAccept, maxSize } = getUploadConfig(field as ActionFieldDef)
2589
+ const accept = declaredAccept || 'image/*'
2590
+
2591
+ async function upload(file: File) {
2592
+ const rejected = validateUploadFile(file, { accept: declaredAccept, maxSize })
2593
+ if (rejected) {
2594
+ const msg =
2595
+ rejected === 'type'
2596
+ ? t('common.upload.invalid_type', { defaultValue: 'File type not allowed.' })
2597
+ : t('common.upload.too_large', {
2598
+ mb: ((maxSize ?? 0) / (1024 * 1024)).toFixed(1),
2599
+ defaultValue: 'File too large (max {{mb}} MB).',
2600
+ })
2601
+ setError(msg)
2602
+ toast.error(msg)
2603
+ if (inputRef.current) inputRef.current.value = ''
2604
+ return
2605
+ }
2606
+ setError(null)
2450
2607
  setUploading(true)
2451
2608
  try {
2452
2609
  const formData = new FormData()
@@ -2463,35 +2620,67 @@ function ImageUploadField({ field: _field, value, onChange }: { field: FieldDef;
2463
2620
  }
2464
2621
  }
2465
2622
 
2623
+ function handleFile(e: React.ChangeEvent<HTMLInputElement>) {
2624
+ const file = e.target.files?.[0]
2625
+ if (!file) return
2626
+ void upload(file)
2627
+ }
2628
+
2466
2629
  return (
2467
- <div className="flex items-center gap-3">
2468
- {value ? (
2469
- <div className="relative">
2470
- <img src={getImageUrl(String(value))} alt="" className="h-16 w-16 rounded-lg object-cover border" />
2630
+ <div className="grid gap-1.5">
2631
+ <div
2632
+ className="flex items-center gap-3"
2633
+ onDragOver={(e) => {
2634
+ // Siempre preventDefault: si no, el navegador abre el archivo soltado.
2635
+ e.preventDefault()
2636
+ if (value || uploading) return
2637
+ setDragging(true)
2638
+ }}
2639
+ onDragLeave={() => setDragging(false)}
2640
+ onDrop={(e) => {
2641
+ e.preventDefault()
2642
+ setDragging(false)
2643
+ const dropped = e.dataTransfer?.files?.[0]
2644
+ if (!dropped || value || uploading) return
2645
+ void upload(dropped)
2646
+ }}
2647
+ >
2648
+ {value ? (
2649
+ <div className="relative">
2650
+ <img src={getImageUrl(String(value))} alt="" className="h-16 w-16 rounded-lg object-cover border" />
2651
+ <button
2652
+ type="button"
2653
+ onClick={() => onChange('')}
2654
+ className="absolute -top-1.5 -right-1.5 size-5 bg-destructive text-white rounded-full flex items-center justify-center hover:bg-destructive/90"
2655
+ >
2656
+ <XIcon className="size-3" />
2657
+ </button>
2658
+ </div>
2659
+ ) : (
2471
2660
  <button
2472
2661
  type="button"
2473
- onClick={() => onChange('')}
2474
- className="absolute -top-1.5 -right-1.5 size-5 bg-destructive text-white rounded-full flex items-center justify-center hover:bg-destructive/90"
2662
+ onClick={() => inputRef.current?.click()}
2663
+ disabled={uploading}
2664
+ className={cn(
2665
+ 'h-16 w-16 rounded-lg border-2 border-dashed border-muted-foreground/30 flex flex-col items-center justify-center gap-1 hover:border-primary/50 hover:bg-muted/50 transition-colors disabled:opacity-50',
2666
+ dragging && 'border-primary/50 bg-muted/50',
2667
+ )}
2475
2668
  >
2476
- <XIcon className="size-3" />
2669
+ {uploading ? (
2670
+ <Loader2 className="size-4 animate-spin text-muted-foreground" />
2671
+ ) : (
2672
+ <Upload className="size-4 text-muted-foreground" />
2673
+ )}
2477
2674
  </button>
2478
- </div>
2479
- ) : (
2480
- <button
2481
- type="button"
2482
- onClick={() => inputRef.current?.click()}
2483
- disabled={uploading}
2484
- className="h-16 w-16 rounded-lg border-2 border-dashed border-muted-foreground/30 flex flex-col items-center justify-center gap-1 hover:border-primary/50 hover:bg-muted/50 transition-colors disabled:opacity-50"
2485
- >
2486
- {uploading ? (
2487
- <Loader2 className="size-4 animate-spin text-muted-foreground" />
2488
- ) : (
2489
- <Upload className="size-4 text-muted-foreground" />
2490
- )}
2491
- </button>
2675
+ )}
2676
+ <input ref={inputRef} type="file" accept={accept} onChange={handleFile} className="hidden" />
2677
+ {!value && <span className="text-xs text-muted-foreground">PNG, JPG, WebP</span>}
2678
+ </div>
2679
+ {error && (
2680
+ <span className="text-sm text-destructive" role="alert">
2681
+ {error}
2682
+ </span>
2492
2683
  )}
2493
- <input ref={inputRef} type="file" accept="image/*" onChange={handleFile} className="hidden" />
2494
- {!value && <span className="text-xs text-muted-foreground">PNG, JPG, WebP</span>}
2495
2684
  </div>
2496
2685
  )
2497
2686
  }
@@ -30,6 +30,11 @@ export interface ModelSchema {
30
30
  title?: string
31
31
  createTitle?: string
32
32
  editTitle?: string
33
+ createDescription?: string
34
+ editDescription?: string
35
+ viewDescription?: string
36
+ createSubmitLabel?: string
37
+ editSubmitLabel?: string
33
38
  fields?: Array<{
34
39
  key: string
35
40
  label: string