@asteby/metacore-runtime-react 49.2.1 → 49.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/CHANGELOG.md +30 -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 +12 -1
  5. package/dist/business/document-editor-model.d.ts.map +1 -1
  6. package/dist/business/document-editor-model.js +49 -3
  7. package/dist/business/document-editor.d.ts.map +1 -1
  8. package/dist/business/document-editor.js +14 -5
  9. package/dist/document-form-dialog.d.ts.map +1 -1
  10. package/dist/document-form-dialog.js +20 -12
  11. package/dist/dynamic-form-schema.d.ts +3 -26
  12. package/dist/dynamic-form-schema.d.ts.map +1 -1
  13. package/dist/dynamic-form-schema.js +4 -56
  14. package/dist/option-when.d.ts +27 -0
  15. package/dist/option-when.d.ts.map +1 -0
  16. package/dist/option-when.js +56 -0
  17. package/dist/validator.d.ts.map +1 -1
  18. package/dist/validator.js +17 -7
  19. package/package.json +1 -1
  20. package/src/__tests__/document-editor-model.test.ts +14 -1
  21. package/src/__tests__/document-editor.test.tsx +23 -1
  22. package/src/__tests__/document-form-dialog.no-stale-flash.test.tsx +169 -0
  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/action-modal-dispatcher.tsx +14 -5
  27. package/src/business/document-editor-model.ts +48 -3
  28. package/src/business/document-editor.tsx +15 -4
  29. package/src/document-form-dialog.tsx +20 -11
  30. package/src/dynamic-form-schema.ts +5 -55
  31. package/src/option-when.ts +61 -0
  32. package/src/validator.ts +17 -5
package/dist/validator.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { applyOptionWhen, getDependsOn } from './option-when';
1
2
  const NIL_UUID = '00000000-0000-0000-0000-000000000000';
2
3
  const NUMERIC_TYPES = new Set(['int', 'integer', 'bigint', 'decimal', 'numeric', 'number', 'float', 'double']);
