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
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ const config: ControlPanelConfig = {
visibility: ({ controls }) => {
const dttmLookup = Object.fromEntries(
ensureIsArray(controls?.groupby?.options).map(option => [
option.column_name,
(option.column_name || '').toLowerCase(),
option.is_dttm,
]),
);
Expand All @@ -285,7 +285,7 @@ const config: ControlPanelConfig = {
return true;
}
if (isPhysicalColumn(selection)) {
return !!dttmLookup[selection];
return !!dttmLookup[(selection || '').toLowerCase()];
}
return false;
})
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/* eslint-disable camelcase */
/**
* 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
*/

import {
ControlPanelConfig,
ControlPanelsContainerProps,
ControlState,
CustomControlItem,
} from '@superset-ui/chart-controls';
import config from '../src/controlPanel';

type VisibilityFn = (
props: ControlPanelsContainerProps,
control?: ControlState,
) => boolean;

function isControlWithVisibility(
controlItem: unknown,
): controlItem is CustomControlItem & {
config: Required<CustomControlItem['config']> & { visibility: VisibilityFn };
} {
return (
typeof controlItem === 'object' &&
controlItem !== null &&
'name' in controlItem &&
'config' in controlItem &&
typeof (controlItem as CustomControlItem).config?.visibility === 'function'
);
}

function getVisibility(
panel: ControlPanelConfig,
controlName: string,
): VisibilityFn {
const item = (panel.controlPanelSections || [])
.flatMap(section => section?.controlSetRows || [])
.flat()
.find(c => isControlWithVisibility(c) && c.name === controlName);

if (!isControlWithVisibility(item)) {
throw new Error(`Control "${controlName}" with visibility not found`);
}
return item.config.visibility;
}

function mkProps(
groupbyValue: string[],
options = [
{ column_name: 'ORDERDATE', is_dttm: true },
{ column_name: 'some_other_col', is_dttm: false },
],
): ControlPanelsContainerProps {
return {
controls: {
groupby: { value: groupbyValue, options },
},
} as unknown as ControlPanelsContainerProps;
}

test('time_grain_sqla visibility should be case-insensitive', () => {
const vis = getVisibility(config, 'time_grain_sqla');
const controlState = {} as ControlState;

expect(vis(mkProps(['orderdate']), controlState)).toBe(true);
expect(vis(mkProps(['ORDERDATE']), controlState)).toBe(true);
expect(vis(mkProps(['some_other_col']), controlState)).toBe(false);
});
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
import { render } from 'spec/helpers/testing-library';
import { render, selectOption } from 'spec/helpers/testing-library';
import { CurrencyControl } from './CurrencyControl';

