The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Sync relation targets with their cached lists on attach and detach (#25500)
Félix Malfaited75604b1b39
diff --git a/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/__tests__/triggerAttachAndDetachRelationOptimisticEffect.test.ts b/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/__tests__/triggerAttachAndDetachRelationOptimisticEffect.test.tsnew file mode 100644index 00000000000..4cfc840c85a--- /dev/null+++ b/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/__tests__/triggerAttachAndDetachRelationOptimisticEffect.test.ts@@ -0,0 +1,245 @@+import { gql } from '@apollo/client';++import { triggerAttachRelationOptimisticEffect } from '@/apollo/optimistic-effect/utils/triggerAttachRelationOptimisticEffect';+import { triggerDetachRelationOptimisticEffect } from '@/apollo/optimistic-effect/utils/triggerDetachRelationOptimisticEffect';+import { type ObjectRecord } from '@/object-record/types/ObjectRecord';+import { InMemoryTestingCacheInstance } from '~/testing/cache/inMemoryTestingCacheInstance';+import { getTestEnrichedObjectMetadataItemsMock } from '~/testing/utils/getTestEnrichedObjectMetadataItemsMock';++const objectMetadataItems = getTestEnrichedObjectMetadataItemsMock();++const personObjectMetadataItem = objectMetadataItems.find(+ ({ nameSingular }) => nameSingular === 'person',+)!;++const opportunityObjectMetadataItem = objectMetadataItems.find(+ ({ nameSingular }) => nameSingular === 'opportunity',+)!;++const PERSON_ID = '20202020-2d40-4e49-8df4-9c6a049190ef';+const OPPORTUNITY_ID = '20202020-83f4-4c4f-95c1-b7be9f2d36d1';+const OTHER_OPPORTUNITY_ID = '20202020-0000-4000-8000-000000000001';++const opportunityRecord: ObjectRecord = {+ __typename: 'Opportunity',+ id: OPPORTUNITY_ID,+ name: 'Opportunity',+ pointOfContactId: PERSON_ID,+};++const PEOPLE_QUERY = gql`+ query People($filter: PersonFilterInput) {+ people(filter: $filter) {+ __typename+ edges {+ __typename+ node {+ __typename+ id+ }+ cursor+ }+ totalCount+ }+ }+`;++const buildPeopleQueryVariables = (opportunityId: string) => ({+ filter: { pointOfContactForOpportunities: { id: { eq: opportunityId } } },+});++const upsertRecordsInStore = jest.fn();++const buildCache = ({+ personRecord,+ cachedPeopleIdsByOpportunityId,+}: {+ personRecord: ObjectRecord;+ cachedPeopleIdsByOpportunityId: Record<string, string[]>;+}) => {+ const { cache } = new InMemoryTestingCacheInstance({+ objectMetadataItems,+ initialRecordsInCache: [+ { objectMetadataItem: personObjectMetadataItem, records: [personRecord] },+ {+ objectMetadataItem: opportunityObjectMetadataItem,+ records: [opportunityRecord],+ },+ ],+ });++ Object.entries(cachedPeopleIdsByOpportunityId).forEach(+ ([opportunityId, peopleIds]) => {+ cache.writeQuery({+ query: PEOPLE_QUERY,+ variables: buildPeopleQueryVariables(opportunityId),+ data: {+ people: {+ __typename: 'PersonConnection',+ edges: peopleIds.map((personId) => ({+ __typename: 'PersonEdge',+ node: { __typename: 'Person', id: personId },+ cursor: '',+ })),+ totalCount: peopleIds.length,+ },+ },+ });+ },+ );++ return cache;+};++const readCachedPeople = (+ cache: ReturnType<typeof buildCache>,+ opportunityId: string,+) => {+ const result = cache.readQuery<{+ people: { edges: { node: { id: string } }[]; totalCount: number };+ }>({+ query: PEOPLE_QUERY,+ variables: buildPeopleQueryVariables(opportunityId),+ });++ return {+ peopleIds: result?.people.edges.map(({ node }) => node.id),+ totalCount: result?.people.totalCount,+ };+};++const attachOpportunityToPerson = (cache: ReturnType<typeof buildCache>) =>+ triggerAttachRelationOptimisticEffect({+ cache,+ sourceObjectNameSingular: 'opportunity',+ sourceRecord: opportunityRecord,+ targetObjectMetadataItem: personObjectMetadataItem,+ fieldNameOnTargetRecord: 'pointOfContactForOpportunities',+ targetRecordId: PERSON_ID,+ objectMetadataItems,+ objectPermissionsByObjectMetadataId: {},+ upsertRecordsInStore,+ });++const detachOpportunityFromPerson = (cache: ReturnType<typeof buildCache>) =>+ triggerDetachRelationOptimisticEffect({+ cache,+ sourceObjectNameSingular: 'opportunity',+ sourceRecordId: OPPORTUNITY_ID,+ targetObjectMetadataItem: personObjectMetadataItem,+ fieldNameOnTargetRecord: 'pointOfContactForOpportunities',+ targetRecordId: PERSON_ID,+ objectMetadataItems,+ objectPermissionsByObjectMetadataId: {},+ upsertRecordsInStore,+ });++describe('relation attach and detach optimistic effects', () => {+ beforeEach(() => {+ upsertRecordsInStore.mockClear();+ });++ it('adds the target to the cached lists it now matches', () => {+ const cache = buildCache({+ personRecord: {+ __typename: 'Person',+ id: PERSON_ID,+ pointOfContactForOpportunities: [],+ },+ cachedPeopleIdsByOpportunityId: {+ [OPPORTUNITY_ID]: [],+ [OTHER_OPPORTUNITY_ID]: [],+ },+ });++ attachOpportunityToPerson(cache);++ expect(readCachedPeople(cache, OPPORTUNITY_ID)).toEqual({+ peopleIds: [PERSON_ID],+ totalCount: 1,+ });+ expect(readCachedPeople(cache, OTHER_OPPORTUNITY_ID)).toEqual({+ peopleIds: [],+ totalCount: 0,+ });+ });++ it('adds a target fetched without the relation field to the cached lists it now matches', () => {+ const cache = buildCache({+ personRecord: { __typename: 'Person', id: PERSON_ID },+ cachedPeopleIdsByOpportunityId: { [OPPORTUNITY_ID]: [] },+ });++ attachOpportunityToPerson(cache);++ expect(readCachedPeople(cache, OPPORTUNITY_ID)).toEqual({+ peopleIds: [PERSON_ID],+ totalCount: 1,+ });+ });++ it('leaves a cached list untouched when the target was already in it', () => {+ const cache = buildCache({+ personRecord: {+ __typename: 'Person',+ id: PERSON_ID,+ pointOfContactForOpportunities: [opportunityRecord],+ },+ cachedPeopleIdsByOpportunityId: { [OPPORTUNITY_ID]: [PERSON_ID] },+ });++ attachOpportunityToPerson(cache);++ expect(readCachedPeople(cache, OPPORTUNITY_ID)).toEqual({+ peopleIds: [PERSON_ID],+ totalCount: 1,+ });+ });++ it('removes the target from the cached lists it no longer matches', () => {+ const cache = buildCache({+ personRecord: {+ __typename: 'Person',+ id: PERSON_ID,+ pointOfContactForOpportunities: [opportunityRecord],+ },+ cachedPeopleIdsByOpportunityId: { [OPPORTUNITY_ID]: [PERSON_ID] },+ });++ detachOpportunityFromPerson(cache);++ expect(readCachedPeople(cache, OPPORTUNITY_ID)).toEqual({+ peopleIds: [],+ totalCount: 0,+ });+ });++ it('removes a target cached without the relation field from the cached lists it was in', () => {+ const cache = buildCache({+ personRecord: { __typename: 'Person', id: PERSON_ID },+ cachedPeopleIdsByOpportunityId: { [OPPORTUNITY_ID]: [PERSON_ID] },+ });++ detachOpportunityFromPerson(cache);++ expect(readCachedPeople(cache, OPPORTUNITY_ID)).toEqual({+ peopleIds: [],+ totalCount: 0,+ });+ });++ it('does nothing when the target is not cached', () => {+ const cache = buildCache({+ personRecord: { __typename: 'Person', id: OTHER_OPPORTUNITY_ID },+ cachedPeopleIdsByOpportunityId: { [OPPORTUNITY_ID]: [] },+ });++ attachOpportunityToPerson(cache);++ expect(readCachedPeople(cache, OPPORTUNITY_ID)).toEqual({+ peopleIds: [],+ totalCount: 0,+ });+ expect(upsertRecordsInStore).not.toHaveBeenCalled();+ });+});diff --git a/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerAttachRelationOptimisticEffect.ts b/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerAttachRelationOptimisticEffect.tsindex 191eb06f753..6383677fb7c 100644--- a/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerAttachRelationOptimisticEffect.ts+++ b/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerAttachRelationOptimisticEffect.ts@@ -1,18 +1,27 @@import { type ApolloCache, type StoreObject } from '@apollo/client';+import { triggerUpdateRootQueriesOptimisticEffect } from '@/apollo/optimistic-effect/utils/triggerUpdateRootQueriesOptimisticEffect';import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';import { type RecordGqlRefEdge } from '@/object-record/cache/types/RecordGqlRefEdge';+import { getFieldMetadataFromGqlField } from '@/object-record/cache/utils/getFieldMetadataFromGqlField';import { getRecordFromCache } from '@/object-record/cache/utils/getRecordFromCache';import { getRecordFromRecordNode } from '@/object-record/cache/utils/getRecordFromRecordNode';+import { getRecordNodeFromRecord } from '@/object-record/cache/utils/getRecordNodeFromRecord';import { isObjectRecordConnectionWithRefs } from '@/object-record/cache/utils/isObjectRecordConnectionWithRefs';+import { type RecordGqlNode } from '@/object-record/graphql/types/RecordGqlNode';import { type ObjectRecord } from '@/object-record/types/ObjectRecord';-import { type ObjectPermissions } from 'twenty-shared/types';-import { capitalize, isDefined } from 'twenty-shared/utils';+import { type ObjectPermissions, RelationType } from 'twenty-shared/types';+import {+ capitalize,+ getConnectionTypename,+ getEdgeTypename,+ isDefined,+} from 'twenty-shared/utils';export const triggerAttachRelationOptimisticEffect = ({cache,sourceObjectNameSingular,- sourceRecordId,+ sourceRecord,targetObjectMetadataItem,fieldNameOnTargetRecord,targetRecordId,@@ -22,11 +31,8 @@ export const triggerAttachRelationOptimisticEffect = ({}: {cache: ApolloCache;sourceObjectNameSingular: string;- sourceRecordId: string;- targetObjectMetadataItem: Pick<- EnrichedObjectMetadataItem,- 'fields' | 'nameSingular' | 'id' | 'readableFields'- >;+ sourceRecord: RecordGqlNode;+ targetObjectMetadataItem: EnrichedObjectMetadataItem;fieldNameOnTargetRecord: string;targetRecordId: string;objectMetadataItems: EnrichedObjectMetadataItem[];@@ -36,6 +42,7 @@ export const triggerAttachRelationOptimisticEffect = ({>;upsertRecordsInStore: (props: { partialRecords: ObjectRecord[] }) => void;}) => {+ const sourceRecordId = sourceRecord.id;const sourceRecordTypeName = capitalize(sourceObjectNameSingular);const targetRecordTypeName = capitalize(targetObjectMetadataItem.nameSingular,@@ -123,4 +130,75 @@ export const triggerAttachRelationOptimisticEffect = ({}upsertRecordsInStore({ partialRecords: [newCachedRecord] });++ const newCachedRecordNode = getRecordNodeFromRecord({+ objectMetadataItems,+ objectMetadataItem: targetObjectMetadataItem,+ record: newCachedRecord,+ computeReferences: false,+ });++ if (!isDefined(newCachedRecordNode)) {+ return;+ }++ triggerUpdateRootQueriesOptimisticEffect({+ cache,+ objectMetadataItem: targetObjectMetadataItem,+ objectMetadataItems,+ updatedRecords: [+ isDefined(newCachedRecordNode[fieldNameOnTargetRecord])+ ? newCachedRecordNode+ : {+ ...newCachedRecordNode,+ [fieldNameOnTargetRecord]: buildRelationValueFromSourceRecord({+ sourceObjectNameSingular,+ sourceRecord,+ targetObjectMetadataItem,+ fieldNameOnTargetRecord,+ }),+ },+ ],+ });+};++// A target fetched without the relation field cannot be modified in the cache,+// but it is still attached to the source record, which is all the target's+// cached lists need to know to place it.+const buildRelationValueFromSourceRecord = ({+ sourceObjectNameSingular,+ sourceRecord,+ targetObjectMetadataItem,+ fieldNameOnTargetRecord,+}: {+ sourceObjectNameSingular: string;+ sourceRecord: RecordGqlNode;+ targetObjectMetadataItem: EnrichedObjectMetadataItem;+ fieldNameOnTargetRecord: string;+}) => {+ const fieldMetadataItemOnTargetRecord = getFieldMetadataFromGqlField({+ objectMetadataItem: targetObjectMetadataItem,+ gqlField: fieldNameOnTargetRecord,+ });++ const isToManyRelation =+ fieldMetadataItemOnTargetRecord?.relation?.type ===+ RelationType.ONE_TO_MANY ||+ fieldMetadataItemOnTargetRecord?.settings?.relationType ===+ RelationType.ONE_TO_MANY;++ if (!isToManyRelation) {+ return sourceRecord;+ }++ return {+ __typename: getConnectionTypename(sourceObjectNameSingular),+ edges: [+ {+ __typename: getEdgeTypename(sourceObjectNameSingular),+ node: sourceRecord,+ cursor: '',+ },+ ],+ };};diff --git a/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerDetachRelationOptimisticEffect.ts b/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerDetachRelationOptimisticEffect.tsindex e2319084c16..67be2e2289b 100644--- a/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerDetachRelationOptimisticEffect.ts+++ b/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerDetachRelationOptimisticEffect.ts@@ -1,7 +1,9 @@import { type ApolloCache, type StoreObject } from '@apollo/client';+import { triggerUpdateRootQueriesOptimisticEffect } from '@/apollo/optimistic-effect/utils/triggerUpdateRootQueriesOptimisticEffect';import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';import { getRecordFromCache } from '@/object-record/cache/utils/getRecordFromCache';+import { getRecordNodeFromRecord } from '@/object-record/cache/utils/getRecordNodeFromRecord';import { isObjectRecordConnectionWithRefs } from '@/object-record/cache/utils/isObjectRecordConnectionWithRefs';import { type ObjectRecord } from '@/object-record/types/ObjectRecord';import { type ObjectPermissions } from 'twenty-shared/types';@@ -21,10 +23,7 @@ export const triggerDetachRelationOptimisticEffect = ({cache: ApolloCache;sourceObjectNameSingular: string;sourceRecordId: string;- targetObjectMetadataItem: Pick<- EnrichedObjectMetadataItem,- 'fields' | 'nameSingular' | 'id' | 'readableFields'- >;+ targetObjectMetadataItem: EnrichedObjectMetadataItem;fieldNameOnTargetRecord: string;targetRecordId: string;objectMetadataItems: EnrichedObjectMetadataItem[];@@ -90,4 +89,22 @@ export const triggerDetachRelationOptimisticEffect = ({}upsertRecordsInStore({ partialRecords: [newCachedRecord] });++ const newCachedRecordNode = getRecordNodeFromRecord({+ objectMetadataItems,+ objectMetadataItem: targetObjectMetadataItem,+ record: newCachedRecord,+ computeReferences: false,+ });++ if (!isDefined(newCachedRecordNode)) {+ return;+ }++ triggerUpdateRootQueriesOptimisticEffect({+ cache,+ objectMetadataItem: targetObjectMetadataItem,+ objectMetadataItems,+ updatedRecords: [newCachedRecordNode],+ });};diff --git a/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerUpdateRecordOptimisticEffect.ts b/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerUpdateRecordOptimisticEffect.tsindex ce63dde76b1..0e86ea9747c 100644--- a/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerUpdateRecordOptimisticEffect.ts+++ b/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerUpdateRecordOptimisticEffect.ts@@ -1,20 +1,12 @@-import { type ApolloCache, type StoreObject } from '@apollo/client';+import { type ApolloCache } from '@apollo/client';-import { triggerUpdateGroupByQueriesOptimisticEffect } from '@/apollo/optimistic-effect/group-by/utils/triggerUpdateGroupByQueriesOptimisticEffect';-import { sortCachedObjectEdges } from '@/apollo/optimistic-effect/utils/sortCachedObjectEdges';import { triggerUpdateRelationsOptimisticEffect } from '@/apollo/optimistic-effect/utils/triggerUpdateRelationsOptimisticEffect';-import { type CachedObjectRecordQueryVariables } from '@/apollo/types/CachedObjectRecordQueryVariables';+import { triggerUpdateRootQueriesOptimisticEffect } from '@/apollo/optimistic-effect/utils/triggerUpdateRootQueriesOptimisticEffect';import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';-import { type RecordGqlRefEdge } from '@/object-record/cache/types/RecordGqlRefEdge';-import { isObjectRecordConnectionWithRefs } from '@/object-record/cache/utils/isObjectRecordConnectionWithRefs';import { type RecordGqlNode } from '@/object-record/graphql/types/RecordGqlNode';-import { isRecordMatchingFilter } from '@/object-record/record-filter/utils/isRecordMatchingFilter';import { type ObjectRecord } from '@/object-record/types/ObjectRecord';import { type ObjectPermissions } from 'twenty-shared/types';-import { getEdgeTypename, isDefined } from 'twenty-shared/utils';-import { parseApolloStoreFieldName } from '~/utils/parseApolloStoreFieldName';-// TODO: add extensive unit tests for this function-// That will also serve as documentation+export const triggerUpdateRecordOptimisticEffect = ({cache,objectMetadataItem,@@ -45,126 +37,10 @@ export const triggerUpdateRecordOptimisticEffect = ({upsertRecordsInStore,});- cache.modify<StoreObject>({- fields: {- [objectMetadataItem.namePlural]: (- rootQueryCachedResponse,- { readField, storeFieldName, toReference },- ) => {- const shouldSkip = !isObjectRecordConnectionWithRefs(- objectMetadataItem.nameSingular,- rootQueryCachedResponse,- );-- if (shouldSkip) {- return rootQueryCachedResponse;- }-- const rootQueryConnection = rootQueryCachedResponse;-- const { fieldVariables: rootQueryVariables } =- parseApolloStoreFieldName<CachedObjectRecordQueryVariables>(- storeFieldName,- );-- const rootQueryCurrentEdges =- readField<RecordGqlRefEdge[]>('edges', rootQueryConnection) ?? [];-- let rootQueryNextEdges = [...rootQueryCurrentEdges];-- const rootQueryFilter = rootQueryVariables?.filter;- const rootQueryOrderBy = rootQueryVariables?.orderBy;-- const updatedRecordMatchesThisRootQueryFilter = isRecordMatchingFilter({- record: updatedRecord,- filter: rootQueryFilter ?? {},- objectMetadataItem,- objectMetadataItems,- });-- const currentRecordIndexInRootQueryEdges = isRecordMatchingFilter({- record: currentRecord,- filter: rootQueryFilter ?? {},- objectMetadataItem,- objectMetadataItems,- });-- const totalCount = readField<number | undefined>(- 'totalCount',- rootQueryConnection,- );-- const newTotalCount = isDefined(totalCount)- ? Math.max(- totalCount +- (updatedRecordMatchesThisRootQueryFilter ? 1 : 0) +- (currentRecordIndexInRootQueryEdges ? -1 : 0),- 0,- )- : undefined;-- const updatedRecordIndexInRootQueryEdges =- rootQueryCurrentEdges.findIndex(- (cachedEdge) =>- readField('id', cachedEdge.node) === updatedRecord.id,- );-- const updatedRecordFoundInRootQueryEdges =- updatedRecordIndexInRootQueryEdges > -1;-- const updatedRecordShouldBeAddedToRootQueryEdges =- updatedRecordMatchesThisRootQueryFilter &&- !updatedRecordFoundInRootQueryEdges;-- const updatedRecordShouldBeRemovedFromRootQueryEdges =- !updatedRecordMatchesThisRootQueryFilter &&- updatedRecordFoundInRootQueryEdges;-- if (updatedRecordShouldBeAddedToRootQueryEdges) {- const updatedRecordNodeReference = toReference(updatedRecord);-- if (isDefined(updatedRecordNodeReference)) {- rootQueryNextEdges.push({- __typename: getEdgeTypename(objectMetadataItem.nameSingular),- node: updatedRecordNodeReference,- cursor: '',- });- }- }-- if (updatedRecordShouldBeRemovedFromRootQueryEdges) {- rootQueryNextEdges.splice(updatedRecordIndexInRootQueryEdges, 1);- }-- const rootQueryNextEdgesShouldBeSorted = isDefined(rootQueryOrderBy);-- if (- rootQueryNextEdgesShouldBeSorted &&- Array.isArray(rootQueryOrderBy) &&- rootQueryOrderBy.length > 0- ) {- rootQueryNextEdges = sortCachedObjectEdges({- edges: rootQueryNextEdges,- orderBy: rootQueryOrderBy,- readCacheField: readField,- });- }-- return {- ...rootQueryConnection,- edges: rootQueryNextEdges,- totalCount: newTotalCount,- };- },- },- });-- triggerUpdateGroupByQueriesOptimisticEffect({+ triggerUpdateRootQueriesOptimisticEffect({cache,objectMetadataItem,objectMetadataItems,- operation: 'update',- records: [updatedRecord],- shouldMatchRootQueryFilter: true,+ updatedRecords: [updatedRecord],});};diff --git a/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerUpdateRecordOptimisticEffectByBatch.ts b/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerUpdateRecordOptimisticEffectByBatch.tsindex ce202ad7958..b309e677746 100644--- a/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerUpdateRecordOptimisticEffectByBatch.ts+++ b/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerUpdateRecordOptimisticEffectByBatch.ts@@ -1,21 +1,12 @@-import { type ApolloCache, type StoreObject } from '@apollo/client';+import { type ApolloCache } from '@apollo/client';-import { triggerUpdateGroupByQueriesOptimisticEffect } from '@/apollo/optimistic-effect/group-by/utils/triggerUpdateGroupByQueriesOptimisticEffect';-import { sortCachedObjectEdges } from '@/apollo/optimistic-effect/utils/sortCachedObjectEdges';import { triggerUpdateRelationsOptimisticEffect } from '@/apollo/optimistic-effect/utils/triggerUpdateRelationsOptimisticEffect';-import { type CachedObjectRecordQueryVariables } from '@/apollo/types/CachedObjectRecordQueryVariables';+import { triggerUpdateRootQueriesOptimisticEffect } from '@/apollo/optimistic-effect/utils/triggerUpdateRootQueriesOptimisticEffect';import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';-import { type RecordGqlRefEdge } from '@/object-record/cache/types/RecordGqlRefEdge';-import { isObjectRecordConnectionWithRefs } from '@/object-record/cache/utils/isObjectRecordConnectionWithRefs';import { type RecordGqlNode } from '@/object-record/graphql/types/RecordGqlNode';-import { isRecordMatchingFilter } from '@/object-record/record-filter/utils/isRecordMatchingFilter';import { type ObjectRecord } from '@/object-record/types/ObjectRecord';import { type ObjectPermissions } from 'twenty-shared/types';-import { getEdgeTypename, isDefined } from 'twenty-shared/utils';-import { parseApolloStoreFieldName } from '~/utils/parseApolloStoreFieldName';-// TODO: add extensive unit tests for this function-// That will also serve as documentationexport const triggerUpdateRecordOptimisticEffectByBatch = ({cache,objectMetadataItem,@@ -48,107 +39,10 @@ export const triggerUpdateRecordOptimisticEffectByBatch = ({});}- cache.modify<StoreObject>({- fields: {- [objectMetadataItem.namePlural]: (- rootQueryCachedResponse,- { readField, storeFieldName, toReference },- ) => {- const shouldSkip = !isObjectRecordConnectionWithRefs(- objectMetadataItem.nameSingular,- rootQueryCachedResponse,- );-- if (shouldSkip) {- return rootQueryCachedResponse;- }-- const rootQueryConnection = rootQueryCachedResponse;-- const { fieldVariables: rootQueryVariables } =- parseApolloStoreFieldName<CachedObjectRecordQueryVariables>(- storeFieldName,- );-- const rootQueryCurrentEdges =- readField<RecordGqlRefEdge[]>('edges', rootQueryConnection) ?? [];-- let rootQueryNextEdges = [...rootQueryCurrentEdges];-- const rootQueryFilter = rootQueryVariables?.filter;- const rootQueryOrderBy = rootQueryVariables?.orderBy;-- for (const updatedRecord of updatedRecords) {- const updatedRecordMatchesThisRootQueryFilter =- isRecordMatchingFilter({- record: updatedRecord,- filter: rootQueryFilter ?? {},- objectMetadataItem,- objectMetadataItems,- });-- const updatedRecordFoundInRootQueryEdges = isDefined(- rootQueryCurrentEdges.find(- (cachedEdge) =>- readField('id', cachedEdge.node) === updatedRecord.id,- ),- );-- const updatedRecordShouldBeAddedToRootQueryEdges =- updatedRecordMatchesThisRootQueryFilter &&- !updatedRecordFoundInRootQueryEdges;-- const updatedRecordShouldBeRemovedFromRootQueryEdges =- !updatedRecordMatchesThisRootQueryFilter &&- updatedRecordFoundInRootQueryEdges;-- if (updatedRecordShouldBeAddedToRootQueryEdges) {- const updatedRecordNodeReference = toReference(updatedRecord);-- if (isDefined(updatedRecordNodeReference)) {- rootQueryNextEdges.push({- __typename: getEdgeTypename(objectMetadataItem.nameSingular),- node: updatedRecordNodeReference,- cursor: '',- });- }- }-- if (updatedRecordShouldBeRemovedFromRootQueryEdges) {- rootQueryNextEdges = rootQueryNextEdges.filter(- (cachedEdge) =>- readField('id', cachedEdge.node) !== updatedRecord.id,- );- }- }-- const rootQueryNextEdgesShouldBeSorted = isDefined(rootQueryOrderBy);-- if (- rootQueryNextEdgesShouldBeSorted &&- Object.getOwnPropertyNames(rootQueryOrderBy).length > 0- ) {- rootQueryNextEdges = sortCachedObjectEdges({- edges: rootQueryNextEdges,- orderBy: rootQueryOrderBy,- readCacheField: readField,- });- }-- return {- ...rootQueryConnection,- edges: rootQueryNextEdges,- };- },- },- });-- triggerUpdateGroupByQueriesOptimisticEffect({+ triggerUpdateRootQueriesOptimisticEffect({cache,objectMetadataItem,objectMetadataItems,- operation: 'update',- records: updatedRecords,- shouldMatchRootQueryFilter: true,+ updatedRecords,});};diff --git a/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerUpdateRelationsOptimisticEffect.ts b/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerUpdateRelationsOptimisticEffect.tsindex d40792c4b2d..7ace5572223 100644--- a/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerUpdateRelationsOptimisticEffect.ts+++ b/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerUpdateRelationsOptimisticEffect.ts@@ -250,7 +250,7 @@ const triggerUpdateRelationOptimisticEffect = ({triggerAttachRelationOptimisticEffect({cache,sourceObjectNameSingular: sourceObjectMetadataItem.nameSingular,- sourceRecordId: updatedSourceRecord.id,+ sourceRecord: updatedSourceRecord,fieldNameOnTargetRecord: gqlFieldNameOnTargetRecord,targetObjectMetadataItem: fullTargetObjectMetadataItem,targetRecordId: targetRecordToAttachTo.id,@@ -405,7 +405,7 @@ const triggerUpdateMorphRelationOptimisticEffect = ({triggerAttachRelationOptimisticEffect({cache,sourceObjectNameSingular: sourceObjectMetadataItem.nameSingular,- sourceRecordId: updatedSourceRecord.id,+ sourceRecord: updatedSourceRecord,fieldNameOnTargetRecord: targetFieldMetadata.name,targetObjectMetadataItem: fullTargetObjectMetadataItem,objectMetadataItems,diff --git a/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerUpdateRootQueriesOptimisticEffect.ts b/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerUpdateRootQueriesOptimisticEffect.tsnew file mode 100644index 00000000000..da2d8762a82--- /dev/null+++ b/packages/twenty-front/src/modules/apollo/optimistic-effect/utils/triggerUpdateRootQueriesOptimisticEffect.ts@@ -0,0 +1,130 @@+import { type ApolloCache, type StoreObject } from '@apollo/client';++import { triggerUpdateGroupByQueriesOptimisticEffect } from '@/apollo/optimistic-effect/group-by/utils/triggerUpdateGroupByQueriesOptimisticEffect';+import { sortCachedObjectEdges } from '@/apollo/optimistic-effect/utils/sortCachedObjectEdges';+import { type CachedObjectRecordQueryVariables } from '@/apollo/types/CachedObjectRecordQueryVariables';+import { encodeCursor } from '@/apollo/utils/encodeCursor';+import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';+import { type RecordGqlRefEdge } from '@/object-record/cache/types/RecordGqlRefEdge';+import { isObjectRecordConnectionWithRefs } from '@/object-record/cache/utils/isObjectRecordConnectionWithRefs';+import { type RecordGqlNode } from '@/object-record/graphql/types/RecordGqlNode';+import { isRecordMatchingFilter } from '@/object-record/record-filter/utils/isRecordMatchingFilter';+import { getEdgeTypename, isDefined } from 'twenty-shared/utils';+import { parseApolloStoreFieldName } from '~/utils/parseApolloStoreFieldName';++export const triggerUpdateRootQueriesOptimisticEffect = ({+ cache,+ objectMetadataItem,+ objectMetadataItems,+ updatedRecords,+}: {+ cache: ApolloCache;+ objectMetadataItem: EnrichedObjectMetadataItem;+ objectMetadataItems: EnrichedObjectMetadataItem[];+ updatedRecords: RecordGqlNode[];+}) => {+ cache.modify<StoreObject>({+ fields: {+ [objectMetadataItem.namePlural]: (+ rootQueryCachedResponse,+ { readField, storeFieldName, toReference },+ ) => {+ if (+ !isObjectRecordConnectionWithRefs(+ objectMetadataItem.nameSingular,+ rootQueryCachedResponse,+ )+ ) {+ return rootQueryCachedResponse;+ }++ const rootQueryConnection = rootQueryCachedResponse;++ const { fieldVariables: rootQueryVariables } =+ parseApolloStoreFieldName<CachedObjectRecordQueryVariables>(+ storeFieldName,+ );++ const rootQueryFilter = rootQueryVariables?.filter ?? {};+ const rootQueryOrderBy = rootQueryVariables?.orderBy;++ const isMatchingRootQueryFilter = (record: RecordGqlNode) =>+ isRecordMatchingFilter({+ record,+ filter: rootQueryFilter,+ objectMetadataItem,+ objectMetadataItems,+ });++ // The count follows the edges rather than the filter alone: the same+ // change can reach a list several times (a record update, then the+ // detach of a relation it cascaded to), and only an edge that actually+ // comes or goes may move the count.+ let rootQueryNextEdges = [+ ...(readField<RecordGqlRefEdge[]>('edges', rootQueryConnection) ??+ []),+ ];+ let totalCountDelta = 0;++ for (const updatedRecord of updatedRecords) {+ const updatedRecordIndexInRootQueryEdges =+ rootQueryNextEdges.findIndex(+ (cachedEdge) =>+ readField('id', cachedEdge.node) === updatedRecord.id,+ );+ const updatedRecordFoundInRootQueryEdges =+ updatedRecordIndexInRootQueryEdges > -1;+ const updatedRecordMatches = isMatchingRootQueryFilter(updatedRecord);++ if (updatedRecordMatches && !updatedRecordFoundInRootQueryEdges) {+ const updatedRecordNodeReference = toReference(updatedRecord);++ if (isDefined(updatedRecordNodeReference)) {+ rootQueryNextEdges.push({+ __typename: getEdgeTypename(objectMetadataItem.nameSingular),+ node: updatedRecordNodeReference,+ cursor: encodeCursor(updatedRecord),+ });+ totalCountDelta += 1;+ }+ }++ if (!updatedRecordMatches && updatedRecordFoundInRootQueryEdges) {+ rootQueryNextEdges.splice(updatedRecordIndexInRootQueryEdges, 1);+ totalCountDelta -= 1;+ }+ }++ if (Array.isArray(rootQueryOrderBy) && rootQueryOrderBy.length > 0) {+ rootQueryNextEdges = sortCachedObjectEdges({+ edges: rootQueryNextEdges,+ orderBy: rootQueryOrderBy,+ readCacheField: readField,+ });+ }++ const totalCount = readField<number | undefined>(+ 'totalCount',+ rootQueryConnection,+ );++ return {+ ...rootQueryConnection,+ edges: rootQueryNextEdges,+ ...(isDefined(totalCount) && {+ totalCount: Math.max(totalCount + totalCountDelta, 0),+ }),+ };+ },+ },+ });++ triggerUpdateGroupByQueriesOptimisticEffect({+ cache,+ objectMetadataItem,+ objectMetadataItems,+ operation: 'update',+ records: updatedRecords,+ shouldMatchRootQueryFilter: true,+ });+};diff --git a/packages/twenty-front/src/modules/object-record/record-filter/utils/__tests__/isRecordMatchingFilter.test.ts b/packages/twenty-front/src/modules/object-record/record-filter/utils/__tests__/isRecordMatchingFilter.test.tsindex 206172964f9..55015929b2a 100644--- a/packages/twenty-front/src/modules/object-record/record-filter/utils/__tests__/isRecordMatchingFilter.test.ts+++ b/packages/twenty-front/src/modules/object-record/record-filter/utils/__tests__/isRecordMatchingFilter.test.ts@@ -776,6 +776,100 @@ describe('isRecordMatchingFilter', () => {).toBe(false);});+ it('matches a to-many relation held as a connection, the way records reach the optimistic effects', () => {+ const personMockObjectMetadataItem = objectMetadataItems.find(+ (item) => item.nameSingular === 'person',+ )!;++ const filter = {+ pointOfContactForOpportunities: {+ id: { eq: opportunityWithPointOfContact.id },+ },+ } as RecordGqlOperationFilter;++ const buildPersonWithOpportunityConnection = (+ opportunityIds: string[],+ ) => ({+ id: personId,+ pointOfContactForOpportunities: {+ __typename: 'OpportunityConnection',+ edges: opportunityIds.map((id) => ({+ __typename: 'OpportunityEdge',+ node: { id },+ })),+ },+ });++ expect(+ isRecordMatchingFilter({+ record: buildPersonWithOpportunityConnection([+ '20202020-0000-4000-8000-000000000001',+ opportunityWithPointOfContact.id,+ ]),+ filter,+ objectMetadataItem: personMockObjectMetadataItem,+ objectMetadataItems,+ }),+ ).toBe(true);++ expect(+ isRecordMatchingFilter({+ record: buildPersonWithOpportunityConnection([]),+ filter,+ objectMetadataItem: personMockObjectMetadataItem,+ objectMetadataItems,+ }),+ ).toBe(false);++ expect(+ isRecordMatchingFilter({+ record: { id: personId },+ filter,+ objectMetadataItem: personMockObjectMetadataItem,+ objectMetadataItems,+ }),+ ).toBe(false);+ });++ it('reads a join column filter from the related record when the column is not loaded', () => {+ const personMockObjectMetadataItem = objectMetadataItems.find(+ (item) => item.nameSingular === 'person',+ )!;++ const filter = {+ pointOfContactForOpportunities: {+ pointOfContactId: { in: [personId] },+ },+ } as RecordGqlOperationFilter;++ const buildPersonWithOpportunityPointOfContact = (+ pointOfContact: { id: string } | null,+ ) => ({+ id: personId,+ pointOfContactForOpportunities: [+ { id: opportunityWithPointOfContact.id, pointOfContact },+ ],+ });++ expect(+ isRecordMatchingFilter({+ record: buildPersonWithOpportunityPointOfContact({ id: personId }),+ filter,+ objectMetadataItem: personMockObjectMetadataItem,+ objectMetadataItems,+ }),+ ).toBe(true);++ expect(+ isRecordMatchingFilter({+ record: buildPersonWithOpportunityPointOfContact(null),+ filter,+ objectMetadataItem: personMockObjectMetadataItem,+ objectMetadataItems,+ }),+ ).toBe(false);+ });+it('evaluates composite conditions against the related record', () => {const filter = {pointOfContact: {diff --git a/packages/twenty-front/src/modules/object-record/record-filter/utils/isRecordMatchingFilter.ts b/packages/twenty-front/src/modules/object-record/record-filter/utils/isRecordMatchingFilter.tsindex 30b0b5a0f59..b34b0079c1e 100644--- a/packages/twenty-front/src/modules/object-record/record-filter/utils/isRecordMatchingFilter.ts+++ b/packages/twenty-front/src/modules/object-record/record-filter/utils/isRecordMatchingFilter.ts@@ -51,6 +51,7 @@ import {import { type FieldMetadataItem } from '@/object-metadata/types/FieldMetadataItem';import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';import { computePossibleMorphGqlFieldForFieldName } from '@/object-record/cache/utils/computePossibleMorphGqlFieldForFieldName';+import { isObjectRecordConnection } from '@/object-record/cache/utils/isObjectRecordConnection';const isLeafFilter = (filter: RecordGqlOperationFilter,@@ -115,6 +116,26 @@ const isNestedRelationFilter = (isObject(filterValue) &&Object.keys(filterValue).some((key) => !UUID_FILTER_OPERATOR_KEYS.has(key));+// A record fetched through a relation often carries the related record+// without its join column, like { list: { id } } and no listId.+const getJoinColumnValue = ({+ record,+ joinColumnName,+}: {+ record: Record<string, any>;+ joinColumnName: string;+}) => {+ if (record[joinColumnName] !== undefined) {+ return record[joinColumnName];+ }++ const relationRecord = record[joinColumnName.slice(0, -'Id'.length)];++ return isObject(relationRecord)+ ? (relationRecord.id ?? null)+ : relationRecord;+};+const isRecordMatchingNestedRelationFilter = ({relationRecord,nestedFilter,@@ -161,14 +182,37 @@ const isRecordMatchingNestedRelationFilter = ({// A to-many relation matches when any of its loaded records does, the way// the backend EXISTS does.+ return getLoadedRelationRecords({+ relationRecord,+ relationTargetObjectNameSingular:+ relationTargetObjectMetadataItem.nameSingular,+ }).some(+ (relatedRecord) =>+ isObject(relatedRecord) && isRecordMatchingNestedFilter(relatedRecord),+ );+};++// A relation value is a single record for a to-one relation, and for a to-many+// relation either an array of records or a connection, depending on whether+// the record comes from the store or from a GraphQL response.+const getLoadedRelationRecords = ({+ relationRecord,+ relationTargetObjectNameSingular,+}: {+ relationRecord: object;+ relationTargetObjectNameSingular: string;+}): unknown[] => {if (Array.isArray(relationRecord)) {- return relationRecord.some(- (relatedRecord) =>- isObject(relatedRecord) && isRecordMatchingNestedFilter(relatedRecord),- );+ return relationRecord;+ }++ if (+ isObjectRecordConnection(relationTargetObjectNameSingular, relationRecord)+ ) {+ return relationRecord.edges?.map((edge) => edge.node) ?? [];}- return isRecordMatchingNestedFilter(relationRecord);+ return [relationRecord];};export const isRecordMatchingFilter = ({@@ -523,7 +567,7 @@ export const isRecordMatchingFilter = ({if (isJoinColumn) {return isMatchingUUIDFilter({uuidFilter: filterValue as UUIDFilter,- value: record[filterKey],+ value: getJoinColumnValue({ record, joinColumnName: filterKey }),});}diff --git a/packages/twenty-front/src/modules/object-record/record-index/hooks/useRecordIndexTableQuery.ts b/packages/twenty-front/src/modules/object-record/record-index/hooks/useRecordIndexTableQuery.tsindex 145f38515c3..60427ea0205 100644--- a/packages/twenty-front/src/modules/object-record/record-index/hooks/useRecordIndexTableQuery.ts+++ b/packages/twenty-front/src/modules/object-record/record-index/hooks/useRecordIndexTableQuery.ts@@ -22,7 +22,6 @@ export const useRecordIndexTableQuery = (objectNameSingular: string) => {error,totalCount,fetchMoreRecords,- refetch,} = useFindManyRecords({...params,recordGqlFields,@@ -36,6 +35,5 @@ export const useRecordIndexTableQuery = (objectNameSingular: string) => {queryIdentifier,totalCount,fetchMoreRecords,- refetch,};};diff --git a/packages/twenty-front/src/modules/object-record/record-table/record-table-body/components/RecordTableRecordGroupBodyEffects.tsx b/packages/twenty-front/src/modules/object-record/record-table/record-table-body/components/RecordTableRecordGroupBodyEffects.tsxindex ca09728b9fa..ff0455f019f 100644--- a/packages/twenty-front/src/modules/object-record/record-table/record-table-body/components/RecordTableRecordGroupBodyEffects.tsx+++ b/packages/twenty-front/src/modules/object-record/record-table/record-table-body/components/RecordTableRecordGroupBodyEffects.tsx@@ -1,25 +1,16 @@import { RecordGroupContext } from '@/object-record/record-group/states/context/RecordGroupContext';import { recordGroupIdsComponentState } from '@/object-record/record-group/states/recordGroupIdsComponentState';-import { RecordTableWidgetContext } from '@/object-record/record-table-widget/contexts/RecordTableWidgetContext';import { RecordTableRecordGroupBodyEffect } from '@/object-record/record-table/record-table-body/components/RecordTableRecordGroupBodyEffect';-import { RecordTableRecordGroupJunctionDataChangedEffect } from '@/object-record/record-table/record-table-body/components/RecordTableRecordGroupJunctionDataChangedEffect';import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';-import { useContext } from 'react';-import { isDefined } from 'twenty-shared/utils';export const RecordTableRecordGroupBodyEffects = () => {const recordGroupIds = useAtomComponentStateValue(recordGroupIdsComponentState,);- const isJunctionTable = isDefined(- useContext(RecordTableWidgetContext)?.junctionCreateThrough,- );-return recordGroupIds.map((recordGroupId) => (<RecordGroupContext.Provider key={recordGroupId} value={{ recordGroupId }}><RecordTableRecordGroupBodyEffect />- {isJunctionTable && <RecordTableRecordGroupJunctionDataChangedEffect />}</RecordGroupContext.Provider>));};diff --git a/packages/twenty-front/src/modules/object-record/record-table/record-table-body/components/RecordTableRecordGroupJunctionDataChangedEffect.tsx b/packages/twenty-front/src/modules/object-record/record-table/record-table-body/components/RecordTableRecordGroupJunctionDataChangedEffect.tsxdeleted file mode 100644index 359ff357f73..00000000000--- a/packages/twenty-front/src/modules/object-record/record-table/record-table-body/components/RecordTableRecordGroupJunctionDataChangedEffect.tsx+++ /dev/null@@ -1,29 +0,0 @@-import { useRecordIndexTableQuery } from '@/object-record/record-index/hooks/useRecordIndexTableQuery';-import { useListenToJunctionRecordOperation } from '@/object-record/record-table-widget/hooks/useListenToJunctionRecordOperation';-import { useRecordTableContextOrThrow } from '@/object-record/record-table/contexts/RecordTableContext';-import { SSE_TABLE_DEBOUNCE_TIME_IN_MS_TO_AVOID_SSE_OWN_EVENTS_RACE_CONDITION } from '@/object-record/record-table/virtualization/constants/SseTableDebounceTimeInMsToAvoidSseOwnEventsRaceCondition';-import { useDebouncedCallback } from 'use-debounce';--// Grouped tables are not virtualized: their rows come from the group query,-// which the junction write does not touch, so the query is refetched.-export const RecordTableRecordGroupJunctionDataChangedEffect = () => {- const { objectNameSingular } = useRecordTableContextOrThrow();-- const { refetch } = useRecordIndexTableQuery(objectNameSingular);-- const debouncedRefetch = useDebouncedCallback(- () => {- refetch();- },- SSE_TABLE_DEBOUNCE_TIME_IN_MS_TO_AVOID_SSE_OWN_EVENTS_RACE_CONDITION,- {- leading: false,- },- );-- useListenToJunctionRecordOperation({- onJunctionRecordOperation: debouncedRefetch,- });-- return <></>;-};