@asteby/metacore-runtime-react 49.2.0 → 49.3.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.
Files changed (34) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/dist/action-modal-dispatcher.d.ts.map +1 -1
  3. package/dist/action-modal-dispatcher.js +12 -3
  4. package/dist/business/document-editor-model.d.ts +33 -1
  5. package/dist/business/document-editor-model.d.ts.map +1 -1
  6. package/dist/business/document-editor-model.js +105 -3
  7. package/dist/business/document-editor.d.ts.map +1 -1
  8. package/dist/business/document-editor.js +54 -25
  9. package/dist/dynamic-form-schema.d.ts +3 -26
  10. package/dist/dynamic-form-schema.d.ts.map +1 -1
  11. package/dist/dynamic-form-schema.js +4 -56
  12. package/dist/dynamic-row-actions.d.ts +6 -0
  13. package/dist/dynamic-row-actions.d.ts.map +1 -1
  14. package/dist/dynamic-row-actions.js +9 -4
  15. package/dist/option-when.d.ts +27 -0
  16. package/dist/option-when.d.ts.map +1 -0
  17. package/dist/option-when.js +56 -0
  18. package/dist/validator.d.ts.map +1 -1
  19. package/dist/validator.js +17 -7
  20. package/package.json +1 -1
  21. package/src/__tests__/document-editor-model.test.ts +14 -1
  22. package/src/__tests__/document-editor.test.tsx +23 -1
  23. package/src/__tests__/invoice-document-editor.test.tsx +4 -3
  24. package/src/__tests__/option-when-validation.test.tsx +87 -0
  25. package/src/__tests__/r6-editor-option-when.test.tsx +104 -0
  26. package/src/__tests__/r6-editor-source-seeds.test.tsx +137 -0
  27. package/src/__tests__/row-action-link-navigation.test.ts +10 -6
  28. package/src/action-modal-dispatcher.tsx +14 -5
  29. package/src/business/document-editor-model.ts +116 -3
  30. package/src/business/document-editor.tsx +59 -19
  31. package/src/dynamic-form-schema.ts +5 -55
  32. package/src/dynamic-row-actions.tsx +12 -4
  33. package/src/option-when.ts +61 -0
  34. package/src/validator.ts +17 -5