test('CurrencyControl renders position and symbol selects', () => {
Expand All @@ -36,3 +36,30 @@ test('CurrencyControl renders position and symbol selects', () => {
).toBeInTheDocument();
expect(container.querySelectorAll('.ant-select')).toHaveLength(2);
});

test('CurrencyControl handles string currency value', async () => {
const onChange = jest.fn();
const { container } = render(
<CurrencyControl
onChange={onChange}
value='{"symbol":"USD","symbolPosition":"prefix"}'
/>,
{
useRedux: true,
initialState: {
common: { currencies: ['USD', 'EUR'] },
explore: { datasource: {} },
},
},
);

expect(
container.querySelector('[data-test="currency-control-container"]'),
).toBeInTheDocument();

await selectOption('Suffix', 'Currency prefix or suffix');
expect(onChange).toHaveBeenLastCalledWith({
symbol: 'USD',
symbolPosition: 'suffix',
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import ControlHeader from '../../ControlHeader';

export interface CurrencyControlProps {
onChange: (currency: Partial<Currency>) => void;
value?: Partial<Currency>;
value?: Partial<Currency> | string | null;
symbolSelectOverrideProps?: Partial<SelectProps>;
currencySelectOverrideProps?: Partial<SelectProps>;
symbolSelectAdditionalStyles?: CSSObject;
Expand Down Expand Up @@ -59,16 +59,37 @@ export const CURRENCY_SYMBOL_POSITION_OPTIONS = [
{ value: 'suffix', label: t('Suffix') },
];

const isCurrencyObject = (value: unknown): value is Partial<Currency> =>
!!value && typeof value === 'object' && !Array.isArray(value);

export const CurrencyControl = ({
onChange,
value: currency = {},
value: rawCurrency = {},
symbolSelectOverrideProps = {},
currencySelectOverrideProps = {},
symbolSelectAdditionalStyles,
currencySelectAdditionalStyles,
...props
}: CurrencyControlProps) => {
const theme = useTheme();
const normalizedCurrency = useMemo<Partial<Currency>>(() => {
if (isCurrencyObject(rawCurrency)) {
return rawCurrency;
}

if (typeof rawCurrency === 'string') {
try {
const parsed = JSON.parse(rawCurrency) as unknown;
if (isCurrencyObject(parsed)) {
return parsed;
}
} catch {
return {};
}
}

return {};
}, [rawCurrency]);
const currencies = useSelector<ViewState, string[]>(
state => state.common?.currencies,
);
Expand Down Expand Up @@ -155,10 +176,12 @@ export const CurrencyControl = ({
options={CURRENCY_SYMBOL_POSITION_OPTIONS}
placeholder={t('Prefix or suffix')}
onChange={(symbolPosition: string) => {
onChange({ ...currency, symbolPosition });
onChange({ ...normalizedCurrency, symbolPosition });
}}
onClear={() => onChange({ ...currency, symbolPosition: undefined })}
value={currency?.symbolPosition}
onClear={() =>
onChange({ ...normalizedCurrency, symbolPosition: undefined })
}
value={normalizedCurrency?.symbolPosition}
allowClear
{...symbolSelectOverrideProps}
/>
Expand All @@ -167,10 +190,10 @@ export const CurrencyControl = ({
options={currenciesOptions}
placeholder={t('Currency')}
onChange={(symbol: string) => {
onChange({ ...currency, symbol });
onChange({ ...normalizedCurrency, symbol });
}}
onClear={() => onChange({ ...currency, symbol: undefined })}
value={currency?.symbol}
onClear={() => onChange({ ...normalizedCurrency, symbol: undefined })}
value={normalizedCurrency?.symbol}
allowClear
allowNewOptions
sortComparator={currencySortComparator}
Expand Down
7 changes: 6 additions & 1 deletion superset-frontend/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,12 @@ const config = {
menu: addPreamble('src/views/menu.tsx'),
spa: addPreamble('src/views/index.tsx'),
embedded: addPreamble('src/embedded/index.tsx'),
'service-worker': path.join(APP_DIR, 'src/service-worker.ts'),
// Skip service-worker build in dev mode to avoid overwriting the placeholder
...(isDevMode
? {}
: {
'service-worker': path.join(APP_DIR, 'src/service-worker.ts'),
}),
},
cache: {
type: 'filesystem',
Expand Down
3 changes: 2 additions & 1 deletion superset/connectors/sqla/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@
SQLA_QUERY_KEYS,
)
from superset.models.slice import Slice
from superset.models.sql_types.base import CurrencyType
from superset.sql.parse import Table
from superset.superset_typing import (
AdhocColumn,
Expand Down Expand Up @@ -1093,7 +1094,7 @@ class SqlMetric(AuditMixinNullable, ImportExportMixin, CertificationMixin, Model
metric_type = Column(String(32))
description = Column(utils.MediumText())
d3format = Column(String(128))
currency = Column(JSON, nullable=True)
currency = Column(CurrencyType, nullable=True)
warning_text = Column(Text)
table_id = Column(Integer, ForeignKey("tables.id", ondelete="CASCADE"))
expression = Column(utils.MediumText(), nullable=False)
Expand Down
22 changes: 17 additions & 5 deletions superset/datasets/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
from superset import security_manager
from superset.connectors.sqla.models import SqlaTable
from superset.exceptions import SupersetMarshmallowValidationError
from superset.models.sql_types import parse_currency_string
from superset.utils import json

get_delete_ids_schema = {"type": "array", "items": {"type": "integer"}}
Expand Down Expand Up @@ -97,6 +98,20 @@ class DatasetMetricCurrencyPutSchema(Schema):
symbolPosition = fields.String(validate=Length(1, 128)) # noqa: N815


class CurrencyField(fields.Nested):
"""
Nested field that tolerates legacy string payloads for currency.
"""

def _deserialize(
self, value: Any, attr: str | None, data: dict[str, Any], **kwargs: Any
) -> Any:
if isinstance(value, str):
value = parse_currency_string(value)

return super()._deserialize(value, attr, data, **kwargs)


class DatasetMetricsPutSchema(Schema):
id = fields.Integer()
expression = fields.String(required=True)
Expand All @@ -105,7 +120,7 @@ class DatasetMetricsPutSchema(Schema):
metric_name = fields.String(required=True, validate=Length(1, 255))
metric_type = fields.String(allow_none=True, validate=Length(1, 32))
d3format = fields.String(allow_none=True, validate=Length(1, 128))
currency = fields.Nested(DatasetMetricCurrencyPutSchema, allow_none=True)
currency = CurrencyField(DatasetMetricCurrencyPutSchema, allow_none=True)
verbose_name = fields.String(allow_none=True, metadata={Length: (1, 1024)})
warning_text = fields.String(allow_none=True)
uuid = fields.UUID(allow_none=True)
Expand Down Expand Up @@ -276,9 +291,6 @@ def fix_fields(self, data: dict[str, Any], **kwargs: Any) -> dict[str, Any]:
if isinstance(data.get("extra"), str):
data["extra"] = json.loads(data["extra"])

if isinstance(data.get("currency"), str):
data["currency"] = json.loads(data["currency"])

return data

metric_name = fields.String(required=True)
Expand All @@ -287,7 +299,7 @@ def fix_fields(self, data: dict[str, Any], **kwargs: Any) -> dict[str, Any]:
expression = fields.String(required=True)
description = fields.String(allow_none=True)
d3format = fields.String(allow_none=True)
currency = fields.Nested(ImportMetricCurrencySchema, allow_none=True)
currency = CurrencyField(ImportMetricCurrencySchema, allow_none=True)
extra = fields.Dict(allow_none=True)
warning_text = fields.String(allow_none=True)

Expand Down
7 changes: 7 additions & 0 deletions superset/models/sql_types/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,10 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

from superset.models.sql_types.base import CurrencyType, parse_currency_string

__all__ = [
"CurrencyType",
"parse_currency_string",
]
Loading
Loading