@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
@@ -0,0 +1,113 @@
1
+ // Núcleo genérico de «filas borrador»: filas capturadas en el cliente que aún
2
+ // no existen en el servidor. Lo comparten el editor de renglones de documento
3
+ // (`business/line-items.ts`: claves de UI) y las relaciones hijas capturadas
4
+ // al crear (`dialogs/inline-relation-rows.tsx`). Puro y sin React.
5
+ //
6
+ // Convenciones compartidas:
7
+ // - Clave de UI estable por fila (`key`), nunca se envía al backend.
8
+ // - Errores por celda con la ruta `"<índice>.<campo>"` (mismo formato que
9
+ // `validateLineItems` y `lineItemErrorsFor`).
10
+
11
+ export interface DraftRow {
12
+ /** Clave estable de UI (sobrevive a reordenar/quitar); no se envía. */
13
+ key: string
14
+ values: Record<string, any>
15
+ }
16
+
17
+ let seq = 0
18
+ /** Clave de UI única en el proceso. `prefix` solo ayuda a depurar. */
19
+ export function newDraftKey(prefix = 'row'): string {
20
+ seq += 1
21
+ return `${prefix}_${Date.now().toString(36)}_${seq}`
22
+ }
23
+
24
+ export function makeDraftRow(values: Record<string, any> = {}, key?: string): DraftRow {
25
+ return { key: key ?? newDraftKey(), values }
26
+ }
27
+
28
+ /** Agrega al final (orden de captura = orden de envío). */
29
+ export function appendDraftRow(rows: DraftRow[], row: DraftRow): DraftRow[] {
30
+ return [...rows, row]
31
+ }
32
+
33
+ export function removeDraftRow(rows: DraftRow[], key: string): DraftRow[] {
34
+ return rows.filter((r) => r.key !== key)
35
+ }
36
+
37
+ export function updateDraftCell(rows: DraftRow[], key: string, field: string, value: unknown): DraftRow[] {
38
+ return rows.map((r) => (r.key === key ? { ...r, values: { ...r.values, [field]: value } } : r))
39
+ }
40
+
41
+ /** Ruta de error de una celda: `"<índice>.<campo>"`. */
42
+ export const cellErrorKey = (index: number, field: string): string => `${index}.${field}`
43
+
44
+ export const isBlankValue = (v: unknown): boolean =>
45
+ v === undefined || v === null || (typeof v === 'string' && v.trim() === '')
46
+
47
+ export interface DraftColumn {
48
+ key: string
49
+ label: string
50
+ required?: boolean
51
+ type?: string
52
+ }
53
+
54
+ export interface DraftRowsPolicy {
55
+ /** Mínimo de filas (`RelationMeta.min`). Default 0. */
56
+ min?: number
57
+ messages?: {
58
+ required?: (label: string) => string
59
+ min?: (min: number, count: number) => string
60
+ }
61
+ }
62
+
63
+ export interface DraftRowsValidation {
64
+ /** Errores por celda `"<índice>.<campo>"`. */
65
+ errors: Record<string, string>
66
+ /** Error de conjunto (menos filas que el mínimo). */
67
+ form?: string
68
+ valid: boolean
69
+ }
70
+
71
+ /** Requeridos por celda + mínimo de filas. */
72
+ export function validateDraftRows(
73
+ rows: DraftRow[],
74
+ columns: DraftColumn[],
75
+ policy: DraftRowsPolicy = {},
76
+ ): DraftRowsValidation {
77
+ const min = policy.min ?? 0
78
+ const requiredMsg = policy.messages?.required ?? ((label: string) => `El campo ${label} es obligatorio`)
79
+ const minMsg =
80
+ policy.messages?.min ??
81
+ ((m: number) => `Agrega al menos ${m} ${m === 1 ? 'fila' : 'filas'}`)
82
+ const errors: Record<string, string> = {}
83
+ rows.forEach((row, i) => {
84
+ for (const col of columns) {
85
+ if (col.required && isBlankValue(row.values[col.key])) {
86
+ errors[cellErrorKey(i, col.key)] = requiredMsg(col.label)
87
+ }
88
+ }
89
+ })
90
+ const form = min > 0 && rows.length < min ? minMsg(min, rows.length) : undefined
91
+ return { errors, form, valid: !form && Object.keys(errors).length === 0 }
92
+ }
93
+
94
+ /**
95
+ * Valores listos para el backend: solo las columnas conocidas, opcionales
96
+ * vacíos omitidos (nunca `""`), números reales y booleanos tal cual.
97
+ */
98
+ export function serializeDraftRows(rows: DraftRow[], columns: DraftColumn[]): Array<Record<string, unknown>> {
99
+ return rows.map((row) => {
100
+ const out: Record<string, unknown> = {}
101
+ for (const col of columns) {
102
+ const v = row.values[col.key]
103
+ if (isBlankValue(v)) continue
104
+ if (col.type === 'number' || col.type === 'integer' || col.type === 'decimal') {
105
+ const n = typeof v === 'number' ? v : Number(String(v).replace(',', '.'))
106
+ out[col.key] = Number.isFinite(n) ? n : v
107
+ } else {
108
+ out[col.key] = typeof v === 'string' ? v.trim() : v
109
+ }
110
+ }
111
+ return out
112
+ })
113
+ }
@@ -14,6 +14,7 @@ import * as React from 'react'
14
14
  import { useTranslation } from 'react-i18next'
