@asteby/metacore-runtime-react 53.22.0 → 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 (50) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/assist-interview.d.ts.map +1 -1
  3. package/dist/assist-interview.js +7 -10
  4. package/dist/custom-stages.d.ts.map +1 -1
  5. package/dist/custom-stages.js +2 -10
  6. package/dist/dialogs/dynamic-record.d.ts.map +1 -1
  7. package/dist/dialogs/dynamic-record.js +5 -3
  8. package/dist/dialogs/use-inline-relations.d.ts.map +1 -1
  9. package/dist/dialogs/use-inline-relations.js +4 -4
  10. package/dist/genui/settings-block.d.ts.map +1 -1
  11. package/dist/genui/settings-block.js +7 -12
  12. package/dist/index.d.ts +1 -0
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +1 -0
  15. package/dist/record-picker-dialog.d.ts.map +1 -1
  16. package/dist/record-picker-dialog.js +4 -3
  17. package/dist/setup/addon-config-surface.d.ts.map +1 -1
  18. package/dist/setup/addon-config-surface.js +14 -12
  19. package/dist/stage-automations.d.ts.map +1 -1
  20. package/dist/stage-automations.js +3 -12
  21. package/dist/stage-layout.d.ts.map +1 -1
  22. package/dist/stage-layout.js +2 -7
  23. package/dist/use-addon-installed-probe.d.ts +8 -0
  24. package/dist/use-addon-installed-probe.d.ts.map +1 -0
  25. package/dist/use-addon-installed-probe.js +36 -0
  26. package/dist/use-addon-settings.d.ts +24 -0
  27. package/dist/use-addon-settings.d.ts.map +1 -1
  28. package/dist/use-addon-settings.js +39 -13
  29. package/dist/use-org-document-templates.d.ts.map +1 -1
  30. package/dist/use-org-document-templates.js +5 -9
  31. package/dist/views/data-source.d.ts.map +1 -1
  32. package/dist/views/data-source.js +9 -14
  33. package/package.json +4 -3
  34. package/src/__tests__/genui-settings-block.test.tsx +6 -3
  35. package/src/__tests__/use-addon-settings-hooks.test.tsx +73 -0
  36. package/src/__tests__/use-addon-settings.test.ts +19 -3
  37. package/src/assist-interview.tsx +7 -11
  38. package/src/custom-stages.tsx +2 -7
  39. package/src/dialogs/dynamic-record.tsx +7 -2
  40. package/src/dialogs/use-inline-relations.ts +4 -5
  41. package/src/genui/settings-block.tsx +7 -13
  42. package/src/index.ts +1 -0
  43. package/src/record-picker-dialog.tsx +4 -3
  44. package/src/setup/addon-config-surface.tsx +16 -15
  45. package/src/stage-automations.tsx +3 -9
  46. package/src/stage-layout.ts +2 -7
  47. package/src/use-addon-installed-probe.ts +39 -0
  48. package/src/use-addon-settings.ts +66 -12
  49. package/src/use-org-document-templates.ts +5 -10
  50. package/src/views/data-source.ts +6 -16
@@ -10,7 +10,7 @@
10
10
  // the image-url resolver and the org IANA timezone — are passed as props so the
11
11
  // SDK stays transport- and host-agnostic.
12
12
  import { emitRecordMutation } from '../record-mutation-events'
13
- import { createContext, useCallback, useContext, useEffect, useId, useMemo, useRef, useState } from 'react'
13
+ import { createContext, lazy, Suspense, useCallback, useContext, useEffect, useId, useMemo, useRef, useState } from 'react'
14
14
  import { useTranslation } from 'react-i18next'
15
15
  import type { ModelSchema } from './types'
16
16
 
@@ -72,9 +72,12 @@ import { isNullableBooleanField, omitUntouchedNullBooleans, usesTriState } from
72
72
  import { NullBooleanMark, TriStateBooleanField } from '../tri-state-boolean'
73
73
  import { isNilUuid, normalizeNilUuid } from '../nil-uuid'
74
74
  import { normalizeRefFieldsForSubmit, withInlineChildren } from './normalize-submit'
75
- import { InlineRelationRows } from './inline-relation-rows'
76
75
  import { relationMin, splitChildErrors } from './inline-relations'
77
76
  import { useInlineRelations } from './use-inline-relations'