@@ -0,0 +1,137 @@
1
+ // @vitest-environment happy-dom
2
+ // Retest Pitsline r6 (P0 UX): «Cargar desde» venta/OT/cotización debe dejar el
3
+ // CLIENTE elegido (su nombre en el selector y su tarjeta), aunque los renglones
4
+ // del origen fallen; y el selector «Factura a abonar» de la NC abierta desde una
5
+ // factura muestra el folio, no el UUID. El selector es el dynamic_select real
6
+ // (cerrado: no consulta opciones), así que la etiqueta sale de lo que el editor
7
+ // ya sabe del registro.
8
+ import { afterEach, describe, expect, it, vi } from 'vitest'
9
+ import { cleanup, render, screen, waitFor } from '@testing-library/react'
10
+
11
+ vi.mock('@tanstack/react-router', () => ({ useNavigate: () => () => {} }))
12
+ vi.mock('react-i18next', () => {
13
+ const value = {
14
+ t: (k: string, o?: Record<string, any>) => {
15
+ let s: string = o?.defaultValue ?? k
16
+ for (const [key, v] of Object.entries(o ?? {})) s = s.replace(`{{${key}}}`, String(v))
17
+ return s
18
+ },
19
+ i18n: { language: 'es' },
20
+ }
21
+ return { useTranslation: () => value }
22
+ })
23
+
24
+ import { DocumentFormDialog } from '../document-form-dialog'
25
+ import { ApiProvider, type ApiClient } from '../api-context'
26
+ import { TaxRateContext } from '../org-runtime-context'
27
+ import { seedRecord, sourceHeaderSeeds } from '../business/document-editor-model'
28
+ import type { DocumentFormsManifest, DocumentFormType } from '../types'
29
+
30
+ afterEach(cleanup)
31
+
32
+ const CUSTOMER = '6f1c2a9e-3b7d-4c55-9a51-0d2b8e7f4a10'
33
+ const INVOICE = '0b9d7c1e-5a4f-4e2b-8c3d-7f6e5d4c3b2a'
34
+
35
+ const invoice: DocumentFormType = {
36
+ key: 'invoice',
37
+ label: 'Factura',
38
+ layout: 'editor',
39
+ party: { field: 'customer_id', model: 'customers.Customer', summary: ['tax_id'] },
40
+ fields: [
41
+ { key: 'customer_id', label: 'Cliente', type: 'dynamic_select', ref: 'customers.Customer', required: true } as any,
42
+ { key: 'work_order_id', label: 'Orden de trabajo', type: 'dynamic_select', ref: 'workshop.WorkOrder' } as any,
43
+ ],
44
+ lines: { title: 'Renglones' },
45
+ sources: [
46
+ { key: 'work_order', label: 'Orden de trabajo', model: 'workshop.WorkOrder', lines: 'items', header: { customer_id: 'customer_id' }, link_field: 'work_order_id', line_link_field: 'work_order_item_id' },
47
+ ],
48
+ submit_label: 'Crear factura',
49
+ }
50
+
51
+ const creditNote: DocumentFormType = {
52
+ key: 'credit_note',
53
+ label: 'Nota de crédito',
54
+ layout: 'editor',
55
+ fields: [
56
+ { key: 'invoice_id', label: 'Factura a abonar', type: 'dynamic_select', ref: 'customers.Invoice', required: true, options: { source: 'customers.Invoice', value: 'id', label: 'number' } } as any,
57
+ ],
58
+ lines: { kind: 'credit', title: 'Conceptos' },
59
+ sources: [{ key: 'invoice', label: 'Factura', model: 'customers.Invoice', lines: 'items', link_field: 'invoice_id', line_link_field: 'invoice_item_id' }],
60
+ submit_label: 'Crear nota de crédito',
61
+ }
62
+
63
+ function makeApi(rows: Record<string, unknown[]>) {
64
+ const get = vi.fn(async (url: string) => {
65
+ if (url === '/data/customers.Customer') return { data: { data: [{ id: CUSTOMER, name: 'Transportes del Bajío', tax_id: 'TBA850312KJ9' }] } }
66
+ if (url.startsWith('/data/')) return { data: { data: rows[url.slice(6)] ?? [] } }
67
+ // Los renglones del origen no cargan (host sin source-lines ni relación).
68
+ if (url.endsWith('/source-lines') || url.startsWith('/metadata/table/')) throw new Error('boom')
69
+ return { data: { data: [] } }
70
+ })
71
+ const client = { get, post: vi.fn(), put: vi.fn(), delete: vi.fn() }
72
+ return client as unknown as ApiClient
73
+ }
74
+
75
+ function open(model: string, type: DocumentFormType, api: ApiClient, initialSource: { key: string; id: string }) {
76
+ const forms: DocumentFormsManifest = { lines_field: 'items', types: [type] }
77
+ return render(
78
+ <ApiProvider client={api}>
79
+ <TaxRateContext.Provider value={0.16}>
80
+ <DocumentFormDialog open onOpenChange={() => {}} model={model} forms={forms} initialType={type.key} initialSource={initialSource} currency="MXN" />
81
+ </TaxRateContext.Provider>
82
+ </ApiProvider>,
83
+ )
84
+ }
85
+
86
+ const trigger = (key: string) => document.getElementById(key) as HTMLElement
87
+
88
+ describe('«Cargar desde» llena el cliente', () => {
89
+ it('OT: el selector muestra el cliente por nombre y su tarjeta carga aunque los renglones fallen', async () => {
90
+ const api = makeApi({ 'workshop.WorkOrder': [{ id: 'wo-1', order_number: 'OT-00031', customer_id: CUSTOMER }] })
91
+ open('customers.Invoice', invoice, api, { key: 'work_order', id: 'wo-1' })
92
+ await waitFor(() => expect(trigger('customer_id').textContent).toContain('Transportes del Bajío'))
93
+ expect(trigger('customer_id').textContent).not.toContain(CUSTOMER)
94
+ expect(document.querySelector('[data-slot="party-card"]')).toBeTruthy()
95
+ expect(trigger('work_order_id').textContent).toContain('OT-00031')
96
+ })
97
+
98
+ it('el nombre del cliente que el host sirve junto a la FK se usa de inmediato', async () => {
99
+ const api = makeApi({
100
+ 'workshop.WorkOrder': [{ id: 'wo-1', customer_id: CUSTOMER, customer: { value: CUSTOMER, label: 'Transportes del Bajío' } }],
101
+ })
102
+ open('customers.Invoice', invoice, api, { key: 'work_order', id: 'wo-1' })
103
+ await waitFor(() => expect(trigger('customer_id').textContent).toContain('Transportes del Bajío'))
104
+ })
105
+ })
106
+
107
+ describe('NC desde la factura', () => {
108
+ it('«Factura a abonar» muestra el folio, no el UUID', async () => {
109
+ const api = makeApi({ 'customers.Invoice': [{ id: INVOICE, number: 'FAC-00014', customer_id: CUSTOMER }] })
110
+ open('fiscal_mexico.CreditNote', creditNote, api, { key: 'invoice', id: INVOICE })
111
+ await waitFor(() => expect(trigger('invoice_id').textContent).toContain('FAC-00014'))
112
+ expect(trigger('invoice_id').textContent).not.toContain(INVOICE)
113
+ expect(screen.queryByText(INVOICE)).toBeNull()
114
+ })
115
+ })
116
+
117
+ describe('reglas puras', () => {
118
+ it('sourceHeaderSeeds: hermano {value,label} de la FK y folio del origen', () => {
119
+ const seeds = sourceHeaderSeeds(
120
+ invoice.sources![0],
121
+ { id: 'wo-1', order_number: 'OT-7', customer_id: 'c-1', customer: { value: 'c-1', label: 'Ana' } },
122
+ 'wo-1',
123
+ invoice.fields,
124
+ )
125
+ expect(seeds).toEqual({ customer_id: { value: 'c-1', label: 'Ana' }, work_order_id: { value: 'wo-1', label: 'OT-7' } })
126
+ expect(sourceHeaderSeeds(invoice.sources![0], { id: 'wo-1', customer_id: 'c-1' }, 'wo-1')).toEqual({})
127
+ })
128
+
129
+ it('seedRecord: siembra el hermano y conserva el registro de origen', () => {
130
+ expect(seedRecord({}, undefined)).toBeUndefined()
131
+ expect(seedRecord({ customer_id: { value: 'c-1', label: 'Ana' } }, { id: 'inv-1', number: 'F-1' })).toEqual({
132
+ id: 'inv-1',
133
+ number: 'F-1',
134
+ customer: { value: 'c-1', label: 'Ana' },
135
+ })
136
+ })
137
+ })
@@ -1,17 +1,21 @@
1
1
  import { describe, expect, it } from 'vitest'