3
4
  const RULE_NAMES = new Set([
@@ -203,7 +204,13 @@ function checkBuiltin(slug, value) {
203
204
  return undefined;
204
205
  }
205
206
  }
206
- function specFromField(field) {
207
+ /**
208
+ * `context` son los valores hermanos contra los que se evalúa el `when` de
209
+ * cada opción: una opción que su `when` descarta con el valor actual (forma de
210
+ * pago «99» con método PUE) es `invalid_option`, igual que una fuera de catálogo
211
+ * — y como la rechaza el kernel al guardar.
212
+ */
213
+ function specFromField(field, context) {
207
214
  const v = fieldValidationOf(field);
208
215
  const spec = {
209
216
  required: !!field.required,
@@ -213,8 +220,10 @@ function specFromField(field) {
213
220
  max: v.max,
214
221
  custom: v.custom,
215
222
  };
216
- if (field.options?.length)
217
- spec.options = field.options.map(o => String(o.value));
223
+ if (field.options?.length) {
224
+ const applicable = context ? applyOptionWhen(field.options, context, getDependsOn(field)) : field.options;
225
+ spec.options = applicable.map(o => String(o.value));
226
+ }
218
227
  return spec;
219
228
  }
220
229
  function isLineItems(field) {
@@ -229,10 +238,10 @@ function itemFieldsOf(field) {
229
238
  * field issue, dotted keys for line-items (`items.0.qty`). */
230
239
  export function validateValues(fields, values) {
231
240
  const bag = {};
232
- walk(fields, values ?? {}, '', bag);
241
+ walk(fields, values ?? {}, '', bag, values ?? {});
233
242
  return bag;
234
243
  }
235
- function walk(fields, values, prefix, bag) {
244
+ function walk(fields, values, prefix, bag, context) {
236
245
  for (const field of fields) {
237
246
  const key = field.key;
238
247
  if (!key)
@@ -247,11 +256,12 @@ function walk(fields, values, prefix, bag) {
247
256
  }
248
257
  rows.forEach((row, i) => {
249
258
  const obj = row && typeof row === 'object' ? row : {};
250
- walk(itemFieldsOf(field), obj, `${path}.${i}`, bag);
259
+ // Una celda puede depender de otra del renglón o del encabezado.
260
+ walk(itemFieldsOf(field), obj, `${path}.${i}`, bag, { ...context, ...obj });
251
261
  });
252
262
  continue;
253
263
  }
254
- const issues = checkValue(raw, specFromField(field));
264
+ const issues = checkValue(raw, specFromField(field, context));
255
265
  if (issues.length)
256
266
  bag[path] = issues;
257
267
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asteby/metacore-runtime-react",
3
- "version": "49.2.1",
3
+ "version": "49.3.1",
4
4
  "description": "React runtime for metacore hosts — renders addon contributions dynamically",
5
5
  "repository": {
6
6
  "type": "git",
@@ -17,7 +17,7 @@ import {
17
17
  splitEditorFields,
18
18
  toOpenDocuments,
19
19
  } from '../business/document-editor-model'
20
- import { makeLine, serializeLineItems } from '../business/line-items'
20
+ import { makeLine, serializeLineItems, validateLineItems } from '../business/line-items'
21
21
  import { allocatePayment, validateAllocation } from '../primitives/allocation'
22
22
  import type { ActionFieldDef, DocumentFormOpenDocuments } from '../types'
23
23
 
@@ -100,6 +100,19 @@ describe('linesFromSource', () => {
100
100
  expect(l.discount).toBe(10)
101
101
  expect(l.tax_rate).toBe(0.16)
102
102
  })
103
+ it('carga parcial: el descuento en importe se prorratea a lo pendiente (no supera el importe)', () => {
104
+ // Cotización 4 llantas × $1,000 con $400 de descuento; 3 ya facturadas.
105
+ const rows = [{ id: 'q1', description: 'Llanta', quantity: 4, unit_price: 1000, discount_amount: 400, tax_rate: 16, source_quantity: 4, remaining_quantity: 1 }]
106
+ const [l] = linesFromSource(rows, { discount: 'discount_amount' }, { discountMode: 'amount' })
107
+ expect(l).toMatchObject({ quantity: 1, max_quantity: 1, discount: 100, discount_kind: 'amount' })
108
+ expect(validateLineItems([l]).errors).toEqual({})
109
+ // Sin lo pendiente servido (o completo) el importe queda intacto.
110
+ const [full] = linesFromSource([{ ...rows[0], remaining_quantity: 4 }], { discount: 'discount_amount' }, { discountMode: 'amount' })
111
+ expect(full.discount).toBe(400)
112
+ // Un porcentaje no depende de la cantidad.
113
+ const [pct] = linesFromSource([{ ...rows[0], discount_pct: 10 }], { discount: 'discount_pct' })
114
+ expect(pct.discount).toBe(10)
115
+ })
103
116
  it('NC (credit): la cantidad queda topada en lo facturado', () => {
104
117
  const [l] = linesFromSource([{ description: 'Llanta', quantity: 4, unit_price: 1500, tax_rate: 0.16 }], {}, { kind: 'credit' })
105
118
  expect(l.max_quantity).toBe(4)
@@ -224,6 +224,28 @@ describe('DocumentEditor — cobro / REP (lines.kind: allocation)', () => {
224
224
  expect(body.type).toBeUndefined()
225
225
  })
226
226
 
227
+ it('«crear desde» una factura: toma su cliente y lista sus facturas abiertas con saldo', async () => {
228
+ const fromInvoice: DocumentFormType = {
229
+ ...payment,
230
+ fields: payment.fields.map((f) => ({ ...f, default_from_record: undefined }) as any),
231
+ sources: [{ key: 'invoice', label: 'Factura', model: 'customers.Invoice', lines: 'items', header: { customer_id: 'customer_id' } }],
232
+ }
233
+ const api = makeApi({
234
+ ...routes,
235
+ '/data/customers.Invoice': (_url: string, cfg?: { params?: Record<string, unknown> }) =>
236
+ cfg?.params?.f_id
237
+ ? { data: [{ id: 'inv-new', number: 'A-2', customer_id: 'c1', amount_due: 1000 }] }
238
+ : (routes['/data/customers.Invoice'] as unknown),
239
+ })
240
+ renderEditor(fromInvoice, api, { initialSource: { key: 'invoice', id: 'inv-new' } })
241
+ await screen.findByText('A-1')
242
+ expect(screen.getByText('A-2')).toBeTruthy()
243
+ expect(api.get).toHaveBeenCalledWith('/data/customers.Invoice', expect.objectContaining({ params: expect.objectContaining({ f_id: 'eq:inv-new' }) }))
244
+ expect(api.get).toHaveBeenCalledWith('/data/customers.Invoice', expect.objectContaining({ params: expect.objectContaining({ f_customer_id: 'eq:c1' }) }))
245
+ // Sin renglones que copiar: no pide source-lines ni la relación.
246
+ expect(api.get.mock.calls.some(([u]) => String(u).includes('source-lines'))).toBe(false)
247
+ })
248
+
227
249
  it('editar un monto pasa a reparto manual; «Autoaplicar» regresa al automático', async () => {
228
250
  const api = makeApi(routes)
229
251
  renderEditor(payment, api, { record: { customer_id: 'c1' } })
@@ -298,7 +320,7 @@ describe('DocumentEditor — «crear desde» con lo pendiente del servidor', ()
298
320
  await screen.findByDisplayValue('Llanta 205/55R16')
299
321
  expect(screen.queryByDisplayValue('Balanceo')).toBeNull()
300
322
  expect(api.get).toHaveBeenCalledWith('/dynamic/customers.Invoice/source-lines', { params: { source: 'sales_order', id: 'so-1' } })
301
- expect(await screen.findByText('1 renglones con lo pendiente · 1 ya cubiertos se omitieron')).toBeTruthy()
323
+ expect(await screen.findByText('1 renglones con lo que falta · 1 ya completos (omitidos)')).toBeTruthy()
302
324
  })
303
325
 
304
326
  it('si el host aún no sirve source-lines (404) cae a la relación del origen', async () => {
@@ -0,0 +1,169 @@
1
+ // @vitest-environment happy-dom
2
+ // QA Pitsline r6: «al abrir una Nota de crédito se ve un instante el modal viejo»
3
+ // antes del DocumentEditor. El host reutiliza el diálogo montado (misma ruta
4
+ // /m/$model para Facturas → Notas de crédito, o formularios que cambian de la
5
+ // caché a la metadata viva mientras está cerrado) y el primer render al abrir
6
+ // pintaba el wizard con el tipo de la apertura anterior: el reinicio vivía en un
7
+ // efecto, que corre DESPUÉS de que ese frame ya se pintó.
8
+ import { afterEach, describe, expect, it, vi } from 'vitest'
9
+ import { cleanup, render } from '@testing-library/react'
10
+
11
+ vi.mock('@tanstack/react-router', () => ({ useNavigate: () => () => {} }))
12
+ vi.mock('react-i18next', () => {
13
+ const i18n = { language: 'es' }
14
+ const t = (k: string, o?: { defaultValue?: string }) => o?.defaultValue ?? k
15
+ const value = { t, i18n }
16
+ return { useTranslation: () => value }
17
+ })
18
+ // Dialog sin portal ni Presence: cada commit de React llega tal cual al DOM. Con
19
+ // el portal de Radix el primer commit al abrir queda vacío y, en act(), el efecto
20
+ // de reinicio alcanza a correr antes del siguiente; en el navegador ese reinicio
21
+ // va en otra prioridad y el frame intermedio sí se pinta.
22
+ vi.mock('@asteby/metacore-ui/primitives', async (importOriginal) => {
23
+ const actual = await importOriginal<Record<string, unknown>>()
24
+ const React = await import('react')
25
+ return {
26
+ ...actual,
27
+ Dialog: ({ open, children }: { open?: boolean; children?: React.ReactNode }) =>
28
+ open ? React.createElement(React.Fragment, null, children) : null,
29
+ DialogContent: ({ children, ...rest }: Record<string, unknown> & { children?: React.ReactNode }) => {
30
+ const attrs: Record<string, unknown> = {}
31
+ for (const [k, v] of Object.entries(rest)) if (k.startsWith('data-')) attrs[k] = v
32
+ return React.createElement('div', { role: 'dialog', ...attrs }, children)
33
+ },
34
+ DialogHeader: ({ children }: { children?: React.ReactNode }) => React.createElement('div', null, children),
35
+ DialogFooter: ({ children }: { children?: React.ReactNode }) => React.createElement('div', null, children),
36
+ DialogTitle: ({ children }: { children?: React.ReactNode }) => React.createElement('h2', null, children),
37
+ DialogDescription: ({ children }: { children?: React.ReactNode }) => React.createElement('p', null, children),
38
+ }
39
+ })
40
+
41
+ import { DocumentFormDialog } from '../document-form-dialog'
42
+ import { ApiProvider, type ApiClient } from '../api-context'
43
+ import type { DocumentFormsManifest } from '../types'
44
+
45
+ afterEach(cleanup)
46
+
47
+ const client = {
48
+ get: vi.fn().mockResolvedValue({ data: { data: [] } }),
49
+ post: vi.fn(),
50
+ put: vi.fn(),
51
+ delete: vi.fn(),
52
+ } as unknown as ApiClient
53
+
54
+ // Formularios genéricos con layout editor (cualquier document_form, no sólo fiscal).
55
+ const formsA: DocumentFormsManifest = {
56
+ types: [
57
+ {
58
+ key: 'doc_a',
59
+ label: 'Documento A',
60
+ layout: 'editor',
61
+ fields: [{ key: 'party', label: 'Contraparte', type: 'text' }],
62
+ },
63
+ ],
64
+ }
65
+ const formsB: DocumentFormsManifest = {
66
+ types: [
67
+ {
68
+ key: 'doc_b',
69
+ label: 'Documento B',
70
+ layout: 'editor',
71
+ submit_action: 'create_doc_b',
72
+ fields: [{ key: 'origin', label: 'Origen', type: 'text' }],
73
+ },
74
+ ],
75
+ }
76
+ const formsAB: DocumentFormsManifest = { types: [...formsA.types, ...formsB.types] }
77
+
78
+ /** Registra si el wizard llegó a montarse en el DOM, aunque sea un frame. */
79
+ function watchLegacyDialog(forbiddenText?: string) {
80
+ let seen = false
81
+ let sawText = false
82
+ const hasText = (v: string | null | undefined) => !!forbiddenText && !!v && v.includes(forbiddenText)
83
+ const hit = (n: Node) =>
84
+ n instanceof Element &&
85
+ (n.matches('[data-slot="document-form-dialog"]') || !!n.querySelector('[data-slot="document-form-dialog"]'))
86
+ const check = () => {
87
+ if (document.querySelector('[data-slot="document-form-dialog"]')) seen = true
88
+ }
89
+ // React reutiliza el mismo nodo del Dialog entre ramas y sólo cambia
90
+ // `data-slot`: se mira también el valor anterior del atributo.
91
+ const scan = (records: MutationRecord[]) => {
92
+ for (const r of records) {
93
+ if (r.type === 'attributes' && r.oldValue === 'document-form-dialog') seen = true
94
+ if (r.type === 'characterData' && hasText(r.oldValue)) sawText = true
95
+ r.addedNodes.forEach((n) => {
96
+ if (hit(n)) seen = true
97
+ if (hasText(n.textContent)) sawText = true
98
+ })
99
+ }
100
+ }
101
+ const obs = new MutationObserver(scan)
102
+ obs.observe(document.body, {
103
+ childList: true,
104
+ subtree: true,
105
+ attributes: true,
106
+ attributeOldValue: true,
107
+ attributeFilter: ['data-slot'],
108
+ characterData: true,
109
+ characterDataOldValue: true,
110
+ })
111
+ return {
112
+ check,
113
+ seen: () => {
114
+ scan(obs.takeRecords())
115
+ obs.disconnect()
116
+ return seen
117
+ },
118
+ sawText: () => sawText,
119
+ }
120
+ }
121
+
122
+ function dialog(props: { open: boolean; forms: DocumentFormsManifest; initialType?: string }) {
123
+ return (
124
+ <ApiProvider client={client}>
125
+ <DocumentFormDialog
126
+ open={props.open}
127
+ onOpenChange={() => {}}
128
+ model="docs"
129
+ endpoint="/data/docs/me"
130
+ forms={props.forms}
131
+ initialType={props.initialType}
132
+ />
133
+ </ApiProvider>
134
+ )
135
+ }
136
+
137
+ describe('DocumentFormDialog no pinta el wizard antes del DocumentEditor', () => {
138
+ it('reutilizado con otros formularios (otra vista del mismo host): abre directo el editor', () => {
139
+ const { rerender } = render(dialog({ open: false, forms: formsA }))
140
+ rerender(dialog({ open: false, forms: formsB }))
141
+ const watch = watchLegacyDialog()
142
+ rerender(dialog({ open: true, forms: formsB, initialType: 'doc_b' }))
143
+ watch.check()
144
+ expect(watch.seen()).toBe(false)
145
+ expect(document.querySelector('[data-slot="document-editor"]')).toBeTruthy()
146
+ })
147
+
148
+ it('«Crear» sin tipo inicial en la vista nueva: tampoco hay frame del wizard', () => {
149
+ const { rerender } = render(dialog({ open: false, forms: formsA }))
150
+ rerender(dialog({ open: false, forms: formsB }))
151
+ const watch = watchLegacyDialog()
152
+ rerender(dialog({ open: true, forms: formsB }))
153
+ watch.check()
154
+ expect(watch.seen()).toBe(false)
155
+ expect(document.querySelector('[data-slot="document-editor"]')).toBeTruthy()
156
+ })
157
+
158
+ it('reabierto con otro initialType: el primer frame ya es el editor del tipo pedido', () => {
159
+ const { rerender } = render(dialog({ open: true, forms: formsAB, initialType: 'doc_a' }))
160
+ rerender(dialog({ open: false, forms: formsAB, initialType: 'doc_a' }))
161
+ const watch = watchLegacyDialog('Documento A')
162
+ rerender(dialog({ open: true, forms: formsAB, initialType: 'doc_b' }))
163
+ watch.check()
164
+ expect(watch.seen()).toBe(false)
165
+ // Ni un frame del editor del tipo de la apertura anterior.
166
+ expect(watch.sawText()).toBe(false)
167
+ expect(document.querySelector('[data-slot="document-editor"]')).toBeTruthy()
168
+ })
169
+ })
@@ -164,7 +164,7 @@ describe('Factura con layout editor — pantalla única', () => {
164
164
 
165
165
  it('«Cargar desde» ofrece venta, OT y cotización como opciones', () => {
166
166
  renderInvoice(makeApi())
167
- const group = screen.getByRole('radiogroup', { name: 'Tipo de documento origen' })
167
+ const group = screen.getByRole('radiogroup', { name: 'Documento de origen' })
168
168
  expect(within(group).getAllByRole('radio').map((r) => r.textContent)).toEqual(['Venta', 'Orden de trabajo', 'Cotización'])
169
169
  fireEvent.click(within(group).getByRole('radio', { name: 'Orden de trabajo' }))
170
170
  expect(within(group).getByRole('radio', { name: 'Orden de trabajo' }).getAttribute('aria-checked')).toBe('true')
@@ -180,7 +180,7 @@ describe('Factura — «Cargar desde» OT y cotización con lo restante', () =>
180
180
  expect(screen.getByDisplayValue('Alineación eje direccional')).toBeTruthy()
181
181
  expect(screen.queryByDisplayValue('Montaje y balanceo')).toBeNull()
182
182
  expect(api.get).toHaveBeenCalledWith('/dynamic/customers.Invoice/source-lines', { params: { source: 'work_order', id: 'wo-1' } })
183
- expect(await screen.findByText('2 renglones con lo pendiente · 1 ya cubiertos se omitieron')).toBeTruthy()
183
+ expect(await screen.findByText('2 renglones con lo que falta · 1 ya completos (omitidos)')).toBeTruthy()
184
184
 
185
185
  // La tarjeta del cliente: datos fiscales con etiquetas del modelo.
186
186
  await waitFor(() => expect(slot('party-card')).toBeTruthy())
@@ -214,8 +214,9 @@ describe('Factura — «Cargar desde» OT y cotización con lo restante', () =>
214
214
  const [, body] = api.post.mock.calls[0] as [string, any]
215
215
  expect(body.quote_id).toBe('q-1')
216
216
  expect(body.currency_code).toBe('MXN')
217
+ // El descuento ($1,200 de las 6 piezas) se prorratea a las 4 pendientes.
217
218
  expect(body.items).toEqual([
218
- expect.objectContaining({ product_id: 'p-llanta', quantity: 4, unit_price: 5890, discount: 1200, tax_rate: 0.16, quote_item_id: 'qi-1' }),
219
+ expect.objectContaining({ product_id: 'p-llanta', quantity: 4, unit_price: 5890, discount: 800, tax_rate: 0.16, quote_item_id: 'qi-1' }),
219
220
  ])
220
221
  expect(body.items[0]).not.toHaveProperty('work_order_item_id')
221
222
  })
@@ -0,0 +1,87 @@
1
+ // @vitest-environment happy-dom
2
+ // Forma de pago «99 · Por definir» solo con método PPD, y con PPD solo «99»:
3
+ // la regla viaja en el `when` de las opciones del manifest. El validador y el
4
+ // render compartido de campos (renderField, que usan el DocumentEditor, el
5
+ // diálogo de document_forms y los modales de acción) la respetan.
6
+ import { afterEach, describe, expect, it, vi } from 'vitest'
7
+ import { cleanup, render } from '@testing-library/react'
8
+
9
+ vi.mock('react-i18next', () => ({
10
+ useTranslation: () => ({ t: (k: string, o?: { defaultValue?: string }) => o?.defaultValue ?? k, i18n: { language: 'es' } }),
11
+ }))
12
+
13
+ import { validateValues } from '../validator'
14
+ import { renderField } from '../action-modal-dispatcher'
15
+ import type { ActionFieldDef } from '../types'
16
+
17
+ const notPPD = { field: 'fiscal_data.metodo_pago', not_in: ['PPD'] }
18
+ const ppd = { field: 'fiscal_data.metodo_pago', in: ['PPD'] }
19
+ const fields: ActionFieldDef[] = [
20
+ {
21
+ key: 'fiscal_data.metodo_pago',
22
+ label: 'Método',
23
+ type: 'select',
24
+ options: [
25
+ { value: 'PUE', label: 'PUE' },
26
+ { value: 'PPD', label: 'PPD' },
27
+ ],
28
+ },
29
+ {
30
+ key: 'fiscal_data.forma_pago',
31
+ label: 'Forma',
32
+ type: 'select',
33
+ options: [
34
+ { value: '01', label: 'Efectivo', when: notPPD },
35
+ { value: '03', label: 'Transferencia', when: notPPD },
36
+ { value: '99', label: 'Por definir', when: ppd },
37
+ ],
38
+ },
39
+ ]
40
+
41
+ const header = (metodo: string, forma: string) => ({ 'fiscal_data.metodo_pago': metodo, 'fiscal_data.forma_pago': forma })
42
+
43
+ afterEach(cleanup)
44
+
45
+ describe('validateValues con options[].when', () => {
46
+ it('99 con PUE es invalid_option', () => {
47
+ const bag = validateValues(fields, header('PUE', '99'))
48
+ expect(bag['fiscal_data.forma_pago']?.[0]?.code).toBe('invalid_option')
49
+ expect(bag['fiscal_data.forma_pago']?.[0]?.params).toEqual({ allowed: ['01', '03'] })
50
+ })
51
+ it('PPD exige 99', () => {
52
+ const bag = validateValues(fields, header('PPD', '01'))
53
+ expect(bag['fiscal_data.forma_pago']?.[0]).toEqual({ code: 'invalid_option', params: { allowed: ['99'] } })
54
+ })
55
+ it('PPD + 99 y PUE + 01 pasan', () => {
56
+ expect(validateValues(fields, header('PPD', '99'))).toEqual({})
57
+ expect(validateValues(fields, header('PUE', '01'))).toEqual({})
58
+ })
59
+ it('una celda de renglón se evalúa contra su renglón y el encabezado', () => {
60
+ const lines: ActionFieldDef = {
61
+ key: 'items',
62
+ label: 'Renglones',
63
+ type: 'array',
64
+ itemFields: [{ ...fields[1]!, key: 'forma' }],
65
+ }
66
+ const bag = validateValues([fields[0]!, lines], { 'fiscal_data.metodo_pago': 'PPD', items: [{ forma: '03' }, { forma: '99' }] })
67
+ expect(bag['items.0.forma']?.[0]?.code).toBe('invalid_option')
68
+ expect(bag['items.1.forma']).toBeUndefined()
69
+ })
70
+ })
71
+
72
+ describe('renderField con options[].when', () => {
73
+ const trigger = (metodo: string, forma: string) => {
74
+ const { container } = render(<>{renderField(fields[1]!, forma, () => {}, header(metodo, forma))}</>)
75
+ return container.querySelector('[aria-invalid], button, [role="combobox"]') as HTMLElement
76
+ }
77
+ it('marca en el acto una forma que el método ya no permite', () => {
78
+ const el = trigger('PUE', '99')
79
+ expect(el.getAttribute('aria-invalid')).toBe('true')
80
+ expect(el.getAttribute('data-stale-option')).toBe('true')
81
+ })
82
+ it('una combinación válida no se marca', () => {
83
+ const el = trigger('PPD', '99')
84
+ expect(el.getAttribute('aria-invalid')).toBeNull()
85
+ expect(el.getAttribute('data-stale-option')).toBeNull()
86
+ })
87
+ })
@@ -0,0 +1,104 @@
1
+ // @vitest-environment happy-dom
2
+ // Retest Pitsline r6 (P0 UX): en el editor de la factura, método PPD exige
3
+ // forma de pago 99 (`options[].when` del manifest). Elegir PPD fija 99 solo y
4
+ // el alta lleva los dos valores, no solo el diálogo de Timbrar.
5
+ import { afterEach, describe, expect, it, vi } from 'vitest'
6
+ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
7
+
8
+ vi.mock('@tanstack/react-router', () => ({ useNavigate: () => () => {} }))
9
+ vi.mock('react-i18next', () => {
10
+ const value = { t: (k: string, o?: Record<string, any>) => o?.defaultValue ?? k, i18n: { language: 'es' } }
11
+ return { useTranslation: () => value }
12
+ })
13
+
14
+ import { DocumentFormDialog } from '../document-form-dialog'
15
+ import { ApiProvider, type ApiClient } from '../api-context'
16
+ import { TaxRateContext } from '../org-runtime-context'
17
+ import { gatedOptionFixes } from '../business/document-editor-model'
18
+ import type { ActionFieldDef, DocumentFormsManifest, DocumentFormType } from '../types'
19
+
20
+ afterEach(cleanup)
21
+
22
+ const notPPD = { field: 'fiscal_data.metodo_pago', not_in: ['PPD'] }
23
+ const formaPago: ActionFieldDef = {
24
+ key: 'fiscal_data.forma_pago',
25
+ label: 'Forma de pago',
26
+ type: 'select',
27
+ required: true,
28
+ defaultValue: '01',
29
+ options: [
30
+ { value: '01', label: 'Efectivo · 01', when: notPPD },
31
+ { value: '03', label: 'Transferencia · 03', when: notPPD },
32
+ { value: '99', label: 'Por definir · 99', when: { field: 'fiscal_data.metodo_pago', in: ['PPD'] } },
33
+ ],
34
+ } as ActionFieldDef
35
+ const metodoPago: ActionFieldDef = {
36
+ key: 'fiscal_data.metodo_pago',
37
+ label: 'Método de pago',
38
+ type: 'select',
39
+ required: true,
40
+ defaultValue: 'PUE',
41
+ options: [
42
+ { value: 'PUE', label: 'Una sola exhibición · PUE' },
43
+ { value: 'PPD', label: 'Parcialidades o diferido · PPD' },
44
+ ],
45
+ }
46
+
47
+ const invoice: DocumentFormType = {
48
+ key: 'invoice',
49
+ label: 'Factura',
50
+ layout: 'editor',
51
+ fields: [{ key: 'customer_id', label: 'Cliente', type: 'text', required: true }, metodoPago, formaPago],
52
+ defaults: { 'fiscal_data.metodo_pago': 'PUE', 'fiscal_data.forma_pago': '01' },
53
+ lines: { title: 'Renglones', required: false },
54
+ submit_label: 'Crear factura',
55
+ }
56
+
57
+ function renderInvoice(post: ReturnType<typeof vi.fn>) {
58
+ const client = { get: vi.fn(async () => ({ data: { data: [] } })), post, put: vi.fn(), delete: vi.fn() } as unknown as ApiClient
59
+ const forms: DocumentFormsManifest = { lines_field: 'items', types: [invoice] }
60
+ return render(
61
+ <ApiProvider client={client}>
62
+ <TaxRateContext.Provider value={0.16}>
63
+ <DocumentFormDialog open onOpenChange={() => {}} model="customers.Invoice" forms={forms} initialType="invoice" currency="MXN" />
64
+ </TaxRateContext.Provider>
65
+ </ApiProvider>,
66
+ )
67
+ }
68
+
69
+ async function pick(fieldLabel: RegExp, option: RegExp) {
70
+ const trigger = screen.getAllByRole('combobox').find((el) => fieldLabel.test(el.closest('[data-slot="field-cell"], div')?.textContent ?? '')) as HTMLElement
71
+ fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false, pointerType: 'mouse' })
72
+ fireEvent.click(await screen.findByRole('option', { name: option }))
73
+ }
74
+
75
+ describe('factura: método PPD ⇒ forma de pago 99', () => {
76
+ it('elegir PPD fija la forma 99 y el alta la lleva', async () => {
77
+ const post = vi.fn().mockResolvedValue({ data: { success: true, data: { id: 'inv-1' } } })
78
+ renderInvoice(post)
79
+ fireEvent.change(document.getElementById('customer_id')!, { target: { value: 'c-1' } })
80
+
81
+ await pick(/Método de pago/, /PPD/)
82
+ await waitFor(() => expect(screen.getAllByText('Por definir · 99').length).toBeGreaterThan(0))
83
+ fireEvent.click(screen.getByRole('button', { name: 'Crear factura' }))
84
+ await waitFor(() => expect(post).toHaveBeenCalled())
85
+ const body = post.mock.calls[0][1] as Record<string, unknown>
86
+ expect(body['fiscal_data.metodo_pago']).toBe('PPD')
87
+ expect(body['fiscal_data.forma_pago']).toBe('99')
88
+ })
89
+ })
90
+
91
+ describe('gatedOptionFixes', () => {
92
+ const fields = [metodoPago, formaPago]
93
+ it('PPD con forma 01 → 99 (la única que aplica)', () => {
94
+ expect(gatedOptionFixes(fields, { 'fiscal_data.metodo_pago': 'PPD', 'fiscal_data.forma_pago': '01' })).toEqual({ 'fiscal_data.forma_pago': '99' })
95
+ })
96
+ it('PUE con forma 99 → el default del campo', () => {
97
+ expect(gatedOptionFixes(fields, { 'fiscal_data.metodo_pago': 'PUE', 'fiscal_data.forma_pago': '99' })).toEqual({ 'fiscal_data.forma_pago': '01' })
98
+ })
99
+ it('valor válido o vacío con varias opciones: sin cambios (converge)', () => {
100
+ expect(gatedOptionFixes(fields, { 'fiscal_data.metodo_pago': 'PUE', 'fiscal_data.forma_pago': '03' })).toEqual({})
101
+ expect(gatedOptionFixes(fields, { 'fiscal_data.metodo_pago': 'PUE', 'fiscal_data.forma_pago': '' })).toEqual({})
102
+ expect(gatedOptionFixes(fields, { 'fiscal_data.metodo_pago': 'PPD', 'fiscal_data.forma_pago': '99' })).toEqual({})
103
+ })
104
+ })
@@ -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
@@ -384,7 +429,7 @@ export function localIssues(lines: LineItem[], opts: { requireLines?: boolean; r
384
429
  issues.push({
385
430
  field: `lines.${i}`,
386
431
  severity: 'error',
387
- 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}).`,
388
433
  })
389
434
  }
390
435
  if (opts.requireTax && toAmount(l.tax_rate) === 0) {