Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(plugins): BigNumber Time Comparison with existing time_offset API #27718

Merged
merged 27 commits into from
May 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
7943596
BigNumber with Time Comparison:
Antonio-RiveroMartnez Apr 8, 2024
eaef79d
BigNumber with Time Comparison:
Antonio-RiveroMartnez Apr 8, 2024
090ba4e
implement start date offset controls
lilykuang Apr 11, 2024
72539d8
fix time shift
lilykuang Apr 24, 2024
9d3d149
custom and inherit start date
lilykuang Apr 25, 2024
57e7aed
Table with Time Comparison:
Antonio-RiveroMartnez Apr 25, 2024
908cea3
Fixes
kgabryje Apr 24, 2024
333e93e
Improve coverage
kgabryje Apr 24, 2024
701a38b
Big Number with Time Comparison:
Antonio-RiveroMartnez Apr 25, 2024
b90fa30
Table with Time Comparison:
Antonio-RiveroMartnez Apr 23, 2024
41f52d9
Table with Time Comparison:
Antonio-RiveroMartnez Apr 25, 2024
29b9880
BigNumber with Time Comparison:
Antonio-RiveroMartnez Apr 25, 2024
74e3127
added getTimeOffset
lilykuang Apr 26, 2024
2407e00
BigNumber with Time Comparison:
Antonio-RiveroMartnez Apr 26, 2024
fcc3797
BigNumber with Time Comparison:
Antonio-RiveroMartnez Apr 26, 2024
7f66348
BigNumber with Time Comparison:
Antonio-RiveroMartnez Apr 26, 2024
7c16e60
user parseDttmToMoment
lilykuang Apr 26, 2024
131a6e6
change parse dttm from moment to date
lilykuang Apr 27, 2024
669a5bf
update tests
lilykuang Apr 27, 2024
f5f534a
BigNumber with Time Comparison:
Antonio-RiveroMartnez Apr 30, 2024
9e59a97
BigNumber with Time Comparison:
Antonio-RiveroMartnez May 7, 2024
9d66fc3
Time Comparison:
Antonio-RiveroMartnez May 13, 2024
10c716f
Time Comparison:
Antonio-RiveroMartnez May 14, 2024
336fc9a
Time Comparison:
Antonio-RiveroMartnez May 15, 2024
661adcd
Time Comparison:
Antonio-RiveroMartnez May 15, 2024
5a6b770
Time Comparison:
Antonio-RiveroMartnez May 16, 2024
85a7494
- Fix migration order
Antonio-RiveroMartnez May 16, 2024
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 @@ -23,3 +23,4 @@ export * from './annotationsAndLayers';
export * from './forecastInterval';
export * from './chartTitle';
export * from './echartsTimeSeriesQuery';
export * from './timeComparison';
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
/**
* 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 { t, ComparisonType } from '@superset-ui/core';

import { ControlPanelSectionConfig } from '../types';

const fullChoices = [
['1 day ago', t('1 day ago')],
['1 week ago', t('1 week ago')],
['28 days ago', t('28 days ago')],
['30 days ago', t('30 days ago')],
['1 month ago', t('1 month ago')],
['52 weeks ago', t('52 weeks ago')],
['1 year ago', t('1 year ago')],
['104 weeks ago', t('104 weeks ago')],
['2 years ago', t('2 years ago')],
['156 weeks ago', t('156 weeks ago')],
['3 years ago', t('3 years ago')],
['custom', t('Custom date')],
['inherit', t('Inherit range from time filter')],
];

const reducedKeys = new Set([
'1 day ago',
'1 week ago',
'1 month ago',
'1 year ago',
'custom',
'inherit',
]);

// Filter fullChoices to get only the entries whose keys are in reducedKeys
const reducedChoices = fullChoices.filter(choice => reducedKeys.has(choice[0]));

type TimeComparisonControlsType = {
multi?: boolean;
showCalculationType?: boolean;
showFullChoices?: boolean;
};
export const timeComparisonControls: ({
multi,
showCalculationType,
showFullChoices,
}: TimeComparisonControlsType) => ControlPanelSectionConfig = ({
multi = true,
showCalculationType = true,
showFullChoices = true,
}) => ({
label: t('Time Comparison'),
tabOverride: 'data',
description: t('Compare results with other time periods.'),
controlSetRows: [
[
{
name: 'time_compare',
config: {
type: 'SelectControl',
multi,
freeForm: true,
placeholder: t('Select or type a custom value...'),
label: t('Time shift'),
choices: showFullChoices ? fullChoices : reducedChoices,
description: t(
'Overlay results from a relative time period. ' +
'Expects relative time deltas ' +
'in natural language (example: 24 hours, 7 days, ' +
'52 weeks, 365 days). Free text is supported. ' +
'Use "Inherit range from time filters" ' +
'to shift the comparison time range ' +
'by the same length as your time range ' +
'and use "Custom" to set a custom comparison range.',
),
},
},
],
[
{
name: 'start_date_offset',
config: {
type: 'TimeOffsetControl',
label: t('shift start date'),
visibility: ({ controls }) =>
controls?.time_compare.value === 'custom',
},
},
],
[
{
name: 'comparison_type',
config: {
type: 'SelectControl',
label: t('Calculation type'),
default: 'values',
choices: [
[ComparisonType.Values, t('Actual values')],
[ComparisonType.Difference, t('Difference')],
[ComparisonType.Percentage, t('Percentage change')],
[ComparisonType.Ratio, t('Ratio')],
],
description: t(
'How to display time shifts: as individual lines; as the ' +
'difference between the main time series and each time shift; ' +
'as the percentage change; or as the ratio between series and time shifts.',
),
visibility: () => Boolean(showCalculationType),
},
},
],
[
{
name: 'comparison_range_label',
config: {
type: 'ComparisonRangeLabel',
multi,
visibility: ({ controls }) => Boolean(controls?.time_compare.value),
},
},
],
],
});
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,12 @@
* under the License.
*/
import rison from 'rison';
import { SupersetClient, getClientErrorObject } from '@superset-ui/core';
import { isEmpty } from 'lodash';
import {
SupersetClient,
getClientErrorObject,
ensureIsArray,
} from '@superset-ui/core';