2
2
  import { linkNavigation } from '../dynamic-row-actions'
3
3
 
4
- // «Crear desde»: el botón de la fila del origen es una acción link con query
5
- // (`/m/invoices?create=invoice&from=sales_order&from_id={id}`). En `to` el
6
- // router la tomaba como parte del path y `$model` quedaba "invoices?create=…".
7
4
  describe('linkNavigation', () => {
8
- it('separa la query como search', () => {
5
+ it('parte /m/<tabla>?create… en ruta parametrizada + search (retest r6b)', () => {
9
6
  expect(linkNavigation('/m/invoices?create=invoice&from=sales_order&from_id=so-1')).toEqual({
10
- to: '/m/invoices',
7
+ to: '/m/$model',
8
+ params: { model: 'invoices' },
11
9
  search: { create: 'invoice', from: 'sales_order', from_id: 'so-1' },
12
10
  })
11
+ expect(linkNavigation('/m/credit_notes?create=credit_note&from=invoice&from_id=fac-1')).toEqual({
12
+ to: '/m/$model',
13
+ params: { model: 'credit_notes' },
14
+ search: { create: 'credit_note', from: 'invoice', from_id: 'fac-1' },
15
+ })
13
16
  })
14
- it('sin query deja el destino igual', () => {
17
+ it('deja paths que no son /m/<tabla> como pathname', () => {
15
18
  expect(linkNavigation('/m/quotes/abc')).toEqual({ to: '/m/quotes/abc' })
19
+ expect(linkNavigation('/settings')).toEqual({ to: '/settings' })
16
20
  })
17
21
  })
@@ -69,7 +69,7 @@ import { DynamicRelations } from './dynamic-relations'
69
69
  import { DynamicSelectField } from './dynamic-select-field'
70
70
  import { DynamicDateField } from './dynamic-date-field'
71
71
  import { UploadField } from './upload-field'
72
- import { isLineItemsField, resolveWidget, resolveDependsValue, getDependsOn, getFieldRef } from './dynamic-form-schema'
72
+ import { isLineItemsField, resolveWidget, resolveDependsValue, getDependsOn, getFieldRef, applyOptionWhen } from './dynamic-form-schema'
73
73
  import { FieldGrid, FieldCell, FieldLabel } from './field-grid'
74
74
  import { useMetadataCache } from './metadata-cache'
75
75
  import {
@@ -1752,15 +1752,24 @@ export function renderField(
1752
1752
  switch (widget) {
1753
1753
  case 'textarea':
1754
1754
  return <Textarea id={field.key} value={value || ''} onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => onChange(e.target.value)} placeholder={field.placeholder} aria-invalid={invalid || undefined} className={invalidCls || undefined} />
1755
- case 'select':
1755
+ case 'select': {
1756
+ // Opciones condicionadas por un campo hermano (`options[].when`, p. ej.
1757
+ // forma de pago «99» solo con método PPD): solo se ofrecen las que
1758
+ // aplican, y un valor ya elegido que dejó de aplicar se marca en el
1759
+ // acto (el validador y el kernel lo rechazan como invalid_option).
1760
+ const options = formValues ? applyOptionWhen(field.options, formValues, getDependsOn(field)) : field.options ?? []
1761
+ const stale = !!value && !options.some((o) => String(o.value) === String(value))
1762
+ const selectInvalid = invalid || stale
1763
+ const selectCls = selectInvalid ? 'border-destructive ring-1 ring-destructive/30 focus-visible:ring-destructive' : ''
1756
1764
  return (
1757
- <Select value={value || ''} onValueChange={onChange}>
1758
- <SelectTrigger className={'w-full' + (invalidCls ? ` ${invalidCls}` : '')} aria-invalid={invalid || undefined}><SelectValue placeholder={field.placeholder || 'Seleccionar...'} /></SelectTrigger>
1765
+ <Select value={stale ? '' : value || ''} onValueChange={onChange}>
1766
+ <SelectTrigger className={'w-full' + (selectCls ? ` ${selectCls}` : '')} aria-invalid={selectInvalid || undefined} data-stale-option={stale || undefined}><SelectValue placeholder={field.placeholder || 'Seleccionar...'} /></SelectTrigger>
1759
1767
  <SelectContent>
1760
- {field.options?.map((opt) => <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>)}
1768
+ {options.map((opt) => <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>)}
1761
1769
  </SelectContent>
1762
1770
  </Select>
1763
1771
  )
1772
+ }
1764
1773
  case 'switch':
1765
1774
  return <Switch id={field.key} checked={!!value} onCheckedChange={onChange} />
1766
1775
  case 'number':
@@ -6,6 +6,7 @@
6
6
  import { roundMoney, toAmount } from './format'
7
7
  import { computeTotals, makeLine, type LineItem } from './line-items'
8
8
  import { optionPassesRule, getOptionFilter } from '../option-filter'
9
+ import { applyOptionWhen, getDependsOn } from '../dynamic-form-schema'
9
10
  import type { ResolvedOption } from '../use-options-resolver'
10
11
  import type { Allocation, AllocationIssue, OpenDocument } from '../primitives/allocation'
11
12
  import type {
@@ -119,6 +120,40 @@ export function withFriendlyOptions(f: ActionFieldDef): ActionFieldDef {
119
120
  return { ...f, options: f.options.map((o) => ({ ...o, label: friendlyOptionLabel(String(o.label ?? o.value)) })) }
120
121
  }
121
122
 
123
+ /** Select estático con alguna opción condicionada por otro campo (`options[].when`). */
124
+ function isGatedSelect(f: ActionFieldDef): boolean {
125
+ return Array.isArray(f.options) && f.options.some((o) => !!o?.when)
126
+ }
127
+
128
+ /** Opciones del select que aplican con los valores actuales (`options[].when`). */
129
+ export function gatedOptions(f: ActionFieldDef, values: Record<string, unknown>): ActionFieldDef {
130
+ if (!isGatedSelect(f)) return f
131
+ return { ...f, options: applyOptionWhen(f.options, values, getDependsOn(f)) }
132
+ }
133
+
134
+ /**
135
+ * Selects con opciones condicionadas (`options[].when`, p. ej. forma de pago
136
+ * «99» solo con método PPD): cuando el valor actual deja de aplicar —o está
137
+ * vacío y solo queda una opción— devuelve el que toca. Una sola opción
138
+ * permitida se elige sola; si hay varias, el default del campo si aplica; si
139
+ * no, vacío. Sin cambios devuelve `{}`, así que aplicarlo converge.
140
+ */
141
+ export function gatedOptionFixes(fields: readonly ActionFieldDef[], values: Record<string, unknown>): Record<string, unknown> {
142
+ const out: Record<string, unknown> = {}
143
+ for (const f of fields) {
144
+ if (!isGatedSelect(f)) continue
145
+ const allowed = applyOptionWhen(f.options, values, getDependsOn(f))
146
+ const cur = values[f.key]
147
+ const ok = (v: unknown) => hasValue(v) && allowed.some((o) => String(o.value) === String(v))
148
+ if (ok(cur)) continue
149
+ if (!hasValue(cur) && allowed.length !== 1) continue
150
+ const def = declaredDefault(f)
151
+ const next = allowed.length === 1 ? allowed[0].value : ok(def) ? def : ''
152
+ if (String(next ?? '') !== String(cur ?? '')) out[f.key] = next
153
+ }
154
+ return out
155
+ }
156
+
122
157
  /**
123
158
  * Defaults del encabezado que salen de la contraparte: los campos de extensión
124
159
  * con la MISMA clave en ambos modelos (p. ej. `fiscal_data.uso_cfdi` de Customer
@@ -200,7 +235,8 @@ export function creditStatus(
200
235
  *
201
236
  * Con `remaining_quantity` (lo sirve el host: cantidad − lo ya facturado o
202
237
  * devuelto) la cantidad sugerida y el tope son lo pendiente y los renglones ya
203
- * cubiertos se omiten. Cada línea guarda `source_line_id` para el vínculo.
238
+ * cubiertos se omiten; un descuento en importe se prorratea a lo pendiente (un
239
+ * porcentaje no cambia). Cada línea guarda `source_line_id` para el vínculo.
204
240
  */
205
241
  export function linesFromSource(
206
242
  rows: unknown,
@@ -237,7 +273,16 @@ export function linesFromSource(
237
273
  })
238
274
  // El descuento del origen se lee en la unidad del documento (importe en
239
275
  // modelos cuyo subtotal resta un monto).
240
- if (opts.discountMode === 'amount') line.discount_kind = 'amount'
276
+ if (opts.discountMode === 'amount') {
277
+ line.discount_kind = 'amount'
278
+ // Un importe es de TODO el renglón de origen: al cargar solo lo
279
+ // pendiente se prorratea a esa cantidad (4 llantas con $400 de
280
+ // descuento, 1 pendiente → $100), si no superaría el importe.
281
+ const sourceQty = toAmount(r.source_quantity ?? get('quantity'))
282
+ if (pending != null && sourceQty > 0 && pending < sourceQty) {
283
+ line.discount = roundMoney((toAmount(line.discount) * pending) / sourceQty)
284
+ }
285
+ }
241
286
  if (pending != null) line.max_quantity = pending
242
287
  else if (opts.kind === 'credit') line.max_quantity = hasValue(get('max_quantity')) ? toAmount(get('max_quantity')) : qty
243
288
  const sourceLine = r.source_line_id ?? r.id
@@ -292,6 +337,74 @@ export function sourceTracksRemaining(src: Pick<DocumentFormSource, 'line_link_f
292
337
  return !!(src.line_link_field || src.remaining_qty_field || src.remaining_endpoint)
293
338
  }
294
339
 
340
+ /** Opción ya resuelta de un selector de la cabecera que el editor llenó por código. */
341
+ export interface SeedLabel {
342
+ value: string
343
+ label: string
344
+ }
345
+
346
+ /** Columnas con las que se nombra un documento (folio antes que nombre). */
347
+ const DOCUMENT_LABEL_COLUMNS = ['number', 'folio', 'order_number', 'name', 'title', 'code']
348
+
349
+ function declaredOptionLabel(f: ActionFieldDef | undefined): string | undefined {
350
+ const opts = (f as { options?: unknown } | undefined)?.options
351
+ const l = opts && !Array.isArray(opts) && typeof opts === 'object' ? (opts as { label?: unknown }).label : undefined
352
+ return typeof l === 'string' && l ? l : undefined
353
+ }
354
+
355
+ /** Nombre visible de un registro: la columna declarada por el campo, luego folio/nombre. */
356
+ export function recordLabel(rec: Record<string, any> | null | undefined, preferred?: string): string | undefined {
357
+ if (!rec) return undefined
358
+ for (const c of preferred ? [preferred, ...DOCUMENT_LABEL_COLUMNS] : DOCUMENT_LABEL_COLUMNS) {
359
+ const v = rec[c]
360
+ if ((typeof v === 'string' && v.trim()) || typeof v === 'number') return String(v)
361
+ }
362
+ return undefined
363
+ }
364
+
365
+ /**
366
+ * Etiquetas de lo que «Cargar desde…» escribe en la cabecera, para que el
367
+ * selector muestre el nombre y no el UUID sin abrirse:
368
+ * - `header` (`customer_id ← customer_id`): el objeto hermano `{value,label}`
369
+ * que el host sirve junto a la FK (`customer`);
370
+ * - `link_field`: el propio documento origen, con su folio.
371
+ */
372
+ export function sourceHeaderSeeds(
373
+ src: Pick<DocumentFormSource, 'header' | 'link_field'>,
374
+ rec: Record<string, any>,
375
+ id: string,
376
+ fields: readonly ActionFieldDef[] = [],
377
+ ): Record<string, SeedLabel> {
378
+ const out: Record<string, SeedLabel> = {}
379
+ for (const [to, from] of Object.entries(src.header ?? {})) {
380
+ if (!from.endsWith('_id')) continue
381
+ const v = refValue(rec[from])
382
+ const label = refLabel(rec[from]) ?? refLabel(rec[from.slice(0, -3)])
383
+ if (v && label) out[to] = { value: v, label }
384
+ }
385
+ if (src.link_field) {
386
+ const label = recordLabel(rec, declaredOptionLabel(fields.find((f) => f.key === src.link_field)))
387
+ if (label) out[src.link_field] = { value: id, label }
388
+ }
389
+ return out
390
+ }
391
+
392
+ /**
393
+ * Registro para `renderField` con las etiquetas sembradas como objeto hermano
394
+ * (`customer_id` → `customer: {value,label}`), el mismo contrato que sirve el
395
+ * host en una fila. Conserva el registro desde el que se abrió.
396
+ */
397
+ export function seedRecord(
398
+ seeds: Record<string, SeedLabel>,
399
+ record?: Record<string, any>,
400
+ ): Record<string, any> | undefined {
401
+ const keys = Object.keys(seeds).filter((k) => k.endsWith('_id'))
402
+ if (keys.length === 0) return record
403
+ const out: Record<string, any> = { ...(record ?? {}) }
404
+ for (const k of keys) out[k.slice(0, -3)] = seeds[k]
405
+ return out
406
+ }
407
+
295
408
  export interface EditorIssue {
296
409
  field?: string
297
410
  severity: 'error' | 'warning'
@@ -316,7 +429,7 @@ export function localIssues(lines: LineItem[], opts: { requireLines?: boolean; r
316
429
  issues.push({
317
430
  field: `lines.${i}`,
318
431
  severity: 'error',
319
- message: `Renglón ${i + 1}: la cantidad excede lo pendiente del documento origen (${l.max_quantity}).`,
432
+ message: `Renglón ${i + 1}: la cantidad excede lo pendiente del documento origen (quedan ${l.max_quantity}).`,
320
433
  })
321
434
  }
322
435
  if (opts.requireTax && toAmount(l.tax_rate) === 0) {
@@ -42,11 +42,17 @@ import {
42
42
  sourceTracksRemaining,
43
43
  partyDefaults,
44
44
  partySummaryRows,
45
+ recordLabel,
46
+ seedRecord,
47
+ sourceHeaderSeeds,
45
48
  splitEditorFields,
46
49
  toOpenDocuments,
47
50
  friendlyOptionLabel,
51
+ gatedOptionFixes,
52
+ gatedOptions,
48
53
  withFriendlyOptions,
49
54
  type EditorIssue,
55
+ type SeedLabel,
50
56
  } from './document-editor-model'
51
57
  import {
52
58
  CollapsibleSection,
@@ -140,6 +146,9 @@ export function DocumentEditor({
140
146
  const [extFields, setExtFields] = useState<ActionFieldDef[]>([])
141
147
  const [party, setParty] = useState<Record<string, any> | null>(null)
142
148
  const [partyLabels, setPartyLabels] = useState<Record<string, string>>({})
149
+ // Etiquetas de los selectores que el editor llena por código (contraparte y
150
+ // documento origen de «Cargar desde…»): sin ellas el selector cerrado pinta el UUID.
151
+ const [seeds, setSeeds] = useState<Record<string, SeedLabel>>({})
143
152
  const [openDocs, setOpenDocs] = useState<OpenDocument[]>([])
144
153
  const [docsLoading, setDocsLoading] = useState(false)
145
154
  const [alloc, setAlloc] = useState<PaymentAllocatorValue>({ strategy: 'oldest_due_first', manual: {} })
@@ -159,6 +168,7 @@ export function DocumentEditor({
159
168
  // renglón para que el servidor descuente lo ya facturado/devuelto y valide.
160
169
  const [loadedSource, setLoadedSource] = useState<DocumentFormSource | null>(null)
161
170
  const [sourceNote, setSourceNote] = useState<string | undefined>()
171
+ const [sourceSeed, setSourceSeed] = useState<SeedLabel | null>(null)
162
172
  const relCache = useRef(new Map<string, Promise<any[]>>())
163
173
 
164
174
  const taxRate = defaultTaxRate ?? orgTaxRate
@@ -207,6 +217,15 @@ export function DocumentEditor({
207
217
  const fieldKeys = useRef<string[]>([])
208
218
  fieldKeys.current = allFields.map((f) => f.key)
209
219
 
220
+ // Opciones condicionadas (`options[].when`): al cambiar el campo del que
221
+ // dependen —a mano, por la contraparte o por «Cargar desde…»— el valor que
222
+ // dejó de aplicar se ajusta solo (método PPD → forma de pago 99) y viaja así
223
+ // en el alta, no solo en el diálogo de timbrado.
224
+ useEffect(() => {
225
+ const fixes = gatedOptionFixes(allFields, header)
226
+ if (Object.keys(fixes).length > 0) setHeader((h) => ({ ...h, ...gatedOptionFixes(allFields, h) }))
227
+ }, [allFields, header])
228
+
210
229
  // Contraparte: tarjeta + defaults de las extensiones con la misma clave.
211
230
  const partyId = type.party ? header[type.party.field] : undefined
212
231
  useEffect(() => {
@@ -223,6 +242,11 @@ export function DocumentEditor({
223
242
  if (cancelled) return
224
243
  setParty(rec)
225
244
  setHeader((h) => ({ ...h, ...partyDefaults(rec, fieldKeys.current, h) }))
245
+ const label = recordLabel(rec, 'name') ?? recordLabel(rec, 'legal_name')
246
+ if (label && type.party) {
247
+ const key = type.party.field
248
+ setSeeds((s) => ({ ...s, [key]: { value: String(partyId), label } }))
249
+ }
226
250
  })
227
251
  .catch(() => !cancelled && setParty(null))
228
252
  return () => {
@@ -392,6 +416,26 @@ export function DocumentEditor({
392
416
  if (!lineCfg || !id) return
393
417
  setBusy('source')
394
418
  try {
419
+ // Cabecera primero (cliente, moneda, vínculo): llega aunque los
420
+ // renglones del origen fallen, y la tarjeta del cliente se carga.
421
+ if (src.header || src.link_field) {
422
+ const h = await api.get(`/data/${src.model}`, { params: { f_id: `eq:${id}`, per_page: 1 } })
423
+ const rec = ((h?.data?.data ?? [])[0] ?? {}) as Record<string, any>
424
+ setHeader((prev) => {
425
+ const next = { ...prev }
426
+ for (const [to, from] of Object.entries(src.header ?? {})) {
427
+ const v = rec[from]
428
+ if (v == null || v === '') continue
429
+ next[to] = typeof v === 'object' && !Array.isArray(v) ? v.value ?? v.id ?? v : v
430
+ }
431
+ if (src.link_field) next[src.link_field] = id
432
+ return next
433
+ })
434
+ const seeded = sourceHeaderSeeds(src, rec, id, type.fields)
435
+ setSeeds((s) => ({ ...s, ...seeded }))
436
+ const label = src.link_field ? seeded[src.link_field]?.label : recordLabel(rec)
437
+ setSourceSeed(label ? { value: id, label } : null)
438
+ }
395
439
  if (!isAllocation) {
396
440
  const rows = await fetchSourceRows(src, id)
397
441
  const loaded = linesFromSource(rows, src.map, { kind, discountMode: lineCfg.discount_mode, defaultTaxRate: taxRate })
@@ -402,27 +446,17 @@ export function DocumentEditor({
402
446
  setSourceNote(
403
447
  loaded.length === 0 && covered > 0
404
448
  ? t('documentEditor.source_all_covered', {
405
- defaultValue: 'Todo el documento ya está registrado en otros documentos; no queda nada pendiente.',
449
+ defaultValue: 'Ese documento ya se registró completo; no queda nada pendiente.',
406
450
  })
407
451
  : covered > 0
408
452
  ? t('documentEditor.source_loaded_partial', {
409
- defaultValue: '{{count}} renglones con lo pendiente · {{covered}} ya cubiertos se omitieron',
453
+ defaultValue: '{{count}} renglones con lo que falta · {{covered}} ya completos (omitidos)',
410
454
  count: loaded.length,
411
455
  covered,
412
456
  })
413
457
  : t('documentEditor.source_loaded', { defaultValue: '{{count}} renglones cargados', count: loaded.length }),
414
458
  )
415
459
  }
416
- if (src.header || src.link_field) {
417
- const h = await api.get(`/data/${src.model}`, { params: { f_id: `eq:${id}`, per_page: 1 } })
418
- const rec = ((h?.data?.data ?? [])[0] ?? {}) as Record<string, any>
419
- setHeader((prev) => {
420
- const next = { ...prev }
421
- for (const [to, from] of Object.entries(src.header ?? {})) if (rec[from] != null) next[to] = rec[from]
422
- if (src.link_field) next[src.link_field] = id
423
- return next
424
- })
425
- }
426
460
  setServerIssues([])
427
461
  } catch (err) {
428
462
  toast.error(t('documentEditor.source_failed', { defaultValue: 'No se pudo cargar el documento' }), {
@@ -432,7 +466,7 @@ export function DocumentEditor({
432
466
  setBusy(null)
433
467
  }
434
468
  },
435
- [api, lineCfg, isAllocation, kind, t, fetchSourceRows, taxRate],
469
+ [api, lineCfg, isAllocation, kind, t, fetchSourceRows, taxRate, type.fields],
436
470
  )
437
471
 
438
472
  // Prefill al abrir desde un documento origen (acción de fila «Crear NC», «Facturar venta»…).
@@ -549,13 +583,14 @@ export function DocumentEditor({
549
583
  setFieldErrors((prev) => clearFieldErrorTree(prev, key))
550
584
  }
551
585
 
586
+ const fieldRecord = useMemo(() => seedRecord(seeds, record), [seeds, record])
552
587
  const fieldCell = (field: ActionFieldDef, fullWidth = false) =>
553
588
  visible(field) ? (
554
589
  <FieldCell key={field.key} fullWidth={fullWidth}>
555
590
  <FieldLabel htmlFor={field.key} required={field.required}>
556
591
  {tl(field.label)}
557
592
  </FieldLabel>
558
- {renderField(withFriendlyOptions(field), header[field.key], (v: any) => updateField(field.key, v), header, undefined, fieldErrors)}
593
+ {renderField(withFriendlyOptions(gatedOptions(field, header)), header[field.key], (v: any) => updateField(field.key, v), header, fieldRecord, fieldErrors)}
559
594
  {fieldErrors[field.key] && <p className="mt-1 text-xs text-destructive">{fieldErrors[field.key]}</p>}
560
595
  </FieldCell>
561
596
  ) : null
@@ -569,7 +604,7 @@ export function DocumentEditor({
569
604
  .map((f) => {
570
605
  const v = header[f.key]
571
606
  if (v == null || v === '') return null
572
- const opt = f.options?.find((o) => String(o.value) === String(v))
607
+ const opt = Array.isArray(f.options) ? f.options.find((o) => String(o.value) === String(v)) : undefined
573
608
  return opt ? String(opt.value) : String(v)
574
609
  })
575
610
  .filter(Boolean)
@@ -630,7 +665,7 @@ export function DocumentEditor({
630
665
  {sources.length > 1 && (
631
666
  <div
632
667
  role="radiogroup"
633
- aria-label={t('documentEditor.source_kind', { defaultValue: 'Tipo de documento origen' })}
668
+ aria-label={t('documentEditor.source_kind', { defaultValue: 'Documento de origen' })}
634
669
  className="inline-flex flex-wrap gap-1 rounded-md border p-1"
635
670
  >
636
671
  {sources.map((s) => (
@@ -658,6 +693,7 @@ export function DocumentEditor({
658
693
  key={activeSource.key}
659
694
  source={activeSource}
660
695
  value={sourceId}
696
+ seed={sourceSeed}
661
697
  header={header}
662
698
  label={tl(activeSource.label)}
663
699
  onPick={(id) => {
@@ -769,8 +805,9 @@ export function DocumentEditor({
769
805
  .filter(visible)
770
806
  .map((f) => {
771
807
  const v = header[f.key]
772
- const opt = f.options?.find((o) => String(o.value) === String(v))
773
- return { label: tl(f.label), value: v == null || v === '' ? '' : opt ? friendlyOptionLabel(tl(String(opt.label ?? v))) : String(v) }
808
+ const opt = Array.isArray(f.options) ? f.options.find((o) => String(o.value) === String(v)) : undefined
809
+ const seeded = seeds[f.key] && String(seeds[f.key].value) === String(v) ? seeds[f.key].label : undefined
810
+ return { label: tl(f.label), value: v == null || v === '' ? '' : opt ? friendlyOptionLabel(tl(String(opt.label ?? v))) : seeded ?? String(v) }
774
811
  })
775
812
  .filter((r) => r.value)}
776
813
  lines={lines}
@@ -835,12 +872,15 @@ export function DocumentEditor({
835
872
  function SourcePicker({
836
873
  source,
837
874
  value,
875
+ seed,
838
876
  header,
839
877
  label,
840
878
  onPick,
841
879
  }: {
842
880
  source: DocumentFormSource
843
881
  value: string
882
+ /** Folio del origen ya cargado: el selector cerrado lo muestra en vez del UUID. */
883
+ seed?: SeedLabel | null
844
884
  header: Record<string, any>
845
885
  label: string
846
886
  onPick: (id: string) => void
@@ -858,7 +898,7 @@ function SourcePicker({
858
898
  )
859
899
  return (
860
900
  <div className="min-w-[240px] flex-1" data-source={source.key}>
861
- {renderField(field, value, (v: any) => onPick(v == null || v === '' ? '' : String(v)), header)}
901
+ {renderField(field, value, (v: any) => onPick(v == null || v === '' ? '' : String(v)), header, seed ? { id: seed.value, label: seed.label } : undefined)}
862
902
  </div>
863
903
  )
864
904
  }
@@ -4,8 +4,13 @@
4
4
  import { z, type ZodTypeAny } from 'zod'
5
5
  import type { ActionFieldDef, FieldOptionsConfig, OptionDef, VisibleWhen } from './types'
6
6
  import { fieldValidationOf } from './validator'
7
+ import { applyOptionWhen, getDependsOn } from './option-when'
7
8
  import { resolveValidatorToken } from './use-org-config-bridge'
8
9
 
10
+ // Viven en option-when.ts (el validador también los usa); se re-exportan aquí
11
+ // para no romper a quien los importaba de este módulo.
12
+ export { applyOptionWhen, getDependsOn }
13
+
9
14
  /**
10
15
  * Built-in validators the SDK knows how to apply by symbolic name. Apps
11
16
  * that wire `OrgConfigProvider` map `$org.<key>` references to one of
@@ -389,18 +394,6 @@ export function fieldHasRef(field: ActionFieldDef): boolean {
389
394
  return getFieldRef(field) !== undefined
390
395
  }
391
396
 
392
- /**
393
- * Resolves a field's cascade dependency — the key of another form field whose
394
- * current value scopes this picker's options (`filter_value`). Tolerates the
395
- * camelCase `dependsOn` (authored SDK shape) and the snake_case `depends_on`
396
- * the kernel manifest serves. Returns the trimmed field key, or `undefined`
397
- * when the field declares no dependency.
398
- */
399
- export function getDependsOn(field: ActionFieldDef): string | undefined {
400
- const dep = field.dependsOn ?? field.depends_on
401
- if (typeof dep === 'string' && dep.trim() !== '') return dep.trim()
402
- return undefined
403
- }
404
397
 
405
398
  /**
406
399
  * Resolves the cascade `filter_value` for a field from the surrounding form
@@ -424,49 +417,6 @@ export function resolveDependsValue(
424
417
  return String(raw)
425
418
  }
426
419
 
427
- /**
428
- * Filters a STATIC enum's `options[]` by each option's `when` gate against the
429
- * current form values. Pure — no React, no side effects.
430
- *
431
- * Rule per option:
432
- * - No `when` → always included (retrocompat; existing enums untouched).
433
- * - With `when`: the gating field is `when.field ?? dependsOn`. If neither is
434
- * present the option is included (nothing to gate on). Otherwise the form's
435
- * value for that field is compared AS STRING: included when (no `in`, or
436
- * value ∈ `in`) AND (no `not_in`, or value ∉ `not_in`). Tolerates the
437
- * snake_case `not_in` the kernel serves alongside camelCase `notIn`.
438
- *
439
- * `formValues` is the flat map of the surrounding form/row values the gating
440
- * field is read from; `dependsOn` is the containing field's declared dependency
441
- * used as the default gating field.
442
- */
443
- export function applyOptionWhen(
444
- options: OptionDef[] | undefined,
445
- formValues: Record<string, any> | null | undefined,
446
- dependsOn?: string,
447
- ): OptionDef[] {
448
- if (!Array.isArray(options)) return []
449
- return options.filter((opt) => {
450
- const when = opt?.when
451
- if (!when) return true
452
- const gate = (typeof when.field === 'string' && when.field.trim() !== '')
453
- ? when.field.trim()
454
- : dependsOn
455
- if (!gate) return true
456
- const raw = formValues ? formValues[gate] : undefined
457
- const current = raw == null ? '' : String(raw)
458
- const inList = when.in
459
- const notIn = when.notIn ?? when.not_in
460
- if (Array.isArray(inList) && inList.length > 0) {
461
- if (!inList.some((v) => String(v) === current)) return false
462
- }
463
- if (Array.isArray(notIn) && notIn.length > 0) {
464
- if (notIn.some((v) => String(v) === current)) return false
465
- }
466
- return true
467
- })
468
- }
469
-
470
420
  /**
471
421
  * Reads a field's `visible_when` predicate, tolerating the camelCase alias
472
422
  * (`visibleWhen`) an app may author and the snake_case (`visible_when`) the