From 4fffca7e3ed5e8f6f79839bdc644be0ac3c1571a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 16:48:39 +0000 Subject: [PATCH 1/3] feat(formula): rmbUpper(amount) writes an amount in Chinese capital numerals MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Chinese quote, contract or invoice prints its total a second time in capital numerals (人民币大写) under the figures. The new CEL stdlib function rmbUpper(dyn): string writes that line: rmbUpper(245000) is 贰拾肆万伍仟元整, rmbUpper(10500.5) is 壹万零伍佰元伍角. The amount is read as the exact decimal it spells and rounded once to fen, half away from zero, with the home-amount arithmetic (toScaledDecimal, divideToPlaces). Zero runs, the wan and yi groups, jiao, fen and zheng follow the usual rules; 0 is 零元整, a negative is prefixed 负, null reads ''. Text that spells no number, a boolean, a list, and 10^16 yuan or more are refused with a runtime error. The function is advertised in CEL_STDLIB_FUNCTIONS, documented in the objectstack-formula skill and formulas.mdx, and counted in the platform checklist's stdlib matrix item. Claude-Session: https://claude.ai/code/session_01FEkQ5nHvfaZE5NLUTcWkFZ Co-Authored-By: Claude --- .changeset/34332-formula-rmb-upper.md | 22 +++ content/docs/data-modeling/formulas.mdx | 31 ++++ .../platform-checklist/areas/api-backend.json | 21 +-- packages/formula/src/cel-engine.test.ts | 2 +- packages/formula/src/rmb-upper.ts | 131 ++++++++++++++ packages/formula/src/stdlib-rmb-upper.test.ts | 165 ++++++++++++++++++ packages/formula/src/stdlib.ts | 6 + packages/formula/src/validate.ts | 14 +- skills/objectstack-formula/SKILL.md | 4 +- 9 files changed, 375 insertions(+), 21 deletions(-) create mode 100644 .changeset/34332-formula-rmb-upper.md create mode 100644 packages/formula/src/rmb-upper.ts create mode 100644 packages/formula/src/stdlib-rmb-upper.test.ts diff --git a/.changeset/34332-formula-rmb-upper.md b/.changeset/34332-formula-rmb-upper.md new file mode 100644 index 00000000000..1e82ee6ace7 --- /dev/null +++ b/.changeset/34332-formula-rmb-upper.md @@ -0,0 +1,22 @@ +--- +'@objectstack/formula': minor +'@objectstack/skills': patch +--- + +feat(formula): `rmbUpper(amount)` writes an amount in Chinese capital numerals (人民币大写) for printed quotes, contracts and invoices + +Clause-②: yes (widening) — a new CEL stdlib function, `rmbUpper(dyn): string`, registered by `registerStdLib` and advertised in `CEL_STDLIB_FUNCTIONS`; an expression that calls it was refused as an unknown function before, and nothing that worked before is refused or changes value. +Metadata-protocol: added — a formula, predicate or flow value may now call `rmbUpper(...)`. +Skills-docs: updated here — `skills/objectstack-formula/SKILL.md` lists it in the stdlib Numbers table, and `content/docs/data-modeling/formulas.mdx` adds the catalog row and an "Amount in Chinese capitals" cookbook entry. + +`rmbUpper(245000)` is `贰拾肆万伍仟元整` and `rmbUpper(10500.5)` is `壹万零伍佰元伍角`. A formula field reads it as text: + +```ts +Field.formula({ label: '大写金额', returnType: 'text', expression: 'rmbUpper(record.total_amount)' }) +``` + +- The amount is rounded once to 分, half away from zero, on the exact decimal it spells, so `1.005` is `壹元零壹分` and binary floating point never decides a cent. +- One `零` stands for each run of zeros (`壹仟零伍元整`, `壹万零伍佰元整`, `壹亿零壹元整`), a ten is `壹拾`, the 万 and 亿 groups follow the usual rules, and the count of 亿 above 亿 is written with 万 (`壹拾万零壹亿元整`). +- A whole amount ends in `整`; a 分 with no 角 writes `零` for the 角 (`壹元零伍分`); an amount under one yuan is its 角 and 分 alone (`伍角`). +- `0` is `零元整`, a negative amount is prefixed `负`, and `null` reads `''`, so an empty total prints an empty line. +- A number, a currency field and decimal text (`'245000.00'`) are read. Text that spells no number, a boolean or a list, and an amount of 10^16 yuan or more, is a runtime error rather than some text. diff --git a/content/docs/data-modeling/formulas.mdx b/content/docs/data-modeling/formulas.mdx index 791675585c4..f553711a30b 100644 --- a/content/docs/data-modeling/formulas.mdx +++ b/content/docs/data-modeling/formulas.mdx @@ -206,6 +206,7 @@ All functions are pure given a pinned `now`, which is what makes | `abs(x)` / `round(x)` | number | Numeric helpers | | `floor(x)` / `ceil(x)` | number | Round toward −∞ / +∞ (`floor(-1.2) == -2`) — **not** integer-division's round-toward-zero | | `min(a, b)` / `max(a, b)` | dyn | Smaller / larger operand (numeric comparison) | +| `rmbUpper(x)` | string | An amount in Chinese capital numerals (人民币大写), rounded to 分: `rmbUpper(10500.5)` is `壹万零伍佰元伍角` — see [Amount in Chinese capitals](#amount-in-chinese-capitals) | | `label(record.f)` | string | A select field's option label in the reader's locale — see [Record name from an option label](#record-name-from-an-option-label) | Add new helpers in @@ -589,6 +590,36 @@ Field.formula({ }) ``` +### Amount in Chinese capitals + +A Chinese quote, contract or invoice prints its total a second time in capital +numerals (大写金额), under the figures. `rmbUpper()` writes that line: + +```typescript +Field.formula({ + label: '大写金额', + returnType: 'text', + expression: 'rmbUpper(record.total_amount)', +}) +``` + +| `total_amount` | `rmbUpper(record.total_amount)` | +|:---|:---| +| `245000` | `贰拾肆万伍仟元整` | +| `10500.5` | `壹万零伍佰元伍角` | +| `1.05` | `壹元零伍分` | +| `100000001` | `壹亿零壹元整` | +| `0` | `零元整` | +| `-1200` | `负壹仟贰佰元整` | +| `null` | `''` | + +The amount is rounded once to 分, half away from zero, on the decimal it spells +(`1.005` is `壹元零壹分`), so binary floating point never decides a cent. One `零` +stands for each run of zeros, a ten is `壹拾`, a whole amount ends in `整` and an +amount under one yuan is its 角 and 分 alone (`0.5` is `伍角`). A number, a +currency field and decimal text (`'245000.00'`) are read; any other value, and +an amount of 10^16 yuan or more, is a runtime error rather than some text. + ### Text Manipulation ```typescript diff --git a/docs/qa/platform-checklist/areas/api-backend.json b/docs/qa/platform-checklist/areas/api-backend.json index 44f79cf711a..b14d9b2b1ca 100644 --- a/docs/qa/platform-checklist/areas/api-backend.json +++ b/docs/qa/platform-checklist/areas/api-backend.json @@ -2237,10 +2237,10 @@ }, { "id": "api-backend.formula-stdlib-matrix", - "title": "CEL formula stdlib: all 30 bare-callable stdlib functions give known answers against the BUILT package — calendar-day timezone contract, addMonths month-end clamp, floor(-1.2)==-2, null-dropping joins, mixed int/double arithmetic, isoDate/isoDatetime text — and a formula calling an unregistered function is REFUSED at the authoring door (422), never stored to read null", + "title": "CEL formula stdlib: all 31 bare-callable stdlib functions give known answers against the BUILT package — calendar-day timezone contract, addMonths month-end clamp, floor(-1.2)==-2, null-dropping joins, mixed int/double arithmetic, isoDate/isoDatetime text, rmbUpper capital numerals — and a formula calling an unregistered function is REFUSED at the authoring door (422), never stored to read null", "since": "v16", "status": "active", - "revision": 7, + "revision": 8, "priority": "P1", "surface": "mixed", "personas": [ @@ -2254,13 +2254,13 @@ "runtime metadata authoring for the stdlib-through-the-live-door leg and the unregistered-function probe, into a WRITABLE package (the showcase package is read-only): install a scratch package that DECLARES its namespace — POST /api/v1/packages { manifest: { id: 'com.objectstack.qa.formula', name: 'QA formula fixture', version: '1.0.0', type: 'app', namespace: 'qaformula' }, enableOnInstall: true } — then PUT /api/v1/meta/object/qaformula_NAME?package=com.objectstack.qa.formula. The object name carries the namespace prefix, or the save answers 422 NAMESPACE_PREFIX (a manifest with no namespace gets one derived from the id's last segment). Every scratch object body declares a `sharingModel` (e.g. 'private'): an active-state object save without one is refused 422 security-owd-unset (packages/lint/src/validate-security-posture.ts, run on every active object publish) before any formula is judged" ], "knownGaps": [ - "The stock formulas exercise only null-guard ternaries and arithmetic — NOT the stdlib catalog. The 30-function matrix therefore runs in a harness against the BUILT package (the same discipline as api-backend.formula-gates), and the live-door leg proves the same evaluator serves reads, not each function individually; a scratch formula field authored through the metadata channel carries two representative stdlib calls onto the live path. Record which oracle each function's verdict rests on." + "The stock formulas exercise only null-guard ternaries and arithmetic — NOT the stdlib catalog. The 31-function matrix therefore runs in a harness against the BUILT package (the same discipline as api-backend.formula-gates), and the live-door leg proves the same evaluator serves reads, not each function individually; a scratch formula field authored through the metadata channel carries two representative stdlib calls onto the live path. Record which oracle each function's verdict rests on." ] }, "steps": [ - "count the registration chain: packages/formula/src/stdlib.ts registerStdLib (through registerBoundStdLib) registers exactly 30 bare-callable functions: 29 by chained registerFunction call — now, today, daysFromNow, daysAgo, isBlank, coalesce, trim, joinNonEmpty, daysBetween, addDays, addMonths, date, datetime, isoDate, isoDatetime, abs, round, floor, ceil, min, max, upper, lower, contains, startsWith, endsWith, matches, len, isEmpty (isoDate and isoDatetime since #22347) — plus the MACRO label(record.), which bindOptionLabel registers at the head of the chain (#26608). The receiver methods `can` (current_user.can(object, verb)) and `hasCapability`, which bindPermissionPredicate and bindCapabilityPredicate add at the same head, are permission predicates, not bare-callable catalog functions, and are outside this count — validate.ts's CEL_STDLIB_FUNCTIONS docblock tallies the same 30 ('30 added by registerStdLib'). NOT enumSource-pinnable (a builder chain, not a named z.enum) — re-count the calls in source at run time and fail the matrix stale if the count moved; cross-check the docs catalog (content/docs/data-modeling/formulas.mdx) advertises the same set, no more, no fewer (its table lists label(record.f) last)", + "count the registration chain: packages/formula/src/stdlib.ts registerStdLib (through registerBoundStdLib) registers exactly 31 bare-callable functions: 30 by chained registerFunction call — now, today, daysFromNow, daysAgo, isBlank, coalesce, trim, joinNonEmpty, daysBetween, addDays, addMonths, date, datetime, isoDate, isoDatetime, abs, round, floor, ceil, min, max, rmbUpper, upper, lower, contains, startsWith, endsWith, matches, len, isEmpty (isoDate and isoDatetime since #22347, rmbUpper since #34332) — plus the MACRO label(record.), which bindOptionLabel registers at the head of the chain (#26608). The receiver methods `can` (current_user.can(object, verb)) and `hasCapability`, which bindPermissionPredicate and bindCapabilityPredicate add at the same head, are permission predicates, not bare-callable catalog functions, and are outside this count — validate.ts's CEL_STDLIB_FUNCTIONS docblock tallies the same 31 ('31 added by registerStdLib'). NOT enumSource-pinnable (a builder chain, not a named z.enum) — re-count the calls in source at run time and fail the matrix stale if the count moved; cross-check the docs catalog (content/docs/data-modeling/formulas.mdx) advertises the same set, no more, no fewer (its table lists label(record.f) last)", "build the workspace (or confirm dist freshness — the stale-dist trap is the known false-negative here, same as api-backend.formula-gates); the harness must import the BUILT package and record the resolved module path", - "drive every one of the 30 with a pinned now and a known-answer expectation, at minimum: floor(-1.2)==-2 and ceil(-1.2)==-1 (round toward −∞/+∞, NOT toward zero); addMonths(date('2026-01-31'), 1) == 2026-02-28T00:00:00Z (month-end clamp, never a March overflow); daysBetween(a,b) sign convention (b−a, negative when b earlier); date()/datetime() alias parity on the same ISO input; isoDate(date('2026-02-28T13:45:00Z'))=='2026-02-28' and isoDatetime(date('2026-02-28T13:45:00Z'))=='2026-02-28T13:45:00.000Z' (the UTC calendar), isoDate(today()) under the boundary zone below == that zone's calendar day, and text refused (isoDate('2026-01-01') faults no matching overload — write isoDate(date(s))); coalesce(null,'x')=='x' but coalesce('', 'x')=='' (null/undefined only — from CEL only the null half is authorable: the function treats undefined like null, but an absent record key faults 'No such key' before coalesce runs, so the undefined arm is the harness table's, not an expression's); joinNonEmpty([record.a, record.b, record.c, record.d], '-')=='a-b' with record {a: 'a', b: null, c: ' ', d: 'b'} (null AND blank-after-trim dropped — written through record fields, because cel-js refuses a list LITERAL that mixes string and null at type-check, 'List elements must have the same type', so the literal ['a', null, ' ', 'b'] never evaluates); isBlank vs isEmpty on null/''/[]; trim(null)==''; upper/lower/contains/startsWith/endsWith on mixed input; matches regex truthiness; len over string/list/map; min/max returning the SMALLER/LARGER OPERAND VERBATIM (type preserved, numeric comparison); abs/round; now() === the pinned instant; label(record.kind) over record {kind: 'clean'} with optionLabels {kind: {clean: 'Clean'}} on the EvalContext == 'Clean', the same call with no optionLabels refused at run time (never the stored value 'clean'), and label() of a field the map declares no options for refused (packages/formula/src/option-label.test.ts pins these shapes)", + "drive every one of the 31 with a pinned now and a known-answer expectation, at minimum: floor(-1.2)==-2 and ceil(-1.2)==-1 (round toward −∞/+∞, NOT toward zero); addMonths(date('2026-01-31'), 1) == 2026-02-28T00:00:00Z (month-end clamp, never a March overflow); daysBetween(a,b) sign convention (b−a, negative when b earlier); date()/datetime() alias parity on the same ISO input; isoDate(date('2026-02-28T13:45:00Z'))=='2026-02-28' and isoDatetime(date('2026-02-28T13:45:00Z'))=='2026-02-28T13:45:00.000Z' (the UTC calendar), isoDate(today()) under the boundary zone below == that zone's calendar day, rmbUpper(245000)=='贰拾肆万伍仟元整', rmbUpper(10500.5)=='壹万零伍佰元伍角', rmbUpper(1.005)=='壹元零壹分' (fen rounding on the exact decimal, never the double), rmbUpper(0)=='零元整', rmbUpper(-1200)=='负壹仟贰佰元整' and rmbUpper(record.amount)=='' with amount null, and text refused (isoDate('2026-01-01') faults no matching overload — write isoDate(date(s))); coalesce(null,'x')=='x' but coalesce('', 'x')=='' (null/undefined only — from CEL only the null half is authorable: the function treats undefined like null, but an absent record key faults 'No such key' before coalesce runs, so the undefined arm is the harness table's, not an expression's); joinNonEmpty([record.a, record.b, record.c, record.d], '-')=='a-b' with record {a: 'a', b: null, c: ' ', d: 'b'} (null AND blank-after-trim dropped — written through record fields, because cel-js refuses a list LITERAL that mixes string and null at type-check, 'List elements must have the same type', so the literal ['a', null, ' ', 'b'] never evaluates); isBlank vs isEmpty on null/''/[]; trim(null)==''; upper/lower/contains/startsWith/endsWith on mixed input; matches regex truthiness; len over string/list/map; min/max returning the SMALLER/LARGER OPERAND VERBATIM (type preserved, numeric comparison); abs/round; now() === the pinned instant; label(record.kind) over record {kind: 'clean'} with optionLabels {kind: {clean: 'Clean'}} on the EvalContext == 'Clean', the same call with no optionLabels refused at run time (never the stored value 'clean'), and label() of a field the map declares no options for refused (packages/formula/src/option-label.test.ts pins these shapes)", "calendar-day timezone contract (ADR-0053 Phase 2 D1): pin now to an instant whose calendar day DIFFERS between UTC and the reference zone (e.g. 2026-08-30T22:00:00Z with timezone Asia/Shanghai — locally already 08-31) and assert today() == 2026-08-31T00:00:00Z (the reference-tz calendar day expressed as UTC MIDNIGHT — never an instant carrying wall-clock time), daysFromNow/daysAgo offset from that same day; an unknown zone falls back to the UTC calendar day, never throws", "mixed-arithmetic overloads (registerNumericCoercions, stdlib.ts): a double-typed record field divided/multiplied by an int literal (record.amount / 100) evaluates to the promoted double instead of faulting 'no such overload' to silent null (#1928), while pure int 7/2 == 3 keeps integer-division semantics untouched", "live-door parity: GET a showcase_project row and confirm budget_remaining materializes (read-path evaluation); author a scratch object through the metadata channel, declaring its sharingModel (fixtures.requires[1]), whose formula field composes two stdlib calls (e.g. joinNonEmpty + upper) and read back the known answer — the stdlib reaching the LIVE read path, not just the harness", @@ -2268,10 +2268,10 @@ ], "acceptance": [ { - "clause": "all 30 advertised functions evaluate to their known answers against the BUILT package — the matrix is exhaustive over the hand-counted registration chain (registerStdLib's 29 chained registerFunction calls plus the label() macro; the receiver methods `can` and `hasCapability` are permission predicates, not catalog functions), and the docs catalog matches it in both directions (an advertised-but-unregistered function or a registered-but-undocumented one each fail this clause)", + "clause": "all 31 advertised functions evaluate to their known answers against the BUILT package — the matrix is exhaustive over the hand-counted registration chain (registerStdLib's 30 chained registerFunction calls plus the label() macro; the receiver methods `can` and `hasCapability` are permission predicates, not catalog functions), and the docs catalog matches it in both directions (an advertised-but-unregistered function or a registered-but-undocumented one each fail this clause)", "oracle": "test", "verify": "harness output: one known-answer row per function, resolved module path pointing into dist/node_modules; the source count and the docs-table cross-check recorded", - "evidence": "the 30-row harness table + the resolved path + the two counts" + "evidence": "the 31-row harness table + the resolved path + the two counts" }, { "clause": "the calendar-day trio (today/daysFromNow/daysAgo) resolves to the REFERENCE-TIMEZONE calendar day expressed as UTC midnight (ADR-0053 D1) — proven with an instant whose calendar day differs between UTC and the zone, so a UTC-only implementation cannot pass by accident; unknown zone falls back to UTC without throwing", @@ -2315,8 +2315,8 @@ "timezone-boundary" ], "source": [ - "packages/formula/src/stdlib.ts#registerStdLib (registerStdLib — the 29 chained registerFunction calls, isoDate / isoDatetime since #22347, plus label(), the macro bindOptionLabel registers (#26608): 30 bare-callable; the receiver methods `can` and `hasCapability`, from bindPermissionPredicate and bindCapabilityPredicate, are outside the count; calendarDayUtc ADR-0053 D1; addMonthsUtc clamp; the floor/ceil #3306 note), (registerNumericCoercions #1928)", - "packages/formula/src/validate.ts#CEL_STDLIB_FUNCTIONS (the advertised bare-callable list; its docblock tallies the 30 registerStdLib adds and why a receiver-only name such as `can` is never in it)", + "packages/formula/src/stdlib.ts#registerStdLib (registerStdLib — the 30 chained registerFunction calls, isoDate / isoDatetime since #22347, rmbUpper since #34332, plus label(), the macro bindOptionLabel registers (#26608): 31 bare-callable; the receiver methods `can` and `hasCapability`, from bindPermissionPredicate and bindCapabilityPredicate, are outside the count; calendarDayUtc ADR-0053 D1; addMonthsUtc clamp; the floor/ceil #3306 note), (registerNumericCoercions #1928)", + "packages/formula/src/validate.ts#CEL_STDLIB_FUNCTIONS (the advertised bare-callable list; its docblock tallies the 31 registerStdLib adds and why a receiver-only name such as `can` is never in it)", "packages/lint/src/authoring-rules.ts#EXPRESSION_INVALID (the expression-invalid rule the object save door now dispatches on a formula field, #22031) + packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts (the #22019 block: sqrt(record.amount) refused 422 INVALID_METADATA on an active save and on a draft's promotion, nothing lands) + packages/lint/src/runtime-gate.object-formula-writes.test.ts + packages/objectql/src/engine-formula-fault-log.test.ts (the read-path residual: a pre-gate row still reads null, one warn line per object and field)", "packages/objectql/src/engine-top-level.ts#applyFormulaPlan (applyFormulaPlan — evaluate-fault → null, the silent-null contract; the evaluateFormulaField docblock states the compile-throws vs evaluate-nulls split)", "content/docs/data-modeling/formulas.mdx (the advertised catalog the matrix cross-checks)", @@ -2357,7 +2357,8 @@ "ref": "#25807" }, { "revision": 6, "date": "2026-10-31", "change": "The function count is 30, not 29, and the scratch-object legs name their writable package. Re-point of the red row QA run #27441 (18.3.0 sweep, wave 3, manual set, at c4c515ad) parked on sweep anchor #27377 §1, plus its fixture finding. (1) The registry gained label(record.f), a macro bindOptionLabel registers beside the permission predicates, and the docs table lists it, so the title, steps[0], steps[2], knownGaps[0], acceptance[0] (clause and evidence) and source[0]/[1] count 30, steps[2] adds the label() known-answer rows, and the receiver-only names outside the count are `can` and `hasCapability` (registerPermissionPredicate is now bindPermissionPredicate). (2) fixtures.requires[1] and steps[6]: a runtime object save needs a writable package and its namespace prefix as well as a sharingModel. Re-read at base 488b3ed0: packages/formula/src/stdlib.ts registerBoundStdLib and bindOptionLabel, packages/formula/src/validate.ts CEL_STDLIB_FUNCTIONS docblock ('30 added by registerStdLib'), content/docs/data-modeling/formulas.mdx, packages/metadata-protocol/src/protocol-authoring-gate.ts (NAMESPACE_PREFIX). The clause still fails on any count drift in either direction", "ref": "#27441" }, - { "revision": 7, "date": "2026-11-01", "change": "QA run #28656 (W3-RT) finding: acceptance[5] and steps[6] named only publish-drafts as the draft's promotion door. The single-item POST /api/v1/meta/object/NAME/publish refuses too, 422 INVALID_METADATA with the same expression-invalid finding: #28656 read it live at 6e11a929, publishMetaItem's refusal is pinned in packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts (the formula field verdict block, on a draft's promotion), and the route is meta.publishItem in packages/rest/src/rest-route-ledger.ts. Both now name the two promotion doors. The clause asks for both refusals, so it is stronger, never weaker. Re-verified against source at base 1c5b1773ec. Wave anchor #27377, wave-3 accuracy slice S10 (#28701); finding parked in anchor comment 6557904764", "ref": "#28656" } + { "revision": 7, "date": "2026-11-01", "change": "QA run #28656 (W3-RT) finding: acceptance[5] and steps[6] named only publish-drafts as the draft's promotion door. The single-item POST /api/v1/meta/object/NAME/publish refuses too, 422 INVALID_METADATA with the same expression-invalid finding: #28656 read it live at 6e11a929, publishMetaItem's refusal is pinned in packages/metadata-protocol/src/protocol.runtime-authoring-gate.test.ts (the formula field verdict block, on a draft's promotion), and the route is meta.publishItem in packages/rest/src/rest-route-ledger.ts. Both now name the two promotion doors. The clause asks for both refusals, so it is stronger, never weaker. Re-verified against source at base 1c5b1773ec. Wave anchor #27377, wave-3 accuracy slice S10 (#28701); finding parked in anchor comment 6557904764", "ref": "#28656" }, + { "revision": 8, "date": "2026-11-16", "change": "#34332 added rmbUpper(x) to the stdlib: an amount as Chinese capital numerals, rounded to fen half away from zero on the exact decimal, empty text for null, a runtime error for a value that spells no number or for 10^16 yuan and above. registerStdLib now chains 30 registerFunction calls, so the title, knownGaps[0], steps[0] (count and list), steps[2], acceptance[0] (clause and evidence) and both source notes say 31; validate.ts's CEL_STDLIB_FUNCTIONS docblock tallies 31 added by registerStdLib, and formulas.mdx carries the new row before label(record.f). steps[2] gains the rmbUpper known answers. No clause's assertion was weakened. Counted against source at base 9e6fee19 plus the #34332 branch", "ref": "#34332" } ] }, { diff --git a/packages/formula/src/cel-engine.test.ts b/packages/formula/src/cel-engine.test.ts index dcfd4c6a952..8b6b38a96be 100644 --- a/packages/formula/src/cel-engine.test.ts +++ b/packages/formula/src/cel-engine.test.ts @@ -505,7 +505,7 @@ describe('celEngine', () => { datetime: 'datetime("2026-03-15T08:00:00Z")', isoDate: 'isoDate(today())', isoDatetime: 'isoDatetime(now())', abs: 'abs(-3.5)', round: 'round(2.6)', floor: 'floor(6.7)', ceil: 'ceil(6.1)', - min: 'min(1, 2)', max: 'max(1, 2)', upper: 'upper("hi")', lower: 'lower("HI")', + min: 'min(1, 2)', max: 'max(1, 2)', rmbUpper: 'rmbUpper(10500.5)', upper: 'upper("hi")', lower: 'lower("HI")', trim: 'trim(" x ")', contains: 'contains("hello", "ell")', startsWith: 'startsWith("hi", "h")', endsWith: 'endsWith("hi", "i")', matches: 'matches("a1", "a.")', joinNonEmpty: 'joinNonEmpty(["a", "b"], "-")', isBlank: 'isBlank("")', isEmpty: 'isEmpty([])', coalesce: 'coalesce(null, "x")', len: 'len("ab")', diff --git a/packages/formula/src/rmb-upper.ts b/packages/formula/src/rmb-upper.ts new file mode 100644 index 00000000000..22257fca98e --- /dev/null +++ b/packages/formula/src/rmb-upper.ts @@ -0,0 +1,131 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `rmbUpper(amount)` — an amount of money as Chinese capital numerals + * (人民币大写金额), the line a Chinese quote, contract, order confirmation or + * invoice prints beside the figures: `245000` → `贰拾肆万伍仟元整`, + * `10500.5` → `壹万零伍佰元伍角`. + * + * The rules are the ones bank and accounting documents follow: + * + * - Digits 零壹贰叁肆伍陆柒捌玖, places 拾佰仟 inside a group of four, groups + * 万 and 亿. A ten is written `壹拾` (`10` → `壹拾元整`), never a bare `拾`. + * - One `零` stands for any run of zeros inside the number, and none is + * written at the end of a group or of the yuan part: `1005` → `壹仟零伍`, + * `10500` → `壹万零伍佰`, `100000001` → `壹亿零壹`, `1000000` → `壹佰万`. + * A group of four that starts with zeros after a higher group takes a `零` + * (`壹万零伍佰`); a full group does not (`壹拾万柒仟`, the form the rules + * allow without the optional `零`). + * - Above 亿 the count of 亿 is itself written with 万: `10_0001_0000_0000` + * → `壹拾万零壹亿`. Amounts are refused from 10^16 (一亿亿) up. + * - The yuan part ends in `元`; with no 角 and no 分 the text ends in `整`. + * A 角 with no 分 ends at the 角 (`伍角`). A 分 with no 角 after a yuan part + * writes `零` for the empty 角 (`壹元零伍分`). An amount under one yuan is + * its 角 and 分 alone (`0.5` → `伍角`, `0.05` → `伍分`). + * - Zero is `零元整`. A negative amount is prefixed `负`; one that rounds to + * zero is `零元整`, never `负零元整`. + * + * The amount is rounded to 分 (two decimals) once, half away from zero, on + * the exact decimal it spells — the reading and the rounding the home-amount + * projection uses (`home-amount-arithmetic.ts`), so `1.005` is `壹元零壹分` + * and binary floating point never decides a cent. A number, a bigint or the + * decimal text a driver answers a currency column with (`"245000.00"`) is + * read; `null` reads `''`, the way `trim(null)` and `label()` of an empty + * field do, so an empty total prints an empty line. Anything else — text that + * spells no decimal, a boolean, a list, NaN, an infinity — is refused with a + * throw, which the engine reports as a runtime error, rather than printed as + * some amount. + * + * Package-internal (NOT re-exported from `index.ts`): the CEL function is the + * published surface. + */ + +import { divideToPlaces, toScaledDecimal } from './home-amount-arithmetic'; + +const DIGITS = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'] as const; +const PLACES = ['', '拾', '佰', '仟'] as const; + +const TEN_THOUSAND = 10_000n; +const HUNDRED_MILLION = 100_000_000n; + +/** 10^16 yuan in 分: the first amount the 万/亿 scheme would have to write as 亿亿. */ +const LIMIT_FEN = 10n ** 18n; + +/** `n` in 1..9999 with places, one `零` per inner run of zeros and none at the end. */ +function group(n: number): string { + let text = ''; + let pendingZero = false; + for (let place = 3; place >= 0; place--) { + const digit = Math.floor(n / 10 ** place) % 10; + if (digit === 0) { + if (text !== '') pendingZero = true; + continue; + } + if (pendingZero) { + text += '零'; + pendingZero = false; + } + text += DIGITS[digit] + PLACES[place]; + } + return text; +} + +/** A positive whole number of yuan, below 10^16. */ +function yuan(n: bigint): string { + if (n < TEN_THOUSAND) return group(Number(n)); + if (n < HUNDRED_MILLION) { + const low = n % TEN_THOUSAND; + const head = group(Number(n / TEN_THOUSAND)) + '万'; + if (low === 0n) return head; + return head + (low < 1_000n ? '零' : '') + group(Number(low)); + } + const low = n % HUNDRED_MILLION; + const head = yuan(n / HUNDRED_MILLION) + '亿'; + if (low === 0n) return head; + return head + (low < 10_000_000n ? '零' : '') + yuan(low); +} + +/** The capital-numeral text of `amount`, rounded to 分; see the module docblock. */ +export function rmbUpper(amount: unknown): string { + if (amount === null || amount === undefined) return ''; + const exact = typeof amount === 'number' || typeof amount === 'bigint' || typeof amount === 'string' + ? toScaledDecimal(amount) + : undefined; + if (exact === undefined) { + throw new Error( + `rmbUpper(amount): \`amount\` is not a number (${describe(amount)}). ` + + 'Pass a number, a currency field, or decimal text such as "245000.00".', + ); + } + const fen = divideToPlaces(exact, { digits: 1n, scale: 0 }, 2).digits; + const negative = fen < 0n; + const abs = negative ? -fen : fen; + if (abs >= LIMIT_FEN) { + throw new Error( + 'rmbUpper(amount): `amount` is too large to write in capital numerals (10^16 yuan or more).', + ); + } + if (abs === 0n) return '零元整'; + + const whole = abs / 100n; + const jiao = Number((abs / 10n) % 10n); + const fenDigit = Number(abs % 10n); + + let text = whole > 0n ? yuan(whole) + '元' : ''; + if (jiao === 0 && fenDigit === 0) { + text += '整'; + } else { + if (jiao > 0) text += DIGITS[jiao] + '角'; + else if (whole > 0n) text += '零'; + if (fenDigit > 0) text += DIGITS[fenDigit] + '分'; + } + return (negative ? '负' : '') + text; +} + +/** A short, value-free description of a refused argument for the error text. */ +function describe(value: unknown): string { + if (typeof value === 'string') return 'text that spells no decimal'; + if (typeof value === 'number') return Number.isNaN(value) ? 'NaN' : 'an infinite number'; + if (Array.isArray(value)) return 'a list'; + return typeof value === 'object' ? 'a map' : `a ${typeof value}`; +} diff --git a/packages/formula/src/stdlib-rmb-upper.test.ts b/packages/formula/src/stdlib-rmb-upper.test.ts new file mode 100644 index 00000000000..d7f7bbbba27 --- /dev/null +++ b/packages/formula/src/stdlib-rmb-upper.test.ts @@ -0,0 +1,165 @@ +import { describe, expect, it } from 'vitest'; + +import { celEngine } from './cel-engine'; +import { inferExpressionType, validateExpression } from './validate'; + +/** + * `rmbUpper(amount)` — an amount as Chinese capital numerals (人民币大写), the + * line a Chinese quote, contract or invoice prints under the total. The rules + * are in `rmb-upper.ts`; every expectation here is evaluated through the + * engine, the way a formula field reads it. + */ + +function value(source: string, record: Record = {}): unknown { + const r = celEngine.evaluate({ dialect: 'cel', source }, { record }); + if (!r.ok) throw new Error(`${source}: ${r.error.kind}: ${r.error.message}`); + return r.value; +} + +/** The text of a record's `amount`, read the way a formula field over it reads it. */ +const upper = (amount: unknown) => value('rmbUpper(record.amount)', { amount }); + +describe('rmbUpper — the amounts on the card', () => { + it.each([ + [245000, '贰拾肆万伍仟元整'], + [245000.0, '贰拾肆万伍仟元整'], + [10500.5, '壹万零伍佰元伍角'], + ])('%s → %s', (amount, text) => { + expect(upper(amount)).toBe(text); + }); +}); + +describe('rmbUpper — places, groups and 零', () => { + it.each([ + [1, '壹元整'], + [10, '壹拾元整'], + [15, '壹拾伍元整'], + [100, '壹佰元整'], + [101, '壹佰零壹元整'], + [110, '壹佰壹拾元整'], + [1005, '壹仟零伍元整'], + [1050, '壹仟零伍拾元整'], + [1500, '壹仟伍佰元整'], + [10000, '壹万元整'], + [10001, '壹万零壹元整'], + [10010, '壹万零壹拾元整'], + [10500, '壹万零伍佰元整'], + [11000, '壹万壹仟元整'], + [100000, '壹拾万元整'], + [107000, '壹拾万柒仟元整'], + [1000000, '壹佰万元整'], + [1001000, '壹佰万壹仟元整'], + [1000100, '壹佰万零壹佰元整'], + [100000000, '壹亿元整'], + [100000001, '壹亿零壹元整'], + [100010000, '壹亿零壹万元整'], + [110000000, '壹亿壹仟万元整'], + [101000000, '壹亿零壹佰万元整'], + [123456789, '壹亿贰仟叁佰肆拾伍万陆仟柒佰捌拾玖元整'], + [1000000000000, '壹万亿元整'], + [10000100000000, '壹拾万零壹亿元整'], + // Beyond 2^53 as text: a double cannot hold it. + ['9999999999999999', '玖仟玖佰玖拾玖万玖仟玖佰玖拾玖亿玖仟玖佰玖拾玖万玖仟玖佰玖拾玖元整'], + ])('%s → %s', (amount, text) => { + expect(upper(amount)).toBe(text); + }); +}); + +describe('rmbUpper — 角, 分 and 整', () => { + it.each([ + [0, '零元整'], + [0.5, '伍角'], + [0.05, '伍分'], + [0.55, '伍角伍分'], + [1.5, '壹元伍角'], + [1.05, '壹元零伍分'], + [1.55, '壹元伍角伍分'], + [1680.32, '壹仟陆佰捌拾元叁角贰分'], + [100.1, '壹佰元壹角'], + [100.01, '壹佰元零壹分'], + ])('%s → %s', (amount, text) => { + expect(upper(amount)).toBe(text); + }); +}); + +describe('rmbUpper — rounding to 分, half away from zero, on the exact decimal', () => { + it.each([ + // 1.005 is 1.00499999999999989… as a double; the decimal it spells rounds up. + [1.005, '壹元零壹分'], + [2.675, '贰元陆角捌分'], + [0.004, '零元整'], + [0.005, '壹分'], + [9.995, '壹拾元整'], + [-1.005, '负壹元零壹分'], + ])('%s → %s', (amount, text) => { + expect(upper(amount)).toBe(text); + }); +}); + +describe('rmbUpper — negatives', () => { + it.each([ + [-1, '负壹元整'], + [-1200, '负壹仟贰佰元整'], + [-10500.5, '负壹万零伍佰元伍角'], + [-0.05, '负伍分'], + [-0.004, '零元整'], + ])('%s → %s', (amount, text) => { + expect(upper(amount)).toBe(text); + }); +}); + +describe('rmbUpper — what it reads', () => { + it('an int literal and a double literal', () => { + expect(value('rmbUpper(10500)')).toBe('壹万零伍佰元整'); + expect(value('rmbUpper(10500.5)')).toBe('壹万零伍佰元伍角'); + }); + + it('the decimal text a currency column is answered with', () => { + expect(upper('245000.00')).toBe('贰拾肆万伍仟元整'); + expect(upper(' 10500.50 ')).toBe('壹万零伍佰元伍角'); + expect(upper('1e4')).toBe('壹万元整'); + }); + + it('arithmetic on the record, the shape of a total', () => { + expect(value('rmbUpper(record.qty * record.price)', { qty: 2, price: 5250.25 })).toBe('壹万零伍佰元伍角'); + // 3 × 0.1 is 0.30000000000000004 as a double: the 分 rounding absorbs it. + expect(value('rmbUpper(record.qty * record.price)', { qty: 3, price: 0.1 })).toBe('叁角'); + }); + + it('null reads the empty string, so an empty total prints an empty line', () => { + expect(upper(null)).toBe(''); + }); +}); + +describe('rmbUpper — what it refuses', () => { + it.each([ + ['text that spells no decimal', 'abc'], + ['a currency symbol', '¥100'], + ['a boolean', true], + ['a list', [1]], + ])('%s is a runtime error, never some amount', (_label, amount) => { + const r = celEngine.evaluate({ dialect: 'cel', source: 'rmbUpper(record.amount)' }, { record: { amount } }); + expect(r.ok).toBe(false); + if (!r.ok) expect(r.error.message).toContain('rmbUpper(amount)'); + }); + + it('10^16 yuan and above is refused, not written as 亿亿', () => { + const r = celEngine.evaluate({ dialect: 'cel', source: 'rmbUpper(record.amount)' }, { record: { amount: '10000000000000000' } }); + expect(r.ok).toBe(false); + if (!r.ok) expect(r.error.message).toContain('too large'); + // CONTROL — one 分 below the limit is written. + expect(upper('9999999999999999.99')).toBe( + '玖仟玖佰玖拾玖万玖仟玖佰玖拾玖亿玖仟玖佰玖拾玖万玖仟玖佰玖拾玖元玖角玖分', + ); + }); +}); + +describe('rmbUpper — authoring', () => { + it('a formula over a currency field validates, and is typed text', () => { + const schema = { fields: ['total'], fieldTypes: { total: 'currency' }, scope: 'record' as const }; + const r = validateExpression('value', 'rmbUpper(record.total)', schema); + expect(r.errors).toEqual([]); + expect(r.warnings).toEqual([]); + expect(inferExpressionType('rmbUpper(record.total)', schema)).toBe('text'); + }); +}); diff --git a/packages/formula/src/stdlib.ts b/packages/formula/src/stdlib.ts index f57fb498402..5e288d5a781 100644 --- a/packages/formula/src/stdlib.ts +++ b/packages/formula/src/stdlib.ts @@ -22,6 +22,7 @@ import type { Environment } from '@marcbachmann/cel-js'; import type { EvalContext, EvalOptionLabels, EvalPermissions, EvalSystemPermissions } from './types'; +import { rmbUpper } from './rmb-upper'; import { createEvalUser, type EvalUser } from '@objectstack/spec'; // The verb vocabulary lives on the SECURITY subpath, where the permission // contract it is seeded from lives — not on the root barrel, which exports a @@ -772,6 +773,11 @@ export function registerBoundStdLib(env: Environment, read: () => StdLibBinding) // are ints. Comparison is numeric. .registerFunction('min(dyn, dyn): dyn', (a: unknown, b: unknown) => (Number(a) <= Number(b) ? a : b)) .registerFunction('max(dyn, dyn): dyn', (a: unknown, b: unknown) => (Number(a) >= Number(b) ? a : b)) + // An amount as Chinese capital numerals (人民币大写), the line a Chinese quote + // or invoice prints under the total: `rmbUpper(245000)` is `贰拾肆万伍仟元整`. + // Rounded to 分 half away from zero on the exact decimal; `''` for null; a + // value that spells no number is refused. Rules: `rmb-upper.ts`. + .registerFunction('rmbUpper(dyn): string', (x: unknown) => rmbUpper(x)) // ── Strings ────────────────────────────────────────────────────────── // Free-function forms of the common string ops. CEL also exposes some as // receiver methods (`s.contains(x)`), but the authoring catalog advertises diff --git a/packages/formula/src/validate.ts b/packages/formula/src/validate.ts index 447806a18ea..3c8b5d1d0b4 100644 --- a/packages/formula/src/validate.ts +++ b/packages/formula/src/validate.ts @@ -1730,18 +1730,18 @@ export function inferExpressionType(input: ExprInput, schema?: ExprSchemaHint): * * ## This is a CURATED SUBSET of what the environment resolves — by construction * - * The evaluation `Environment` resolves **77** distinct function names. This list - * carries 38 of them, and the 39-name gap is NOT staleness. Measured decomposition + * The evaluation `Environment` resolves **78** distinct function names. This list + * carries 39 of them, and the 39-name gap is NOT staleness. Measured decomposition * (`cel-stdlib-drift.test.ts` re-measures all four numbers on every run): * - * 77 registered names - * = 42 callable BARE, as `fn(x)` -> the only shape this list may carry + * 78 registered names + * = 43 callable BARE, as `fn(x)` -> the only shape this list may carry * + 35 callable only on a RECEIVER, `x.fn()` -> structurally ineligible * (cel-js's 33, plus our `can` * and `hasCapability`) * - * 42 bare-callable - * = 30 added by `registerStdLib` -> ALL advertised (one per registration site) + * 43 bare-callable + * = 31 added by `registerStdLib` -> ALL advertised (one per registration site) * + 8 cel-js built-ins -> advertised: has size int string bool double * timestamp duration * + 4 cel-js built-ins WITHHELD -> bytes dyn type uint @@ -1773,7 +1773,7 @@ export const CEL_STDLIB_FUNCTIONS: string[] = [ 'now', 'today', 'daysFromNow', 'daysAgo', 'daysBetween', 'addDays', 'addMonths', 'date', 'datetime', 'isoDate', 'isoDatetime', // Numbers (registered stdlib) - 'abs', 'round', 'floor', 'ceil', 'min', 'max', + 'abs', 'round', 'floor', 'ceil', 'min', 'max', 'rmbUpper', // Strings (registered stdlib) 'upper', 'lower', 'trim', 'contains', 'startsWith', 'endsWith', 'matches', 'joinNonEmpty', // Collections / null-ish (registered stdlib) diff --git a/skills/objectstack-formula/SKILL.md b/skills/objectstack-formula/SKILL.md index 551963783b4..eaad399726a 100644 --- a/skills/objectstack-formula/SKILL.md +++ b/skills/objectstack-formula/SKILL.md @@ -187,6 +187,7 @@ tests: every entry resolves at runtime, and this table documents them all. | `round(x)` | int | Round to the nearest integer | | `floor(x)` / `ceil(x)` | int | Round toward −∞ / +∞ (`floor(-1.2)` = −2, not −1) | | `min(a, b)` / `max(a, b)` | dyn | Smaller / larger operand (numeric comparison) | +| `rmbUpper(x)` | string | Amount in Chinese capitals, rounded to 分: `rmbUpper(10500.5)` = `壹万零伍佰元伍角`; `''` for null | **Strings** @@ -217,9 +218,6 @@ tests: every entry resolves at runtime, and this table documents them all. Plus CEL built-ins: `has(x)`, `size(x)`, `int(x)`, `string(x)`, `bool(x)`, `double(x)`, `timestamp(s)`, `duration(s)`. -If you need a helper that doesn't exist, prefer adding it to the stdlib -(small, pure, dependency-free) over inlining a complex CEL expression. - > Receiver methods (`s.split(',')`, > `list.map(...)`) are called on a value, never bare, and are not in this table; > four bare primitives (`bytes`, `dyn`, `type`, `uint`) resolve but are withheld From 9224c0c3e8b630c3c29431066fe5227ca4653535 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 17:32:54 +0000 Subject: [PATCH 2/3] fix(formula): rmbUpper refuses an out-of-range amount before converting it rmbUpper now reads the amount's spelling itself: the magnitude comes from the digits and the exponent, 10^16 yuan or more is refused with the too-large error, an amount below 0.001 is zero, and only the digits from the leading one down to the 0.001 place (the place half-away-from-zero rounding to fen reads) are converted. Exponent spellings such as 1e3 and 1050050e-2 keep reading as before. formulas.mdx: a formula field reads rmbUpper's runtime error as null. Claude-Session: https://claude.ai/code/session_01FEkQ5nHvfaZE5NLUTcWkFZ Co-Authored-By: Claude --- content/docs/data-modeling/formulas.mdx | 3 +- packages/formula/src/rmb-upper.ts | 90 +++++++++++++------ packages/formula/src/stdlib-rmb-upper.test.ts | 45 ++++++++++ 3 files changed, 111 insertions(+), 27 deletions(-) diff --git a/content/docs/data-modeling/formulas.mdx b/content/docs/data-modeling/formulas.mdx index f553711a30b..a609740f5fb 100644 --- a/content/docs/data-modeling/formulas.mdx +++ b/content/docs/data-modeling/formulas.mdx @@ -618,7 +618,8 @@ The amount is rounded once to 分, half away from zero, on the decimal it spells stands for each run of zeros, a ten is `壹拾`, a whole amount ends in `整` and an amount under one yuan is its 角 and 分 alone (`0.5` is `伍角`). A number, a currency field and decimal text (`'245000.00'`) are read; any other value, and -an amount of 10^16 yuan or more, is a runtime error rather than some text. +an amount of 10^16 yuan or more, is a runtime error rather than some text; a +formula field reads that error as `null`. ### Text Manipulation diff --git a/packages/formula/src/rmb-upper.ts b/packages/formula/src/rmb-upper.ts index 22257fca98e..34025efb04c 100644 --- a/packages/formula/src/rmb-upper.ts +++ b/packages/formula/src/rmb-upper.ts @@ -26,21 +26,28 @@ * zero is `零元整`, never `负零元整`. * * The amount is rounded to 分 (two decimals) once, half away from zero, on - * the exact decimal it spells — the reading and the rounding the home-amount - * projection uses (`home-amount-arithmetic.ts`), so `1.005` is `壹元零壹分` + * the exact decimal it spells — the rounding the home-amount projection uses + * (`divideToPlaces`, `home-amount-arithmetic.ts`), so `1.005` is `壹元零壹分` * and binary floating point never decides a cent. A number, a bigint or the - * decimal text a driver answers a currency column with (`"245000.00"`) is - * read; `null` reads `''`, the way `trim(null)` and `label()` of an empty - * field do, so an empty total prints an empty line. Anything else — text that - * spells no decimal, a boolean, a list, NaN, an infinity — is refused with a - * throw, which the engine reports as a runtime error, rather than printed as - * some amount. + * decimal text a driver answers a currency column with (`"245000.00"`, an + * exponent spelling too) is read; `null` reads `''`, the way `trim(null)` and + * `label()` of an empty field do, so an empty total prints an empty line. + * Anything else — text that spells no decimal, a boolean, a list, NaN, an + * infinity — is refused with a throw, which the engine reports as a runtime + * error, rather than printed as some amount. + * + * The spelling is judged before any conversion ({@link spelledFen}): its + * magnitude is read off its digits and exponent, an amount of 10^16 yuan or + * more is refused there, an amount below 0.001 is zero there, and only the + * digits down to the 0.001 place — the place half-away-from-zero rounding to + * 分 reads — are converted. So the work is bounded by the length of the text, + * whatever its exponent says. * * Package-internal (NOT re-exported from `index.ts`): the CEL function is the * published surface. */ -import { divideToPlaces, toScaledDecimal } from './home-amount-arithmetic'; +import { divideToPlaces } from './home-amount-arithmetic'; const DIGITS = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'] as const; const PLACES = ['', '拾', '佰', '仟'] as const; @@ -48,8 +55,21 @@ const PLACES = ['', '拾', '佰', '仟'] as const; const TEN_THOUSAND = 10_000n; const HUNDRED_MILLION = 100_000_000n; -/** 10^16 yuan in 分: the first amount the 万/亿 scheme would have to write as 亿亿. */ -const LIMIT_FEN = 10n ** 18n; +/** The decimal spellings read: sign, integer digits, fraction digits, exponent. */ +const DECIMAL_SPELLING = /^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/; + +/** + * The power of ten of the highest place an amount may reach: 10^15, so the + * largest amount written is 9999万9999亿9999万9999 yuan and 99 分, and 10^16 + * (一亿亿, which the 万/亿 scheme would have to write as 亿亿) is refused. + */ +const TOP_PLACE = 15; + +/** The lowest place rounding to 分 reads: 0.001. */ +const BOTTOM_PLACE = -3; + +const TOO_LARGE = + 'rmbUpper(amount): `amount` is too large to write in capital numerals (10^16 yuan or more).'; /** `n` in 1..9999 with places, one `零` per inner run of zeros and none at the end. */ function group(n: number): string { @@ -88,23 +108,9 @@ function yuan(n: bigint): string { /** The capital-numeral text of `amount`, rounded to 分; see the module docblock. */ export function rmbUpper(amount: unknown): string { if (amount === null || amount === undefined) return ''; - const exact = typeof amount === 'number' || typeof amount === 'bigint' || typeof amount === 'string' - ? toScaledDecimal(amount) - : undefined; - if (exact === undefined) { - throw new Error( - `rmbUpper(amount): \`amount\` is not a number (${describe(amount)}). ` + - 'Pass a number, a currency field, or decimal text such as "245000.00".', - ); - } - const fen = divideToPlaces(exact, { digits: 1n, scale: 0 }, 2).digits; + const fen = spelledFen(amount); const negative = fen < 0n; const abs = negative ? -fen : fen; - if (abs >= LIMIT_FEN) { - throw new Error( - 'rmbUpper(amount): `amount` is too large to write in capital numerals (10^16 yuan or more).', - ); - } if (abs === 0n) return '零元整'; const whole = abs / 100n; @@ -122,6 +128,38 @@ export function rmbUpper(amount: unknown): string { return (negative ? '负' : '') + text; } +/** + * `amount` in 分, rounded half away from zero, with the magnitude judged from + * the spelling before anything is converted: 10^16 yuan or more throws, an + * amount below 0.001 is 0, and only the digits from the leading one down to + * the 0.001 place become a number — the digits below it cannot move the + * rounding, because half away from zero at 分 reads the 0.001 digit alone. + */ +function spelledFen(amount: unknown): bigint { + let text: string | undefined; + if (typeof amount === 'number') text = Number.isFinite(amount) ? String(amount) : undefined; + else if (typeof amount === 'bigint') text = amount.toString(); + else if (typeof amount === 'string') text = amount.trim(); + const m = text === undefined ? null : DECIMAL_SPELLING.exec(text); + if (!m || (m[2] === '' && (m[3] ?? '') === '')) { + throw new Error( + `rmbUpper(amount): \`amount\` is not a number (${describe(amount)}). ` + + 'Pass a number, a currency field, or decimal text such as "245000.00".', + ); + } + const [, sign, int, frac = '', exp] = m; + const digits = int + frac; + const lead = digits.search(/[1-9]/); + if (lead === -1) return 0n; + // The power of ten of the leading digit; a long exponent reads ±Infinity. + const place = int.length - 1 - lead + (exp === undefined ? 0 : Number(exp)); + if (place > TOP_PLACE) throw new Error(TOO_LARGE); + if (place < BOTTOM_PLACE) return 0n; + const kept = digits.slice(lead, lead + place - BOTTOM_PLACE + 1).padEnd(place - BOTTOM_PLACE + 1, '0'); + const thousandths = BigInt(sign === '-' ? `-${kept}` : kept); + return divideToPlaces({ digits: thousandths, scale: -BOTTOM_PLACE }, { digits: 1n, scale: 0 }, 2).digits; +} + /** A short, value-free description of a refused argument for the error text. */ function describe(value: unknown): string { if (typeof value === 'string') return 'text that spells no decimal'; diff --git a/packages/formula/src/stdlib-rmb-upper.test.ts b/packages/formula/src/stdlib-rmb-upper.test.ts index d7f7bbbba27..889f5d8983c 100644 --- a/packages/formula/src/stdlib-rmb-upper.test.ts +++ b/packages/formula/src/stdlib-rmb-upper.test.ts @@ -154,6 +154,51 @@ describe('rmbUpper — what it refuses', () => { }); }); +describe('rmbUpper — an exponent spelling is judged before it is converted', () => { + /** Evaluate and time one call; every row must answer well inside a second. */ + function timed(amount: string) { + const started = performance.now(); + const r = celEngine.evaluate({ dialect: 'cel', source: 'rmbUpper(record.amount)' }, { record: { amount } }); + return { r, ms: performance.now() - started }; + } + + it.each([ + ['1e3', '壹仟元整'], + ['1.05e2', '壹佰零伍元整'], + ['10500.5e0', '壹万零伍佰元伍角'], + ['1050050e-2', '壹万零伍佰元伍角'], + ['9.999999999999999e15', '玖仟玖佰玖拾玖万玖仟玖佰玖拾玖亿玖仟玖佰玖拾玖万玖仟玖佰玖拾玖元整'], + ['5e-3', '壹分'], + ['4.99e-3', '零元整'], + ])('%s → %s', (amount, text) => { + expect(upper(amount)).toBe(text); + }); + + it.each(['1e16', '1e400', '1e200000000', '9'.repeat(400), '1e' + '9'.repeat(400)])( + '%s is refused as too large, promptly', + (amount) => { + const { r, ms } = timed(amount); + expect(r.ok).toBe(false); + if (!r.ok) expect(r.error.message).toContain('too large'); + expect(ms).toBeLessThan(1000); + }, + ); + + it.each(['1e-400', '1e-999999999', '-1e-999999999', '0e-999999999', '0e999999999', '0.' + '0'.repeat(100_000) + '1'])( + 'an amount below 0.001 (here %#) is 零元整, promptly', + (amount) => { + const { r, ms } = timed(amount); + expect(r).toEqual({ ok: true, value: '零元整' }); + expect(ms).toBeLessThan(1000); + }, + ); + + it('digits below the 0.001 place never move the rounding', () => { + expect(upper('1.0049' + '9'.repeat(1000))).toBe('壹元整'); + expect(upper('1.005' + '0'.repeat(1000))).toBe('壹元零壹分'); + }); +}); + describe('rmbUpper — authoring', () => { it('a formula over a currency field validates, and is typed text', () => { const schema = { fields: ['total'], fieldTypes: { total: 'currency' }, scope: 'record' as const }; From 92e409e84a9ea966cc5bfc593c1b36f9babf86bc Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 18:08:00 +0000 Subject: [PATCH 3/3] fix(formula): rmbUpper refuses an amount that rounds up to 10^16 yuan MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 9999999999999999.995 rounds to 10^16 yuan, which the 万/亿 scheme would write as 亿亿; the limit is checked again after rounding to 分. Pins the .995 rows (both signs) as refused and .994 as the written control. Claude-Session: https://claude.ai/code/session_01FEkQ5nHvfaZE5NLUTcWkFZ Co-Authored-By: Claude --- packages/formula/src/rmb-upper.ts | 12 ++++++++++-- packages/formula/src/stdlib-rmb-upper.test.ts | 18 ++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/packages/formula/src/rmb-upper.ts b/packages/formula/src/rmb-upper.ts index 34025efb04c..71aa2987949 100644 --- a/packages/formula/src/rmb-upper.ts +++ b/packages/formula/src/rmb-upper.ts @@ -38,7 +38,8 @@ * * The spelling is judged before any conversion ({@link spelledFen}): its * magnitude is read off its digits and exponent, an amount of 10^16 yuan or - * more is refused there, an amount below 0.001 is zero there, and only the + * more is refused there (and again after rounding, which can carry + * 9999999999999999.995 up to 10^16), an amount below 0.001 is zero there, and only the * digits down to the 0.001 place — the place half-away-from-zero rounding to * 分 reads — are converted. So the work is bounded by the length of the text, * whatever its exponent says. @@ -65,6 +66,9 @@ const DECIMAL_SPELLING = /^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/; */ const TOP_PLACE = 15; +/** 10^16 yuan in 分: the smallest amount refused once rounded. */ +const LIMIT_FEN = 10n ** 18n; + /** The lowest place rounding to 分 reads: 0.001. */ const BOTTOM_PLACE = -3; @@ -157,7 +161,11 @@ function spelledFen(amount: unknown): bigint { if (place < BOTTOM_PLACE) return 0n; const kept = digits.slice(lead, lead + place - BOTTOM_PLACE + 1).padEnd(place - BOTTOM_PLACE + 1, '0'); const thousandths = BigInt(sign === '-' ? `-${kept}` : kept); - return divideToPlaces({ digits: thousandths, scale: -BOTTOM_PLACE }, { digits: 1n, scale: 0 }, 2).digits; + const fen = divideToPlaces({ digits: thousandths, scale: -BOTTOM_PLACE }, { digits: 1n, scale: 0 }, 2).digits; + // Rounding can carry an amount at the top place up to 10^16 itself + // (9999999999999999.995 → 10^16): refused like any other amount that large. + if ((fen < 0n ? -fen : fen) >= LIMIT_FEN) throw new Error(TOO_LARGE); + return fen; } /** A short, value-free description of a refused argument for the error text. */ diff --git a/packages/formula/src/stdlib-rmb-upper.test.ts b/packages/formula/src/stdlib-rmb-upper.test.ts index 889f5d8983c..7e37674a64f 100644 --- a/packages/formula/src/stdlib-rmb-upper.test.ts +++ b/packages/formula/src/stdlib-rmb-upper.test.ts @@ -193,6 +193,24 @@ describe('rmbUpper — an exponent spelling is judged before it is converted', ( }, ); + it.each(['9999999999999999.995', '-9999999999999999.995', '9.9999999999999999995e15'])( + '%s rounds up to 10^16 yuan and is refused as too large, never written as 亿亿', + (amount) => { + const { r } = timed(amount); + expect(r.ok).toBe(false); + if (!r.ok) expect(r.error.message).toContain('too large'); + }, + ); + + it('CONTROL — one 0.001 below that rounds down and is written', () => { + expect(upper('9999999999999999.994')).toBe( + '玖仟玖佰玖拾玖万玖仟玖佰玖拾玖亿玖仟玖佰玖拾玖万玖仟玖佰玖拾玖元玖角玖分', + ); + expect(upper('-9999999999999999.994')).toBe( + '负玖仟玖佰玖拾玖万玖仟玖佰玖拾玖亿玖仟玖佰玖拾玖万玖仟玖佰玖拾玖元玖角玖分', + ); + }); + it('digits below the 0.001 place never move the rounding', () => { expect(upper('1.0049' + '9'.repeat(1000))).toBe('壹元整'); expect(upper('1.005' + '0'.repeat(1000))).toBe('壹元零壹分');