export const SEPARATOR = ' : ';

Expand All @@ -39,20 +44,64 @@ export const formatTimeRange = (
)} ≤ ${columnPlaceholder} < ${formatDateEndpoint(splitDateRange[1])}`;
};

export const formatTimeRangeComparison = (
initialTimeRange: string,
shiftedTimeRange: string,
columnPlaceholder = 'col',
) => {
const splitInitialDateRange = initialTimeRange.split(SEPARATOR);
const splitShiftedDateRange = shiftedTimeRange.split(SEPARATOR);
return `${columnPlaceholder}: ${formatDateEndpoint(
splitInitialDateRange[0],
true,
)} to ${formatDateEndpoint(splitInitialDateRange[1])} vs
${formatDateEndpoint(splitShiftedDateRange[0], true)} to ${formatDateEndpoint(
splitShiftedDateRange[1],
)}`;
};

export const fetchTimeRange = async (
timeRange: string,
columnPlaceholder = 'col',
shifts?: string[],
) => {
const query = rison.encode_uri(timeRange);
const endpoint = `/api/v1/time_range/?q=${query}`;
let query;
let endpoint;
if (!isEmpty(shifts)) {
const timeRanges = ensureIsArray(shifts).map(shift => ({
timeRange,
shift,
}));
query = rison.encode_uri([{ timeRange }, ...timeRanges]);
endpoint = `/api/v1/time_range/?q=${query}`;
} else {
query = rison.encode_uri(timeRange);
endpoint = `/api/v1/time_range/?q=${query}`;
}
try {
const response = await SupersetClient.get({ endpoint });
const timeRangeString = buildTimeRangeString(
response?.json?.result[0]?.since || '',
response?.json?.result[0]?.until || '',
if (isEmpty(shifts)) {
const timeRangeString = buildTimeRangeString(
response?.json?.result[0]?.since || '',
response?.json?.result[0]?.until || '',
);
return {
value: formatTimeRange(timeRangeString, columnPlaceholder),
};
}
const timeRanges = response?.json?.result.map((result: any) =>
buildTimeRangeString(result.since, result.until),
);
return {
value: formatTimeRange(timeRangeString, columnPlaceholder),
value: timeRanges
.slice(1)
.map((timeRange: string) =>
formatTimeRangeComparison(
timeRanges[0],
timeRange,
columnPlaceholder,
),
),
};
} catch (response) {
const clientError = await getClientErrorObject(response);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
/**
* 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 { ensureIsArray } from '../utils';

const DAY_IN_MS = 24 * 60 * 60 * 1000;
export const parseDttmToDate = (dttm: string): Date => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't parseDttmToDate similar to parse_human_datetime? If yes, is there a way we can reuse that so we don't have 2 implementations to maintain?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for pointing this out. parseDttmToDate and parse_human_datetime are very similar. However, parse_human_datetime is in the backend, while parseDttmToDate is also for validating a DatePicker component in the frontend. This separation makes unifying them tricky. I'm open to any suggestions you might have.

const now = new Date();
now.setUTCHours(0, 0, 0, 0);

if (dttm === 'now' || dttm === 'today' || dttm === 'No filter') {
return now;
}
if (dttm === 'Last week') {
now.setUTCDate(now.getUTCDate() - 7);
return now;
}
if (dttm === 'Last month') {
now.setUTCMonth(now.getUTCMonth() - 1);
now.setUTCDate(1);
return now;
}
if (dttm === 'Last quarter') {
now.setUTCMonth(now.getUTCMonth() - 3);
now.setUTCDate(1);
return now;
}
if (dttm === 'Last year') {
now.setUTCFullYear(now.getUTCFullYear() - 1);
now.setUTCDate(1);
return now;
}
if (dttm === 'previous calendar week') {
now.setUTCDate(now.getUTCDate() - now.getUTCDay());
return now;
}
if (dttm === 'previous calendar month') {
now.setUTCMonth(now.getUTCMonth() - 1, 1);
return now;
}
if (dttm === 'previous calendar year') {
now.setUTCFullYear(now.getUTCFullYear() - 1, 0, 1);
return now;
}
if (dttm?.includes('ago')) {
const parts = dttm.split(' ');
const amount = parseInt(parts[0], 10);
const unit = parts[1];

switch (unit) {
case 'day':
case 'days':
now.setUTCDate(now.getUTCDate() - amount);
break;
case 'week':
case 'weeks':
now.setUTCDate(now.getUTCDate() - amount * 7);
break;
case 'month':
case 'months':
now.setUTCMonth(now.getUTCMonth() - amount);
break;
case 'year':
case 'years':
now.setUTCFullYear(now.getUTCFullYear() - amount);
break;
default:
break;
}
return now;
}
const parsed = new Date(dttm);
parsed.setUTCHours(0, 0, 0, 0);
return parsed;
};

export const getTimeOffset = (
timeRangeFilter: any,
shifts: string[],
startDate: string,
): string[] => {
const isCustom = shifts?.includes('custom');
const isInherit = shifts?.includes('inherit');
const customStartDate = isCustom && parseDttmToDate(startDate).getTime();
const filterStartDate = parseDttmToDate(
timeRangeFilter.comparator.split(' : ')[0],
).getTime();
const filterEndDate = parseDttmToDate(
timeRangeFilter.comparator.split(' : ')[1],
).getTime();

const customShift =
customStartDate &&
Math.ceil((filterStartDate - customStartDate) / DAY_IN_MS);
const inInheritShift =
isInherit && Math.ceil((filterEndDate - filterStartDate) / DAY_IN_MS);

let newShifts = shifts;
if (isCustom) {
newShifts = [`${customShift} days ago`];
}
if (isInherit) {
newShifts = [`${inInheritShift} days ago`];
}
return ensureIsArray(newShifts);
};
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,5 @@ export * from './types';

export { default as getComparisonInfo } from './getComparisonInfo';
export { default as getComparisonFilters } from './getComparisonFilters';
export { parseDttmToDate, getTimeOffset } from './getTimeOffset';
export { SEPARATOR, fetchTimeRange } from './fetchTimeRange';
Loading
Loading