From 06cec014790130a59d0e860beda2f5b325d3b20c Mon Sep 17 00:00:00 2001 From: Marco Liberati Date: Tue, 24 Jan 2023 11:32:17 +0100 Subject: [PATCH] [Lens] Enable previous time shift when using a date histogram (#149126) ## Summary Fixes #104259 This PR expands the support of the `previous` time shift for visualisations with a date histogram defined. On the implementation side, an absolute time shift in the shape of `endAt( startRange )` is leveraged to make it work the `previous` shift: anchoring the shift to the beginning of the current range will make sure to compute the right shift in terms of buckets in order to avoid misaligned shifts and the main reason why this feature has been disabled initially. I've tried to condense an explanation here with this diagram of the misalignment problem: ![previous_before](https://user-images.githubusercontent.com/924948/213234848-40e3382a-843d-43fa-83d1-769a5f2e7953.png) With the current approach, there's a small time range overlap between the two requested interval, but that's the result of the rounding logic to get both shifts aligned. ![previous_2](https://user-images.githubusercontent.com/924948/213235429-1c99aefb-e18b-450a-b2d7-45b7d74c9e71.png) The only alternative to avoid the overlap is to get a gap between the two, but the former seems a better result to me. ### Checklist Delete any items that are not applicable to this PR. - [ ] Any text added follows [EUI's writing guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses sentence case text and includes [i18n support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md) - [ ] [Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html) was added for features that require explanation or tutorials - [ ] [Unit or functional tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html) were updated or added to match the most common scenarios - [ ] Any UI touched in this PR is usable by keyboard only (learn more about [keyboard accessibility](https://webaim.org/techniques/keyboard/)) - [ ] Any UI touched in this PR does not create any new axe failures (run axe in browser: [FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/), [Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US)) - [ ] If a plugin configuration key changed, check if it needs to be allowlisted in the cloud and added to the [docker list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker) - [ ] This renders correctly on smaller devices using a responsive layout. (You can test this [in your browser](https://www.browserstack.com/guide/responsive-testing-on-local-server)) - [ ] This was checked for [cross-browser compatibility](https://www.elastic.co/support/matrix#matrix_browsers) ### Risk Matrix Delete this section if it is not applicable to this PR. Before closing this PR, invite QA, stakeholders, and other developers to identify risks that should be tested prior to the change/feature release. When forming the risk matrix, consider some of the following examples and how they may potentially impact the change: | Risk | Probability | Severity | Mitigation/Notes | |---------------------------|-------------|----------|-------------------------| | Multiple Spaces—unexpected behavior in non-default Kibana Space. | Low | High | Integration tests will verify that all features are still supported in non-default Kibana Space and when user switches between spaces. | | Multiple nodes—Elasticsearch polling might have race conditions when multiple Kibana nodes are polling for the same tasks. | High | Low | Tasks are idempotent, so executing them multiple times will not result in logical error, but will degrade performance. To test for this case we add plenty of unit tests around this logic and document manual testing procedure. | | Code should gracefully handle cases when feature X or plugin Y are disabled. | Medium | High | Unit tests will verify that any feature flag or plugin combination still results in our service operational. | | [See more potential risk examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) | ### For maintainers - [ ] This was checked for breaking API changes and was [labeled appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process) Co-authored-by: Stratoula Kalafateli --- .../form_based/dimension_panel/time_shift.tsx | 5 +- .../definitions/calculations/counter_rate.tsx | 20 ++--- .../calculations/cumulative_sum.tsx | 20 ++--- .../definitions/calculations/differences.tsx | 20 ++--- .../calculations/moving_average.tsx | 25 ++---- .../definitions/calculations/time_scale.tsx | 4 +- .../operations/definitions/cardinality.tsx | 2 - .../operations/definitions/count.tsx | 2 - .../formula/editor/math_completion.ts | 6 +- .../operations/definitions/last_value.tsx | 2 - .../operations/definitions/metrics.tsx | 2 - .../operations/definitions/percentile.tsx | 2 - .../definitions/percentile_ranks.tsx | 2 - .../form_based/time_shift_utils.test.tsx | 77 ++----------------- .../form_based/time_shift_utils.tsx | 52 ++++--------- .../datasources/form_based/to_expression.ts | 21 ++++- .../translations/translations/fr-FR.json | 1 - .../translations/translations/ja-JP.json | 1 - .../translations/translations/zh-CN.json | 1 - 19 files changed, 74 insertions(+), 191 deletions(-) diff --git a/x-pack/plugins/lens/public/datasources/form_based/dimension_panel/time_shift.tsx b/x-pack/plugins/lens/public/datasources/form_based/dimension_panel/time_shift.tsx index 1d3cfefa66a4d..8bf26114416de 100644 --- a/x-pack/plugins/lens/public/datasources/form_based/dimension_panel/time_shift.tsx +++ b/x-pack/plugins/lens/public/datasources/form_based/dimension_panel/time_shift.tsx @@ -151,10 +151,7 @@ export function TimeShift({ options={timeShiftOptions.filter(({ value }) => { const parsedValue = parseTimeShift(value); return ( - parsedValue && - !isValueTooSmall(parsedValue) && - !isValueNotMultiple(parsedValue) && - !(parsedValue === 'previous' && dateHistogramInterval.interval) + parsedValue && !isValueTooSmall(parsedValue) && !isValueNotMultiple(parsedValue) // && ); })} selectedOptions={getSelectedOption()} diff --git a/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/calculations/counter_rate.tsx b/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/calculations/counter_rate.tsx index 3b89de8e94c51..e516ce206eb87 100644 --- a/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/calculations/counter_rate.tsx +++ b/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/calculations/counter_rate.tsx @@ -18,8 +18,7 @@ import { } from './utils'; import { DEFAULT_TIME_SCALE } from '../../time_scale_utils'; import { OperationDefinition } from '..'; -import { getFormatFromPreviousColumn, getFilter, combineErrorMessages } from '../helpers'; -import { getDisallowedPreviousShiftMessage } from '../../../time_shift_utils'; +import { getFormatFromPreviousColumn, getFilter } from '../helpers'; const ofName = buildLabelFunction((name?: string) => { return i18n.translate('xpack.lens.indexPattern.CounterRateOf', { @@ -107,16 +106,13 @@ export const counterRateOperation: OperationDefinition< return hasDateField(newIndexPattern); }, getErrorMessage: (layer: FormBasedLayer, columnId: string) => { - return combineErrorMessages([ - getErrorsForDateReference( - layer, - columnId, - i18n.translate('xpack.lens.indexPattern.counterRate', { - defaultMessage: 'Counter rate', - }) - ), - getDisallowedPreviousShiftMessage(layer, columnId), - ]); + return getErrorsForDateReference( + layer, + columnId, + i18n.translate('xpack.lens.indexPattern.counterRate', { + defaultMessage: 'Counter rate', + }) + ); }, getDisabledStatus(indexPattern, layer, layerType) { const opName = i18n.translate('xpack.lens.indexPattern.counterRate', { diff --git a/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/calculations/cumulative_sum.tsx b/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/calculations/cumulative_sum.tsx index 339f5e4bc4003..773f366990799 100644 --- a/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/calculations/cumulative_sum.tsx +++ b/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/calculations/cumulative_sum.tsx @@ -17,8 +17,7 @@ import { checkForDataLayerType, } from './utils'; import { OperationDefinition } from '..'; -import { getFormatFromPreviousColumn, getFilter, combineErrorMessages } from '../helpers'; -import { getDisallowedPreviousShiftMessage } from '../../../time_shift_utils'; +import { getFormatFromPreviousColumn, getFilter } from '../helpers'; import { DOCUMENT_FIELD_NAME } from '../../../../../../common'; const ofName = buildLabelFunction((name?: string) => { @@ -107,16 +106,13 @@ export const cumulativeSumOperation: OperationDefinition< return true; }, getErrorMessage: (layer: FormBasedLayer, columnId: string) => { - return combineErrorMessages([ - getErrorsForDateReference( - layer, - columnId, - i18n.translate('xpack.lens.indexPattern.cumulativeSum', { - defaultMessage: 'Cumulative sum', - }) - ), - getDisallowedPreviousShiftMessage(layer, columnId), - ]); + return getErrorsForDateReference( + layer, + columnId, + i18n.translate('xpack.lens.indexPattern.cumulativeSum', { + defaultMessage: 'Cumulative sum', + }) + ); }, getDisabledStatus(indexPattern, layer, layerType) { const opName = i18n.translate('xpack.lens.indexPattern.cumulativeSum', { diff --git a/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/calculations/differences.tsx b/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/calculations/differences.tsx index f2c379b5af5c1..f6ce789859b8c 100644 --- a/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/calculations/differences.tsx +++ b/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/calculations/differences.tsx @@ -17,8 +17,7 @@ import { checkForDataLayerType, } from './utils'; import { OperationDefinition } from '..'; -import { getFormatFromPreviousColumn, getFilter, combineErrorMessages } from '../helpers'; -import { getDisallowedPreviousShiftMessage } from '../../../time_shift_utils'; +import { getFormatFromPreviousColumn, getFilter } from '../helpers'; const OPERATION_NAME = 'differences'; @@ -93,16 +92,13 @@ export const derivativeOperation: OperationDefinition< return hasDateField(newIndexPattern); }, getErrorMessage: (layer: FormBasedLayer, columnId: string) => { - return combineErrorMessages([ - getErrorsForDateReference( - layer, - columnId, - i18n.translate('xpack.lens.indexPattern.derivative', { - defaultMessage: 'Differences', - }) - ), - getDisallowedPreviousShiftMessage(layer, columnId), - ]); + return getErrorsForDateReference( + layer, + columnId, + i18n.translate('xpack.lens.indexPattern.derivative', { + defaultMessage: 'Differences', + }) + ); }, getDisabledStatus(indexPattern, layer, layerType) { const opName = i18n.translate('xpack.lens.indexPattern.derivative', { diff --git a/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/calculations/moving_average.tsx b/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/calculations/moving_average.tsx index d7b46d09c0f1e..1d20f20521698 100644 --- a/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/calculations/moving_average.tsx +++ b/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/calculations/moving_average.tsx @@ -21,14 +21,8 @@ import { checkForDataLayerType, } from './utils'; import { updateColumnParam } from '../../layer_helpers'; -import { - getFormatFromPreviousColumn, - isValidNumber, - getFilter, - combineErrorMessages, -} from '../helpers'; +import { getFormatFromPreviousColumn, isValidNumber, getFilter } from '../helpers'; import type { OperationDefinition, ParamEditorProps } from '..'; -import { getDisallowedPreviousShiftMessage } from '../../../time_shift_utils'; const ofName = buildLabelFunction((name?: string) => { return i18n.translate('xpack.lens.indexPattern.movingAverageOf', { @@ -115,16 +109,13 @@ export const movingAverageOperation: OperationDefinition< return hasDateField(newIndexPattern); }, getErrorMessage: (layer: FormBasedLayer, columnId: string) => { - return combineErrorMessages([ - getErrorsForDateReference( - layer, - columnId, - i18n.translate('xpack.lens.indexPattern.movingAverage', { - defaultMessage: 'Moving average', - }) - ), - getDisallowedPreviousShiftMessage(layer, columnId), - ]); + return getErrorsForDateReference( + layer, + columnId, + i18n.translate('xpack.lens.indexPattern.movingAverage', { + defaultMessage: 'Moving average', + }) + ); }, helpComponent: () => , helpComponentTitle: i18n.translate('xpack.lens.indexPattern.movingAverage.titleHelp', { diff --git a/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/calculations/time_scale.tsx b/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/calculations/time_scale.tsx index 59eb7fea46233..ecf91b9bd3609 100644 --- a/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/calculations/time_scale.tsx +++ b/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/calculations/time_scale.tsx @@ -14,7 +14,6 @@ import { getErrorsForDateReference } from './utils'; import type { OperationDefinition } from '..'; import { combineErrorMessages, getFormatFromPreviousColumn } from '../helpers'; import { FormBasedLayer } from '../../../types'; -import { getDisallowedPreviousShiftMessage } from '../../../time_shift_utils'; type OverallMetricIndexPatternColumn = FormattedIndexPatternColumn & ReferenceBasedIndexPatternColumn & { @@ -110,7 +109,6 @@ export const timeScaleOperation: OperationDefinition combineErrorMessages([ getInvalidFieldMessage(layer.columns[columnId] as FieldBasedIndexPatternColumn, indexPattern), - getDisallowedPreviousShiftMessage(layer, columnId), getColumnReducedTimeRangeError(layer, columnId, indexPattern), ]), isTransferable: (column, newIndexPattern) => { diff --git a/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/count.tsx b/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/count.tsx index 60c1a0cdf0f5d..b5bd36d94225e 100644 --- a/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/count.tsx +++ b/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/count.tsx @@ -23,7 +23,6 @@ import { isColumnOfType, } from './helpers'; import { adjustTimeScaleLabelSuffix } from '../time_scale_utils'; -import { getDisallowedPreviousShiftMessage } from '../../time_shift_utils'; import { updateColumnParam } from '../layer_helpers'; import { getColumnReducedTimeRangeError } from '../../reduced_time_range_utils'; import { getGroupByKey } from './get_group_by_key'; @@ -92,7 +91,6 @@ export const countOperation: OperationDefinition combineErrorMessages([ getInvalidFieldMessage(layer.columns[columnId] as FieldBasedIndexPatternColumn, indexPattern), - getDisallowedPreviousShiftMessage(layer, columnId), getColumnReducedTimeRangeError(layer, columnId, indexPattern), ]), allowAsReference: true, diff --git a/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/formula/editor/math_completion.ts b/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/formula/editor/math_completion.ts index a0a968a136886..11d6797a1c997 100644 --- a/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/formula/editor/math_completion.ts +++ b/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/formula/editor/math_completion.ts @@ -395,9 +395,9 @@ export async function getNamedArgumentSuggestions({ if (dateHistogramInterval == null) return true; const parsedValue = parseTimeShift(value); return ( - parsedValue !== 'previous' && - (parsedValue === 'invalid' || - Number.isInteger(parsedValue.asMilliseconds() / dateHistogramInterval)) + parsedValue === 'previous' || + parsedValue === 'invalid' || + Number.isInteger(parsedValue.asMilliseconds() / dateHistogramInterval) ); }) .map(({ value }) => value); diff --git a/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/last_value.tsx b/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/last_value.tsx index db9c7c0d6ab0c..cde3f10b64c0b 100644 --- a/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/last_value.tsx +++ b/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/last_value.tsx @@ -29,7 +29,6 @@ import { getFilter, } from './helpers'; import { adjustTimeScaleLabelSuffix } from '../time_scale_utils'; -import { getDisallowedPreviousShiftMessage } from '../../time_shift_utils'; import { isRuntimeField, isScriptedField } from './terms/helpers'; import { FormRow } from './shared_components/form_row'; import { getColumnReducedTimeRangeError } from '../../reduced_time_range_utils'; @@ -214,7 +213,6 @@ export const lastValueOperation: OperationDefinition< if (invalidSortFieldMessage) { errorMessages = [invalidSortFieldMessage]; } - errorMessages.push(...(getDisallowedPreviousShiftMessage(layer, columnId) || [])); errorMessages.push(...(getColumnReducedTimeRangeError(layer, columnId, indexPattern) || [])); return errorMessages.length ? errorMessages : undefined; }, diff --git a/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/metrics.tsx b/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/metrics.tsx index bb15831a31854..4c11393af08e0 100644 --- a/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/metrics.tsx +++ b/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/metrics.tsx @@ -25,7 +25,6 @@ import { ValueFormatConfig, } from './column_types'; import { adjustTimeScaleLabelSuffix } from '../time_scale_utils'; -import { getDisallowedPreviousShiftMessage } from '../../time_shift_utils'; import { updateColumnParam } from '../layer_helpers'; import { getColumnReducedTimeRangeError } from '../../reduced_time_range_utils'; import { getGroupByKey } from './get_group_by_key'; @@ -215,7 +214,6 @@ function buildMetricOperation>({ layer.columns[columnId] as FieldBasedIndexPatternColumn, indexPattern ), - getDisallowedPreviousShiftMessage(layer, columnId), getColumnReducedTimeRangeError(layer, columnId, indexPattern), ]), filterable: true, diff --git a/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/percentile.tsx b/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/percentile.tsx index b55b1325a245e..34f9f854d3745 100644 --- a/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/percentile.tsx +++ b/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/percentile.tsx @@ -28,7 +28,6 @@ import { import { FieldBasedIndexPatternColumn } from './column_types'; import { adjustTimeScaleLabelSuffix } from '../time_scale_utils'; import { useDebouncedValue } from '../../../../shared_components'; -import { getDisallowedPreviousShiftMessage } from '../../time_shift_utils'; import { FormRow } from './shared_components'; import { getColumnReducedTimeRangeError } from '../../reduced_time_range_utils'; import { getGroupByKey, groupByKey } from './get_group_by_key'; @@ -290,7 +289,6 @@ export const percentileOperation: OperationDefinition< getErrorMessage: (layer, columnId, indexPattern) => combineErrorMessages([ getInvalidFieldMessage(layer.columns[columnId] as FieldBasedIndexPatternColumn, indexPattern), - getDisallowedPreviousShiftMessage(layer, columnId), getColumnReducedTimeRangeError(layer, columnId, indexPattern), ]), paramEditor: function PercentileParamEditor({ diff --git a/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/percentile_ranks.tsx b/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/percentile_ranks.tsx index 3d7b12802858c..3aadcb293114e 100644 --- a/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/percentile_ranks.tsx +++ b/x-pack/plugins/lens/public/datasources/form_based/operations/definitions/percentile_ranks.tsx @@ -23,7 +23,6 @@ import { import { FieldBasedIndexPatternColumn } from './column_types'; import { adjustTimeScaleLabelSuffix } from '../time_scale_utils'; import { useDebouncedValue } from '../../../../shared_components'; -import { getDisallowedPreviousShiftMessage } from '../../time_shift_utils'; import { FormRow } from './shared_components'; import { getColumnReducedTimeRangeError } from '../../reduced_time_range_utils'; @@ -168,7 +167,6 @@ export const percentileRanksOperation: OperationDefinition< getErrorMessage: (layer, columnId, indexPattern) => combineErrorMessages([ getInvalidFieldMessage(layer.columns[columnId] as FieldBasedIndexPatternColumn, indexPattern), - getDisallowedPreviousShiftMessage(layer, columnId), getColumnReducedTimeRangeError(layer, columnId, indexPattern), ]), paramEditor: function PercentileParamEditor({ diff --git a/x-pack/plugins/lens/public/datasources/form_based/time_shift_utils.test.tsx b/x-pack/plugins/lens/public/datasources/form_based/time_shift_utils.test.tsx index 3405752d3ec4f..a2495fbbbc1f6 100644 --- a/x-pack/plugins/lens/public/datasources/form_based/time_shift_utils.test.tsx +++ b/x-pack/plugins/lens/public/datasources/form_based/time_shift_utils.test.tsx @@ -6,80 +6,9 @@ */ import moment from 'moment'; -import { getDisallowedPreviousShiftMessage, resolveTimeShift } from './time_shift_utils'; -import { FormBasedLayer } from './types'; +import { resolveTimeShift } from './time_shift_utils'; describe('time_shift_utils', () => { - describe('getDisallowedPreviousShiftMessage', () => { - const layer: FormBasedLayer = { - indexPatternId: '', - columnOrder: [], - columns: { - a: { - operationType: 'date_histogram', - dataType: 'date', - isBucketed: true, - label: '', - references: [], - sourceField: 'timestamp', - }, - b: { - operationType: 'count', - dataType: 'number', - isBucketed: false, - label: 'non shifted', - references: [], - sourceField: 'records', - }, - c: { - operationType: 'count', - dataType: 'number', - isBucketed: false, - label: 'shifted', - timeShift: '1d', - references: [], - sourceField: 'records', - }, - }, - }; - - it('shoud not produce an error for no shift', () => { - expect(getDisallowedPreviousShiftMessage(layer, 'b')).toBeUndefined(); - }); - - it('shoud not produce an error for non-previous shift', () => { - expect(getDisallowedPreviousShiftMessage(layer, 'c')).toBeUndefined(); - }); - - it('shoud produce an error for previous shift with date histogram', () => { - expect( - getDisallowedPreviousShiftMessage( - { - ...layer, - columns: { ...layer.columns, c: { ...layer.columns.c, timeShift: 'previous' } }, - }, - 'c' - ) - ).toHaveLength(1); - }); - - it('shoud not produce an error for previous shift without date histogram', () => { - expect( - getDisallowedPreviousShiftMessage( - { - ...layer, - columns: { - ...layer.columns, - a: { ...layer.columns.a, operationType: 'terms' }, - c: { ...layer.columns.c, timeShift: 'previous' }, - }, - }, - 'c' - ) - ).toBeUndefined(); - }); - }); - describe('resolveTimeShift', () => { const dateString = '2022-11-02T00:00:00.000Z'; // shift by 2 days + 2500 s (to get a shift which is not a multiple of the given interval) @@ -113,6 +42,10 @@ describe('time_shift_utils', () => { .toBe('261000s'); }); + it('should convert previous relative time shift to seconds (rounded) when a date histogram is present', () => { + expect(resolveTimeShift(`previous`, getDateRange(), 100, true)).toBe('171000s'); + }); + it('should always include the passed date in the computed interval', () => { const dateRange = getDateRange(); for (const anchor of ['startAt', 'endAt']) { diff --git a/x-pack/plugins/lens/public/datasources/form_based/time_shift_utils.tsx b/x-pack/plugins/lens/public/datasources/form_based/time_shift_utils.tsx index b673f00a34392..c287a93675f64 100644 --- a/x-pack/plugins/lens/public/datasources/form_based/time_shift_utils.tsx +++ b/x-pack/plugins/lens/public/datasources/form_based/time_shift_utils.tsx @@ -23,10 +23,13 @@ import type { FormBasedLayer, FormBasedPrivateState } from './types'; import type { FramePublicAPI, IndexPattern } from '../../types'; export function parseTimeShiftWrapper(timeShiftString: string, dateRange: DateRange) { - return isAbsoluteTimeShift(timeShiftString.trim()) - ? parseAbsoluteTimeShift(timeShiftString, { from: dateRange.fromDate, to: dateRange.toDate }) - .value - : parseTimeShift(timeShiftString); + if (isAbsoluteTimeShift(timeShiftString.trim())) { + return parseAbsoluteTimeShift(timeShiftString, { + from: dateRange.fromDate, + to: dateRange.toDate, + }).value; + } + return parseTimeShift(timeShiftString); } export const timeShiftOptions = [ @@ -142,7 +145,6 @@ export function getDateHistogramInterval( export function getLayerTimeShiftChecks({ interval: dateHistogramInterval, - hasDateHistogram, canShift, }: ReturnType) { return { @@ -164,42 +166,11 @@ export function getLayerTimeShiftChecks({ ); }, isInvalid: (parsedValue: ReturnType) => { - return Boolean( - parsedValue === 'invalid' || (hasDateHistogram && parsedValue && parsedValue === 'previous') - ); + return Boolean(parsedValue === 'invalid'); }, }; } -export function getDisallowedPreviousShiftMessage( - layer: FormBasedLayer, - columnId: string -): string[] | undefined { - const currentColumn = layer.columns[columnId]; - const hasPreviousShift = - currentColumn.timeShift && - !isAbsoluteTimeShift(currentColumn.timeShift) && - parseTimeShift(currentColumn.timeShift) === 'previous'; - if (!hasPreviousShift) { - return; - } - const hasDateHistogram = Object.values(layer.columns).some( - (column) => column.operationType === 'date_histogram' - ); - if (!hasDateHistogram) { - return; - } - return [ - i18n.translate('xpack.lens.indexPattern.dateHistogramTimeShift', { - defaultMessage: - 'In a single layer, you are unable to combine previous time range shift with date histograms. Either use an explicit time shift duration in "{column}" or replace the date histogram.', - values: { - column: currentColumn.label, - }, - }), - ]; -} - export function getStateTimeShiftWarningMessages( datatableUtilities: DatatableUtilitiesService, state: FormBasedPrivateState, @@ -346,10 +317,15 @@ function roundAbsoluteInterval(timeShift: string, dateRange: DateRange, targetBa export function resolveTimeShift( timeShift: string | undefined, dateRange: DateRange, - targetBars: number + targetBars: number, + hasDateHistogram: boolean = false ) { if (timeShift && isAbsoluteTimeShift(timeShift)) { return roundAbsoluteInterval(timeShift, dateRange, targetBars); } + // Translate a relative "previous" shift into an absolute endAt() + if (timeShift && hasDateHistogram && timeShift === 'previous') { + return roundAbsoluteInterval(`endAt(${dateRange.fromDate})`, dateRange, targetBars); + } return timeShift; } diff --git a/x-pack/plugins/lens/public/datasources/form_based/to_expression.ts b/x-pack/plugins/lens/public/datasources/form_based/to_expression.ts index 61e17c72ca829..9ec654c47868f 100644 --- a/x-pack/plugins/lens/public/datasources/form_based/to_expression.ts +++ b/x-pack/plugins/lens/public/datasources/form_based/to_expression.ts @@ -158,7 +158,12 @@ function getExpressionForLayer( let aggAst = def.toEsAggsFn( { ...col, - timeShift: resolveTimeShift(col.timeShift, dateRange, histogramBarsTarget), + timeShift: resolveTimeShift( + col.timeShift, + dateRange, + histogramBarsTarget, + hasDateHistogram + ), }, wrapInFilter || wrapInTimeFilter ? `${aggId}-metric` : aggId, indexPattern, @@ -181,11 +186,21 @@ function getExpressionForLayer( schema: 'bucket', filter: col.filter && queryToAst(col.filter), timeWindow: wrapInTimeFilter ? col.reducedTimeRange : undefined, - timeShift: resolveTimeShift(col.timeShift, dateRange, histogramBarsTarget), + timeShift: resolveTimeShift( + col.timeShift, + dateRange, + histogramBarsTarget, + hasDateHistogram + ), }), ]), customMetric: buildExpression({ type: 'expression', chain: [aggAst] }), - timeShift: resolveTimeShift(col.timeShift, dateRange, histogramBarsTarget), + timeShift: resolveTimeShift( + col.timeShift, + dateRange, + histogramBarsTarget, + hasDateHistogram + ), } ).toAst(); } diff --git a/x-pack/plugins/translations/translations/fr-FR.json b/x-pack/plugins/translations/translations/fr-FR.json index ae0994252e749..eb0d05782eaa8 100644 --- a/x-pack/plugins/translations/translations/fr-FR.json +++ b/x-pack/plugins/translations/translations/fr-FR.json @@ -18116,7 +18116,6 @@ "xpack.lens.indexPattern.cumulativeSumOf": "Somme cumulée de {name}", "xpack.lens.indexPattern.dateHistogram.autoLongerExplanation": "Pour choisir l'intervalle, Lens divise la plage temporelle spécifiée par le paramètre avancé {targetBarSetting} et calcule le meilleur intervalle pour vos données. Par exemple, lorsque la plage temporelle est de 4 jours, les données sont divisées en compartiments horaires. Pour configurer le nombre de barres maximal, utilisez le paramètre avancé {maxBarSetting}.", "xpack.lens.indexPattern.dateHistogram.restrictedInterval": "Intervalle fixé à {intervalValue} en raison de restrictions d'agrégation.", - "xpack.lens.indexPattern.dateHistogramTimeShift": "Dans un calque unique, vous ne pouvez pas combiner un décalage de plage temporelle précédent avec des histogrammes de dates. Utilisez une durée de décalage temporel explicite dans \"{column}\" ou remplacez l’histogramme de dates.", "xpack.lens.indexPattern.derivativeOf": "Différences de {name}", "xpack.lens.indexPattern.fieldNoOperation": "Le champ {field} ne peut pas être utilisé sans opération", "xpack.lens.indexPattern.fieldsNotFound": "{count, plural, one {Champ} other {Champs}} {missingFields} {count, plural, one {introuvable} other {introuvables}}", diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index 1082e2930effb..cfaed97466f36 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -18098,7 +18098,6 @@ "xpack.lens.indexPattern.cumulativeSumOf": "{name}の累積和", "xpack.lens.indexPattern.dateHistogram.autoLongerExplanation": "間隔を選択するために、Lensでは、指定された時間範囲が{targetBarSetting}詳細設定で分割され、データに最適な間隔が計算されます。たとえば、時間範囲が4日の場合、データは1時間のバケットに分割されます。バーの最大数を設定するには、{maxBarSetting}詳細設定を使用します。", "xpack.lens.indexPattern.dateHistogram.restrictedInterval": "集約の制限により間隔は {intervalValue} に固定されています。", - "xpack.lens.indexPattern.dateHistogramTimeShift": "単一のレイヤーでは、前の時間範囲シフトと日付ヒストグラムを結合できません。\"{column}\"で明示的な時間シフト期間を使用するか、日付ヒストグラムを置換してください。", "xpack.lens.indexPattern.derivativeOf": "{name} の差異", "xpack.lens.indexPattern.fieldNoOperation": "フィールド{field}は演算なしで使用できません", "xpack.lens.indexPattern.fieldsNotFound": "{count, plural, other {個のフィールド}} {missingFields} {count, plural, other {が}}見つかりません", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 9a3d2c6a2b0b5..add5fcecf5ea6 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -18121,7 +18121,6 @@ "xpack.lens.indexPattern.cumulativeSumOf": "{name} 的累计和", "xpack.lens.indexPattern.dateHistogram.autoLongerExplanation": "要选择时间间隔,Lens 会按 {targetBarSetting} 高级设置分割指定的时间范围,并为您的数据计算最佳时间间隔。例如,当时间间隔为 4 天时,数据将分割为每小时存储桶。要配置最大条形数,请使用 {maxBarSetting} 高级设置。", "xpack.lens.indexPattern.dateHistogram.restrictedInterval": "由于聚合限制,时间间隔固定为 {intervalValue}。", - "xpack.lens.indexPattern.dateHistogramTimeShift": "在单个图层中,您无法组合上一时间范围偏移与 Date Histogram。在“{column}”中使用显式时间偏移持续时间,或替换 Date Histogram。", "xpack.lens.indexPattern.derivativeOf": "{name} 的差异", "xpack.lens.indexPattern.fieldNoOperation": "没有运算,无法使用字段 {field}", "xpack.lens.indexPattern.fieldsNotFound": "找不到{count, plural, other {字段}} {missingFields} {count, plural, other {}}",