@asteby/metacore-runtime-react 53.21.1 → 53.23.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 (78) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/assist-interview.d.ts.map +1 -1
  3. package/dist/assist-interview.js +7 -10
  4. package/dist/business/line-items.d.ts +1 -1
  5. package/dist/business/line-items.d.ts.map +1 -1
  6. package/dist/business/line-items.js +3 -4
  7. package/dist/custom-stages.d.ts.map +1 -1
  8. package/dist/custom-stages.js +2 -10
  9. package/dist/dialogs/dynamic-record.d.ts.map +1 -1
  10. package/dist/dialogs/dynamic-record.js +79 -7
  11. package/dist/dialogs/inline-relation-rows.d.ts +26 -0
  12. package/dist/dialogs/inline-relation-rows.d.ts.map +1 -0
  13. package/dist/dialogs/inline-relation-rows.js +99 -0
  14. package/dist/dialogs/inline-relations.d.ts +46 -0
  15. package/dist/dialogs/inline-relations.d.ts.map +1 -0
  16. package/dist/dialogs/inline-relations.js +79 -0
  17. package/dist/dialogs/normalize-submit.d.ts +1 -1
  18. package/dist/dialogs/normalize-submit.d.ts.map +1 -1
  19. package/dist/dialogs/normalize-submit.js +3 -0
  20. package/dist/dialogs/use-inline-relations.d.ts +18 -0
  21. package/dist/dialogs/use-inline-relations.d.ts.map +1 -0
  22. package/dist/dialogs/use-inline-relations.js +69 -0
  23. package/dist/draft-rows.d.ts +44 -0
  24. package/dist/draft-rows.d.ts.map +1 -0
  25. package/dist/draft-rows.js +70 -0
  26. package/dist/genui/settings-block.d.ts.map +1 -1
  27. package/dist/genui/settings-block.js +7 -12
  28. package/dist/index.d.ts +1 -0
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +1 -0
  31. package/dist/record-picker-dialog.d.ts.map +1 -1
  32. package/dist/record-picker-dialog.js +4 -3
  33. package/dist/setup/addon-config-surface.d.ts.map +1 -1
  34. package/dist/setup/addon-config-surface.js +14 -12
  35. package/dist/stage-automations.d.ts.map +1 -1
  36. package/dist/stage-automations.js +3 -12
  37. package/dist/stage-layout.d.ts.map +1 -1
  38. package/dist/stage-layout.js +2 -7
  39. package/dist/types.d.ts +11 -0
  40. package/dist/types.d.ts.map +1 -1
  41. package/dist/use-addon-installed-probe.d.ts +8 -0
  42. package/dist/use-addon-installed-probe.d.ts.map +1 -0
  43. package/dist/use-addon-installed-probe.js +36 -0
  44. package/dist/use-addon-settings.d.ts +24 -0
  45. package/dist/use-addon-settings.d.ts.map +1 -1
  46. package/dist/use-addon-settings.js +39 -13
  47. package/dist/use-org-document-templates.d.ts.map +1 -1
  48. package/dist/use-org-document-templates.js +5 -9
  49. package/dist/views/data-source.d.ts.map +1 -1
  50. package/dist/views/data-source.js +9 -14
  51. package/docs/relations.md +17 -0
  52. package/package.json +8 -7
  53. package/src/__tests__/draft-rows.test.ts +117 -0
  54. package/src/__tests__/dynamic-record-edit-payload-upload.test.tsx +8 -6
  55. package/src/__tests__/dynamic-record-inline-relations.test.tsx +184 -0
  56. package/src/__tests__/genui-settings-block.test.tsx +6 -3
  57. package/src/__tests__/use-addon-settings-hooks.test.tsx +73 -0
  58. package/src/__tests__/use-addon-settings.test.ts +19 -3
  59. package/src/assist-interview.tsx +7 -11
  60. package/src/business/line-items.ts +3 -4
  61. package/src/custom-stages.tsx +2 -7
  62. package/src/dialogs/dynamic-record.tsx +117 -6
  63. package/src/dialogs/inline-relation-rows.tsx +257 -0
  64. package/src/dialogs/inline-relations.ts +129 -0
  65. package/src/dialogs/normalize-submit.ts +4 -0
  66. package/src/dialogs/use-inline-relations.ts +78 -0
  67. package/src/draft-rows.ts +113 -0
  68. package/src/genui/settings-block.tsx +7 -13
  69. package/src/index.ts +1 -0
  70. package/src/record-picker-dialog.tsx +4 -3
  71. package/src/setup/addon-config-surface.tsx +16 -15
  72. package/src/stage-automations.tsx +3 -9
  73. package/src/stage-layout.ts +2 -7
  74. package/src/types.ts +11 -0
  75. package/src/use-addon-installed-probe.ts +39 -0
  76. package/src/use-addon-settings.ts +66 -12
  77. package/src/use-org-document-templates.ts +5 -10
  78. package/src/views/data-source.ts +6 -16
