@asteby/metacore-runtime-react 49.2.1 → 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.
@@ -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 () => {
@@ -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) {
@@ -48,6 +48,8 @@ import {
48
48
  splitEditorFields,
49
49
  toOpenDocuments,
50
50
  friendlyOptionLabel,
51
+ gatedOptionFixes,
52
+ gatedOptions,
51
53
  withFriendlyOptions,
52
54
  type EditorIssue,
53
55
  type SeedLabel,
@@ -215,6 +217,15 @@ export function DocumentEditor({
215
217
  const fieldKeys = useRef<string[]>([])
216
218
  fieldKeys.current = allFields.map((f) => f.key)
217
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
+
218
229
  // Contraparte: tarjeta + defaults de las extensiones con la misma clave.
219
230
  const partyId = type.party ? header[type.party.field] : undefined
220
231
  useEffect(() => {
@@ -435,11 +446,11 @@ export function DocumentEditor({
435
446
  setSourceNote(
436
447
  loaded.length === 0 && covered > 0
437
448
  ? t('documentEditor.source_all_covered', {
438
- 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.',
439
450
  })
440
451
  : covered > 0
441
452
  ? t('documentEditor.source_loaded_partial', {
442
- defaultValue: '{{count}} renglones con lo pendiente · {{covered}} ya cubiertos se omitieron',
453
+ defaultValue: '{{count}} renglones con lo que falta · {{covered}} ya completos (omitidos)',
443
454
  count: loaded.length,
444
455
  covered,
445
456
  })
@@ -579,7 +590,7 @@ export function DocumentEditor({
579
590
  <FieldLabel htmlFor={field.key} required={field.required}>
580
591
  {tl(field.label)}
581
592
  </FieldLabel>
582
- {renderField(withFriendlyOptions(field), header[field.key], (v: any) => updateField(field.key, v), header, fieldRecord, fieldErrors)}
593
+ {renderField(withFriendlyOptions(gatedOptions(field, header)), header[field.key], (v: any) => updateField(field.key, v), header, fieldRecord, fieldErrors)}
583
594
  {fieldErrors[field.key] && <p className="mt-1 text-xs text-destructive">{fieldErrors[field.key]}</p>}
584
595
  </FieldCell>
585
596
  ) : null
@@ -654,7 +665,7 @@ export function DocumentEditor({
654
665
  {sources.length > 1 && (
655
666
  <div
656
667
  role="radiogroup"
657
- aria-label={t('documentEditor.source_kind', { defaultValue: 'Tipo de documento origen' })}
668
+ aria-label={t('documentEditor.source_kind', { defaultValue: 'Documento de origen' })}
658
669
  className="inline-flex flex-wrap gap-1 rounded-md border p-1"
659
670
  >
660
671
  {sources.map((s) => (
@@ -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
@@ -0,0 +1,61 @@
1
+ // option-when.ts — opciones estáticas de un select condicionadas por el valor
2
+ // de un campo hermano (`options[].when`) y la dependencia declarada del campo
3
+ // (`dependsOn`). Módulo hoja: lo usan el formulario (dynamic-form-schema), el
4
+ // render compartido de campos (renderField) y el validador, sin ciclos.
5
+ import type { ActionFieldDef, OptionDef } from './types'
6
+
7
+ /**
8
+ * Resolves a field's cascade dependency — the key of another form field whose
9
+ * current value scopes this picker's options (`filter_value`). Tolerates the
10
+ * camelCase `dependsOn` (authored SDK shape) and the snake_case `depends_on`
11
+ * the kernel manifest serves. Returns the trimmed field key, or `undefined`
12
+ * when the field declares no dependency.
13
+ */
14
+ export function getDependsOn(field: ActionFieldDef): string | undefined {
15
+ const dep = field.dependsOn ?? field.depends_on
16
+ if (typeof dep === 'string' && dep.trim() !== '') return dep.trim()
17
+ return undefined
18
+ }
19
+
20
+ /**
21
+ * Filters a STATIC enum's `options[]` by each option's `when` gate against the
22
+ * current form values. Pure — no React, no side effects.
23
+ *
24
+ * Rule per option:
25
+ * - No `when` → always included (retrocompat; existing enums untouched).
26
+ * - With `when`: the gating field is `when.field ?? dependsOn`. If neither is
27
+ * present the option is included (nothing to gate on). Otherwise the form's
28
+ * value for that field is compared AS STRING: included when (no `in`, or
29
+ * value ∈ `in`) AND (no `not_in`, or value ∉ `not_in`). Tolerates the
30
+ * snake_case `not_in` the kernel serves alongside camelCase `notIn`.
31
+ *
32
+ * `formValues` is the flat map of the surrounding form/row values the gating
33
+ * field is read from; `dependsOn` is the containing field's declared dependency
34
+ * used as the default gating field.
35
+ */
36
+ export function applyOptionWhen(
37
+ options: OptionDef[] | undefined,
38
+ formValues: Record<string, any> | null | undefined,
39
+ dependsOn?: string,
40
+ ): OptionDef[] {
41
+ if (!Array.isArray(options)) return []
42
+ return options.filter((opt) => {
43
+ const when = opt?.when
44
+ if (!when) return true
45
+ const gate = (typeof when.field === 'string' && when.field.trim() !== '')
46
+ ? when.field.trim()
47
+ : dependsOn
48
+ if (!gate) return true
49
+ const raw = formValues ? formValues[gate] : undefined
50
+ const current = raw == null ? '' : String(raw)
51
+ const inList = when.in
52
+ const notIn = when.notIn ?? when.not_in
53
+ if (Array.isArray(inList) && inList.length > 0) {
54
+ if (!inList.some((v) => String(v) === current)) return false
55
+ }
56
+ if (Array.isArray(notIn) && notIn.length > 0) {
57
+ if (notIn.some((v) => String(v) === current)) return false
58
+ }
59
+ return true
60
+ })
61
+ }