From bc85b22c37050f2fd34d2e56ebe0abb382a6fb78 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 15:37:29 +0000 Subject: [PATCH 1/3] fix(service-analytics): a lookup dimension labels by its column's object and the target's nameField A relationship-path dimension (hop.column) now reads its column's field meta on the object the path's last hop reaches, named by the one hop resolver the query joins with, in the display pass and the sort-key pass. The label read prefers the target object's declared nameField before the name/title/label/first-text convention. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzrvnam3RUBqcsfRHq --- ...cs-dataset-lookup-dimension-labels.test.ts | 316 ++++++++++++++++++ .../src/analytics-service.ts | 14 +- .../service-analytics/src/dimension-labels.ts | 112 +++++-- .../services/service-analytics/src/plugin.ts | 5 +- 4 files changed, 424 insertions(+), 23 deletions(-) create mode 100644 packages/rest/src/analytics-dataset-lookup-dimension-labels.test.ts diff --git a/packages/rest/src/analytics-dataset-lookup-dimension-labels.test.ts b/packages/rest/src/analytics-dataset-lookup-dimension-labels.test.ts new file mode 100644 index 00000000000..7d7ed6539d4 --- /dev/null +++ b/packages/rest/src/analytics-dataset-lookup-dimension-labels.test.ts @@ -0,0 +1,316 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A lookup dimension serves the referenced record's display name, not its id, + * in the two shapes a downstream metadata app hit on the published packages: + * + * - **A — a relationship-path lookup** (`field: 'crm_account.owner_id'`): the + * column lives on the HOP object, so the label pass has to read that object's + * field map, not the base object's. The hop is resolved by the one hop + * resolver the query itself joins with (`columnObjectOf`, `hop-object.ts`), + * in the display pass and in the sort-key pass alike. + * - **B — a base-field lookup to an object whose title is its `nameField`** + * (an autonumber `order_number`, no `name`/`title`/`label` field, and a + * null text field declared ahead of it): the label read takes the target's + * declared `nameField` before the name/title/label/first-text convention. + * + * Driven end to end: a real `ObjectQL` engine over SQLite, the analytics + * service `AnalyticsServicePlugin` registers (its real `fetchRecordLabels` + * bridge), and three faces of one saved dataset — the REST door + * (`POST /analytics/dataset/query` with `datasetName`), the `query_dataset` + * tool executor (`AnalyticsService.datasetTools`, the executor MCP's + * `query_dataset` bridge member calls: `packages/runtime/src/domains/mcp.ts`), + * and the direct service call. All three serve the same labelled rows, because + * all three reach `AnalyticsService.queryDataset`'s one label pass. + * + * Pinned around the fix: grouping stays by id (two reps who share a name stay + * two rows), a hop target the API exposure decision does not serve still + * renders its id (the label read is gated as before), and a lookup to an + * object with a `name` field labels exactly as it did. + */ + +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { AnalyticsServicePlugin, type AnalyticsService } from '@objectstack/service-analytics'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { DatasetSchema } from '@objectstack/spec/ui'; +import { RestServer } from './rest-server'; +import { DEFAULT_ORGANIZATION_ID, installDefaultOrganization } from './default-organization.testkit.js'; + +const OBJECTS = [ + { + name: 'ld_rep', label: 'Rep', + fields: { name: { name: 'name', type: 'text' } }, + }, + { + // The API exposure decision does not serve this object: a dimension whose + // label target it is renders the stored id. + name: 'ld_region', label: 'Region', enable: { apiEnabled: false }, + fields: { name: { name: 'name', type: 'text' } }, + }, + { + name: 'ld_grade', label: 'Grade', + fields: { name: { name: 'name', type: 'text' } }, + }, + { + name: 'ld_account', label: 'Account', + fields: { + name: { name: 'name', type: 'text' }, + owner_id: { name: 'owner_id', type: 'lookup', reference: 'ld_rep' }, + region: { name: 'region', type: 'lookup', reference: 'ld_region' }, + }, + }, + { + // B's target: titled by its `nameField`, an autonumber, and no + // `name`/`title`/`label` field. The platform injects the ownership `queue` + // text column (null on every row here), which is the first text field the + // name/title/label/first-text convention finds — the card's shape. + name: 'ld_order', label: 'Order', nameField: 'order_number', + fields: { + order_number: { name: 'order_number', type: 'autonumber', autonumberFormat: 'SO-{YYYY}-{0000}' }, + account: { name: 'account', type: 'lookup', reference: 'ld_account' }, + carbon_grade: { name: 'carbon_grade', type: 'lookup', reference: 'ld_grade' }, + tonnes: { name: 'tonnes', type: 'number' }, + }, + }, + { + name: 'ld_plan', label: 'Plan', + fields: { + cb_order: { name: 'cb_order', type: 'lookup', reference: 'ld_order' }, + margin: { name: 'margin', type: 'number' }, + }, + }, +]; + +const SEED: Record[]> = { + ld_rep: [ + // Ids sort OPPOSITE to names (rep_a < rep_b, "Zed Young" > "Sam Lee"), so + // a sort by the stored id and a sort by the rendered name disagree. + { id: 'rep_a', name: 'Zed Young' }, + // Two reps who share a display name: grouping stays by id. + { id: 'rep_b', name: 'Sam Lee' }, + { id: 'rep_c', name: 'Sam Lee' }, + ], + ld_region: [{ id: 'reg_e', name: 'East' }], + ld_grade: [{ id: 'gr_330', name: 'N330' }, { id: 'gr_550', name: 'N550' }], + ld_account: [ + { id: 'acc_1', name: 'Acme', owner_id: 'rep_a', region: 'reg_e' }, + { id: 'acc_2', name: 'Globex', owner_id: 'rep_b', region: 'reg_e' }, + { id: 'acc_3', name: 'Initech', owner_id: 'rep_c', region: 'reg_e' }, + ], + ld_order: [ + { id: 'ord_1', order_number: 'SO-2026-0001', account: 'acc_1', carbon_grade: 'gr_330', tonnes: 10 }, + { id: 'ord_2', order_number: 'SO-2026-0002', account: 'acc_2', carbon_grade: 'gr_550', tonnes: 20 }, + { id: 'ord_3', order_number: 'SO-2026-0003', account: 'acc_3', carbon_grade: 'gr_330', tonnes: 5 }, + ], + ld_plan: [ + { id: 'pl_1', cb_order: 'ord_1', margin: 1.5 }, + { id: 'pl_2', cb_order: 'ord_2', margin: 2.5 }, + { id: 'pl_3', cb_order: 'ord_2', margin: 1 }, + ], +}; + +const ORDER_METRICS = { + name: 'ld_order_metrics', + label: 'Order metrics', + object: 'ld_order', + include: ['account'], + dimensions: [ + // A — a relationship-path lookup. + { name: 'rep', label: 'Sales Rep', field: 'account.owner_id', type: 'lookup' }, + // A, gated — the path's label target is not served by the API. + { name: 'region', label: 'Region', field: 'account.region', type: 'lookup' }, + // CONTROL — a base-field lookup to an object with a `name` field. + { name: 'customer', label: 'Customer', field: 'account', type: 'lookup' }, + ], + measures: [ + { name: 'order_tonnes', label: 'Tonnes', aggregate: 'sum', field: 'tonnes' }, + { name: 'order_count', label: 'Orders', aggregate: 'count' }, + ], +}; + +const PLAN_METRICS = { + name: 'ld_plan_metrics', + label: 'Plan metrics', + object: 'ld_plan', + include: ['cb_order'], + dimensions: [ + // B — a base-field lookup to an object titled by its `nameField`. + { name: 'order', label: 'Order', field: 'cb_order', type: 'lookup' }, + // A again — the card's "Margin by Grade" path. + { name: 'grade', label: 'Grade', field: 'cb_order.carbon_grade', type: 'lookup' }, + ], + measures: [{ name: 'plan_margin', label: 'Margin', aggregate: 'sum', field: 'margin' }], +}; +const SAVED = [ORDER_METRICS, PLAN_METRICS]; + +const CALLER = { userId: 'u_admin', tenantId: 't1' } as ExecutionContext; + +/** A security service that admits every read: this file is about labels. */ +const security = { + getReadFilter: async () => undefined, + canReadObject: async () => true, + getReadableFields: async (object: string) => + ['id', ...Object.keys(OBJECTS.find((o) => o.name === object)?.fields ?? {})], + getQueryableFields: async (object: string) => + ['id', ...Object.keys(OBJECTS.find((o) => o.name === object)?.fields ?? {})], +}; + +function mockServer() { + return { + get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn(), patch: vi.fn(), + use: vi.fn(), listen: vi.fn().mockResolvedValue(undefined), close: vi.fn().mockResolvedValue(undefined), + }; +} +function mockRes() { + const res: any = { statusCode: 200, body: undefined }; + res.status = vi.fn((c: number) => { res.statusCode = c; return res; }); + res.json = vi.fn((b: any) => { res.body = b; return res; }); + res.end = vi.fn(() => res); + return res; +} + +let engine: ObjectQL; +let service: AnalyticsService; +let restRoute: any; + +type Rows = Record[]; + +const faces: Record) => Promise> = { + rest: async (datasetName, selection) => { + const res = mockRes(); + await restRoute.handler({ method: 'POST', params: {}, headers: {}, query: {}, body: { datasetName, selection } }, res); + expect(res.statusCode, JSON.stringify(res.body)).toBeLessThan(400); + return res.body.rows; + }, + queryDatasetTool: async (datasetName, selection) => { + const tools = service.datasetTools({ loadDatasets: async () => SAVED }); + const out = await tools.execute({ toolName: 'query_dataset', input: { datasetName, selection } }, CALLER); + return (out as { rows: Rows }).rows; + }, + direct: async (datasetName, selection) => { + const dataset = DatasetSchema.parse(SAVED.find((d) => d.name === datasetName)); + return (await service.queryDataset(dataset as never, selection as never, CALLER)).rows; + }, +}; + +/** Rows as sorted `[k, v]` lists, so face answers compare without caring about row order. */ +const byKey = (rows: Rows) => + rows.map((r) => JSON.stringify(Object.keys(r).sort().map((k) => [k, r[k]]))).sort(); + +/** Every face's rows for one selection, asserted equal; the shared answer is returned. */ +async function served(datasetName: string, selection: Record): Promise { + const answers: Record = {}; + for (const [face, run] of Object.entries(faces)) answers[face] = await run(datasetName, selection); + for (const [face, rows] of Object.entries(answers)) expect(byKey(rows), face).toEqual(byKey(answers.direct)); + return answers.direct; +} + +beforeAll(async () => { + const driver: any = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + engine = new ObjectQL(); + engine.registerDriver(driver, true); + await engine.init(); + for (const object of OBJECTS) engine.registry.registerObject(object as any); + await engine.syncSchemas(); + await installDefaultOrganization(engine as any); + for (const [object, rows] of Object.entries(SEED)) { + for (const row of rows) await driver.create(object, { ...row, organization_id: DEFAULT_ORGANIZATION_ID }); + } + + const registered: Record = {}; + const ctx = { + getService: (name: string) => { + if (name === 'security') return security; + if (name === 'data') return engine; + return registered[name]; + }, + registerService: (name: string, svc: unknown) => { registered[name] = svc; }, + replaceService: (name: string, svc: unknown) => { registered[name] = svc; }, + logger: { info() {}, warn() {}, error() {}, debug() {} }, + }; + await new AnalyticsServicePlugin().init(ctx as never); + service = registered.analytics as AnalyticsService; + + const protocol = { + getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '' } }), + getMetaTypes: vi.fn().mockResolvedValue([]), + getMetaItem: vi.fn().mockImplementation(async ({ name }: { name: string }) => ({ + type: 'dataset', name, item: SAVED.map((d) => ({ ...d })).find((d) => d.name === name), + })), + }; + const rest = new RestServer( + mockServer() as any, protocol as any, { api: { requireAuth: false } } as any, + undefined, undefined, undefined, undefined, undefined, undefined, undefined, + undefined, undefined, undefined, undefined, + async () => service, + ); + (rest as any).resolveExecCtx = async () => CALLER; + rest.registerRoutes(); + restRoute = rest.getRoutes().find((r) => r.method === 'POST' && r.path.endsWith('/analytics/dataset/query')); + expect(restRoute).toBeDefined(); +}); + +afterAll(async () => { + try { await engine?.destroy(); } catch { /* noop */ } +}); + +describe('A — a relationship-path lookup dimension serves the hop target\'s name', () => { + it('labels `account.owner_id` with the rep\'s name on every face, still grouped by rep id', async () => { + const rows = await served(ORDER_METRICS.name, { dimensions: ['rep'], measures: ['order_tonnes', 'order_count'] }); + // Two reps named "Sam Lee" stay two rows: the grid groups by the stored id + // and only the rendered value is the name. + expect(byKey(rows)).toEqual(byKey([ + { rep: 'Zed Young', order_tonnes: 10, order_count: 1 }, + { rep: 'Sam Lee', order_tonnes: 20, order_count: 1 }, + { rep: 'Sam Lee', order_tonnes: 5, order_count: 1 }, + ])); + }); + + it('sorts `account.owner_id` by the name the rows render (the sort-key pass reads the hop too)', async () => { + const all = await served(ORDER_METRICS.name, { + dimensions: ['rep'], measures: ['order_tonnes'], order: { rep: 'asc' }, + }); + expect(all.map((r) => r.rep)).toEqual(['Sam Lee', 'Sam Lee', 'Zed Young']); + // …and the window is taken over that order: by id the first row is rep_a. + const first = await served(ORDER_METRICS.name, { + dimensions: ['rep'], measures: ['order_tonnes'], order: { rep: 'asc' }, limit: 1, + }); + expect(first.map((r) => r.rep)).toEqual(['Sam Lee']); + }); + + it('labels the card\'s second path shape, `cb_order.carbon_grade`, with the grade name', async () => { + const rows = await served(PLAN_METRICS.name, { dimensions: ['grade'], measures: ['plan_margin'] }); + expect(byKey(rows)).toEqual(byKey([ + { grade: 'N330', plan_margin: 1.5 }, + { grade: 'N550', plan_margin: 3.5 }, + ])); + }); + + it('still renders the id when the path\'s label target is not served by the API exposure decision', async () => { + const rows = await served(ORDER_METRICS.name, { dimensions: ['region'], measures: ['order_count'] }); + expect(rows).toEqual([{ region: 'reg_e', order_count: 3 }]); + }); +}); + +describe('B — a lookup to an object titled by its nameField serves that field', () => { + it('labels `cb_order` with the order number, not the id, on every face', async () => { + const rows = await served(PLAN_METRICS.name, { dimensions: ['order'], measures: ['plan_margin'] }); + expect(byKey(rows)).toEqual(byKey([ + { order: 'SO-2026-0001', plan_margin: 1.5 }, + { order: 'SO-2026-0002', plan_margin: 3.5 }, + ])); + }); +}); + +describe('CONTROL — a lookup to an object with a `name` field labels as it did', () => { + it('labels `account` with the account name', async () => { + const rows = await served(ORDER_METRICS.name, { dimensions: ['customer'], measures: ['order_count'] }); + expect(byKey(rows)).toEqual(byKey([ + { customer: 'Acme', order_count: 1 }, + { customer: 'Globex', order_count: 1 }, + { customer: 'Initech', order_count: 1 }, + ])); + }); +}); diff --git a/packages/services/service-analytics/src/analytics-service.ts b/packages/services/service-analytics/src/analytics-service.ts index f8d5577dba6..9dd5c474235 100644 --- a/packages/services/service-analytics/src/analytics-service.ts +++ b/packages/services/service-analytics/src/analytics-service.ts @@ -3227,12 +3227,23 @@ export class AnalyticsService implements IAnalyticsService { // #3680 — hand the executor the sort-key label hook so an `order` on a // select/lookup dimension sorts by the label the user reads. Built over // the SAME capabilities (and read scope) as the display resolution below. + // A relationship-path dimension (`account.owner_id`) labels from its + // COLUMN's meta, on the object the path's last hop reaches — named by the + // one hop resolver the query joins it with (`columnObjectOf`, over the + // compiled cube's joins and the host's hop reference), so the object + // labelled is the object read. Both label passes take it from here. + const columnObjectOfField = (field: string) => + columnObjectOf(compiled.cube, dataset.object, field, this.hopReference); const orderLabels = labelDeps && dataset.dimensions?.length ? createOrderLabelResolver( dataset.object, dataset.dimensions .filter((d) => !!d.field) - .map((d) => ({ name: d.name, field: d.field as string })), + .map((d) => ({ + name: d.name, + field: d.field as string, + columnObject: columnObjectOfField(d.field as string), + })), labelDeps, resolveScope, context, @@ -3489,6 +3500,7 @@ export class AnalyticsService implements IAnalyticsService { .map((d) => ({ name: d.name, field: d.field, + columnObject: columnObjectOfField(d.field), type: d.type, dateGranularity: resolveDimensionGranularity(selection, d.name, d.dateGranularity), })); diff --git a/packages/services/service-analytics/src/dimension-labels.ts b/packages/services/service-analytics/src/dimension-labels.ts index 40b1d74b1c1..12c8172dc68 100644 --- a/packages/services/service-analytics/src/dimension-labels.ts +++ b/packages/services/service-analytics/src/dimension-labels.ts @@ -38,7 +38,7 @@ */ import type { ExecutionContext } from '@objectstack/spec/kernel'; -import { referenceTargetOf } from '@objectstack/spec/data'; +import { isVirtualSearchField, referenceTargetOf } from '@objectstack/spec/data'; import { bucketDateKey, bucketKeyToCalendarRange, isBucketGranularity } from '@objectstack/core'; /** The minimal field shape this resolver needs. */ @@ -154,6 +154,47 @@ function referenceLabelTarget(meta: FieldMetaLite | undefined): string | undefin return meta ? referenceTargetOf(meta) : undefined; } +/** + * A dimension as the label passes read it: its row key (`name`), the `field` + * the dataset declares (a column of the base object, or a relationship path + * `hop.column`), and — for a path — `columnObject`, the object the path's + * COLUMN lives on. + * + * `columnObject` is the answer of the one hop resolver (`columnObjectOf`, + * `hop-object.ts`) the query joins the hop with, computed by the caller that + * holds the compiled cube and the host's hop reference. ⛔ This module walks no + * path itself: a second copy of that walk could name a different object than + * the one the query read. + */ +export interface LabelDimension { + name: string; + field: string; + /** The object the field's column lives on; omitted ⇒ the base object, `field` read verbatim. */ + columnObject?: string; +} + +/** + * Where a dimension's column is declared: the object and the column's name on + * it. A relationship path `account.owner_id` with `columnObject: 'crm_account'` + * reads `owner_id` on `crm_account`; a dimension without `columnObject` reads + * `field` verbatim on the base object, so a dotted path nobody resolved finds + * no field meta and its stored value renders as itself. + */ +function dimensionColumn(baseObject: string, dim: LabelDimension): { object: string; column: string } { + if (!dim.columnObject) return { object: baseObject, column: dim.field }; + return { object: dim.columnObject, column: dim.field.slice(dim.field.lastIndexOf('.') + 1) }; +} + +/** The field meta a dimension's column declares, on the object it lives on. */ +function dimensionFieldMeta( + baseObject: string, + dim: LabelDimension, + deps: DimensionLabelDeps, +): { object: string; column: string; meta: FieldMetaLite | undefined } { + const { object, column } = dimensionColumn(baseObject, dim); + return { object, column, meta: deps.getObjectFields(object)?.[column] }; +} + /** * Sort-key label resolution for `DatasetSelection.order` (#3680). * @@ -199,35 +240,39 @@ export interface OrderLabelResolver { */ export function createOrderLabelResolver( baseObject: string, - dims: Array<{ name: string; field: string }>, + dims: LabelDimension[], deps: DimensionLabelDeps, resolveScope?: LabelScopeResolver, context?: ExecutionContext, ): OrderLabelResolver { const dimByName = new Map(dims.map((d) => [d.name, d])); - const metaFor = (dimension: string): FieldMetaLite | undefined => { + // A relationship-path dimension's meta is its column's, on the object the + // path's last hop reaches (`columnObject`) — the same reading the display + // pass makes, so the sort keys are the labels the rows render. + const columnFor = (dimension: string) => { const dim = dimByName.get(dimension); - return dim ? deps.getObjectFields(baseObject)?.[dim.field] : undefined; + return dim ? dimensionFieldMeta(baseObject, dim, deps) : undefined; }; return { isLabelBearing(dimension) { - const meta = metaFor(dimension); + const meta = columnFor(dimension)?.meta; if (!meta) return false; if (Array.isArray(meta.options) && meta.options.length > 0) return true; return !!referenceLabelTarget(meta); }, async resolveLabels(dimension, values) { - const meta = metaFor(dimension); - if (!meta) return undefined; + const col = columnFor(dimension); + const meta = col?.meta; + if (!col || !meta) return undefined; if (Array.isArray(meta.options) && meta.options.length > 0) { // [#22178] Sort by the label the display pass renders: the options // `translateSelectOptions` answers for this request's locale, else the // authored ones, exactly as `resolveDimensionLabels` reads them below. // Sorting by the authored label while rendering the translated one // ordered a localized grid, and windowed its `limit`, by text the user - // never sees. `meta` was found through this dimension, so it is known. - const field = dimByName.get(dimension)!.field; - const translated = deps.translateSelectOptions?.(baseObject, field, meta.options, context?.locale); + // never sees. Translated under the object and column that declare the + // options — the hop object's, for a relationship path. + const translated = deps.translateSelectOptions?.(col.object, col.column, meta.options, context?.locale); const labelByValue = new Map(); for (const opt of translated ?? meta.options) { if (opt && opt.label != null) labelByValue.set(opt.value, String(opt.label)); @@ -404,9 +449,10 @@ export function formatDateBucket(value: unknown, granularity?: DateGranularity | /** * Replace raw dimension values with display labels, in place. * - * @param baseObject - the dataset's base object (where the dimension fields live) - * @param dims - selected dimensions as `{ name, field, type?, dateGranularity? }` - * (row key = `name`) + * @param baseObject - the dataset's base object (where a base-field dimension's column lives) + * @param dims - selected dimensions as `{ name, field, columnObject?, type?, dateGranularity? }` + * (row key = `name`; `columnObject` = the object a relationship path's column + * lives on, see {@link LabelDimension}) * @param rows - result rows, mutated in place * @param deps - injected runtime capabilities * @param resolveScope - (ADR-0021 D-C, #3602) resolves the referenced object's @@ -421,18 +467,21 @@ export function formatDateBucket(value: unknown, granularity?: DateGranularity | */ export async function resolveDimensionLabels( baseObject: string, - dims: Array<{ name: string; field: string; type?: string; dateGranularity?: DateGranularity | string }>, + dims: Array, rows: Record[], deps: DimensionLabelDeps, resolveScope?: LabelScopeResolver, context?: ExecutionContext, ): Promise { if (!rows.length || !dims.length) return; - const fields = deps.getObjectFields(baseObject); - if (!fields) return; + if (!deps.getObjectFields(baseObject)) return; for (const dim of dims) { - const meta = fields[dim.field]; + // The column's own meta, on the object that declares it: the base object + // for a base field, the hop object (`columnObject`) for a relationship + // path. Reading a path on the base object's field map found nothing, and + // the stored FK id was served in place of the name. + const { object: columnObject, column, meta } = dimensionFieldMeta(baseObject, dim, deps); // ── date: epoch / ISO → human bucket label ──────────────────────── // A date dimension's grouped value is a raw timestamp (or a bucket start); @@ -455,7 +504,7 @@ export async function resolveDimensionLabels( // and fall back to the authored label when no translation is available // (no i18n service configured, nothing for this locale, or the option's // value carries no bundle entry at all). - const translated = deps.translateSelectOptions?.(baseObject, dim.field, meta.options, context?.locale); + const translated = deps.translateSelectOptions?.(columnObject, column, meta.options, context?.locale); const options = translated ?? meta.options; const labelByValue = new Map(); for (const opt of options) { @@ -506,14 +555,35 @@ export async function resolveDimensionLabels( } /** - * Pick the display field for an object from its field map, by convention: - * an explicit `name`/`title`/`label` field, else the first text-like field. - * Returns `undefined` when nothing suitable exists. + * Pick the display field a reference dimension's label is read from, on the + * TARGET object. + * + * 1. The object's declared `nameField` (ADR-0079: "the stored field used as + * the record display name") — the title every other surface shows for the + * record — when the field map declares it and it is stored. The registry + * designates one on every owned object that has a title-eligible field, + * and an author may point it at any stored field (an `autonumber` order + * number is the common case). A `formula` title (the spec's + * `isVirtualSearchField`) has no column the label read can group by, so it + * falls through to the convention below, as before. + * 2. Otherwise, by convention: an explicit `name`/`title`/`label` field, else + * the first text-like field. + * + * Returns `undefined` when nothing suitable exists. Before step 1, a target + * titled by an `autonumber` with no `name`/`title`/`label` field was read + * through its first text field — on most objects the platform-injected + * ownership `queue`, null on every row — so no label came back and the stored + * id was served. */ export function pickDisplayField( fields: Record | undefined, + nameField?: string, ): string | undefined { if (!fields) return undefined; + if (typeof nameField === 'string' && nameField !== '') { + const declared = fields[nameField]; + if (declared && !isVirtualSearchField(declared)) return nameField; + } for (const preferred of ['name', 'title', 'label']) { if (fields[preferred]) return preferred; } diff --git a/packages/services/service-analytics/src/plugin.ts b/packages/services/service-analytics/src/plugin.ts index b0f92153bac..b27db3d15f7 100644 --- a/packages/services/service-analytics/src/plugin.ts +++ b/packages/services/service-analytics/src/plugin.ts @@ -1097,7 +1097,10 @@ export class AnalyticsServicePlugin implements Plugin { getObjectFields: (objectName) => dataEngine()?.getObject?.(objectName)?.fields, fetchRecordLabels: async (targetObject, ids, scope, context) => { const map = new Map(); - const displayField = pickDisplayField(dataEngine()?.getObject?.(targetObject)?.fields); + // The target's declared `nameField` first (ADR-0079), then the + // name/title/label/first-text convention — see `pickDisplayField`. + const target = dataEngine()?.getObject?.(targetObject); + const displayField = pickDisplayField(target?.fields, target?.nameField); if (!displayField || !executeAggregate || ids.length === 0) return map; // [#14329] The FOURTH read-scope door, and the same guard the other // three answer with. #13640 guarded the ObjectQL engine merge and From 026cdd93ac6813957068c27efba4f5454ac0db49 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 15:38:30 +0000 Subject: [PATCH 2/3] test(service-analytics): pin path-dimension and nameField label reads; changeset Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzrvnam3RUBqcsfRHq --- ...107-dimension-labels-path-and-namefield.md | 14 +++ .../src/__tests__/dimension-labels.test.ts | 90 +++++++++++++++++++ 2 files changed, 104 insertions(+) create mode 100644 .changeset/33107-dimension-labels-path-and-namefield.md diff --git a/.changeset/33107-dimension-labels-path-and-namefield.md b/.changeset/33107-dimension-labels-path-and-namefield.md new file mode 100644 index 00000000000..d3b3ede8e7d --- /dev/null +++ b/.changeset/33107-dimension-labels-path-and-namefield.md @@ -0,0 +1,14 @@ +--- +'@objectstack/service-analytics': patch +--- + +fix(service-analytics): a lookup dataset dimension serves the referenced record's name for a relationship path and for a target titled by its `nameField` + +Clause-②: no +Metadata-protocol: none + +**Relationship-path lookups.** A dimension whose `field` is a relationship path ending in a lookup, such as `account.owner_id`, now serves the referenced record's display name instead of its id. The label is read from the column's own field on the object the path reaches, the same object the query joins. A `select` column at the end of a path now serves its option label too, translated under that object and field. Sorting by such a dimension (`order`) sorts by the name the rows show. + +**Targets titled by `nameField`.** A lookup dimension's label is read from the target object's declared `nameField` first, then from a `name`, `title` or `label` field, then from the first text field. Before, an object titled by an `autonumber` order number with no `name`, `title` or `label` field was read through its first text field (usually the platform's ownership `queue`, empty on every row), so the id was served. A `nameField` that is a formula is still skipped, as before. + +**Unchanged.** Rows are still grouped by the stored id, so two records that share a name stay two rows. A target the API does not expose, or that the reader's row scope hides, still serves the stored id. A lookup to an object whose title is its `name` field labels as it did. The same labels reach every face of a saved dataset: `POST /api/v1/analytics/dataset/query`, the `query_dataset` AI tool and its MCP tool. diff --git a/packages/services/service-analytics/src/__tests__/dimension-labels.test.ts b/packages/services/service-analytics/src/__tests__/dimension-labels.test.ts index 5878c0f0195..a5b397b456d 100644 --- a/packages/services/service-analytics/src/__tests__/dimension-labels.test.ts +++ b/packages/services/service-analytics/src/__tests__/dimension-labels.test.ts @@ -5,6 +5,7 @@ import { DatasetSchema } from '@objectstack/spec/ui'; import { AnalyticsService } from '../analytics-service.js'; import { resolveDimensionLabels, + createOrderLabelResolver, pickDisplayField, formatDateBucket, type DimensionLabelDeps, @@ -356,6 +357,34 @@ describe('pickDisplayField', () => { expect(pickDisplayField({ amount: { type: 'number' } })).toBeUndefined(); expect(pickDisplayField(undefined)).toBeUndefined(); }); + + // The target's declared title (ADR-0079 `nameField`) comes first. + const ORDER_FIELDS: Record = { + // The platform-injected ownership column: text, ahead of the title, null + // on every row — what the convention alone picks. + queue: { type: 'text' }, + order_number: { type: 'autonumber' }, + amount: { type: 'number' }, + }; + it('reads the declared nameField before the convention (an autonumber title)', () => { + expect(pickDisplayField(ORDER_FIELDS)).toBe('queue'); + expect(pickDisplayField(ORDER_FIELDS, 'order_number')).toBe('order_number'); + // …over a `name` field too: the declaration names the record's title. + expect(pickDisplayField({ name: { type: 'text' }, code: { type: 'text' } }, 'code')).toBe('code'); + }); + it('CONTROL — a nameField naming the `name` field, or none at all, picks as before', () => { + const fields = { title: { type: 'text' }, name: { type: 'text' } }; + expect(pickDisplayField(fields, 'name')).toBe('name'); + expect(pickDisplayField(fields, undefined)).toBe('name'); + expect(pickDisplayField(fields, '')).toBe('name'); + }); + it('falls through to the convention when the nameField is not in the field map', () => { + expect(pickDisplayField(ORDER_FIELDS, 'ghost')).toBe('queue'); + }); + it('falls through to the convention for a formula title: no column for the label read to group by', () => { + const fields = { first_name: { type: 'text' }, full_name: { type: 'formula' } }; + expect(pickDisplayField(fields, 'full_name')).toBe('first_name'); + }); }); describe('AnalyticsService.queryDataset — label resolution (integration)', () => { @@ -491,3 +520,64 @@ describe('AnalyticsService.queryDataset — label resolution (integration)', () expect(field).toMatchObject({ name: 'spent_sum', label: 'Total Spent', format: '$0,0' }); }); }); + +// ── a relationship-path dimension reads its column on the hop object ──── +// +// `columnObject` is what the service hands in: the object the path's last hop +// reaches, named by the hop resolver the query joins with (`columnObjectOf`). +// The label passes read the column's meta there; they walk no path themselves. +describe('relationship-path dimensions — labelled from the column on the hop object', () => { + const HOP_FIELDS: Record = { + task: { account: { type: 'lookup', reference: 'crm_account' } }, + crm_account: { + name: { type: 'text' }, + owner: { type: 'user' }, + tier: { type: 'select', options: [{ value: 'gold', label: 'Gold' }] }, + }, + }; + const hopDeps = (overrides: Partial = {}) => + deps({ getObjectFields: (obj) => HOP_FIELDS[obj], ...overrides }); + + it('maps `account.owner` (a user column on the hop object) id → the user\'s name', async () => { + const rows = [{ owner: 'usr_ada', n: 1 }]; + await resolveDimensionLabels( + 'task', [{ name: 'owner', field: 'account.owner', columnObject: 'crm_account' }], rows, hopDeps(), + ); + expect(rows).toEqual([{ owner: 'Ada Lovelace', n: 1 }]); + }); + + it('maps a select column on the hop object, translated under THAT object and column', async () => { + const asked: string[] = []; + const rows = [{ tier: 'gold' }]; + await resolveDimensionLabels( + 'task', [{ name: 'tier', field: 'account.tier', columnObject: 'crm_account' }], rows, + hopDeps({ + translateSelectOptions: (object, field, options) => { + asked.push(`${object}.${field}`); + return options.map((o) => ({ ...o, label: `${o.label} (zh)` })); + }, + }), + undefined, + { locale: 'zh-CN' } as never, + ); + expect(asked).toEqual(['crm_account.tier']); + expect(rows).toEqual([{ tier: 'Gold (zh)' }]); + }); + + it('leaves a path no one resolved (no `columnObject`) as its stored id', async () => { + const rows = [{ owner: 'usr_ada' }]; + await resolveDimensionLabels('task', [{ name: 'owner', field: 'account.owner' }], rows, hopDeps()); + expect(rows).toEqual([{ owner: 'usr_ada' }]); + }); + + it('the sort-key pass reads the same column: label-bearing, and keyed by the user\'s name', async () => { + const order = createOrderLabelResolver( + 'task', [{ name: 'owner', field: 'account.owner', columnObject: 'crm_account' }], hopDeps(), + ); + expect(order.isLabelBearing('owner')).toBe(true); + expect(await order.resolveLabels('owner', ['usr_ada'])).toEqual(new Map([['usr_ada', 'Ada Lovelace']])); + // Without the hop object, the path is not label-bearing (the stored value sorts). + const unresolved = createOrderLabelResolver('task', [{ name: 'owner', field: 'account.owner' }], hopDeps()); + expect(unresolved.isLabelBearing('owner')).toBe(false); + }); +}); From 99fa452be030d5ac9775b4a16db085053ac16f60 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 16:20:05 +0000 Subject: [PATCH 3/3] test(service-analytics): type the hop field maps as per-object maps Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzrvnam3RUBqcsfRHq --- .../service-analytics/src/__tests__/dimension-labels.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/services/service-analytics/src/__tests__/dimension-labels.test.ts b/packages/services/service-analytics/src/__tests__/dimension-labels.test.ts index a5b397b456d..5319cbd62f0 100644 --- a/packages/services/service-analytics/src/__tests__/dimension-labels.test.ts +++ b/packages/services/service-analytics/src/__tests__/dimension-labels.test.ts @@ -527,7 +527,7 @@ describe('AnalyticsService.queryDataset — label resolution (integration)', () // reaches, named by the hop resolver the query joins with (`columnObjectOf`). // The label passes read the column's meta there; they walk no path themselves. describe('relationship-path dimensions — labelled from the column on the hop object', () => { - const HOP_FIELDS: Record = { + const HOP_FIELDS: Record> = { task: { account: { type: 'lookup', reference: 'crm_account' } }, crm_account: { name: { type: 'text' },