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

[IMP] pivot: allow to sort the pivot on any column #4998

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
4 changes: 2 additions & 2 deletions src/actions/data_actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const sortAscending: ActionSpec = {
execute: (env) => {
const { anchor, zones } = env.model.getters.getSelection();
const sheetId = env.model.getters.getActiveSheetId();
interactiveSortSelection(env, sheetId, anchor.cell, zones[0], "ascending");
interactiveSortSelection(env, sheetId, anchor.cell, zones[0], "asc");
},
icon: "o-spreadsheet-Icon.SORT_ASCENDING",
};
Expand Down Expand Up @@ -47,7 +47,7 @@ export const sortDescending: ActionSpec = {
execute: (env) => {
const { anchor, zones } = env.model.getters.getSelection();
const sheetId = env.model.getters.getActiveSheetId();
interactiveSortSelection(env, sheetId, anchor.cell, zones[0], "descending");
interactiveSortSelection(env, sheetId, anchor.cell, zones[0], "desc");
},
icon: "o-spreadsheet-Icon.SORT_DESCENDING",
};
Expand Down
4 changes: 2 additions & 2 deletions src/components/filters/filter_menu/filter_menu.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
<div class="o-filter-menu d-flex flex-column bg-white" t-on-wheel.stop="">
<t t-if="isSortable">
<div>
<div class="o-filter-menu-item" t-on-click="() => this.sortFilterZone('ascending')">
<div class="o-filter-menu-item" t-on-click="() => this.sortFilterZone('asc')">
Sort ascending (A ⟶ Z)
</div>
<div class="o-filter-menu-item" t-on-click="() => this.sortFilterZone('descending')">
<div class="o-filter-menu-item" t-on-click="() => this.sortFilterZone('desc')">
Sort descending (Z ⟶ A)
</div>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
} from "../../../../helpers/pivot/pivot_helpers";
import { PivotRuntimeDefinition } from "../../../../helpers/pivot/pivot_runtime_definition";
import { Store, useStore } from "../../../../store_engine";
import { SpreadsheetChildEnv, UID } from "../../../../types";
import { SortDirection, SpreadsheetChildEnv, UID } from "../../../../types";
import {
Aggregator,
Granularity,
Expand All @@ -27,6 +27,7 @@ import { PivotDimension } from "./pivot_dimension/pivot_dimension";
import { PivotDimensionGranularity } from "./pivot_dimension_granularity/pivot_dimension_granularity";
import { PivotDimensionOrder } from "./pivot_dimension_order/pivot_dimension_order";
import { PivotMeasureEditor } from "./pivot_measure/pivot_measure";
import { PivotSortSection } from "./pivot_sort_section/pivot_sort_section";

interface Props {
definition: PivotRuntimeDefinition;
Expand All @@ -53,6 +54,7 @@ export class PivotLayoutConfigurator extends Component<Props, SpreadsheetChildEn
PivotDimensionOrder,
PivotDimensionGranularity,
PivotMeasureEditor,
PivotSortSection,
};
static props = {
definition: Object,
Expand Down Expand Up @@ -274,7 +276,7 @@ export class PivotLayoutConfigurator extends Component<Props, SpreadsheetChildEn
});
}