@@ -26,6 +26,8 @@ const i18n = (() => {
26
26
  })()
27
27
 
28
28
  const post = vi.fn(async (..._a: unknown[]) => ({ data: { data: { url: '/files/x.png' } } }))
29
+ // Llamadas reales (el lote de metadata `/q` también viaja por post).
30
+ const posts = () => post.mock.calls.filter((c) => c[0] !== '/q')
29
31
  const api = {
30
32
  get: vi.fn(async () => ({ data: { data: {} } })),
31
33
  post,
@@ -126,7 +128,7 @@ describe('upload validation', () => {
126
128
  const input = document.querySelector('input[type="file"]') as HTMLInputElement
127
129
  fireEvent.change(input, { target: { files: [png(5000)] } })
128
130
  await waitFor(() => expect(screen.getByRole('alert')).toBeTruthy())
129
- expect(post).not.toHaveBeenCalled()
131
+ expect(posts()).toHaveLength(0)
130
132
  expect(toast.error).toHaveBeenCalled()
131
133
  })
132
134
 
@@ -136,7 +138,7 @@ describe('upload validation', () => {
136
138
  const zone = document.querySelector('input[type="file"]')!.parentElement as HTMLElement
137
139
  fireEvent.drop(zone, { dataTransfer: { files: [png(10, 'image/gif', 'a.gif')] } })
138
140
  await waitFor(() => expect(screen.getByRole('alert')).toBeTruthy())
139
- expect(post).not.toHaveBeenCalled()
141
+ expect(posts()).toHaveLength(0)
140
142
  })
141
143
 
142
144
  it('image: drop/dragover call preventDefault even with a value or while uploading', async () => {
@@ -172,8 +174,8 @@ describe('upload validation', () => {
172
174
  const input = document.querySelector('input[type="file"]') as HTMLInputElement
173
175
  expect(input.accept).toBe('image/*')
174
176
  fireEvent.change(input, { target: { files: [png(10_000_000)] } })
175
- await waitFor(() => expect(post).toHaveBeenCalledTimes(1))
176
- const call = post.mock.calls[0] as unknown[]
177
+ await waitFor(() => expect(posts()).toHaveLength(1))
178
+ const call = posts()[0] as unknown[]
177
179
  expect(call[0]).toBe('/upload')
178
180
  expect((call[1] as FormData).get('folder')).toBe('reviews')
179
181
  })
@@ -184,9 +186,9 @@ describe('upload validation', () => {
184
186
  const input = document.querySelector('input[type="file"]') as HTMLInputElement
185
187
  fireEvent.change(input, { target: { files: [png(10, 'image/gif', 'a.gif')] } })
186
188
  await waitFor(() => expect(screen.getByRole('alert')).toBeTruthy())
187
- expect(post).not.toHaveBeenCalled()
189
+ expect(posts()).toHaveLength(0)
188
190
  fireEvent.change(input, { target: { files: [png(10)] } })
189
- await waitFor(() => expect(post).toHaveBeenCalledTimes(1))
191
+ await waitFor(() => expect(posts()).toHaveLength(1))
190
192
  })
191
193
  })
192
194
 
@@ -0,0 +1,184 @@
1
+ // @vitest-environment happy-dom
2
+ //
3
+ // Crear un padre con relaciones hijas `create_inline`: tabla de filas borrador,
4
+ // `_children` en el cuerpo, `min` que bloquea y errores 422 por fila.
5
+ import { afterEach, describe, expect, it, vi } from 'vitest'
6
+ import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
7
+ import { I18nextProvider } from 'react-i18next'
8
+ import i18next from 'i18next'
9
+
10
+ import { DynamicRecordDialog } from '../dialogs/dynamic-record'
11
+ import { ApiProvider } from '../api-context'
12
+
13
+ afterEach(cleanup)
14
+
15
+ function makeI18n() {
16
+ const inst = i18next.createInstance()
17
+ void inst.init({ lng: 'es', fallbackLng: 'es', react: { useSuspense: false }, resources: { es: { translation: {} } } })
18
+ return inst
19
+ }
20
+
21
+ const parentSchema = {
22
+ title: 'Regla de descuento',
23
+ fields: [{ key: 'name', label: 'Nombre', type: 'text', required: true }],
24
+ }
25
+
26
+ const tierModal = {
27
+ fields: [
28
+ { key: 'rule_id', label: 'Regla', type: 'text' },
29
+ { key: 'min_amount', label: 'Monto mínimo', type: 'number', required: true },
30
+ { key: 'discount_type', label: 'Tipo', type: 'text', required: true },
31
+ { key: 'discount_value', label: 'Valor', type: 'number', required: true },
32
+ { key: 'created_at', label: 'Creado', type: 'date' },
33
+ ],
34
+ }
35
+
36
+ function makeApi(relations: any[]) {
37
+ return {
38
+ get: vi.fn(async (url: string) => {
39
+ if (url === '/metadata/table/DiscountRule') return { data: { data: { relations } } }
40
+ if (url === '/metadata/modal/DiscountRuleTier') return { data: { data: tierModal } }
41
+ return { data: { data: {} } }
42
+ }),
43
+ post: vi.fn(async (_url: string, _body: unknown) => ({ data: { success: true, data: { id: '1' } } })),
44
+ put: async () => ({ data: { success: true } }),
45
+ delete: async () => ({ data: { success: true } }),
46
+ }
47
+ }
48
+
49
+ const tiers = {
50
+ name: 'tiers',
51
+ kind: 'one_to_many',
52
+ through: 'DiscountRuleTier',
53
+ foreign_key: 'rule_id',
54
+ label: 'Escalones',
55
+ create_inline: true,
56
+ embed: true,
57
+ }
58
+
59
+ function setup(api: any, onCreate?: any) {
60
+ render(
61
+ <I18nextProvider i18n={makeI18n()}>
62
+ <ApiProvider client={api as never}>
63
+ <DynamicRecordDialog
64
+ open
65
+ onOpenChange={() => {}}
66
+ mode="create"
67
+ model="DiscountRule"
68
+ schema={parentSchema as never}
69
+ onCreate={onCreate}
70
+ />
71
+ </ApiProvider>
72
+ </I18nextProvider>,
73
+ )
74
+ }
75
+
76
+ const type = (el: HTMLElement, value: string) => fireEvent.change(el, { target: { value } })
77
+ const cell = (field: string, row: number) =>
78
+ within(screen.getByRole('group', { name: `${field}, fila ${row}` })).getByRole(
79
+ field === 'Tipo' ? 'textbox' : 'spinbutton',
80
+ )
81
+ const fillRow = (row: number, amount: string, kind: string, value: string) => {
82
+ type(cell('Monto mínimo', row), amount)
83
+ type(cell('Tipo', row), kind)
84
+ type(cell('Valor', row), value)
85
+ }
86
+ const submit = () => fireEvent.submit(document.querySelector('form') as HTMLFormElement)
87
+ const fillName = () => type(document.querySelector('[data-aby-field="name"] input') as HTMLElement, 'Mayoreo')
88
+
89
+ describe('DynamicRecordDialog create — relaciones create_inline', () => {
90
+ it('pinta la sección solo para relaciones create_inline y oculta FK/auditoría', async () => {
91
+ const other = { name: 'notes', kind: 'one_to_many', through: 'Note', foreign_key: 'rule_id', label: 'Notas', embed: true }
92
+ setup(makeApi([tiers, other]))
93
+ await screen.findByRole('heading', { name: 'Escalones' })
94
+ expect(screen.queryByText('Notas')).toBeNull()
95
+ fireEvent.click(screen.getByRole('button', { name: /Agregar/ }))
96
+ expect(screen.getByRole('columnheader', { name: /Monto mínimo/ })).toBeTruthy()
97
+ expect(screen.queryByRole('columnheader', { name: /Regla/ })).toBeNull()
98
+ expect(screen.queryByRole('columnheader', { name: /Creado/ })).toBeNull()
99
+ })
100
+
101
+ it('agrega, quita y envía _children con el padre en una sola llamada', async () => {
102
+ const api = makeApi([tiers])
103
+ const onCreate = vi.fn(async (_body: Record<string, unknown>) => ({ id: '1' }))
104
+ setup(api, onCreate)
105
+ const add = await screen.findByRole('button', { name: /Agregar/ })
106
+ fireEvent.click(add)
107
+ fireEvent.click(add)
108
+ fireEvent.click(add)
109
+ expect(screen.getAllByRole('button', { name: /Quitar fila/ })).toHaveLength(3)
110
+ fireEvent.click(screen.getByRole('button', { name: 'Quitar fila 3' }))
111
+ fillName()
112
+ fillRow(1, '1000', 'percent', '5')
113
+ fillRow(2, '5000', 'percent', '10')
114
+ submit()
115
+ await waitFor(() => expect(onCreate).toHaveBeenCalledTimes(1))
116
+ expect(onCreate.mock.calls[0][0]).toMatchObject({
117
+ name: 'Mayoreo',
118
+ _children: {
119
+ tiers: [
120
+ { min_amount: 1000, discount_type: 'percent', discount_value: 5 },
121
+ { min_amount: 5000, discount_type: 'percent', discount_value: 10 },
122
+ ],
123
+ },
124
+ })
125
+ })
126
+
127
+ it('bloquea el envío con requeridos por fila y con min', async () => {
128
+ const api = makeApi([{ ...tiers, min: 2 }])
129
+ const onCreate = vi.fn()
130
+ setup(api, onCreate)
131
+ const add = await screen.findByRole('button', { name: /Agregar/ })
132
+ expect(screen.getByText(/0 de 2 como mínimo/)).toBeTruthy()
133
+ fillName()
134
+ fireEvent.click(add)
135
+ submit()
136
+ const alerts = await screen.findAllByRole('alert')
137
+ expect(alerts.some((a) => /al menos 2/.test(a.textContent ?? ''))).toBe(true)
138
+ expect(screen.getAllByText(/obligatorio/).length).toBeGreaterThan(0)
139
+ expect(onCreate).not.toHaveBeenCalled()
140
+ expect(add.getAttribute('class')).toMatch(/min-h-11/)
141
+ })
142
+
143
+ it('sin relaciones inline el cuerpo es idéntico al de hoy (sin _children)', async () => {
144
+ const api = makeApi([{ ...tiers, create_inline: undefined }])
145
+ const onCreate = vi.fn(async (_body: Record<string, unknown>) => ({}))
146
+ setup(api, onCreate)
147
+ await waitFor(() => expect(api.get).toHaveBeenCalledWith('/metadata/table/DiscountRule'))
148
+ fillName()
149
+ submit()
150
+ await waitFor(() => expect(onCreate).toHaveBeenCalledTimes(1))
151
+ expect(onCreate.mock.calls[0][0]).toEqual({ name: 'Mayoreo' })
152
+ expect(screen.queryByRole('heading', { name: 'Escalones' })).toBeNull()
153
+ })
154
+
155
+ it('pinta el 422 en la celda de la fila y conserva lo capturado', async () => {
156
+ const api = makeApi([tiers])
157
+ // `/q` (metadata en lote) también viaja por post: solo falla el create.
158
+ const base = api.post.getMockImplementation()!
159
+ api.post.mockImplementation(async (url: string, body: unknown) => {
160
+ if (url !== '/dynamic/DiscountRule') return base(url, body)
161
+ throw {
162
+ response: {
163
+ status: 422,
164
+ data: { errors: { '_children.tiers.1.discount_value': [{ code: 'invalid_type' }] } },
165
+ },
166
+ }
167
+ })
168
+ setup(api)
169
+ const add = await screen.findByRole('button', { name: /Agregar/ })
170
+ fireEvent.click(add)
171
+ fireEvent.click(add)
172
+ fillName()
173
+ fillRow(1, '100', 'percent', '1')
174
+ fillRow(2, '200', 'percent', '999')
175
+ submit()
176
+ await waitFor(() => expect(api.post.mock.calls.filter(c => c[0] === '/dynamic/DiscountRule')).toHaveLength(1))
177
+ await waitFor(() =>
178
+ expect(screen.getByRole('group', { name: 'Valor, fila 2' }).parentElement?.textContent).toMatch(/formato inválido/),
179
+ )
180
+ expect((cell('Valor', 2) as HTMLInputElement).value).toBe('999')
181
+ expect((cell('Monto mínimo', 1) as HTMLInputElement).value).toBe('100')
182
+ expect(screen.getByRole('group', { name: 'Valor, fila 1' }).parentElement?.textContent).not.toMatch(/inválido/)
183
+ })
184
+ })
@@ -7,6 +7,7 @@ vi.mock('react-i18next', () => {
7
7
  return { useTranslation: () => ({ t, i18n: { language: 'es', exists: () => false } }) }
8
8
  })
9
9
 
10
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
10
11
  import { GenUI } from '@asteby/metacore-genui'
11
12
  import { ApiProvider } from '../api-context'
12
13
  import { coerceSettings, registerGenUISettingsBlock, settingsToFields } from '../genui'
@@ -50,9 +51,11 @@ describe('genui settings block (pilot)', () => {
50
51
  delete: vi.fn(),
51
52
  }
52
53
  render(
53
- <ApiProvider client={client as never}>
54
- <GenUI spec={{ version: 'genui/v2', blocks: [{ type: 'settings', addon: 'inventory', scope: 'org' }] }} />
55
- </ApiProvider>,
54
+ <QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
55
+ <ApiProvider client={client as never}>
56
+ <GenUI spec={{ version: 'genui/v2', blocks: [{ type: 'settings', addon: 'inventory', scope: 'org' }] }} />
57
+ </ApiProvider>
58
+ </QueryClientProvider>,
56
59
  )
57
60
  const lines = await screen.findByRole('spinbutton')
58
61
  expect(screen.queryByText(/Token/)).toBeNull()
@@ -0,0 +1,73 @@
1
+ // @vitest-environment happy-dom
2
+ import { afterEach, describe, expect, it, vi } from 'vitest'
3
+ import { cleanup, renderHook, waitFor } from '@testing-library/react'
4
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
5
+ import type { ReactNode } from 'react'
6
+ import { ApiProvider } from '../api-context'
7
+ import { InstalledAddonsProvider } from '../installed-addons-context'
8
+ import { useAddonSettings } from '../use-addon-settings'
9
+ import { useAddonInstalledProbe } from '../use-addon-installed-probe'
10
+
11
+ afterEach(cleanup)
12
+
13
+ function wrap(get: (url: string) => Promise<unknown>, installed?: string[]) {
14
+ const client = { get: vi.fn(get), post: vi.fn(), put: vi.fn(), delete: vi.fn() }
15
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })
16
+ const W = ({ children }: { children: ReactNode }) => (
17
+ <QueryClientProvider client={qc}>
18
+ <ApiProvider client={client as never}>
19
+ {installed ? <InstalledAddonsProvider addons={installed}>{children}</InstalledAddonsProvider> : children}
20
+ </ApiProvider>
21
+ </QueryClientProvider>
22
+ )
23
+ return { W, client }
24
+ }
25
+
26
+ describe('useAddonSettings', () => {
27
+ it('merges defaults under stored values and exposes definitions/overrides', async () => {
28
+ const { W, client } = wrap(async () => ({ data: { success: true, data: { a: 5 }, definitions: [{ key: 'a' }], overrides: { a: 6 } } }))
29
+ const defaults = { a: 1, b: 2 }
30
+ const { result } = renderHook(() => useAddonSettings('pos', { defaults, branchId: 'b1' }), { wrapper: W })
31
+ await waitFor(() => expect(result.current.isLoading).toBe(false))
32
+ expect(client.get).toHaveBeenCalledWith('/addons/pos/settings?branch_id=b1')
33
+ expect(result.current.settings).toEqual({ a: 5, b: 2 })
34
+ expect(result.current.stored).toEqual({ a: 5 })
35
+ expect(result.current.definitions).toEqual([{ key: 'a' }])
36
+ expect(result.current.overrides).toEqual({ a: 6 })
37
+ })
38
+
39
+ it('reload() fetches again and resolves with the payload', async () => {
40
+ const { W, client } = wrap(async () => ({ data: { data: { a: 1 } } }))
41
+ const { result } = renderHook(() => useAddonSettings('pos', { enabled: false }), { wrapper: W })
42
+ const payload = await result.current.reload()
43
+ expect(payload.values).toEqual({ a: 1 })
44
+ await result.current.reload()
45
+ expect(client.get).toHaveBeenCalledTimes(2)
46
+ })
47
+ })
48
+
49
+ describe('useAddonInstalledProbe', () => {
50
+ it('true on 2xx, false on 404, unknown on other errors', async () => {
51
+ const ok = wrap(async () => ({ data: {} }))
52
+ const r1 = renderHook(() => useAddonInstalledProbe('caja'), { wrapper: ok.W })
53
+ await waitFor(() => expect(r1.result.current.installed).toBe(true))
54
+
55
+ const nf = wrap(async () => Promise.reject({ response: { status: 404 } }))
56
+ const r2 = renderHook(() => useAddonInstalledProbe('caja'), { wrapper: nf.W })
57
+ await waitFor(() => expect(r2.result.current.installed).toBe(false))
58
+
59
+ const forbidden = wrap(async () => Promise.reject({ response: { status: 403 } }))
60
+ const r3 = renderHook(() => useAddonInstalledProbe('caja'), { wrapper: forbidden.W })
61
+ await waitFor(() => expect(r3.result.current.isLoading).toBe(false))
62
+ expect(r3.result.current.installed).toBeUndefined()
63
+ })
64
+
65
+ it('answers from the provider without touching the network', () => {
66
+ const { W, client } = wrap(async () => ({ data: {} }), ['fiscal'])
67
+ const yes = renderHook(() => useAddonInstalledProbe('fiscal'), { wrapper: W })
68
+ const no = renderHook(() => useAddonInstalledProbe('caja'), { wrapper: W })
69
+ expect(yes.result.current.installed).toBe(true)
70
+ expect(no.result.current.installed).toBe(false)
71
+ expect(client.get).not.toHaveBeenCalled()
72
+ })
73
+ })
@@ -4,7 +4,7 @@
4
4
  // itself is a thin react-query wrapper over `useApi`; the load-bearing logic
