Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .changeset/35734-percent-formula-return.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@objectstack/lint': patch
'@object-ui/plugin-grid': patch
'@object-ui/plugin-detail': patch
---

fix: a `percent` or `currency` formula is a KPI chip on the record header; the lint prescription names all six return types

Clause-②: no
Metadata-protocol: none

A `formula` field whose `returnType` is `percent` drew percentages in its list cells, and the record header strip drew it without the figure typography a `percent` field's chip has. The strip now reads a formula's declared `returnType` before it picks its face, for the two return types the spec reads as a field type, `percent` and `currency`. Both are KPI chips on the header strip. A formula of any other return type chips as before.

The grid's footer formatting reads the same two return types, so a browser-computed footer over a `percent` formula reads `Sum: 75%` rather than `Sum: 0.75`, and over a `currency` formula reads as money. That is not a supported authoring shape: a `sum`, `avg`, `min` or `max` column summary over a `formula` field is refused at authoring by `list-view-summary-field-type-refused`, whatever its `returnType`, because a formula is computed on read and stored in no column, and the whole-set footer query answers `400 INVALID_FIELD`. The formatting reaches only an ungrouped, one-page footer the browser computes over a declaration `os validate` refuses. To total a formula's value, make it a stored field of its own, of the formula's `returnType` and carrying the same `expression`, which the engine computes and stores on every write, and summarise that field.

`os explain dimension-virtual-field-refused` told the author to make a stored copy "of the formula's `returnType` (`number`, `text`, `boolean`, `date` or `currency`)", which named no type for a `percent` formula. It now lists all six, and a test holds the list to the spec's own `returnType` enum.
14 changes: 14 additions & 0 deletions packages/lint/src/rule-explanations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@ import {
FUNCTIONAL_COMPLETENESS_RULES,
MAX_CUSTOMIZATION_BASE_NAMESPACE_LENGTH,
} from '@objectstack/spec/kernel';
import { FieldSchema } from '@objectstack/spec/data';

import * as indexBarrel from './index.js';
import { RULE_EXPLANATIONS, explainRule } from './rule-explanations.js';
import { CARRIER_ROOTS, CONSUMER_ROOTS, FIELD_NO_CONSUMERS } from './validate-field-consumers.js';
import { NAMESPACE_NO_CUSTOMIZATION_PAIR } from './validate-customization-namespace.js';
import { DIMENSION_VIRTUAL_FIELD_REFUSED } from './validate-dataset-measure-aggregates.js';

const HERE = dirname(fileURLToPath(import.meta.url));

Expand Down Expand Up @@ -112,6 +114,18 @@ describe('rule explanations (#22161)', () => {
expect(text).toContain(`to ${max} characters or fewer`);
});

// The module imports nothing, so the formula return types the stored copy
// may take are written out in the text; held here to the spec's own enum,
// so a return type the spec adds cannot be missing from the prescription.
it('the dimension-virtual-field-refused prescription names every formula return type', () => {
const text = explainRule(DIMENSION_VIRTUAL_FIELD_REFUSED)!.paragraphs.join('\n');
const listed = /of the formula's `returnType` \(([^)]*)\)/.exec(text)?.[1];
expect(listed).toBeDefined();
const named = [...listed!.matchAll(/`([a-z_]+)`/g)].map((m) => m[1]).sort();
const members = (FieldSchema.shape.returnType.unwrap().options as readonly string[]).slice().sort();
expect(named).toEqual(members);
});