updateOrder(updateDimension: PivotDimensionType, order?: "asc" | "desc") {
updateOrder(updateDimension: PivotDimensionType, order?: SortDirection) {
const { rows, columns } = this.props.definition;
this.props.onDimensionsUpdated({
rows: rows.map((row) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,5 +84,6 @@
</div>
</t>
</div>
<PivotSortSection definition="props.definition" pivotId="props.pivotId"/>
</t>
</templates>
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { Component } from "@odoo/owl";
import { SpreadsheetChildEnv } from "../../../../..";
import { GRAY_100, GRAY_300, PRIMARY_BUTTON_BG } from "../../../../../constants";
import { formatValue } from "../../../../../helpers";
import {
getFieldDisplayName,
isSortedColumnValid,
} from "../../../../../helpers/pivot/pivot_helpers";
import { PivotRuntimeDefinition } from "../../../../../helpers/pivot/pivot_runtime_definition";
import { _t } from "../../../../../translation";
import { PivotDomain, UID } from "../../../../../types";
import { css } from "../../../../helpers";
import { Section } from "../../../components/section/section";

interface Props {
definition: PivotRuntimeDefinition;
pivotId: UID;
}

css/* scss */ `
.o-pivot-sort {
.o-sort-card {
width: fit-content;
background-color: ${GRAY_100};
border: 1px solid ${GRAY_300};

.o-sort-value {
color: ${PRIMARY_BUTTON_BG};
}
}
}
`;

export class PivotSortSection extends Component<Props, SpreadsheetChildEnv> {
static template = "o-spreadsheet-PivotSortSection";
static components = {
Section,
};
static props = {
definition: Object,
pivotId: String,
};

get hasValidSort() {
const pivot = this.env.model.getters.getPivot(this.props.pivotId);
return (
!!this.props.definition.sortedCol &&
isSortedColumnValid(this.props.definition.sortedCol, pivot)
);
}

get sortDescription() {
const sortOrder =
this.props.definition.sortedCol?.order === "asc" ? _t("ascending") : _t("descending");
return _t("Sorted on column (%(ascOrDesc)s):", {
ascOrDesc: sortOrder,
});
}

get sortValuesAndFields() {
const sortedCol = this.props.definition.sortedCol;
if (!sortedCol) {
return [];
}
const pivot = this.env.model.getters.getPivot(this.props.pivotId);
const locale = this.env.model.getters.getLocale();

const currentDomain: PivotDomain = [];
const sortValues: { field?: string; value: string }[] = [];
for (const domainItem of sortedCol.domain) {
currentDomain.push(domainItem);
const { value, format } = pivot.getPivotHeaderValueAndFormat(currentDomain);
const label = formatValue(value, { format, locale });
const field = pivot.definition.getDimension(domainItem.field);
sortValues.push({ field: getFieldDisplayName(field), value: label });
}

if (sortedCol.domain.length === 0) {
sortValues.push({ value: _t("Total") });
}
const measureLabel = pivot.getMeasure(sortedCol.measure).displayName;
sortValues.push({ value: measureLabel, field: _t("Measure") });

return sortValues;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<templates>
<t t-name="o-spreadsheet-PivotSortSection">
<Section t-if="hasValidSort" class="'o-pivot-sort'">
<t t-set-slot="title">Sorting</t>
<div t-esc="sortDescription" class="pb-2"/>
<div class="d-flex flex-column gap-2">
<t t-foreach="sortValuesAndFields" t-as="valueAndField" t-key="valueAndField_index">
<div class="o-sort-card d-flex gap-1 px-2">
<t t-if="valueAndField.field">
<span class="fw-bolder" t-esc="valueAndField.field"/>
=
</t>
<span class="fw-bolder o-sort-value" t-esc="valueAndField.value"/>
</div>
</t>
</div>
</Section>
</t>
</templates>
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@ export class PivotSidePanelStore extends SpreadsheetStore {
format: measure.format,
display: measure.display,
})),
sortedCol: this.shouldRemoveSortedColumn(definition) ? definition.sortedCol : undefined,
};
if (!this.draft && deepEquals(coreDefinition, cleanedDefinition)) {
return;
Expand Down Expand Up @@ -234,4 +235,16 @@ export class PivotSidePanelStore extends SpreadsheetStore {
}
return granularitiesPerFields;
}

private shouldRemoveSortedColumn(newDefinition: PivotCoreDefinition) {
const { sortedCol } = newDefinition;
if (!sortedCol) {
return true;
}
const oldDefinition = this.getters.getPivotCoreDefinition(this.pivotId);
return (
newDefinition.measures.find((measure) => measure.id === sortedCol.measure) &&
deepEquals(oldDefinition.columns, newDefinition.columns)
);
}
}
3 changes: 2 additions & 1 deletion src/functions/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
Locale,
Matrix,
Maybe,
SortDirection,
isMatrix,
} from "../types";
import { CellErrorType, EvaluationError, errorTypes } from "../types/errors";
Expand Down Expand Up @@ -734,7 +735,7 @@ export function dichotomicSearch<T>(
data: T,
target: Maybe<FunctionResultObject>,
mode: "nextGreater" | "nextSmaller" | "strict",
sortOrder: "asc" | "desc",
sortOrder: SortDirection,
rangeLength: number,
getValueInData: (range: T, index: number) => CellValue | undefined
): number {
Expand Down
11 changes: 6 additions & 5 deletions src/functions/module_filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
Locale,
Matrix,
Maybe,
SortDirection,
isMatrix,
} from "../types";
import { EvaluationError, NotAvailableError } from "../types/errors";
Expand All @@ -32,11 +33,11 @@ function sortMatrix(
)
);
}
const sortingOrders: ("ascending" | "descending")[] = [];
const sortingOrders: SortDirection[] = [];
const sortColumns: Matrix<CellValue> = [];
const nRows = matrix.length;
for (let i = 0; i < criteria.length; i += 2) {
sortingOrders.push(toBoolean(toScalar(criteria[i + 1])?.value) ? "ascending" : "descending");
sortingOrders.push(toBoolean(toScalar(criteria[i + 1])?.value) ? "asc" : "desc");
const sortColumn = criteria[i];
if (isMatrix(sortColumn) && (sortColumn.length > 1 || sortColumn[0].length > 1)) {
assert(
Expand All @@ -61,12 +62,12 @@ function sortMatrix(
if (sortColumns.length === 0) {
for (let i = 0; i < matrix[0].length; i++) {
sortColumns.push(matrix.map((row) => row[i].value));
sortingOrders.push("ascending");
sortingOrders.push("asc");
}
}
const sortingCriteria = {
descending: cellsSortingCriterion("descending"),
ascending: cellsSortingCriterion("ascending"),
desc: cellsSortingCriterion("desc"),
asc: cellsSortingCriterion("asc"),
};
const indexes = range(0, matrix.length);
indexes.sort((a, b) => {
Expand Down
26 changes: 26 additions & 0 deletions src/helpers/pivot/pivot_domain_helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
PivotColRowDomain,
PivotDomain,
PivotNode,
SortDirection,
} from "../../types";
import { clip, deepCopy } from "../misc";

Expand Down Expand Up @@ -253,3 +254,28 @@ export function getRunningTotalDomainKey(
}
return domainToString([...domain.slice(0, index), ...domain.slice(index + 1)]);
}

export function sortPivotTree(
tree: DimensionTree,
baseDomain: PivotDomain,
sortDirection: SortDirection,
getSortValue: (domain: PivotDomain) => number
): DimensionTree {
const sortedTree = tree
.map((node) => {
const fullDomain = [...baseDomain, { field: node.field, value: node.value, type: node.type }];
const sortValue = getSortValue(fullDomain);
return { ...node, sortValue, fullDomain };
})
.sort((node1, node2) =>
sortDirection === "asc"
? node1.sortValue - node2.sortValue
: node2.sortValue - node1.sortValue
);

for (const node of sortedTree) {
node.children = sortPivotTree(node.children, node.fullDomain, sortDirection, getSortValue);
}

return sortedTree;
}
25 changes: 25 additions & 0 deletions src/helpers/pivot/pivot_helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
PivotDimension,
PivotDomain,
PivotField,
PivotSortedColumn,
PivotTableCell,
} from "../../types/pivot";
import { domainToColRowDomain } from "./pivot_domain_helpers";
Expand Down Expand Up @@ -300,3 +301,27 @@ export function addIndentAndAlignToPivotHeader(
format: `${" ".repeat(indent)}${format}* `,
};
}

export function isSortedColumnValid(sortedCol: PivotSortedColumn, pivot: Pivot): boolean {
try {
if (!pivot.getMeasure(sortedCol.measure)) {
return false;
}

const columns = pivot.definition.columns;
for (let i = 0; i < sortedCol.domain.length; i++) {
if (columns[i].nameWithGranularity !== sortedCol.domain[i].field) {
return false;
}
const possibleValues: (CellValue | null)[] = pivot
.getPossibleFieldValues(columns[i])
.map((v) => v.value);
if (!possibleValues.includes(sortedCol.domain[i].value)) {
return false;
}
}
return true;
} catch (e) {
return false;
}
}
Loading