codeant-ai-for-open-source[bot] commented on code in PR #40931: URL: https://github.com/apache/superset/pull/40931#discussion_r3503557507
########## superset-frontend/packages/superset-ui-core/src/currency-format/symbolPosition.ts: ########## @@ -0,0 +1,93 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { getCurrencyLocale } from './currencyLocale'; + +export type SymbolPosition = 'prefix' | 'suffix'; + +const NUMERIC_PART_TYPES = new Set<Intl.NumberFormatPartTypes>([ + 'integer', + 'group', + 'decimal', + 'fraction', +]); + +/** + * Memoize resolved positions by `(locale, currencyCode)`. `format` runs on a + * hot per-value path (every currency cell of every chart), so avoid rebuilding + * an `Intl.NumberFormat` and re-parsing the locale for repeated values. + */ +const positionCache = new Map<string, SymbolPosition>(); + +/** + * Resolve where the currency symbol should be placed relative to the value. + * + * An explicit `prefix`/`suffix` is always honored. When the position is unset, + * it is derived from the locale's own convention for that currency via + * `Intl.NumberFormat` (e.g. `$1` in `en-US` is a prefix, `1 €` in `fr-FR` is a + * suffix). Unknown currency codes fall back to `prefix`, the most common + * convention worldwide. + */ +export function resolveSymbolPosition( + currencyCode: string | undefined, + symbolPosition?: string, + locale: string = getCurrencyLocale(), +): SymbolPosition { + if (symbolPosition === 'prefix' || symbolPosition === 'suffix') { + return symbolPosition; + } + + if (currencyCode) { + const cacheKey = `${locale}|${currencyCode}`; + const cached = positionCache.get(cacheKey); + if (cached) { + return cached; + } + try { + const parts = new Intl.NumberFormat(locale, { + style: 'currency', + currency: currencyCode, + }).formatToParts(1); Review Comment: **Suggestion:** `resolveSymbolPosition` forwards the `locale` argument directly to `Intl.NumberFormat` without canonicalizing underscore-style tags. Callers that pass locales like `fr_FR` will hit the catch path and incorrectly default to `prefix`, so suffix locales are formatted on the wrong side. Normalize/canonicalize the `locale` input here (the same way `setCurrencyLocale` does) before building the cache key and formatter. [api mismatch] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ⚠️ Custom currency locale overrides misplace symbols for suffix locales. - ⚠️ Library consumers passing underscore locales get silently wrong formatting. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Use the exported helper `resolveSymbolPosition()` from `superset-frontend/packages/superset-ui-core/src/currency-format/symbolPosition.ts:47` in a consumer, passing a non-canonical locale such as `'fr_FR'` and a suffix currency (e.g. `resolveSymbolPosition('EUR', undefined, 'fr_FR')`). 2. Inside `resolveSymbolPosition`, execution reaches the currency branch at `symbolPosition.ts:56-59`, builds a cache key from the raw `locale` and `currencyCode`, and then constructs `new Intl.NumberFormat(locale, { style: 'currency', currency: currencyCode })` at `symbolPosition.ts:63-66` with the non-BCP-47 tag `'fr_FR'`. 3. As documented in `superset-frontend/packages/superset-ui-core/src/currency-format/currencyLocale.ts:31-43`, underscore-formatted tags are not valid for `Intl.NumberFormat`; the call throws and is caught by the `catch` at `symbolPosition.ts:76-78`, so no `currencyIndex`/`valueIndex` are computed and the function falls through to `return 'prefix';` at `symbolPosition.ts:81`. 4. Call sites such as `CurrencyFormatter.format()` in `superset-frontend/packages/superset-ui-core/src/currency-format/CurrencyFormatter.ts:157-162` then use this incorrect `'prefix'` result to format values, causing currencies that should be suffixes for the effective locale (e.g. `fr-FR` EUR) to be rendered on the wrong side whenever a consumer passes a non-canonical locale override like `'fr_FR'`. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=e236043b3cc84f5ca45035b6f8ad2af1&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=e236043b3cc84f5ca45035b6f8ad2af1&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** superset-frontend/packages/superset-ui-core/src/currency-format/symbolPosition.ts **Line:** 47:66 **Comment:** *Api Mismatch: `resolveSymbolPosition` forwards the `locale` argument directly to `Intl.NumberFormat` without canonicalizing underscore-style tags. Callers that pass locales like `fr_FR` will hit the catch path and incorrectly default to `prefix`, so suffix locales are formatted on the wrong side. Normalize/canonicalize the `locale` input here (the same way `setCurrencyLocale` does) before building the cache key and formatter. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40931&comment_hash=69b759be57b58d1647e7b185d48a94ed1216783eab3b159dc9a43f5552cee619&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40931&comment_hash=69b759be57b58d1647e7b185d48a94ed1216783eab3b159dc9a43f5552cee619&reaction=dislike'>👎</a> ########## superset-frontend/packages/superset-ui-core/test/currency-format/symbolPosition.test.ts: ########## @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { + resolveSymbolPosition, + formatWithSymbolPosition, +} from '@superset-ui/core'; + +test('resolveSymbolPosition honors an explicit position regardless of locale', () => { + expect(resolveSymbolPosition('EUR', 'prefix', 'fr-FR')).toEqual('prefix'); + expect(resolveSymbolPosition('USD', 'suffix', 'en-US')).toEqual('suffix'); +}); + +test('resolveSymbolPosition derives the position from the locale when unset', () => { + // en-US places the symbol before the value for these currencies. + expect(resolveSymbolPosition('USD', undefined, 'en-US')).toEqual('prefix'); + expect(resolveSymbolPosition('GBP', undefined, 'en-US')).toEqual('prefix'); + expect(resolveSymbolPosition('EUR', undefined, 'en-US')).toEqual('prefix'); + + // Eurozone locales place the EUR symbol after the value. + expect(resolveSymbolPosition('EUR', undefined, 'fr-FR')).toEqual('suffix'); + expect(resolveSymbolPosition('EUR', undefined, 'de-DE')).toEqual('suffix'); +}); + +test('resolveSymbolPosition returns the same result on repeated calls (cached)', () => { + // The second call hits the memoized (locale, currencyCode) entry. + expect(resolveSymbolPosition('EUR', undefined, 'fr-FR')).toEqual('suffix'); + expect(resolveSymbolPosition('EUR', undefined, 'fr-FR')).toEqual('suffix'); +}); + +test('resolveSymbolPosition falls back to prefix for unknown currencies', () => { + expect(resolveSymbolPosition('INVALID_CODE', undefined, 'en-US')).toEqual( + 'prefix', + ); + expect(resolveSymbolPosition(undefined, undefined, 'en-US')).toEqual( + 'prefix', + ); +}); + +test('resolveSymbolPosition falls back to prefix when locale parts lack a currency', () => { + const OrigNumberFormat = Intl.NumberFormat; + // formatToParts without a 'currency' part → currencyIndex is -1, so the + // position cannot be derived and the default prefix is returned. Use a + // locale/currency pair not exercised elsewhere so the memoization cache + // does not short-circuit this call. + Intl.NumberFormat = jest.fn().mockImplementation(() => ({ + formatToParts: () => [{ type: 'integer', value: '1' }], + })) as unknown as typeof Intl.NumberFormat; + + expect(resolveSymbolPosition('USD', undefined, 'zz-mock')).toEqual('prefix'); + + Intl.NumberFormat = OrigNumberFormat; Review Comment: **Suggestion:** The test mutates `Intl.NumberFormat` globally but restores it only at the end of the happy path; if the assertion or mock setup throws, the restore line is skipped and later tests run with a polluted global `Intl`. Wrap the override in `try/finally` so cleanup always runs. [code quality] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ⚠️ Failing test leaves global Intl mocked for rest run. - ⚠️ Subsequent currency formatting tests can fail with misleading errors. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Run Jest on `superset-frontend/packages/superset-ui-core/test/currency-format/symbolPosition.test.ts`, focusing on `test('resolveSymbolPosition falls back to prefix when locale parts lack a currency', ...)` at lines 56-69, which saves `OrigNumberFormat` and then overrides the global `Intl.NumberFormat` at lines 62-64. 2. Introduce a regression so that `resolveSymbolPosition('USD', undefined, 'zz-mock')` at line 66 no longer returns `'prefix'` (for example by changing the fallback logic in `superset-frontend/packages/superset-ui-core/src/currency-format/symbolPosition.ts:81`), causing the `expect(...).toEqual('prefix')` assertion at line 66 to throw. 3. Because the assertion throws before reaching the cleanup line `Intl.NumberFormat = OrigNumberFormat;` at `symbolPosition.test.ts:68`, the test exits early and leaves the global `Intl.NumberFormat` mocked for the remainder of the Jest run. 4. Subsequent tests that rely on the real `Intl.NumberFormat` (for example other currency-format tests in this package alongside `currencyLocale.test.ts`, which import `resolveSymbolPosition` and use `Intl` to derive placements) now execute against the stubbed implementation, producing misleading failures and making debugging harder until the Jest process is restarted. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=e8747bc0ebbf49ba89d9ccfa8bbced29&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=e8747bc0ebbf49ba89d9ccfa8bbced29&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** superset-frontend/packages/superset-ui-core/test/currency-format/symbolPosition.test.ts **Line:** 62:68 **Comment:** *Code Quality: The test mutates `Intl.NumberFormat` globally but restores it only at the end of the happy path; if the assertion or mock setup throws, the restore line is skipped and later tests run with a polluted global `Intl`. Wrap the override in `try/finally` so cleanup always runs. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40931&comment_hash=e2286891fc12f030846dd33a6ba2f639de7a9006929a15e913b31e0274297cf2&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40931&comment_hash=e2286891fc12f030846dd33a6ba2f639de7a9006929a15e913b31e0274297cf2&reaction=dislike'>👎</a> -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