5
5
  // is this pure merge, so that's what we test directly.
6
6
  import { describe, it, expect } from 'vitest'
7
- import { mergeAddonSettings, addonSettingsKey, addonSettingsUrl } from '../use-addon-settings'
7
+ import { mergeAddonSettings, addonSettingsKey, addonSettingsUrl, parseAddonSettingsBody } from '../use-addon-settings'
8
8
 
9
9
  interface PosSettings extends Record<string, unknown> {
10
10
  allowNegativeStock: boolean
@@ -77,8 +77,8 @@ describe('branch-scoped settings (POS-1)', () => {
77
77
  it('keys and urls carry the branch only when given', () => {
78
78
  expect(addonSettingsKey('pos', 'b1')).toEqual(['addon-settings', 'pos', 'b1'])
79
79
  expect(addonSettingsKey('pos', null)).toEqual(['addon-settings', 'pos'])
80
- expect(addonSettingsUrl('pos')).toBe('/api/addons/pos/settings')
81
- expect(addonSettingsUrl('pos', 'b 1')).toBe('/api/addons/pos/settings?branch_id=b%201')
80
+ expect(addonSettingsUrl('pos')).toBe('/addons/pos/settings')
81
+ expect(addonSettingsUrl('pos', 'b 1')).toBe('/addons/pos/settings?branch_id=b%201')
82
82
  })
83
83
 
84
84
  it('an org-key prefix matches every branch read (invalidation)', () => {
@@ -87,3 +87,19 @@ describe('branch-scoped settings (POS-1)', () => {
87
87
  expect(branch.slice(0, org.length)).toEqual([...org])
88
88
  })
89
89
  })
90
+
91
+ describe('parseAddonSettingsBody', () => {
92
+ it('reads values, definitions and overrides from the envelope', () => {
93
+ const defs = [{ key: 'a' }]
94
+ expect(parseAddonSettingsBody({ success: true, data: { a: 1 }, definitions: defs, overrides: { a: 2 } })).toEqual({
95
+ values: { a: 1 },
96
+ definitions: defs,
97
+ overrides: { a: 2 },
98
+ })
99
+ })
100
+ it('tolerates a missing data/definitions and a bare map', () => {
101
+ expect(parseAddonSettingsBody({ success: true })).toEqual({ values: {}, definitions: [], overrides: {} })
102
+ expect(parseAddonSettingsBody({ a: 1 })).toEqual({ values: { a: 1 }, definitions: [], overrides: {} })
103
+ expect(parseAddonSettingsBody(null)).toEqual({ values: {}, definitions: [], overrides: {} })
104
+ })
105
+ })
@@ -12,6 +12,7 @@
12
12
  // POST /assist/:provider/sessions { input } → Session
13
13
  // GET /assist/:provider/sessions/:id → Session (poll while working)
14
14
  // POST /assist/:provider/sessions/:id/reply { key, value } → Session
15
+ import { unwrapResponse } from '@asteby/metacore-lib/envelope'
15
16
  import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
16
17
  import { Button, Input } from '@asteby/metacore-ui/primitives'
17
18
  import { ArrowRight, Check, CheckCircle2, Loader2, RotateCcw, Sparkles, XCircle } from 'lucide-react'
@@ -81,11 +82,6 @@ export interface AssistInterviewProps {
81
82
  const POLL_MS = 800
82
83
  const THINKING_HINTS = ['Un momento…', 'Sigo trabajando…', 'Casi listo…']
83
84
 
84
- function unwrap(res: any): AssistSession {
85
- const d = res?.data?.data ?? res?.data ?? res
86
- return d as AssistSession
87
- }
88
-
89
85
  function useTypewriter(text: string) {
90
86
  const [n, setN] = useState(0)
91
87
  const reduce = typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-reduced-motion: reduce)').matches
@@ -128,7 +124,7 @@ export function AssistInterview({ assist, values, onApply, autoStart = true, eye
128
124
  answersRef.current = []
129
125
  try {
130
126
  const res = await api.post(base, { input: inputPayload })
131
- setSession(unwrap(res))
127
+ setSession(unwrapResponse<AssistSession>(res))
132
128
  } catch (e: any) {
133
129
  setError(e?.response?.data?.message || e?.message || 'No se pudo iniciar el asistente')
134
130
  } finally {
@@ -149,7 +145,7 @@ export function AssistInterview({ assist, values, onApply, autoStart = true, eye
149
145
  const t = setInterval(async () => {
150
146
  try {
151
147
  const res = await api.get(`${base}/${session.id}`)
152
- setSession(unwrap(res))
148
+ setSession(unwrapResponse<AssistSession>(res))
153
149
  } catch (e: any) {
154
150
  if (isGone(e)) {
155
151
  try {
@@ -190,15 +186,15 @@ export function AssistInterview({ assist, values, onApply, autoStart = true, eye
190
186
  // Recreate the session and replay every answer (host lost it).
191
187
  const recover = useCallback(async () => {
192
188
  const res = await api.post(base, { input: inputPayload })
193
- let s = unwrap(res)
189
+ let s = unwrapResponse<AssistSession>(res)
194
190
  for (const a of answersRef.current) {
195
191
  // wait until the provider is ready for the next answer
196
192
  for (let i = 0; i < 120 && s.working && !s.done; i++) {
197
193
  await new Promise(r => setTimeout(r, POLL_MS))
198
- s = unwrap(await api.get(`${base}/${s.id}`))
194
+ s = unwrapResponse<AssistSession>(await api.get(`${base}/${s.id}`))
199
195
  }
200
196
  if (s.done) break
201
- s = unwrap(await api.post(`${base}/${s.id}/reply`, { key: a.key, value: a.value }))
197
+ s = unwrapResponse<AssistSession>(await api.post(`${base}/${s.id}/reply`, { key: a.key, value: a.value }))
202
198
  }
203
199
  return s
204
200
  }, [api, base, inputPayload])
@@ -212,7 +208,7 @@ export function AssistInterview({ assist, values, onApply, autoStart = true, eye
212
208
  try {
213
209
  const res = await api.post(`${base}/${session.id}/reply`, { key, value })
214
210
  answersRef.current = [...answersRef.current, { key, value }]
215
- setSession(unwrap(res))
211
+ setSession(unwrapResponse<AssistSession>(res))
216
212
  } catch (e: any) {
217
213
  if (isGone(e)) {
218
214
  try {
@@ -2,6 +2,7 @@
2
2
  // Lógica pura del <LineItemsEditor>: cálculo, validación y serialización. El
3
3
  // guardado de renglones fallaba (PIT-018) por mandar al API cadenas vacías y
4
4
  // claves de UI; `serializeLineItems` es la única puerta de salida hacia el backend.
5
+ import { newDraftKey } from '../draft-rows'
5
6
  import { roundMoney, toAmount } from './format'
6
7
  import type { ProductVariant } from './product-search'
7
8
 
@@ -99,11 +100,9 @@ export interface LineItemsPolicy {
99
100
  allowZeroQuantity?: boolean
100
101
  }
101
102
 
102
- let seq = 0
103
- /** Clave de UI única en el proceso. */
103
+ /** Clave de UI única en el proceso (núcleo compartido con las filas borrador). */
104
104
  export function newLineKey(): string {
105
- seq += 1
106
- return `li_${Date.now().toString(36)}_${seq}`
105
+ return newDraftKey('li')
107
106
  }
108
107
 
109
108
  export function makeLine(partial: Partial<LineItem> = {}): LineItem {
@@ -17,6 +17,7 @@
17
17
  // or errors the hook reports `available: false`, the "+ Agregar etapa" column
18
18
  // and the lane context menus simply don't render, and the board keeps working.
19
19
  // All UI text goes through t() with a Spanish defaultValue.
20
+ import { unwrapResponse } from '@asteby/metacore-lib/envelope'
20
21
  import React, { useCallback, useEffect, useMemo, useState } from 'react'
21
22
  import { useTranslation } from 'react-i18next'
22
23
  import { Plus, Trash2, Pencil, MoreVertical, Filter, Flag, GripVertical, Lock, RotateCcw, X } from 'lucide-react'
@@ -310,12 +311,6 @@ export function slugifyStageKey(label: string): string {
310
311
  // Data hook
311
312
  // ---------------------------------------------------------------------------
312
313
 
313
- function unwrap(res: { data: any }): any {
314
- const body = res?.data
315
- if (body && typeof body === 'object' && 'data' in body) return body.data
316
- return body
317
- }
318
-
319
314
  export interface UseCustomStagesResult {
320
315
  /** False when the endpoint is missing/errored — hide the whole feature. */
321
316
  available: boolean
@@ -351,7 +346,7 @@ export function useCustomStages(model: string): UseCustomStagesResult {
351
346
  const res = await api.get(
352
347
  `/custom-stages?model=${encodeURIComponent(model)}`,
353
348
  )
354
- const data = unwrap(res)
349
+ const data = unwrapResponse<any>(res)
355
350
  setStages(Array.isArray(data) ? data : [])
356
351
  setAvailable(true)
357
352
  } catch {