15
15
  import { registerGenUIBlockRenderer, type GenUIBlockRendererProps } from '@asteby/metacore-genui'
16
16
  import { useApi } from '../api-context'
17
+ import { useAddonSettings } from '../use-addon-settings'
17
18
  import { DynamicForm } from '../dynamic-form'
18
19
  import type { ActionFieldDef } from '../types'
19
20
 
@@ -72,20 +73,13 @@ export function SettingsBlock({ block, text }: GenUIBlockRendererProps) {
72
73
  const api = useApi()
73
74
  const { t } = useTranslation()
74
75
  const addon = String(block.addon)
75
- const [state, setState] = React.useState<{ values: Record<string, unknown>; defs: SettingDefLike[] } | 'loading' | 'error'>('loading')
76
76
  const [msg, setMsg] = React.useState<{ ok: boolean; text: string } | null>(null)
77
-
78
- React.useEffect(() => {
79
- let alive = true
80
- setState('loading')
81
- api
82
- .get(`/addons/${addon}/settings`)
83
- .then((res) => alive && setState({ values: res.data?.data ?? {}, defs: res.data?.definitions ?? [] }))
84
- .catch(() => alive && setState('error'))
85
- return () => {
86
- alive = false
87
- }
88
- }, [api, addon])
77
+ const remote = useAddonSettings(addon, { staleTime: 0 })
78
+ const state: { values: Record<string, unknown>; defs: SettingDefLike[] } | 'loading' | 'error' = remote.error
79
+ ? 'error'
80
+ : remote.isLoading
81
+ ? 'loading'
82
+ : { values: remote.stored, defs: remote.definitions }
89
83
 
90
84
  if (block.scope === 'branch') return block.fallback ? <p className="m-0 text-sm text-muted-foreground">{block.fallback}</p> : null
91
85
  if (state === 'loading') return <div aria-busy="true" role="status" aria-label={t('metacore.genui.loading', { defaultValue: 'Cargando ajustes…' })} className="h-24" />
package/src/index.ts CHANGED
@@ -463,6 +463,7 @@ export * from './i18n-provider'
463
463
  export * from './api-context'
464
464
  export * from './cache-coherence'
465
465
  export * from './use-addon-settings'
466
+ export * from './use-addon-installed-probe'
466
467
  export * from './use-edge-device'
467
468
  export * from './use-print-document'
468
469
  export * from './print-document-button'
@@ -7,6 +7,7 @@
7
7
  // One implementation for EntitySelect, CustomerPicker and VehiclePicker: the
8
8
  // searched text prefills the new record's label field, the saved record is
9
9
  // handed back to select it (create) or refresh its label (edit).
10
+ import { unwrapResponse } from '@asteby/metacore-lib/envelope'
10
11
  import { useState, type ReactNode } from 'react'
11
12
  import { CreateRecordDialog } from './dialogs/create-record-dialog'
12
13
  import { useApi } from './api-context'
@@ -34,7 +35,7 @@ export interface UseRecordPickerDialogResult {
34
35
  dialog: ReactNode
35
36
  }
36
37
 
37
- const unwrap = (res: { data?: any }) => ((res.data?.data ?? res.data) ?? {}) as Record<string, unknown>
38
+ const unwrapRecord = (res: { data?: unknown }) => unwrapResponse<Record<string, unknown> | null>(res) ?? {}
38
39
 
39
40
  export function useRecordPickerDialog({
40
41
  model,
@@ -60,12 +61,12 @@ export function useRecordPickerDialog({
60
61
  defaults={state.recordId ? undefined : state.defaults}
61
62
  lockedFields={state.recordId ? undefined : lockedCreateFields}
62
63
  onCreate={async (data) => {
63
- const rec = unwrap(await api.post(base, data))
64
+ const rec = unwrapRecord(await api.post(base, data))
64
65
  onSaved(rec, 'create')
65
66
  return rec.id != null ? { id: String(rec.id) } : undefined
66
67
  }}
67
68
  onUpdate={async (id, data) => {
68
- const rec = unwrap(await api.put(`${base}/${id}`, data))
69
+ const rec = unwrapRecord(await api.put(`${base}/${id}`, data))
69
70
  onSaved({ ...rec, id: rec.id ?? id }, 'edit')
70
71
  return { id: String(id) }
71
72
  }}
@@ -60,6 +60,7 @@ import {
60
60
  type BlockResult,
61
61
  type ConnectorFormBlock,
62
62
  } from './connector-blocks-model'
63
+ import { useAddonSettings } from '../use-addon-settings'
63
64
  import {
64
65
  isSecretCredential,
65
66
  missingRequired,
@@ -938,6 +939,11 @@ export function AddonConfigSurface({
938
939
  // ones the operator touched are saved (an untouched key keeps inheriting the org
939
940
  // value) and «Heredar de la organización» clears an override.
940
941
  const [target, setTarget] = useState<'org' | 'branch'>('org')
942
+ // One loader for `GET /addons/:key/settings` (branch-aware); `reload()` always hits the network.
943
+ const addonSettings = useAddonSettings(addon.addon_key, {
944
+ branchId: target === 'branch' && activeBranch ? activeBranchId : null,
945
+ enabled: false,
946
+ })
941
947
  const [overrides, setOverrides] = useState<Record<string, unknown>>({})
942
948
  const [touched, setTouched] = useState<Set<string>>(new Set())
943
949
  const [cleared, setCleared] = useState<Set<string>>(new Set())
@@ -1056,17 +1062,14 @@ export function AddonConfigSurface({
1056
1062
  setLoading(true)
1057
1063
  setTouched(new Set())
1058
1064
  setCleared(new Set())
1059
- const branchQuery =
1060
- target === 'branch' && activeBranch ? `?branch_id=${encodeURIComponent(activeBranchId)}` : ''
1061
- api
1062
- .get(`/addons/${addon.addon_key}/settings${branchQuery}`)
1065
+ addonSettings
1066
+ .reload()
1063
1067
  .then((res) => {
1064
- setSettingsValues(res.data?.data || {})
1065
- setOverrides(res.data?.overrides || {})
1066
- const defs: AddonSettingDef[] =
1067
- res.data?.definitions?.length > 0
1068
- ? res.data.definitions
1069
- : (addon.manifest.settings_defs ?? [])
1068
+ setSettingsValues(res.values || {})
1069
+ setOverrides(res.overrides || {})
1070
+ const defs = (
1071
+ res.definitions.length > 0 ? res.definitions : (addon.manifest.settings_defs ?? [])
1072
+ ) as AddonSettingDef[]
1070
1073
  setDefinitions(defs)
1071
1074
  })
1072
1075
  .catch(() => {
@@ -1129,11 +1132,9 @@ export function AddonConfigSurface({
1129
1132
  /* keep what is on screen */
1130
1133
  }
1131
1134
  try {
1132
- const branchQuery =
1133
- target === 'branch' && activeBranch ? `?branch_id=${encodeURIComponent(activeBranchId)}` : ''
1134
- const res = await api.get(`/addons/${addon.addon_key}/settings${branchQuery}`)
1135
- setSettingsValues(res.data?.data || {})
1136
- setOverrides(res.data?.overrides || {})
1135
+ const res = await addonSettings.reload()
1136
+ setSettingsValues(res.values || {})
1137
+ setOverrides(res.overrides || {})
1137
1138
  } catch {
1138
1139
  /* keep what is on screen */
1139
1140
  }
@@ -8,6 +8,7 @@
8
8
  // `available: false` and the lane simply omits the ⚡ affordance — the board
9
9
  // keeps working. All UI text goes through t() with a Spanish defaultValue so a
10
10
  // host that ships no `dynamic.automations.*` keys still renders in Spanish.
11
+ import { unwrapResponse } from '@asteby/metacore-lib/envelope'
11
12
  import React, { useCallback, useEffect, useMemo, useState } from 'react'
12
13
  import { useTranslation } from 'react-i18next'
13
14
  import { Zap, Trash2, Plus } from 'lucide-react'
@@ -127,13 +128,6 @@ export function activeAutomationCount(rules: StageAutomation[] | undefined): num
127
128
  // Data hook
128
129
  // ---------------------------------------------------------------------------
129
130
 
130
- function unwrap(res: { data: any }): any {
131
- const body = res?.data
132
- // Envelope {success, data}; tolerate a bare array/object too.
133
- if (body && typeof body === 'object' && 'data' in body) return body.data
134
- return body
135
- }
136
-
137
131
  export interface UseStageAutomationsResult {
138
132
  /** False when the endpoint is missing/errored — hide the ⚡ affordance. */
139
133
  available: boolean
@@ -162,7 +156,7 @@ export function useStageAutomations(model: string): UseStageAutomationsResult {
162
156
  setLoading(true)
163
157
  try {
164
158
  const res = await api.get(`/stage-automations?model=${encodeURIComponent(model)}`)
165
- const data = unwrap(res)
159
+ const data = unwrapResponse<any>(res)
166
160
  setRules(Array.isArray(data) ? data : [])
167
161
  setAvailable(true)
168
162
  } catch {
@@ -182,7 +176,7 @@ export function useStageAutomations(model: string): UseStageAutomationsResult {
182
176
  async (draft: NewStageAutomation) => {
183
177
  try {
184
178
  const res = await api.post('/stage-automations', draft)
185
- const created = unwrap(res) as StageAutomation | null
179
+ const created = unwrapResponse<any>(res) as StageAutomation | null
186
180
  await load()
187
181
  if (!created) return
188
182
  } catch (e) {
@@ -13,6 +13,7 @@
13
13
  // GET /stage-layout?model=<m> → { model, stage_order: string[] } | null
14
14
  // PUT /stage-layout { model, stage_order: string[] } (full order)
15
15
  // DELETE /stage-layout?model=<m> → reset to the declared order
16
+ import { unwrapResponse } from '@asteby/metacore-lib/envelope'
16
17
  import { useCallback, useEffect, useState } from 'react'
17
18
  import { useApi } from './api-context'
18
19
 
@@ -33,12 +34,6 @@ export interface UseStageLayoutResult {
33
34
  reset: () => Promise<void>
34
35
  }
35
36
 
36
- function unwrap(res: { data: any }): any {
37
- const body = res?.data
38
- if (body && typeof body === 'object' && 'data' in body) return body.data
39
- return body
40
- }
41
-
42
37
  /**
43
38
  * Loads a model's saved lane order (only to learn availability + whether a
44
39
  * custom order exists) and exposes save/reset. A missing endpoint degrades to
@@ -57,7 +52,7 @@ export function useStageLayout(model: string): UseStageLayoutResult {
57
52
  .then((res) => {
58
53
  if (cancelled) return
59
54
  setAvailable(true)
60
- const data = unwrap(res)
55
+ const data = unwrapResponse<any>(res)
61
56
  const order = data?.stage_order
62
57
  setHasCustomLayout(Array.isArray(order) && order.length > 0)
63
58
  })
package/src/types.ts CHANGED
@@ -415,6 +415,17 @@ export interface RelationMeta {
415
415
  * kernels) = not embedded.
416
416
  */
417
417
  embed?: boolean
418
+ /**
419
+ * Capturable al CREAR el padre: el modal de registro en modo crear pinta
420
+ * esta relación como una tabla editable de filas borrador y las envía con
421
+ * el padre en `_children.<name>`. Aditivo; ausente = no se captura al crear.
422
+ */
423
+ create_inline?: boolean
424
+ /**
425
+ * Mínimo de filas hijas que el servidor exige al crear (422 `min` en
426
+ * `_children.<name>`). El cliente lo muestra y bloquea el envío por debajo.
427
+ */
428
+ min?: number
418
429
  }
419
430
 
420
431
  export interface FilterDefinition {
@@ -0,0 +1,39 @@
1
+ // useAddonInstalledProbe — "is addon X installed here?" for hosts/addons that do
2
+ // NOT mount an <InstalledAddonsProvider>: asks the installation API
3
+ // (`GET /addons/:key/settings`, the same call everyone used to hand-roll).
4
+ // With a provider present it answers from it and never touches the network.
5
+ // installed: true → 2xx
6
+ // false → 404 (not installed) or the provider says no
7
+ // undefined → still loading, or unknown (403/network error: never "absent")
8
+ import { useQuery } from '@tanstack/react-query'
9
+ import { useApi } from './api-context'
10
+ import { addonSettingsUrl } from './use-addon-settings'
11
+ import { useInstalledAddons } from './installed-addons-context'
12
+
13
+ export interface UseAddonInstalledProbeResult {
14
+ installed: boolean | undefined
15
+ isLoading: boolean
16
+ }
17
+
18
+ export function useAddonInstalledProbe(addonKey: string, opts: { enabled?: boolean } = {}): UseAddonInstalledProbeResult {
19
+ const api = useApi()
20
+ const ctx = useInstalledAddons()
21
+ const query = useQuery<boolean | undefined>({
22
+ queryKey: ['addon-installed', addonKey],
23
+ queryFn: async () => {
24
+ try {
25
+ await api.get(addonSettingsUrl(addonKey))
26
+ return true
27
+ } catch (e) {
28
+ const status = (e as { response?: { status?: number } })?.response?.status
29
+ if (status === 404) return false
30
+ throw e
31
+ }
32
+ },
33
+ retry: false,
34
+ staleTime: 60_000,
35
+ enabled: !ctx && (opts.enabled ?? true) && !!addonKey,
36
+ })
37
+ if (ctx) return { installed: ctx.addons.has(addonKey), isLoading: false }
38
+ return { installed: query.data, isLoading: query.isLoading }
39
+ }
@@ -4,8 +4,9 @@
4
4
  //
5
5
  // The host (ops) persists settings per org on `AddonInstallation.settings`
6
6
  // (jsonb) and exposes:
7
- // GET /api/addons/:key/settings → { success, data: { <key>: <value> } }
8
- // PUT /api/addons/:key/settings → body = object of values
7
+ // GET /addons/:key/settings → { success, data: { <key>: <value> }, definitions?, overrides? }
8
+ // PUT /addons/:key/settings → body = object of values
9
+ // (paths are relative to the host api client's baseURL, like every other call.)
9
10
  // A setting the org has never saved simply isn't present in `data`; the
10
11
  // caller supplies the fallback via `opts.defaults` (which mirror the
11
12
  // manifest's `settings[].default`). runtime-react has no access to the
@@ -19,13 +20,42 @@
19
20
  // Server-side gating (wasm/Go backends) is out of scope here: a backend that
20
21
  // must gate behaviour on org config reads the same `AddonInstallation.settings`
21
22
  // jsonb directly — this hook is the client-read half of that contract.
22
- import { useMemo } from 'react'
23
+ import { useCallback, useMemo } from 'react'
23
24
  import {
24
25
  useMutation,
25
26
  useQuery,
26
27
  useQueryClient,
27
28
  } from '@tanstack/react-query'
28
29
  import { useApi } from './api-context'
30
+ import type { SettingDefLike } from './genui/settings-block'
31
+
32
+ /** What `GET /addons/:key/settings` answers, normalised. */
33
+ export interface AddonSettingsPayload<T = Record<string, unknown>> {
34
+ /** Stored values (org, or the branch's resolution when `branchId` is given). */
35
+ values: Partial<T>
36
+ /** The manifest's setting definitions the host serves alongside the values. */
37
+ definitions: SettingDefLike[]
38
+ /** Branch overrides (only meaningful with `branchId`). */
39
+ overrides: Record<string, unknown>
40
+ }
41
+
42
+ const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
43
+
44
+ /**
45
+ * Normalises the settings response. Envelope `{ success?, data, definitions?,
46
+ * overrides? }` (definitions/overrides are siblings of `data`); a bare
47
+ * `{ key: value }` map is accepted too. Pure + exported for tests.
48
+ */
49
+ export function parseAddonSettingsBody<T = Record<string, unknown>>(body: unknown): AddonSettingsPayload<T> {
50
+ if (isRecord(body) && ('data' in body || 'success' in body)) {
51
+ return {
52
+ values: (isRecord(body.data) ? body.data : {}) as Partial<T>,
53
+ definitions: Array.isArray(body.definitions) ? (body.definitions as SettingDefLike[]) : [],
54
+ overrides: isRecord(body.overrides) ? body.overrides : {},
55
+ }
56
+ }
57
+ return { values: (isRecord(body) ? body : {}) as Partial<T>, definitions: [], overrides: {} }
58
+ }
29
59
 
30
60
  /** Stable react-query key for an addon's per-org settings (per branch when given). */
31
61
  export function addonSettingsKey(addonKey: string, branchId?: string | null) {
@@ -38,7 +68,9 @@ export function addonSettingsKey(addonKey: string, branchId?: string | null) {
38
68
  * override (POS-1). Without one, the org values (legacy behaviour).
39
69
  */
40
70
  export function addonSettingsUrl(addonKey: string, branchId?: string | null): string {
41
- const base = `/api/addons/${addonKey}/settings`
71
+ // Relative to the host api client's baseURL (ops: `/api`); a literal `/api`
72
+ // here would double-prefix to `/api/api/addons/...`.
73
+ const base = `/addons/${addonKey}/settings`
42
74
  return branchId ? `${base}?branch_id=${encodeURIComponent(branchId)}` : base
43
75
  }
44
76
 
@@ -84,9 +116,17 @@ export interface UseAddonSettingsOptions<T> {
84
116
  export interface UseAddonSettingsResult<T> {
85
117
  /** Saved org values merged over `defaults`. Never null. */
86
118
  settings: T
119
+ /** Stored values only (no defaults merged); `{}` until loaded. */
120
+ stored: Partial<T>
121
+ /** Setting definitions served with the values (`[]` when the host sends none). */
122
+ definitions: SettingDefLike[]
123
+ /** Branch overrides served with the values. */
124
+ overrides: Record<string, unknown>
87
125
  isLoading: boolean
88
126
  error: unknown
89
127
  refetch: () => void
128
+ /** Forces a fresh GET (bypassing staleTime), updates the cache and resolves with the payload. Rejects on error. */
129
+ reload: () => Promise<AddonSettingsPayload<T>>
90
130
  }
91
131
 
92
132
  /**
@@ -110,26 +150,40 @@ export function useAddonSettings<T extends Record<string, unknown> = Record<stri
110
150
  const api = useApi()
111
151
  const { defaults, staleTime, enabled, branchId } = opts
112
152
 
113
- const query = useQuery<Partial<T>>({
114
- queryKey: addonSettingsKey(addonKey, branchId),
115
- queryFn: async () => {
153
+ const qc = useQueryClient()
154
+ const queryKey = addonSettingsKey(addonKey, branchId)
155
+ const fetchPayload = useCallback(
156
+ async (): Promise<AddonSettingsPayload<T>> => {
116
157
  const res = await api.get(addonSettingsUrl(addonKey, branchId))
117
- const body = (res as { data: any }).data
118
- // Host envelope: { success, data: { <key>: <value> } }.
119
- const values = body?.success ? body.data : body
120
- return (values ?? {}) as Partial<T>
158
+ return parseAddonSettingsBody<T>((res as { data: unknown }).data)
121
159
  },
160
+ [api, addonKey, branchId],
161
+ )
162
+
163
+ const query = useQuery<AddonSettingsPayload<T>>({
164
+ queryKey,
165
+ queryFn: fetchPayload,
122
166
  staleTime: staleTime ?? 30_000,
123
167
  enabled: (enabled ?? true) && !!addonKey,
124
168
  })
125
169
 
126
170
  const settings = useMemo(
127
- () => mergeAddonSettings<T>(defaults, query.data),
171
+ () => mergeAddonSettings<T>(defaults, query.data?.values),
128
172
  [defaults, query.data],
129
173
  )
130
174
 
175
+ const reload = useCallback(
176
+ () => qc.fetchQuery({ queryKey, queryFn: fetchPayload, staleTime: 0 }),
177
+ // eslint-disable-next-line react-hooks/exhaustive-deps
178
+ [qc, fetchPayload, addonKey, branchId],
179
+ )
180
+
131
181
  return {
132
182
  settings,
183
+ stored: query.data?.values ?? {},
184
+ definitions: query.data?.definitions ?? [],
185
+ overrides: query.data?.overrides ?? {},
186
+ reload,
133
187
  isLoading: query.isLoading,
134
188
  error: query.error,
135
189
  refetch: () => {
@@ -13,6 +13,7 @@
13
13
  // POST /api/settings/templates/preview → application/pdf
14
14
  //
15
15
  // ApiClient is a PEER via <ApiProvider> (same one usePrintDocument uses).
16
+ import { unwrapResponse } from '@asteby/metacore-lib/envelope'
16
17
  import { useCallback, useMemo } from 'react'
17
18
  import {
18
19
  useMutation,
@@ -45,19 +46,13 @@ export function orgDocumentTemplateKey(addonKey: string, documentKey: string) {
45
46
  return ['org-document-templates', addonKey, documentKey] as const
46
47
  }
47
48
 
48
- function unwrapData<T>(res: { data?: unknown }): T {
49
- const body = (res as { data: any }).data
50
- const values = body?.success ? body.data : body
51
- return values as T
52
- }
53
-
54
49
  export function useOrgDocumentCatalog(opts?: { enabled?: boolean }) {
55
50
  const api = useApi()
56
51
  const query = useQuery<OrgDocumentCatalogItem[]>({
57
52
  queryKey: orgDocumentCatalogKey(),
58
53
  queryFn: async () => {
59
54
  const res = await api.get('/settings/templates')
60
- const data = unwrapData<OrgDocumentCatalogItem[] | null>(res)
55
+ const data = unwrapResponse<OrgDocumentCatalogItem[] | null>(res)
61
56
  return Array.isArray(data) ? data : []
62
57
  },
63
58
  staleTime: 30_000,
@@ -85,7 +80,7 @@ export function useOrgDocumentTemplate(
85
80
  const res = await api.get(
86
81
  `/settings/templates/${encodeURIComponent(addonKey)}/${encodeURIComponent(documentKey)}`,
87
82
  )
88
- return unwrapData<OrgDocumentTemplateDetail>(res)
83
+ return unwrapResponse<OrgDocumentTemplateDetail>(res)
89
84
  },
90
85
  enabled:
91
86
  (opts?.enabled ?? true) && !!addonKey && !!documentKey,
@@ -113,7 +108,7 @@ export function useSaveOrgDocumentTemplate() {
113
108
  `/settings/templates/${encodeURIComponent(addonKey)}/${encodeURIComponent(documentKey)}`,
114
109
  { html, paper },
115
110
  )
116
- return unwrapData<OrgDocumentTemplateDetail>(res)
111
+ return unwrapResponse<OrgDocumentTemplateDetail>(res)
117
112
  },
118
113
  onSuccess: (_data, vars) => {
119
114
  void qc.invalidateQueries({ queryKey: orgDocumentCatalogKey() })
@@ -136,7 +131,7 @@ export function useResetOrgDocumentTemplate() {
136
131
  const res = await api.delete(
137
132
  `/settings/templates/${encodeURIComponent(addonKey)}/${encodeURIComponent(documentKey)}`,
138
133
  )
139
- return unwrapData<OrgDocumentTemplateDetail>(res)
134
+ return unwrapResponse<OrgDocumentTemplateDetail>(res)
140
135
  },
141
136
  onSuccess: (_data, vars) => {
142
137
  void qc.invalidateQueries({ queryKey: orgDocumentCatalogKey() })
@@ -1,6 +1,7 @@
1
1
  // Default ViewDataSource over the runtime-react ApiClient, plus the pure
2
2
  // helpers renderers share (capability input mapping, item extraction, date
3
3
  // grouping). Light on purpose: this module is in the static graph.
4
+ import { unwrapEnvelope, unwrapList } from '@asteby/metacore-lib/envelope'
4
5
  import type { ApiClient } from '../api-context'
5
6
  import type { WidgetData } from '../dashboard-types'
6
7
  import type { ChartRequest, ViewDataSource, ViewListParams, ViewRows } from './types'
@@ -16,17 +17,6 @@ export interface ApiViewDataSourceOptions {
16
17
  capabilityPath?: string
17
18
  }
18
19
 
19
- type Envelope<T> = { success?: boolean; data?: T; meta?: { total?: number }; message?: string }
20
-
21
- function unwrap<T>(body: unknown): { data: T | undefined; total?: number } {
22
- const env = body as Envelope<T>
23
- if (env && typeof env === 'object' && 'success' in env) {
24
- if (env.success === false) throw new Error(env.message || 'request failed')
25
- return { data: env.data, total: env.meta?.total }
26
- }
27
- return { data: body as T }
28
- }
29
-
30
20
  export function createApiViewDataSource(
31
21
  api: ApiClient,
32
22
  opts: ApiViewDataSourceOptions = {},
@@ -36,12 +26,12 @@ export function createApiViewDataSource(
36
26
  return {
37
27
  async list(model: string, params?: ViewListParams): Promise<ViewRows> {
38
28
  const res = await api.get(`/data/${encodeURIComponent(model)}`, params ? { params } : undefined)
39
- const { data, total } = unwrap<Record<string, unknown>[]>(res.data)
40
- return { rows: Array.isArray(data) ? data : [], total }
29
+ const { items, meta } = unwrapList<Record<string, unknown>>(res.data)
30
+ return { rows: items, total: meta.total }
41
31
  },
42
32
  async record(model: string, id: string) {
43
33
  const res = await api.get(`/data/${encodeURIComponent(model)}/${encodeURIComponent(id)}`)
44
- return unwrap<Record<string, unknown>>(res.data).data ?? null
34
+ return unwrapEnvelope<Record<string, unknown> | undefined>(res.data) ?? null
45
35
  },
46
36
  async chart(req: ChartRequest): Promise<WidgetData> {
47
37
  const res = await api.post(chartPath, {
@@ -51,11 +41,11 @@ export function createApiViewDataSource(
51
41
  record_id: req.recordId,
52
42
  panel_key: req.panelKey,
53
43
  })
54
- return unwrap<WidgetData>(res.data).data ?? {}
44
+ return unwrapEnvelope<WidgetData | undefined>(res.data) ?? {}
55
45
  },
56
46
  async capability(key: string, input: Record<string, unknown>) {
57
47
  const res = await api.post(capabilityPath, { capability: key, input })
58
- return unwrap<unknown>(res.data).data
48
+ return unwrapEnvelope<unknown>(res.data)
59
49
  },
60
50
  }
61
51
  }