it('explainRule is an exact-id lookup: no prefix, case or prototype match', () => {
expect(explainRule(FIELD_NO_CONSUMERS)?.rule).toBe(FIELD_NO_CONSUMERS);
expect(explainRule('field-no-consumer')).toBeUndefined();
Expand Down
5 changes: 3 additions & 2 deletions packages/lint/src/rule-explanations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2734,8 +2734,9 @@ const DIMENSION_VIRTUAL_FIELD_REFUSED_EXPLANATION: RuleExplanation = {
'Before those refusals the group key reached the driver as a column that does not exist, or an ' +
'engine that aggregates in memory put every row into one null group while the answer looked served.',
'Denormalise the value: make it a stored field of its own on the object, of the formula\'s ' +
'`returnType` (`number`, `text`, `boolean`, `date` or `currency`) and carrying the same `expression`, ' +
'which the engine computes and stores on every write, and point the dimension at that stored field. ' +
'`returnType` (`number`, `text`, `boolean`, `date`, `currency` or `percent`) and carrying the same ' +
'`expression`, which the engine computes and stores on every write, and point the dimension at that ' +
'stored field. ' +
'This rule makes the same ' +
'refusal where the author is standing. A dotted path is judged on the leaf\'s own declaration.',
ANALYTICS_MEMBER_WALK,
Expand Down
27 changes: 22 additions & 5 deletions ui/packages/plugin-detail/src/HeaderHighlight.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,18 @@ import { hasCellValue } from './emptiness';
import { useDefaultRecordPage } from './defaultRecordPage';
import { dropFieldPredicateHidden, lazyPredicateRecord } from './fieldPredicateVisibility';

/**
* The field type a `formula` reads as, when its declared `returnType` is one
* the spec reads AS a field type: `currency` ("an amount of money … as a
* currency field declares it") and `percent` ("read and displayed as a
* `percent` field reads its stored value"). `undefined` for any other field
* or return type.
*/
function formulaReadsAsFieldType(type: string | undefined, returnType: unknown): 'currency' | 'percent' | undefined {
if (type !== 'formula') return undefined;
return returnType === 'currency' || returnType === 'percent' ? returnType : undefined;
}

export interface HeaderHighlightProps {
fields: HighlightField[];
data?: any;
Expand Down Expand Up @@ -256,12 +268,17 @@ export const HeaderHighlight: React.FC<HeaderHighlightProps> = ({
// coerceToSafeValue() so even object/array data is safe (no error #310).
const CellRenderer = getCellRenderer(drawnType);

// A `formula` declaring a return type the spec reads AS a field
// type (`currency`, `percent`) is a figure of that type, drawn by
// that type's cell, so it is a KPI chip as that field is. Every
// other formula keeps its own type here.
const valueType = formulaReadsAsFieldType(resolvedType, objectDefField?.returnType) ?? resolvedType;
const isKpi =
resolvedType === 'number' ||
resolvedType === 'integer' ||
resolvedType === 'currency' ||
resolvedType === 'percent' ||
resolvedType === 'decimal';
valueType === 'number' ||
valueType === 'integer' ||
valueType === 'currency' ||
valueType === 'percent' ||
valueType === 'decimal';
// Two independent reasons a chip needs the wide basis, kept
// separate because only one of them is a shared table:
// 1. long-text DISPLAY types, whose value simply does not fit a
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/**
* ObjectUI
* Copyright (c) 2024-present ObjectStack Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

/**
* A `formula` whose declared `returnType` the spec reads AS a field type
* (`percent`, `currency`) is a KPI chip on the highlights strip, as a field of
* that type is: its value carries the strip's figure typography. A formula of
* any other return type keeps the face it had (CONTROL: `number`).
*/
import { describe, it, expect, afterEach } from 'vitest';
import { render, screen, cleanup } from '@testing-library/react';
import * as React from 'react';
import { HeaderHighlight } from '../HeaderHighlight';

afterEach(cleanup);

const objectSchema = {
fields: {
win_rate: { type: 'percent', label: 'Win Rate' },
margin_pct: { type: 'formula', label: 'Margin', returnType: 'percent', expression: 'record.profit / record.revenue' },
net_amount: { type: 'formula', label: 'Net', returnType: 'currency', expression: 'record.revenue - record.cost' },
units_left: { type: 'formula', label: 'Units Left', returnType: 'number', expression: 'record.stock - record.sold' },
},
};

function renderStrip() {
render(
<HeaderHighlight
fields={
[
{ name: 'win_rate', label: 'Win Rate' },
{ name: 'margin_pct', label: 'Margin' },
{ name: 'net_amount', label: 'Net' },
{ name: 'units_left', label: 'Units Left' },
] as any
}
data={{ win_rate: 0.4, margin_pct: 0.25, net_amount: 1200, units_left: 7 }}
objectSchema={objectSchema}
/>,
);
}

/** The value span of the chip captioned `label`. */
const valueOf = (label: string) => {
const span = (screen.getByText(label).closest('div.group') as HTMLElement).querySelector('span.truncate');
expect(span, `a value span under "${label}"`).not.toBeNull();
return span as HTMLElement;
};

describe('the highlights strip reads a formula by its declared returnType (objectstack#35734)', () => {
it('a percent field is a KPI chip (the reference)', () => {
renderStrip();
expect(valueOf('Win Rate').className).toMatch(/\btabular-nums\b/);
});

it('a percent-returning formula is a KPI chip, as a percent field is', () => {
renderStrip();
expect(valueOf('Margin').className).toMatch(/\btabular-nums\b/);
expect(valueOf('Margin').className).toBe(valueOf('Win Rate').className);
expect(valueOf('Margin').textContent).toContain('25%');
});

it('a currency-returning formula is a KPI chip too', () => {
renderStrip();
expect(valueOf('Net').className).toMatch(/\btabular-nums\b/);
});

it('CONTROL: a number-returning formula keeps the face it had', () => {
renderStrip();
expect(valueOf('Units Left').className).not.toMatch(/\btabular-nums\b/);
});
});
43 changes: 43 additions & 0 deletions ui/packages/plugin-grid/src/useColumnSummary.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,46 @@ describe('useColumnSummary formatting stays with the numeric family', () => {
expect(result.current.summaries.get('amount')?.label).toMatch(/\$|US\$/);
});
});

/**
* A `formula` column's footer reads its declared `returnType` when the spec
* reads that return type AS a field type (`percent`, `currency`), so the total
* reads in the unit of the cells above it. Every other formula keeps the plain
* arm (CONTROL: `number`).
*/
describe('useColumnSummary reads a formula by its declared returnType (objectstack#35734)', () => {
const RATES = [{ rate: 0.25 }, { rate: 0.5 }];
const sumOf = (meta: Record<string, any>) =>
renderHook(() => useColumnSummary([{ field: 'rate', summary: 'sum' }] as any[], RATES, meta), {
wrapper: wrapper('USD'),
}).result.current.summaries.get('rate')?.label;

it('a percent-returning formula totals as a percentage, as a percent field does', () => {
const formula = sumOf({ rate: { type: 'formula', returnType: 'percent' } });
expect(formula).toBe('Sum: 75%');
expect(formula).toBe(sumOf({ rate: { type: 'percent' } }));
});

it('a percent-returning formula keeps its declared width and storage', () => {
expect(sumOf({ rate: { type: 'formula', returnType: 'percent', scale: 1 } })).toBe('Sum: 75.0%');
// `max` above 1 declares percentage points: 0.75 is under one percent.
expect(sumOf({ rate: { type: 'formula', returnType: 'percent', max: 100 } })).toBe(
sumOf({ rate: { type: 'percent', max: 100 } }),
);
});

it('a currency-returning formula totals as money in its declared currency', () => {
const { result } = renderHook(
() => useColumnSummary([{ field: 'net', summary: 'sum' }] as any[], [{ net: 1000 }, { net: 234 }], {
net: { type: 'formula', returnType: 'currency', currencyConfig: { currencyMode: 'fixed', defaultCurrency: 'USD' } },
}),
{ wrapper: wrapper('CNY') },
);
expect(result.current.summaries.get('net')?.label).toBe('Sum: $1,234.00');
});

it('CONTROL: a number-returning formula totals as it did, a plain number', () => {
expect(sumOf({ rate: { type: 'formula', returnType: 'number' } })).toBe('Sum: 0.75');
expect(sumOf({ rate: { type: 'formula', returnType: 'number' } })).toBe(sumOf({ rate: { type: 'formula' } }));
});
});
43 changes: 39 additions & 4 deletions ui/packages/plugin-grid/src/useColumnSummary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -376,11 +376,31 @@ function summaryValueType(column: { currencyConfig?: unknown; scale?: number | n
return resolveFieldScale(column) === undefined ? 'summary' : 'number';
}

/**
* The return types the spec reads AS a field type: `currency` is "an amount of
* money … as a currency field declares it", and `percent` is "read and
* displayed as a `percent` field reads its stored value". The list cell draws
* them through the currency and percent cells (`FormulaCellRenderer`).
*/
const FIELD_TYPED_FORMULA_RETURNS: ReadonlySet<string> = new Set(['currency', 'percent']);

/**
* The arm a `formula` column's total is formatted by: its declared
* `returnType` when the spec reads that return type as a field type, so a
* percent-returning formula's total reads as a percentage under cells that
* read as percentages, and a currency-returning one's as money. Any other
* formula keeps the plain arm it always took.
*/
function formulaValueType(column: { returnType?: unknown }): string {
const declared = column.returnType;
return typeof declared === 'string' && FIELD_TYPED_FORMULA_RETURNS.has(declared) ? declared : 'formula';
}

function formatSummaryLabel(
type: string,
value: number | null,
t: SummaryTranslate,
column: { type?: string; currency?: string; defaultCurrency?: string; currencyConfig?: { defaultCurrency?: string }; precision?: number | null; scale?: number | null; max?: number } | undefined,
column: { type?: string; returnType?: string; currency?: string; defaultCurrency?: string; currencyConfig?: { defaultCurrency?: string }; precision?: number | null; scale?: number | null; max?: number } | undefined,
tenantDefault: string | undefined,
// The BCP-47 tag from `useDisplayLocale()` — tenant locale, then UI
// language, then a concrete `'en'`, never `undefined`.
Expand Down Expand Up @@ -419,7 +439,9 @@ function formatSummaryLabel(
return join(value.toLocaleString(displayLocale));
}

const colType = column?.type === 'summary' ? summaryValueType(column) : column?.type;
const colType = column?.type === 'summary'
? summaryValueType(column)
: column?.type === 'formula' ? formulaValueType(column) : column?.type;
let formatted: string;
if (colType === 'currency') {
// objectui#10221 — a currency's decimal places are the currency's, not a
Expand Down Expand Up @@ -500,7 +522,17 @@ function formatSummaryLabel(
// over the field's `max`), the answer the cell above reads. The shared
// scaling used to guess from the magnitude, so a fraction-stored column
// summing to `1` (100%) read `Sum: 1%` under cells reading the same rows.
const decimals = resolveFieldScale(column);
//
// A percent-returning `formula` reaches this arm too, and is read as the
// `percent` field it reads like, as the list cell hands it on
// (`FormulaCellRenderer`): `resolveFieldScale` keys its absent-`scale` row
// on the type, and a formula's own type has none, so an undeclared width
// takes the platform's percent width rather than `formatPercent`'s own
// parameter default. Every column that reaches this arm is a percent, so
// the type below changes for the formula alone. Its storage is read off
// the column as is: `percentCellScale` reads the declared `max`, and the
// formula declares it as a percent field does.
const decimals = resolveFieldScale({ ...column, type: 'percent' });
formatted = formatPercent(value, percentCellScale(column), decimals, displayLocale);
} else if (colType === 'number') {
// objectstack#19628, ruled A′ and carried to this footer by objectui#9843:
Expand Down Expand Up @@ -531,7 +563,7 @@ function formatSummaryLabel(
}

/** The `objectSchema.fields` slice the footer formats with. */
type SummaryFieldMetadata = Record<string, { type?: string; format?: string | null; widget?: string | null; currency?: string; defaultCurrency?: string; currencyConfig?: CurrencyConfig; precision?: number | null; scale?: number | null; max?: number }>;
type SummaryFieldMetadata = Record<string, { type?: string; returnType?: string; format?: string | null; widget?: string | null; currency?: string; defaultCurrency?: string; currencyConfig?: CurrencyConfig; precision?: number | null; scale?: number | null; max?: number }>;

/**
* Which rows the footer's figures describe (objectui#12081 item 3).
Expand Down Expand Up @@ -724,6 +756,9 @@ export function useScopedColumnSummary(
// objectui#11475 — a percent field's declared `max`, its STORAGE
// statement (`percentScaleOf`: a fraction unless `max` is above 1).
max: meta?.max,
// A `formula`'s declared value type: a `percent` or `currency` one is
// totalled in that type's arm (`formulaValueType`).
returnType: meta?.returnType,
};

// The widest decimal count among the numeric values this aggregation
Expand Down
Loading