77
+
78
+ // La tabla de filas hijas solo se usa al CREAR un registro cuyo modelo declara `create_inline`: se carga bajo demanda para no
79
+ // engordar el grafo inicial del panel (el shell de Ops tiene un techo de no-regresión).
80
+ const InlineRelationRows = lazy(() => import('./inline-relation-rows').then(m => ({ default: m.InlineRelationRows })))
78
81
  import { validateDraftRows, type DraftRow } from '../draft-rows'
79
82
  import { clearFieldErrorTree, lineItemErrorsFor } from '../field-validation-ui'
80
83
  import { validateValues, bagHasErrors, exemptUnchangedRuleIssues } from '../validator'
@@ -1503,6 +1506,7 @@ export function DynamicRecordDialog({
1503
1506
  )}
1504
1507
  {isCreate && inline.relations.length > 0 && (
1505
1508
  <div className="mt-6 space-y-6" data-slot="inline-relations">
1509
+ <Suspense fallback={<div role="status" aria-busy="true" className="h-24 animate-pulse rounded-md bg-muted" data-slot="inline-relations-loading" />}>
1506
1510
  {inline.relations.map(rel => (
1507
1511
  <InlineRelationRows
1508
1512
  key={rel.name}
@@ -1529,6 +1533,7 @@ export function DynamicRecordDialog({
1529
1533
  )}
1530
1534
  />
1531
1535
  ))}
1536
+ </Suspense>
1532
1537
  </div>
1533
1538
  )}
1534
1539
  {!isCreate && record && audit && (
@@ -6,6 +6,7 @@
6
6
  // mismo contrato que usa el modal del hijo (requeridos, opciones, `ref`);
7
7
  // si no responde, las columnas de `/metadata/table/<through>` pasan por
8
8
  // `deriveRelationFormFields`, el mecanismo que ya usa `<DynamicRelation>`.
9
+ import { unwrapResponse } from '@asteby/metacore-lib/envelope'
9
10
  import { useEffect, useState } from 'react'
10
11
  import { useApi } from '../api-context'
11
12
  import { deriveRelationFormFields } from '../dynamic-relation-helpers'
@@ -19,8 +20,6 @@ export interface InlineRelationsState<F> {
19
20
  loading: boolean
20
21
  }
21
22
 
22
- const unwrap = (res: any) => res?.data?.data ?? res?.data
23
-
24
23
  export function useInlineRelations<F extends { key: string; hidden?: boolean; readonly?: boolean; type?: string }>(
25
24
  opts: { enabled: boolean; model: string; localizeLabel: (label: string) => string },
26
25
  ): InlineRelationsState<F> {
@@ -40,7 +39,7 @@ export function useInlineRelations<F extends { key: string; hidden?: boolean; re
40
39
  setState((s) => ({ ...s, loading: true }))
41
40
  ;(async () => {
42
41
  try {
43
- const meta = unwrap(await api.get(`/metadata/table/${model}`))
42
+ const meta = unwrapResponse<any>(await api.get(`/metadata/table/${model}`))
44
43
  const rels: RelationMeta[] = (Array.isArray(meta?.relations) ? meta.relations : [])
45
44
  .filter(isCreateInline)
46
45
  .map((rel: RelationMeta) => ({ ...rel, label: rel.label ? localize.fn(rel.label) : rel.name }))
@@ -49,14 +48,14 @@ export function useInlineRelations<F extends { key: string; hidden?: boolean; re
49
48
  rels.map(async (rel) => {
50
49
  let raw: any[] | undefined
51
50
  try {
52
- const m = unwrap(await api.get(`/metadata/modal/${rel.through}`))
51
+ const m = unwrapResponse<any>(await api.get(`/metadata/modal/${rel.through}`))
53
52
  if (Array.isArray(m?.fields)) raw = m.fields
54
53
  } catch {
55
54
  /* cae a la metadata de tabla */
56
55
  }
57
56
  if (!raw) {
58
57
  try {
59
- const m = unwrap(await api.get(`/metadata/table/${rel.through}`))
58
+ const m = unwrapResponse<any>(await api.get(`/metadata/table/${rel.through}`))
60
59
  raw = deriveRelationFormFields(m, rel.foreign_key) as any[]
61
60
  } catch {
62
61
  raw = []
@@ -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
  })
@@ -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
  }