Skip to content

The open alternative to Salesforce, designed for AI.

fix(front): honor all sort fields in optimistic record updates (#28741)

I'm Groot 🌳0eb4fb1105b9
diff --git a/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/__tests__/sortCachedObjectEdges.test.ts b/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/__tests__/sortCachedObjectEdges.test.ts
new file mode 100644
index 00000000000..bdcf1a443af
--- /dev/null
+++ b/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/__tests__/sortCachedObjectEdges.test.ts
@@ -0,0 +1,171 @@
+import { gql, InMemoryCache } from '@apollo/client';
+
+import { sortCachedObjectEdges } from '@/apollo/optimistic-effect/utils/sortCachedObjectEdges';
+import { type RecordGqlRefEdge } from '@/object-record/cache/types/RecordGqlRefEdge';
+import { type RecordGqlOperationOrderBy } from 'twenty-shared/types';
+
+const RECORDS_QUERY = gql`
+ query Records {
+ records {
+ edges {
+ cursor
+ node {
+ id
+ score
+ rank
+ name {
+ firstName
+ lastName
+ }
+ owner {
+ id
+ name {
+ firstName
+ lastName
+ }
+ }
+ }
+ }
+ }
+ }
+`;
+
+type TestRecord = {
+ id: string;
+ score?: number | null;
+ rank?: number | null;
+ name?: { firstName: string; lastName: string } | null;
+ owner?: {
+ id: string;
+ name: { firstName: string; lastName: string } | null;
+ } | null;
+};
+
+const sortRecords = (
+ records: TestRecord[],
+ orderBy: RecordGqlOperationOrderBy,
+) => {
+ const cache = new InMemoryCache();
+ cache.writeQuery({
+ query: RECORDS_QUERY,
+ data: {
+ records: {
+ edges: records.map((record) => ({
+ cursor: record.id,
+ node: {
+ __typename: 'Record',
+ score: null,
+ rank: null,
+ name: null,
+ owner: null,
+ ...record,
+ ...(record.owner && {
+ owner: { __typename: 'Owner', ...record.owner },
+ }),
+ },
+ })),
+ },
+ },
+ });
+
+ cache.modify<{ records: { edges: RecordGqlRefEdge[] } }>({
+ fields: {
+ records: (connection, { readField }) => {
+ const sortedEdges = sortCachedObjectEdges({
+ edges: [
+ ...(readField<RecordGqlRefEdge[]>('edges', connection) ?? []),
+ ],
+ orderBy,
+ readCacheField: readField,
+ });
+
+ return { ...connection, edges: sortedEdges };
+ },
+ },
+ });
+
+ return cache
+ .readQuery<{ records: { edges: { node: { id: string } }[] } }>({
+ query: RECORDS_QUERY,
+ })!
+ .records.edges.map(({ node }) => node.id);
+};
+
+describe('sortCachedObjectEdges', () => {
+ it('uses the second sort when the first values are equal', () => {
+ expect(
+ sortRecords(
+ [
+ { id: 'later', score: 10, rank: 2 },
+ { id: 'first', score: 10, rank: 1 },
+ ],
+ [{ score: 'AscNullsLast' }, { rank: 'AscNullsLast' }],
+ ),
+ ).toEqual(['first', 'later']);
+ });
+
+ it('keeps earlier sorts ahead of later sorts with mixed directions', () => {
+ expect(
+ sortRecords(
+ [
+ { id: 'low', score: 1, rank: 0 },
+ { id: 'last', score: 2, rank: 2 },
+ { id: 'first', score: 2, rank: 1 },
+ ],
+ [{ score: 'DescNullsLast' }, { rank: 'AscNullsLast' }],
+ ),
+ ).toEqual(['first', 'last', 'low']);
+ });
+
+ it('applies null placement and descending order to the second field', () => {
+ expect(
+ sortRecords(
+ [
+ { id: 'one', score: 10, rank: 1 },
+ { id: 'null', score: 10 },
+ { id: 'two', score: 10, rank: 2 },
+ ],
+ [{ score: 'AscNullsLast' }, { rank: 'DescNullsFirst' }],
+ ),
+ ).toEqual(['null', 'two', 'one']);
+ });
+
+ it('reads composite fields through normalized relation references', () => {
+ expect(
+ sortRecords(
+ [
+ {
+ id: 'bob',
+ score: 10,
+ owner: { id: 'owner-b', name: { firstName: 'Bob', lastName: 'A' } },
+ },
+ {
+ id: 'alice',
+ score: 10,
+ owner: {
+ id: 'owner-a',
+ name: { firstName: 'Alice', lastName: 'Z' },
+ },
+ },
+ { id: 'missing', score: 10 },
+ ],
+ [
+ { score: 'AscNullsLast' },
+ { owner: { name: { firstName: 'AscNullsLast' } } },
+ ],
+ ),
+ ).toEqual(['alice', 'bob', 'missing']);
+ });
+
+ it('preserves input order when every sort criterion ties', () => {
+ expect(
+ sortRecords(
+ [
+ { id: 'b', score: 0, rank: 1 },
+ { id: 'a', score: 0, rank: 1 },
+ ],
+ [{ score: 'AscNullsLast' }, { rank: 'AscNullsLast' }],
+ ),
+ ).toEqual(['b', 'a']);
+ });
+});
diff --git a/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/sortCachedObjectEdges.ts b/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/sortCachedObjectEdges.ts
index 5643dafe1b3..11f93ff6044 100644
--- a/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/sortCachedObjectEdges.ts
+++ b/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/sortCachedObjectEdges.ts
@@ -1,34 +1,33 @@
import { type Reference, type StoreObject } from '@apollo/client';
import { type FieldFunctionOptions } from '@apollo/client/cache';
-
-type ReadFieldFunction = FieldFunctionOptions['readField'];
import { isNonEmptyString } from '@sniptt/guards';
import { type RecordGqlRefEdge } from '@/object-record/cache/types/RecordGqlRefEdge';
-
+import { doNotTranslate } from 'twenty-shared/i18n';
import {
type OrderBy,
type RecordGqlOperationOrderBy,
} from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
-import { doNotTranslate } from 'twenty-shared/i18n';
import { sortAsc, sortDesc, sortNullsFirst, sortNullsLast } from '~/utils/sort';
-// Extracts the OrderBy direction from a nested orderBy structure
-// Handles up to 3 levels: field, field.subField, or relation.compositeField.subField
-const extractOrderByDirection = (value: unknown): OrderBy | null => {
- if (isNonEmptyString(value)) {
- return value as OrderBy;
- }
- if (typeof value === 'object' && value !== null) {
- const entries = Object.entries(value);
- if (entries.length > 0) {
- return extractOrderByDirection(entries[0][1]);
- }
- }
- return null;
+type SortCriterion = {
+ fieldPath: string[];
+ direction: OrderBy;
};
+const extractSortCriteria = (
+ orderBy: RecordGqlOperationOrderBy[number],
+ parentPath: string[] = [],
+): SortCriterion[] =>
+ Object.entries(orderBy).flatMap(([fieldName, value]) => {
+ const fieldPath = [...parentPath, fieldName];
+
+ return isNonEmptyString(value)
+ ? [{ fieldPath, direction: value }]
+ : extractSortCriteria(value, fieldPath);
+ });
+
export const sortCachedObjectEdges = ({
edges,
orderBy,
@@ -36,83 +35,57 @@ export const sortCachedObjectEdges = ({
}: {
edges: RecordGqlRefEdge[];
orderBy: RecordGqlOperationOrderBy;
- readCacheField: ReadFieldFunction;
+ readCacheField: FieldFunctionOptions['readField'];
}) => {
- const [orderByFieldName, orderByFieldValueOrDirection] = Object.entries(
- orderBy[0],
- )[0];
- const [orderBySubFieldName, orderBySubFieldValueOrDirection] =
- isNonEmptyString(orderByFieldValueOrDirection)
- ? []
- : Object.entries(orderByFieldValueOrDirection)[0];
+ const sortCriteria = orderBy.flatMap((criterion) =>
+ extractSortCriteria(criterion),
+ );
- // For relation fields with composite nested fields (e.g., accountOwner.name.firstName)
- const [orderBySubSubFieldNameOrDirection] =
- isNonEmptyString(orderBySubFieldValueOrDirection) ||
- !isDefined(orderBySubFieldValueOrDirection)
- ? []
- : Object.entries(orderBySubFieldValueOrDirection)[0];
+ if (sortCriteria.length === 0) {
+ return edges;
+ }
const readFieldValueToSort = (
edge: RecordGqlRefEdge,
+ fieldPath: string[],
): string | number | null => {
- const recordFromCache = edge.node;
- const fieldValue =
- readCacheField<Reference | StoreObject | string | number | null>(
- orderByFieldName,
- recordFromCache,
- ) ?? null;
- const isSubFieldFilter = isDefined(fieldValue) && !!orderBySubFieldName;
-
- if (!isSubFieldFilter) return fieldValue as string | number | null;
+ let value: Reference | StoreObject | string | number | null = edge.node;
- const subFieldValue =
- readCacheField<Reference | StoreObject | string | number | null>(
- orderBySubFieldName,
- fieldValue as Reference | StoreObject,
- ) ?? null;
+ for (const fieldName of fieldPath) {
+ if (!isDefined(value)) {
+ return null;
+ }
- // Handle 3-level nesting: relation -> composite field -> sub-field
- // e.g., accountOwner (relation) -> name (composite FULL_NAME) -> firstName
- if (
- isDefined(subFieldValue) &&
- isDefined(orderBySubSubFieldNameOrDirection)
- ) {
- const subSubFieldValue =
- readCacheField<string | number | null>(
- orderBySubSubFieldNameOrDirection,
- // At this level, subFieldValue is the composite object (not a Reference)
- subFieldValue as Reference | StoreObject,
+ value =
+ readCacheField<Reference | StoreObject | string | number | null>(
+ fieldName,
+ value as Reference | StoreObject,
) ?? null;
- return subSubFieldValue;
}
- return subFieldValue as string | number | null;
+ return value as string | number | null;
};
- const orderByDirection =
- extractOrderByDirection(orderBySubFieldValueOrDirection) ||
- extractOrderByDirection(orderByFieldValueOrDirection);
-
- if (!orderByDirection) {
- return edges;
- }
-
- const isAsc = orderByDirection.startsWith(doNotTranslate('Asc'));
- const isNullsFirst = orderByDirection.endsWith('NullsFirst');
-
return [...edges].sort((edgeA, edgeB) => {
- const fieldValueA = readFieldValueToSort(edgeA);
- const fieldValueB = readFieldValueToSort(edgeB);
-
- if (fieldValueA === null || fieldValueB === null) {
- return isNullsFirst
- ? sortNullsFirst(fieldValueA, fieldValueB)
- : sortNullsLast(fieldValueA, fieldValueB);
+ for (const { fieldPath, direction } of sortCriteria) {
+ const fieldValueA = readFieldValueToSort(edgeA, fieldPath);
+ const fieldValueB = readFieldValueToSort(edgeB, fieldPath);
+ const isAsc = direction.startsWith(doNotTranslate('Asc'));
+ const isNullsFirst = direction.endsWith('NullsFirst');
+ const comparison =
+ fieldValueA === null || fieldValueB === null
+ ? isNullsFirst
+ ? sortNullsFirst(fieldValueA, fieldValueB)
+ : sortNullsLast(fieldValueA, fieldValueB)
+ : isAsc
+ ? sortAsc(fieldValueA, fieldValueB)
+ : sortDesc(fieldValueA, fieldValueB);
+
+ if (comparison !== 0) {
+ return comparison;
+ }
}
- return isAsc
- ? sortAsc(fieldValueA, fieldValueB)
- : sortDesc(fieldValueA, fieldValueB);
+ return 0;
});
};