Skip to content

The open alternative to Salesforce, designed for AI.

Link company email threads and calendar events from a record (#28551)

Félix Malfait3901111bc048
diff --git a/packages/twenty-front/src/generated/graphql.ts b/packages/twenty-front/src/generated/graphql.ts
index d2e4e9b3858..5911c8231ce 100644
--- a/packages/twenty-front/src/generated/graphql.ts
+++ b/packages/twenty-front/src/generated/graphql.ts
@@ -577,6 +577,8 @@ export type Query = {
getTimelineThreadsFromPersonId: TimelineThreadsWithTotal;
isMaintenanceModeBannerDismissed: Scalars['Boolean']['output'];
search: SearchResultConnection;
+ searchTimelineCalendarEvents: TimelineCalendarEventSearchResult;
+ searchTimelineThreads: TimelineThreadSearchResult;
workflowStepConnectedAccountHandle?: Maybe<ConnectedAccountHandleDto>;
};
@@ -693,6 +695,20 @@ export type QuerySearchArgs = {
};
+export type QuerySearchTimelineCalendarEventsArgs = {
+ objectNameSingular: Scalars['String']['input'];
+ recordId: Scalars['UUID']['input'];
+ searchInput?: InputMaybe<Scalars['String']['input']>;
+};
+
+
+export type QuerySearchTimelineThreadsArgs = {
+ objectNameSingular: Scalars['String']['input'];
+ recordId: Scalars['UUID']['input'];
+ searchInput?: InputMaybe<Scalars['String']['input']>;
+};
+
+
export type QueryWorkflowStepConnectedAccountHandleArgs = {
connectedAccountId: Scalars['UUID']['input'];
};
@@ -813,6 +829,12 @@ export type TimelineCalendarEventParticipant = {
workspaceMemberId?: Maybe<Scalars['UUID']['output']>;
};
+export type TimelineCalendarEventSearchResult = {
+ __typename?: 'TimelineCalendarEventSearchResult';
+ otherTimelineCalendarEvents: Array<TimelineCalendarEvent>;
+ recordTimelineCalendarEvents: Array<TimelineCalendarEvent>;
+};
+
export type TimelineCalendarEventsWithTotal = {
__typename?: 'TimelineCalendarEventsWithTotal';
relatedPersonIds: Array<Scalars['UUID']['output']>;
@@ -846,6 +868,12 @@ export type TimelineThreadParticipant = {
workspaceMemberId?: Maybe<Scalars['UUID']['output']>;
};
+export type TimelineThreadSearchResult = {
+ __typename?: 'TimelineThreadSearchResult';
+ otherTimelineThreads: Array<TimelineThread>;
+ recordTimelineThreads: Array<TimelineThread>;
+};
+
export type TimelineThreadsWithTotal = {
__typename?: 'TimelineThreadsWithTotal';
relatedPersonIds: Array<Scalars['UUID']['output']>;
@@ -1007,6 +1035,15 @@ export type GetTimelineCalendarEventsFromObjectRecordQueryVariables = Exact<{
export type GetTimelineCalendarEventsFromObjectRecordQuery = { __typename?: 'Query', getTimelineCalendarEventsFromObjectRecord: { __typename?: 'TimelineCalendarEventsWithTotal', totalNumberOfCalendarEvents: number, relatedPersonIds: Array<any>, timelineCalendarEvents: Array<{ __typename?: 'TimelineCalendarEvent', id: any, title: string, description: string, location: string, startsAt: string, endsAt: string, isFullDay: boolean, visibility: CalendarChannelVisibility, participants: Array<{ __typename?: 'TimelineCalendarEventParticipant', personId?: any | null, workspaceMemberId?: any | null, firstName: string, lastName: string, displayName: string, avatarUrl: string, handle: string }>, callRecordings: Array<{ __typename?: 'TimelineCalendarEventCallRecording', id: any, status: CallRecordingStatus, applicationId?: any | null }> }> } };
+export type SearchTimelineCalendarEventsQueryVariables = Exact<{
+ objectNameSingular: Scalars['String']['input'];
+ recordId: Scalars['UUID']['input'];
+ searchInput?: InputMaybe<Scalars['String']['input']>;
+}>;
+
+
+export type SearchTimelineCalendarEventsQuery = { __typename?: 'Query', searchTimelineCalendarEvents: { __typename?: 'TimelineCalendarEventSearchResult', recordTimelineCalendarEvents: Array<{ __typename?: 'TimelineCalendarEvent', id: any, title: string, description: string, location: string, startsAt: string, endsAt: string, isFullDay: boolean, visibility: CalendarChannelVisibility, participants: Array<{ __typename?: 'TimelineCalendarEventParticipant', personId?: any | null, workspaceMemberId?: any | null, firstName: string, lastName: string, displayName: string, avatarUrl: string, handle: string }>, callRecordings: Array<{ __typename?: 'TimelineCalendarEventCallRecording', id: any, status: CallRecordingStatus, applicationId?: any | null }> }>, otherTimelineCalendarEvents: Array<{ __typename?: 'TimelineCalendarEvent', id: any, title: string, description: string, location: string, startsAt: string, endsAt: string, isFullDay: boolean, visibility: CalendarChannelVisibility, participants: Array<{ __typename?: 'TimelineCalendarEventParticipant', personId?: any | null, workspaceMemberId?: any | null, firstName: string, lastName: string, displayName: string, avatarUrl: string, handle: string }>, callRecordings: Array<{ __typename?: 'TimelineCalendarEventCallRecording', id: any, status: CallRecordingStatus, applicationId?: any | null }> }> } };
+
export type ParticipantFragmentFragment = { __typename?: 'TimelineThreadParticipant', personId?: any | null, workspaceMemberId?: any | null, firstName: string, lastName: string, displayName: string, avatarUrl: string, handle: string };
export type TimelineThreadFragmentFragment = { __typename?: 'TimelineThread', id: any, read: boolean, visibility: MessageChannelVisibility, lastMessageReceivedAt: string, lastMessageBody: string, subject: string, numberOfMessagesInThread: number, participantCount: number, lastMessageIsDraft: boolean, firstParticipant: { __typename?: 'TimelineThreadParticipant', personId?: any | null, workspaceMemberId?: any | null, firstName: string, lastName: string, displayName: string, avatarUrl: string, handle: string }, lastTwoParticipants: Array<{ __typename?: 'TimelineThreadParticipant', personId?: any | null, workspaceMemberId?: any | null, firstName: string, lastName: string, displayName: string, avatarUrl: string, handle: string }> };
@@ -1023,6 +1060,15 @@ export type GetTimelineThreadsFromObjectRecordQueryVariables = Exact<{
export type GetTimelineThreadsFromObjectRecordQuery = { __typename?: 'Query', getTimelineThreadsFromObjectRecord: { __typename?: 'TimelineThreadsWithTotal', totalNumberOfThreads: number, relatedPersonIds: Array<any>, timelineThreads: Array<{ __typename?: 'TimelineThread', id: any, read: boolean, visibility: MessageChannelVisibility, lastMessageReceivedAt: string, lastMessageBody: string, subject: string, numberOfMessagesInThread: number, participantCount: number, lastMessageIsDraft: boolean, firstParticipant: { __typename?: 'TimelineThreadParticipant', personId?: any | null, workspaceMemberId?: any | null, firstName: string, lastName: string, displayName: string, avatarUrl: string, handle: string }, lastTwoParticipants: Array<{ __typename?: 'TimelineThreadParticipant', personId?: any | null, workspaceMemberId?: any | null, firstName: string, lastName: string, displayName: string, avatarUrl: string, handle: string }> }> } };
+export type SearchTimelineThreadsQueryVariables = Exact<{
+ objectNameSingular: Scalars['String']['input'];
+ recordId: Scalars['UUID']['input'];
+ searchInput?: InputMaybe<Scalars['String']['input']>;
+}>;
+
+
+export type SearchTimelineThreadsQuery = { __typename?: 'Query', searchTimelineThreads: { __typename?: 'TimelineThreadSearchResult', recordTimelineThreads: Array<{ __typename?: 'TimelineThread', id: any, read: boolean, visibility: MessageChannelVisibility, lastMessageReceivedAt: string, lastMessageBody: string, subject: string, numberOfMessagesInThread: number, participantCount: number, lastMessageIsDraft: boolean, firstParticipant: { __typename?: 'TimelineThreadParticipant', personId?: any | null, workspaceMemberId?: any | null, firstName: string, lastName: string, displayName: string, avatarUrl: string, handle: string }, lastTwoParticipants: Array<{ __typename?: 'TimelineThreadParticipant', personId?: any | null, workspaceMemberId?: any | null, firstName: string, lastName: string, displayName: string, avatarUrl: string, handle: string }> }>, otherTimelineThreads: Array<{ __typename?: 'TimelineThread', id: any, read: boolean, visibility: MessageChannelVisibility, lastMessageReceivedAt: string, lastMessageBody: string, subject: string, numberOfMessagesInThread: number, participantCount: number, lastMessageIsDraft: boolean, firstParticipant: { __typename?: 'TimelineThreadParticipant', personId?: any | null, workspaceMemberId?: any | null, firstName: string, lastName: string, displayName: string, avatarUrl: string, handle: string }, lastTwoParticipants: Array<{ __typename?: 'TimelineThreadParticipant', personId?: any | null, workspaceMemberId?: any | null, firstName: string, lastName: string, displayName: string, avatarUrl: string, handle: string }> }> } };
+
export type AnswerToolCallMutationVariables = Exact<{
input: AnswerToolCallInput;
}>;
@@ -1281,7 +1327,9 @@ export const TimelineThreadFragmentFragmentDoc = {"kind":"Document","definitions
export const TimelineThreadsWithTotalFragmentFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"TimelineThreadsWithTotalFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineThreadsWithTotal"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"totalNumberOfThreads"}},{"kind":"Field","name":{"kind":"Name","value":"relatedPersonIds"}},{"kind":"Field","name":{"kind":"Name","value":"timelineThreads"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"TimelineThreadFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ParticipantFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineThreadParticipant"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"personId"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMemberId"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"avatarUrl"}},{"kind":"Field","name":{"kind":"Name","value":"handle"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"TimelineThreadFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"read"}},{"kind":"Field","name":{"kind":"Name","value":"visibility"}},{"kind":"Field","name":{"kind":"Name","value":"firstParticipant"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ParticipantFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"lastTwoParticipants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ParticipantFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"lastMessageReceivedAt"}},{"kind":"Field","name":{"kind":"Name","value":"lastMessageBody"}},{"kind":"Field","name":{"kind":"Name","value":"subject"}},{"kind":"Field","name":{"kind":"Name","value":"numberOfMessagesInThread"}},{"kind":"Field","name":{"kind":"Name","value":"participantCount"}},{"kind":"Field","name":{"kind":"Name","value":"lastMessageIsDraft"}}]}}]} as unknown as DocumentNode<TimelineThreadsWithTotalFragmentFragment, unknown>;
export const WorkflowDiffFragmentFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"WorkflowDiffFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkflowVersionStepChanges"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"triggerDiff"}},{"kind":"Field","name":{"kind":"Name","value":"stepsDiff"}}]}}]} as unknown as DocumentNode<WorkflowDiffFragmentFragment, unknown>;
export const GetTimelineCalendarEventsFromObjectRecordDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetTimelineCalendarEventsFromObjectRecord"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"objectNameSingular"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"recordId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"page"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"pageSize"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getTimelineCalendarEventsFromObjectRecord"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"objectNameSingular"},"value":{"kind":"Variable","name":{"kind":"Name","value":"objectNameSingular"}}},{"kind":"Argument","name":{"kind":"Name","value":"recordId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"recordId"}}},{"kind":"Argument","name":{"kind":"Name","value":"page"},"value":{"kind":"Variable","name":{"kind":"Name","value":"page"}}},{"kind":"Argument","name":{"kind":"Name","value":"pageSize"},"value":{"kind":"Variable","name":{"kind":"Name","value":"pageSize"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"TimelineCalendarEventsWithTotalFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"TimelineCalendarEventParticipantFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineCalendarEventParticipant"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"personId"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMemberId"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"avatarUrl"}},{"kind":"Field","name":{"kind":"Name","value":"handle"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"TimelineCalendarEventCallRecordingFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineCalendarEventCallRecording"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"TimelineCalendarEventFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineCalendarEvent"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"location"}},{"kind":"Field","name":{"kind":"Name","value":"startsAt"}},{"kind":"Field","name":{"kind":"Name","value":"endsAt"}},{"kind":"Field","name":{"kind":"Name","value":"isFullDay"}},{"kind":"Field","name":{"kind":"Name","value":"visibility"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"TimelineCalendarEventParticipantFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"callRecordings"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"TimelineCalendarEventCallRecordingFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"TimelineCalendarEventsWithTotalFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineCalendarEventsWithTotal"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"totalNumberOfCalendarEvents"}},{"kind":"Field","name":{"kind":"Name","value":"relatedPersonIds"}},{"kind":"Field","name":{"kind":"Name","value":"timelineCalendarEvents"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"TimelineCalendarEventFragment"}}]}}]}}]} as unknown as DocumentNode<GetTimelineCalendarEventsFromObjectRecordQuery, GetTimelineCalendarEventsFromObjectRecordQueryVariables>;
+export const SearchTimelineCalendarEventsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"SearchTimelineCalendarEvents"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"objectNameSingular"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"recordId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"searchInput"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"searchTimelineCalendarEvents"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"objectNameSingular"},"value":{"kind":"Variable","name":{"kind":"Name","value":"objectNameSingular"}}},{"kind":"Argument","name":{"kind":"Name","value":"recordId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"recordId"}}},{"kind":"Argument","name":{"kind":"Name","value":"searchInput"},"value":{"kind":"Variable","name":{"kind":"Name","value":"searchInput"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"recordTimelineCalendarEvents"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"TimelineCalendarEventFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"otherTimelineCalendarEvents"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"TimelineCalendarEventFragment"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"TimelineCalendarEventParticipantFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineCalendarEventParticipant"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"personId"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMemberId"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"avatarUrl"}},{"kind":"Field","name":{"kind":"Name","value":"handle"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"TimelineCalendarEventCallRecordingFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineCalendarEventCallRecording"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"TimelineCalendarEventFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineCalendarEvent"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"location"}},{"kind":"Field","name":{"kind":"Name","value":"startsAt"}},{"kind":"Field","name":{"kind":"Name","value":"endsAt"}},{"kind":"Field","name":{"kind":"Name","value":"isFullDay"}},{"kind":"Field","name":{"kind":"Name","value":"visibility"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"TimelineCalendarEventParticipantFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"callRecordings"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"TimelineCalendarEventCallRecordingFragment"}}]}}]}}]} as unknown as DocumentNode<SearchTimelineCalendarEventsQuery, SearchTimelineCalendarEventsQueryVariables>;
export const GetTimelineThreadsFromObjectRecordDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetTimelineThreadsFromObjectRecord"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"objectNameSingular"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"recordId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"page"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"pageSize"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getTimelineThreadsFromObjectRecord"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"objectNameSingular"},"value":{"kind":"Variable","name":{"kind":"Name","value":"objectNameSingular"}}},{"kind":"Argument","name":{"kind":"Name","value":"recordId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"recordId"}}},{"kind":"Argument","name":{"kind":"Name","value":"page"},"value":{"kind":"Variable","name":{"kind":"Name","value":"page"}}},{"kind":"Argument","name":{"kind":"Name","value":"pageSize"},"value":{"kind":"Variable","name":{"kind":"Name","value":"pageSize"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"TimelineThreadsWithTotalFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ParticipantFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineThreadParticipant"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"personId"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMemberId"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"avatarUrl"}},{"kind":"Field","name":{"kind":"Name","value":"handle"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"TimelineThreadFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"read"}},{"kind":"Field","name":{"kind":"Name","value":"visibility"}},{"kind":"Field","name":{"kind":"Name","value":"firstParticipant"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ParticipantFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"lastTwoParticipants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ParticipantFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"lastMessageReceivedAt"}},{"kind":"Field","name":{"kind":"Name","value":"lastMessageBody"}},{"kind":"Field","name":{"kind":"Name","value":"subject"}},{"kind":"Field","name":{"kind":"Name","value":"numberOfMessagesInThread"}},{"kind":"Field","name":{"kind":"Name","value":"participantCount"}},{"kind":"Field","name":{"kind":"Name","value":"lastMessageIsDraft"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"TimelineThreadsWithTotalFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineThreadsWithTotal"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"totalNumberOfThreads"}},{"kind":"Field","name":{"kind":"Name","value":"relatedPersonIds"}},{"kind":"Field","name":{"kind":"Name","value":"timelineThreads"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"TimelineThreadFragment"}}]}}]}}]} as unknown as DocumentNode<GetTimelineThreadsFromObjectRecordQuery, GetTimelineThreadsFromObjectRecordQueryVariables>;
+export const SearchTimelineThreadsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"SearchTimelineThreads"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"objectNameSingular"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"recordId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"searchInput"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"searchTimelineThreads"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"objectNameSingular"},"value":{"kind":"Variable","name":{"kind":"Name","value":"objectNameSingular"}}},{"kind":"Argument","name":{"kind":"Name","value":"recordId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"recordId"}}},{"kind":"Argument","name":{"kind":"Name","value":"searchInput"},"value":{"kind":"Variable","name":{"kind":"Name","value":"searchInput"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"recordTimelineThreads"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"TimelineThreadFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"otherTimelineThreads"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"TimelineThreadFragment"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ParticipantFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineThreadParticipant"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"personId"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMemberId"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"avatarUrl"}},{"kind":"Field","name":{"kind":"Name","value":"handle"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"TimelineThreadFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"read"}},{"kind":"Field","name":{"kind":"Name","value":"visibility"}},{"kind":"Field","name":{"kind":"Name","value":"firstParticipant"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ParticipantFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"lastTwoParticipants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ParticipantFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"lastMessageReceivedAt"}},{"kind":"Field","name":{"kind":"Name","value":"lastMessageBody"}},{"kind":"Field","name":{"kind":"Name","value":"subject"}},{"kind":"Field","name":{"kind":"Name","value":"numberOfMessagesInThread"}},{"kind":"Field","name":{"kind":"Name","value":"participantCount"}},{"kind":"Field","name":{"kind":"Name","value":"lastMessageIsDraft"}}]}}]} as unknown as DocumentNode<SearchTimelineThreadsQuery, SearchTimelineThreadsQueryVariables>;
export const AnswerToolCallDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"AnswerToolCall"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"AnswerToolCallInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"answerToolCall"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"streamId"}}]}}]}}]} as unknown as DocumentNode<AnswerToolCallMutation, AnswerToolCallMutationVariables>;
export const SearchDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"Search"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"searchInput"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"limit"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"after"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"excludedObjectNameSingulars"}},"type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"includedObjectNameSingulars"}},"type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"filter"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"ObjectRecordFilterInput"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"search"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"searchInput"},"value":{"kind":"Variable","name":{"kind":"Name","value":"searchInput"}}},{"kind":"Argument","name":{"kind":"Name","value":"limit"},"value":{"kind":"Variable","name":{"kind":"Name","value":"limit"}}},{"kind":"Argument","name":{"kind":"Name","value":"after"},"value":{"kind":"Variable","name":{"kind":"Name","value":"after"}}},{"kind":"Argument","name":{"kind":"Name","value":"excludedObjectNameSingulars"},"value":{"kind":"Variable","name":{"kind":"Name","value":"excludedObjectNameSingulars"}}},{"kind":"Argument","name":{"kind":"Name","value":"includedObjectNameSingulars"},"value":{"kind":"Variable","name":{"kind":"Name","value":"includedObjectNameSingulars"}}},{"kind":"Argument","name":{"kind":"Name","value":"filter"},"value":{"kind":"Variable","name":{"kind":"Name","value":"filter"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"edges"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"node"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"recordId"}},{"kind":"Field","name":{"kind":"Name","value":"objectNameSingular"}},{"kind":"Field","name":{"kind":"Name","value":"objectLabelSingular"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"imageUrl"}},{"kind":"Field","name":{"kind":"Name","value":"tsRankCD"}},{"kind":"Field","name":{"kind":"Name","value":"tsRank"}}]}},{"kind":"Field","name":{"kind":"Name","value":"cursor"}}]}},{"kind":"Field","name":{"kind":"Name","value":"pageInfo"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"hasNextPage"}},{"kind":"Field","name":{"kind":"Name","value":"endCursor"}}]}}]}}]}}]} as unknown as DocumentNode<SearchQuery, SearchQueryVariables>;
export const ActivateCoreWorkflowVersionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"ActivateCoreWorkflowVersion"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"coreWorkflowVersionId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"activateWorkflowVersion"},"name":{"kind":"Name","value":"activateCoreWorkflowVersion"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"coreWorkflowVersionId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"coreWorkflowVersionId"}}}]}]}}]} as unknown as DocumentNode<ActivateCoreWorkflowVersionMutation, ActivateCoreWorkflowVersionMutationVariables>;
diff --git a/packages/twenty-front/src/modules/activities/calendar/components/CalendarEventsCardContent.tsx b/packages/twenty-front/src/modules/activities/calendar/components/CalendarEventsCardContent.tsx
index f35e9b469a3..00195f57088 100644
--- a/packages/twenty-front/src/modules/activities/calendar/components/CalendarEventsCardContent.tsx
+++ b/packages/twenty-front/src/modules/activities/calendar/components/CalendarEventsCardContent.tsx
@@ -1,14 +1,12 @@
+import { CalendarEventsEmptyState } from '@/activities/calendar/components/CalendarEventsEmptyState';
import { CalendarMonthCard } from '@/activities/calendar/components/CalendarMonthCard';
import { CalendarContext } from '@/activities/calendar/contexts/CalendarContext';
import { useCalendarEvents } from '@/activities/calendar/hooks/useCalendarEvents';
import { CustomResolverFetchMoreLoader } from '@/activities/components/CustomResolverFetchMoreLoader';
import { SkeletonLoader } from '@/activities/components/SkeletonLoader';
-import { AnimatedPlaceholder } from '@/ui/feedback/empty-state/components/AnimatedPlaceholder/AnimatedPlaceholder';
-import { EmptyState } from '@/ui/feedback/empty-state/components/EmptyState';
import { StyledWidgetScrollContainer } from '@/ui/layout/components/WidgetContentContainer';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
import { styled } from '@linaria/react';
-import { useLingui } from '@lingui/react/macro';
import { format, getYear } from 'date-fns';
import { Section } from 'twenty-ui/components/layout';
@@ -45,7 +43,6 @@ export const CalendarEventsCardContent = ({
onLastRowVisible,
timelineCalendarEvents,
}: CalendarEventsCardContentProps) => {
- const { t } = useLingui();
const { localeCatalog } = useAtomStateValue(dateLocaleState);
const {
@@ -60,18 +57,7 @@ export const CalendarEventsCardContent = ({
}
if (!timelineCalendarEvents?.length) {
- // TODO: change animated placeholder
- return (
- <EmptyState.Root>
- <AnimatedPlaceholder type="noMatchRecord" />
- <EmptyState.Content>
- <EmptyState.Title>{t`No Events`}</EmptyState.Title>
- <EmptyState.Description>
- {t`No events have been scheduled with this ${objectName} yet.`}
- </EmptyState.Description>
- </EmptyState.Content>
- </EmptyState.Root>
- );
+ return <CalendarEventsEmptyState objectName={objectName} />;
}
return (
diff --git a/packages/twenty-front/src/modules/activities/calendar/components/CalendarEventsEmptyState.tsx b/packages/twenty-front/src/modules/activities/calendar/components/CalendarEventsEmptyState.tsx
new file mode 100644
index 00000000000..f4fe46f0c0f
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/calendar/components/CalendarEventsEmptyState.tsx
@@ -0,0 +1,54 @@
+import { LinkCalendarEventsDropdown } from '@/activities/calendar/components/LinkCalendarEventsDropdown';
+import { useComposeCalendarEventRelatedRecordAction } from '@/activities/calendar/hooks/useComposeCalendarEventRelatedRecordAction';
+import { AnimatedPlaceholder } from '@/ui/feedback/empty-state/components/AnimatedPlaceholder/AnimatedPlaceholder';
+import { EmptyState } from '@/ui/feedback/empty-state/components/EmptyState';
+import { useTargetRecord } from '@/ui/layout/contexts/useTargetRecord';
+import { useLingui } from '@lingui/react/macro';
+import { IconCalendarEvent, IconLink } from 'twenty-ui/icon';
+import { Button } from 'twenty-ui/primitives/input';
+
+type CalendarEventsEmptyStateProps = {
+ objectName: string;
+};
+
+export const CalendarEventsEmptyState = ({
+ objectName,
+}: CalendarEventsEmptyStateProps) => {
+ const { t } = useLingui();
+ const targetRecord = useTargetRecord();
+ const { action: createCalendarEventAction } =
+ useComposeCalendarEventRelatedRecordAction(targetRecord);
+
+ return (
+ // TODO: change animated placeholder
+ <EmptyState.Root>
+ <AnimatedPlaceholder type="noMatchRecord" />
+ <EmptyState.Content>
+ <EmptyState.Title>{t`No Events`}</EmptyState.Title>
+ <EmptyState.Description>
+ {t`No events have been scheduled with this ${objectName} yet.`}
+ </EmptyState.Description>
+ </EmptyState.Content>
+ <EmptyState.Actions>
+ <LinkCalendarEventsDropdown
+ dropdownIdPrefix="calendar-empty-state-link-events"
+ trigger={
+ <Button startIcon={<IconLink />} variant="outline">
+ {t`Link events`}
+ </Button>
+ }
+ />
+ {createCalendarEventAction.isVisible && (
+ <Button
+ startIcon={<IconCalendarEvent />}
+ onClick={createCalendarEventAction.execute}
+ disabled={createCalendarEventAction.disabled}
+ variant="outline"
+ >
+ {createCalendarEventAction.label}
+ </Button>
+ )}
+ </EmptyState.Actions>
+ </EmptyState.Root>
+ );
+};
diff --git a/packages/twenty-front/src/modules/activities/calendar/components/LinkCalendarEventsDropdown.tsx b/packages/twenty-front/src/modules/activities/calendar/components/LinkCalendarEventsDropdown.tsx
new file mode 100644
index 00000000000..e42b2a00b20
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/calendar/components/LinkCalendarEventsDropdown.tsx
@@ -0,0 +1,56 @@
+import { getTimelineCalendarEventsFromObjectRecord } from '@/activities/calendar/graphql/queries/getTimelineCalendarEventsFromObjectRecord';
+import { searchTimelineCalendarEvents } from '@/activities/calendar/graphql/queries/searchTimelineCalendarEvents';
+import { getTimelineCalendarEventLabel } from '@/activities/calendar/utils/getTimelineCalendarEventLabel';
+import { LinkActivitiesDropdown } from '@/activities/components/LinkActivitiesDropdown';
+import { useLingui } from '@lingui/react/macro';
+import { type ReactElement } from 'react';
+import { CoreObjectNameSingular } from 'twenty-shared/types';
+import { IconCalendarEvent } from 'twenty-ui/icon';
+import {
+ type SearchTimelineCalendarEventsQuery,
+ type TimelineCalendarEvent,
+} from '~/generated/graphql';
+import { formatToHumanReadableDate } from '~/utils/date-utils';
+
+type LinkCalendarEventsDropdownProps = {
+ dropdownIdPrefix: string;
+ trigger: ReactElement;
+};
+
+export const LinkCalendarEventsDropdown = ({
+ dropdownIdPrefix,
+ trigger,
+}: LinkCalendarEventsDropdownProps) => {
+ const { t } = useLingui();
+
+ return (
+ <LinkActivitiesDropdown<
+ Pick<TimelineCalendarEvent, 'id' | 'title' | 'visibility' | 'startsAt'>,
+ SearchTimelineCalendarEventsQuery
+ >
+ activityObjectNameSingular={CoreObjectNameSingular.CalendarEvent}
+ dropdownIdPrefix={dropdownIdPrefix}
+ ariaLabel={t`Link events`}
+ trigger={trigger}
+ searchQuery={searchTimelineCalendarEvents}
+ getSearchResults={(data) => ({
+ recordActivities:
+ data.searchTimelineCalendarEvents.recordTimelineCalendarEvents,
+ otherActivities:
+ data.searchTimelineCalendarEvents.otherTimelineCalendarEvents,
+ })}
+ timelineQuery={getTimelineCalendarEventsFromObjectRecord}
+ getOption={(calendarEvent) => ({
+ label: getTimelineCalendarEventLabel(calendarEvent),
+ description: formatToHumanReadableDate(calendarEvent.startsAt),
+ startIcon: <IconCalendarEvent />,
+ })}
+ labels={{
+ search: t`Search events`,
+ loading: t`Loading events`,
+ empty: t`No events found`,
+ otherSection: t`Your other events`,
+ }}
+ />
+ );
+};
diff --git a/packages/twenty-front/src/modules/activities/calendar/graphql/queries/searchTimelineCalendarEvents.ts b/packages/twenty-front/src/modules/activities/calendar/graphql/queries/searchTimelineCalendarEvents.ts
new file mode 100644
index 00000000000..c981de60e26
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/calendar/graphql/queries/searchTimelineCalendarEvents.ts
@@ -0,0 +1,24 @@
+import { timelineCalendarEventFragment } from '@/activities/calendar/graphql/queries/fragments/timelineCalendarEventFragment';
+import { gql } from '@apollo/client';
+
+export const searchTimelineCalendarEvents = gql`
+ query SearchTimelineCalendarEvents(
+ $objectNameSingular: String!
+ $recordId: UUID!
+ $searchInput: String
+ ) {
+ searchTimelineCalendarEvents(
+ objectNameSingular: $objectNameSingular
+ recordId: $recordId
+ searchInput: $searchInput
+ ) {
+ recordTimelineCalendarEvents {
+ ...TimelineCalendarEventFragment
+ }
+ otherTimelineCalendarEvents {
+ ...TimelineCalendarEventFragment
+ }
+ }
+ }
+ ${timelineCalendarEventFragment}
+`;
diff --git a/packages/twenty-front/src/modules/activities/calendar/utils/__tests__/getTimelineCalendarEventLabel.test.ts b/packages/twenty-front/src/modules/activities/calendar/utils/__tests__/getTimelineCalendarEventLabel.test.ts
new file mode 100644
index 00000000000..247fadebe1d
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/calendar/utils/__tests__/getTimelineCalendarEventLabel.test.ts
@@ -0,0 +1,22 @@
+import { getTimelineCalendarEventLabel } from '@/activities/calendar/utils/getTimelineCalendarEventLabel';
+import { CalendarChannelVisibility } from '~/generated/graphql';
+
+describe('getTimelineCalendarEventLabel', () => {
+ it('should return the title when everything is shared', () => {
+ expect(
+ getTimelineCalendarEventLabel({
+ title: 'Renewal review',
+ visibility: CalendarChannelVisibility.SHARE_EVERYTHING,
+ }),
+ ).toBe('Renewal review');
+ });
+
+ it('should hide the title when only metadata is shared', () => {
+ expect(
+ getTimelineCalendarEventLabel({
+ title: 'Renewal review',
+ visibility: CalendarChannelVisibility.METADATA,
+ }),
+ ).toBe('Calendar event');
+ });
+});
diff --git a/packages/twenty-front/src/modules/activities/calendar/utils/getTimelineCalendarEventLabel.ts b/packages/twenty-front/src/modules/activities/calendar/utils/getTimelineCalendarEventLabel.ts
new file mode 100644
index 00000000000..04995db0e5a
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/calendar/utils/getTimelineCalendarEventLabel.ts
@@ -0,0 +1,14 @@
+import { t } from '@lingui/core/macro';
+import { isNonEmptyString } from '@sniptt/guards';
+import {
+ CalendarChannelVisibility,
+ type TimelineCalendarEvent,
+} from '~/generated/graphql';
+
+export const getTimelineCalendarEventLabel = (
+ calendarEvent: Pick<TimelineCalendarEvent, 'title' | 'visibility'>,
+) =>
+ calendarEvent.visibility === CalendarChannelVisibility.SHARE_EVERYTHING &&
+ isNonEmptyString(calendarEvent.title)
+ ? calendarEvent.title
+ : t`Calendar event`;
diff --git a/packages/twenty-front/src/modules/activities/components/LinkActivitiesDropdown.tsx b/packages/twenty-front/src/modules/activities/components/LinkActivitiesDropdown.tsx
new file mode 100644
index 00000000000..3a27ceb2764
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/components/LinkActivitiesDropdown.tsx
@@ -0,0 +1,75 @@
+import {
+ LinkActivitiesDropdownContent,
+ type LinkActivitiesDropdownContentProps,
+} from '@/activities/components/LinkActivitiesDropdownContent';
+import { useActivityLinkConfig } from '@/activities/hooks/useActivityLinkConfig';
+import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContent';
+import { DropdownRoot } from '@/ui/layout/dropdown/components/DropdownRoot';
+import { GenericDropdownContentWidth } from '@/ui/layout/dropdown/constants/GenericDropdownContentWidth';
+import { useTargetRecord } from '@/ui/layout/contexts/useTargetRecord';
+import { type ReactElement } from 'react';
+import { type CoreObjectNameSingular } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+import { Dropdown } from 'twenty-ui/components/navigation';
+
+type LinkActivitiesDropdownProps<
+ TActivity extends { id: string },
+ TSearchData,
+> = LinkActivitiesDropdownContentProps<TActivity, TSearchData> & {
+ activityObjectNameSingular:
+ | CoreObjectNameSingular.MessageThread
+ | CoreObjectNameSingular.CalendarEvent;
+ dropdownIdPrefix: string;
+ ariaLabel: string;
+ trigger: ReactElement;
+};
+
+export const LinkActivitiesDropdown = <
+ TActivity extends { id: string },
+ TSearchData,
+>({
+ activityObjectNameSingular,
+ dropdownIdPrefix,
+ ariaLabel,
+ trigger,
+ searchQuery,
+ getSearchResults,
+ timelineQuery,
+ getOption,
+ labels,
+}: LinkActivitiesDropdownProps<TActivity, TSearchData>) => {
+ const targetRecord = useTargetRecord();
+ const activityLinkConfig = useActivityLinkConfig({
+ targetRecord,
+ activityObjectNameSingular,
+ });
+
+ if (!isDefined(activityLinkConfig)) {
+ return null;
+ }
+
+ return (
+ <DropdownRoot
+ dropdownId={`${dropdownIdPrefix}-${targetRecord.id}`}
+ type="picker"
+ multiple
+ >
+ <Dropdown.Trigger render={trigger} />
+ <DropdownContent
+ width={GenericDropdownContentWidth.ExtraLarge}
+ align="end"
+ aria-label={ariaLabel}
+ >
+ <LinkActivitiesDropdownContent
+ targetRecord={targetRecord}
+ activityLinkConfig={activityLinkConfig}
+ searchQuery={searchQuery}
+ getSearchResults={getSearchResults}
+ timelineQuery={timelineQuery}
+ getOption={getOption}
+ labels={labels}
+ />
+ </DropdownContent>
+ </DropdownRoot>
+ );
+};
diff --git a/packages/twenty-front/src/modules/activities/components/LinkActivitiesDropdownContent.tsx b/packages/twenty-front/src/modules/activities/components/LinkActivitiesDropdownContent.tsx
new file mode 100644
index 00000000000..1275a85f559
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/components/LinkActivitiesDropdownContent.tsx
@@ -0,0 +1,140 @@
+import { type ActivityLinkConfig } from '@/activities/hooks/useActivityLinkConfig';
+import { useToggleActivityLink } from '@/activities/hooks/useToggleActivityLink';
+import { type ActivityTargetableObject } from '@/activities/types/ActivityTargetableEntity';
+import { useApolloCoreClient } from '@/object-metadata/hooks/useApolloCoreClient';
+import { type DocumentNode } from '@apollo/client';
+import { useQuery } from '@apollo/client/react';
+import { type ReactNode, useState } from 'react';
+import { CoreObjectNameSingular } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+import { Dropdown } from 'twenty-ui/components/navigation';
+import { useDebounce } from 'use-debounce';
+
+export type LinkActivitiesSearchResults<TActivity> = {
+ recordActivities: TActivity[];
+ otherActivities: TActivity[];
+};
+
+export type LinkActivitiesOption = {
+ label: string;
+ description: string;
+ startIcon: ReactNode;
+};
+
+export type LinkActivitiesLabels = {
+ search: string;
+ loading: string;
+ empty: string;
+ otherSection: string;
+};
+
+export type LinkActivitiesDropdownContentProps<
+ TActivity extends { id: string },
+ TSearchData,
+> = {
+ searchQuery: DocumentNode;
+ getSearchResults: (
+ data: TSearchData,
+ ) => LinkActivitiesSearchResults<TActivity>;
+ timelineQuery: DocumentNode;
+ getOption: (activity: TActivity) => LinkActivitiesOption;
+ labels: LinkActivitiesLabels;
+};
+
+export const LinkActivitiesDropdownContent = <
+ TActivity extends { id: string },
+ TSearchData,
+>({
+ targetRecord,
+ activityLinkConfig,
+ searchQuery,
+ getSearchResults,
+ timelineQuery,
+ getOption,
+ labels,
+}: LinkActivitiesDropdownContentProps<TActivity, TSearchData> & {
+ targetRecord: Pick<ActivityTargetableObject, 'id'>;
+ activityLinkConfig: ActivityLinkConfig;
+}) => {
+ const apolloCoreClient = useApolloCoreClient();
+ const [search, setSearch] = useState('');
+ const trimmedSearch = search.trim();
+ const [debouncedSearch] = useDebounce(trimmedSearch, 300);
+
+ const { relatedCompany } = activityLinkConfig;
+
+ const { data, loading } = useQuery<TSearchData>(searchQuery, {
+ client: apolloCoreClient,
+ variables: {
+ objectNameSingular: CoreObjectNameSingular.Company,
+ recordId: relatedCompany.id,
+ searchInput: debouncedSearch,
+ },
+ });
+
+ const { recordActivities, otherActivities } = isDefined(data)
+ ? getSearchResults(data)
+ : { recordActivities: [], otherActivities: [] };
+
+ const { linkedActivityIds, pendingActivityIds, toggleActivityLink } =
+ useToggleActivityLink({
+ targetRecord,
+ activityLinkConfig,
+ activityIds: [...recordActivities, ...otherActivities].map(
+ ({ id }) => id,
+ ),
+ timelineQuery,
+ });
+
+ const areActivitiesStale = loading || debouncedSearch !== trimmedSearch;
+
+ const renderOption = (activity: TActivity) => {
+ const { label, description, startIcon } = getOption(activity);
+
+ return (
+ <Dropdown.OptionItem
+ key={activity.id}
+ value={activity.id}
+ selected={linkedActivityIds.has(activity.id)}
+ indicator="checkbox"
+ disabled={
+ areActivitiesStale || pendingActivityIds.includes(activity.id)
+ }
+ startIcon={startIcon}
+ description={description}
+ onSelect={() => toggleActivityLink(activity.id)}
+ >
+ {label}
+ </Dropdown.OptionItem>
+ );
+ };
+
+ return (
+ <>
+ <Dropdown.Search
+ aria-label={labels.search}
+ placeholder={labels.search}
+ value={search}
+ onValueChange={setSearch}
+ />
+ <Dropdown.Separator />
+ <Dropdown.Section scrollable label={relatedCompany.name}>
+ {recordActivities.map(renderOption)}
+ {recordActivities.length === 0 &&
+ (areActivitiesStale ? (
+ <Dropdown.Loading>{labels.loading}</Dropdown.Loading>
+ ) : (
+ <Dropdown.Empty>{labels.empty}</Dropdown.Empty>
+ ))}
+ </Dropdown.Section>
+ {otherActivities.length > 0 && (
+ <>
+ <Dropdown.Separator />
+ <Dropdown.Section scrollable label={labels.otherSection}>
+ {otherActivities.map(renderOption)}
+ </Dropdown.Section>
+ </>
+ )}
+ </>
+ );
+};
diff --git a/packages/twenty-front/src/modules/activities/emails/components/EmailThreadPreview.tsx b/packages/twenty-front/src/modules/activities/emails/components/EmailThreadPreview.tsx
index 183dd0eb31a..e70be90c9c8 100644
--- a/packages/twenty-front/src/modules/activities/emails/components/EmailThreadPreview.tsx
+++ b/packages/twenty-front/src/modules/activities/emails/components/EmailThreadPreview.tsx
@@ -3,10 +3,10 @@ import { styled } from '@linaria/react';
import { ActivityRow } from '@/activities/components/ActivityRow';
import { EmailThreadNotShared } from '@/activities/emails/components/EmailThreadNotShared';
import { getEmailParticipantAvatarColorSeed } from '@/activities/emails/utils/getEmailParticipantAvatarColorSeed';
+import { getTimelineThreadLabel } from '@/activities/emails/utils/getTimelineThreadLabel';
import { useOpenRecordInSidePanel } from '@/side-panel/hooks/useOpenRecordInSidePanel';
import { t } from '@lingui/core/macro';
-import { isNonEmptyString } from '@sniptt/guards';
import { CoreObjectNameSingular } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { Avatar, Tag } from 'twenty-ui/primitives/data-display';
@@ -142,13 +142,7 @@ export const EmailThreadPreview = ({
};
const isDisabled = visibility !== MessageChannelVisibility.SHARE_EVERYTHING;
- const isSubjectVisible =
- visibility === MessageChannelVisibility.SUBJECT ||
- visibility === MessageChannelVisibility.SHARE_EVERYTHING;
- const label =
- isSubjectVisible && isNonEmptyString(thread.subject)
- ? thread.subject
- : t`Email thread`;
+ const label = getTimelineThreadLabel(thread);
const draftTag = thread.lastMessageIsDraft ? (
<Tag color="orange">{t`Draft`}</Tag>
) : null;
diff --git a/packages/twenty-front/src/modules/activities/emails/components/EmptyInboxPlaceholder.tsx b/packages/twenty-front/src/modules/activities/emails/components/EmptyInboxPlaceholder.tsx
index df8c035469a..1153d67d39e 100644
--- a/packages/twenty-front/src/modules/activities/emails/components/EmptyInboxPlaceholder.tsx
+++ b/packages/twenty-front/src/modules/activities/emails/components/EmptyInboxPlaceholder.tsx
@@ -1,9 +1,10 @@
+import { LinkEmailThreadsDropdown } from '@/activities/emails/components/LinkEmailThreadsDropdown';
import { useComposeEmailForTargetRecord } from '@/activities/emails/hooks/useComposeEmailForTargetRecord';
import { AnimatedPlaceholder } from '@/ui/feedback/empty-state/components/AnimatedPlaceholder/AnimatedPlaceholder';
import { EmptyState } from '@/ui/feedback/empty-state/components/EmptyState';
import { useTargetRecord } from '@/ui/layout/contexts/useTargetRecord';
import { Trans, useLingui } from '@lingui/react/macro';
-import { IconMail } from 'twenty-ui/icon';
+import { IconLink, IconMail } from 'twenty-ui/icon';
import { Button } from 'twenty-ui/primitives/input';
export const EmptyInboxPlaceholder = () => {
@@ -23,12 +24,22 @@ export const EmptyInboxPlaceholder = () => {
<Trans>No email exchange has occurred with this record yet.</Trans>
</EmptyState.Description>
</EmptyState.Content>
- <Button
- startIcon={<IconMail />}
- onClick={openComposer}
- disabled={loading}
- variant="outline"
- >{t`Send Email`}</Button>
+ <EmptyState.Actions>
+ <LinkEmailThreadsDropdown
+ dropdownIdPrefix="empty-inbox-link-email-threads"
+ trigger={
+ <Button startIcon={<IconLink />} variant="outline">
+ {t`Link email threads`}
+ </Button>
+ }
+ />
+ <Button
+ startIcon={<IconMail />}
+ onClick={openComposer}
+ disabled={loading}
+ variant="outline"
+ >{t`Send Email`}</Button>
+ </EmptyState.Actions>
</EmptyState.Root>
);
};
diff --git a/packages/twenty-front/src/modules/activities/emails/components/LinkEmailThreadsDropdown.tsx b/packages/twenty-front/src/modules/activities/emails/components/LinkEmailThreadsDropdown.tsx
new file mode 100644
index 00000000000..c2989a3390d
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/emails/components/LinkEmailThreadsDropdown.tsx
@@ -0,0 +1,63 @@
+import { LinkActivitiesDropdown } from '@/activities/components/LinkActivitiesDropdown';
+import { getTimelineThreadsFromObjectRecord } from '@/activities/emails/graphql/queries/getTimelineThreadsFromObjectRecord';
+import { searchTimelineThreads } from '@/activities/emails/graphql/queries/searchTimelineThreads';
+import { getEmailParticipantAvatarColorSeed } from '@/activities/emails/utils/getEmailParticipantAvatarColorSeed';
+import { getTimelineThreadLabel } from '@/activities/emails/utils/getTimelineThreadLabel';
+import { useLingui } from '@lingui/react/macro';
+import { type ReactElement } from 'react';
+import { CoreObjectNameSingular } from 'twenty-shared/types';
+import { Avatar } from 'twenty-ui/primitives/data-display';
+import {
+ type SearchTimelineThreadsQuery,
+ type TimelineThread,
+} from '~/generated/graphql';
+import { formatToHumanReadableDate } from '~/utils/date-utils';
+import { getAbsoluteImageUrl } from '~/utils/image/getAbsoluteImageUrl';
+
+type LinkEmailThreadsDropdownProps = {
+ dropdownIdPrefix: string;
+ trigger: ReactElement;
+};
+
+export const LinkEmailThreadsDropdown = ({
+ dropdownIdPrefix,
+ trigger,
+}: LinkEmailThreadsDropdownProps) => {
+ const { t } = useLingui();
+
+ return (
+ <LinkActivitiesDropdown<TimelineThread, SearchTimelineThreadsQuery>
+ activityObjectNameSingular={CoreObjectNameSingular.MessageThread}
+ dropdownIdPrefix={dropdownIdPrefix}
+ ariaLabel={t`Link email threads`}
+ trigger={trigger}
+ searchQuery={searchTimelineThreads}
+ getSearchResults={(data) => ({
+ recordActivities: data.searchTimelineThreads.recordTimelineThreads,
+ otherActivities: data.searchTimelineThreads.otherTimelineThreads,
+ })}
+ timelineQuery={getTimelineThreadsFromObjectRecord}
+ getOption={(thread) => ({
+ label: getTimelineThreadLabel(thread),
+ description: formatToHumanReadableDate(thread.lastMessageReceivedAt),
+ startIcon: (
+ <Avatar
+ src={getAbsoluteImageUrl(thread.firstParticipant.avatarUrl)}
+ name={thread.firstParticipant.displayName}
+ colorSeed={getEmailParticipantAvatarColorSeed(
+ thread.firstParticipant,
+ )}
+ shape="circle"
+ size="sm"
+ />
+ ),
+ })}
+ labels={{
+ search: t`Search email threads`,
+ loading: t`Loading email threads`,
+ empty: t`No email threads found`,
+ otherSection: t`Your other email threads`,
+ }}
+ />
+ );
+};
diff --git a/packages/twenty-front/src/modules/activities/emails/graphql/queries/searchTimelineThreads.ts b/packages/twenty-front/src/modules/activities/emails/graphql/queries/searchTimelineThreads.ts
new file mode 100644
index 00000000000..292ac49b7dd
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/emails/graphql/queries/searchTimelineThreads.ts
@@ -0,0 +1,24 @@
+import { timelineThreadFragment } from '@/activities/emails/graphql/queries/fragments/timelineThreadFragment';
+import { gql } from '@apollo/client';
+
+export const searchTimelineThreads = gql`
+ query SearchTimelineThreads(
+ $objectNameSingular: String!
+ $recordId: UUID!
+ $searchInput: String
+ ) {
+ searchTimelineThreads(
+ objectNameSingular: $objectNameSingular
+ recordId: $recordId
+ searchInput: $searchInput
+ ) {
+ recordTimelineThreads {
+ ...TimelineThreadFragment
+ }
+ otherTimelineThreads {
+ ...TimelineThreadFragment
+ }
+ }
+ }
+ ${timelineThreadFragment}
+`;
diff --git a/packages/twenty-front/src/modules/activities/emails/utils/__tests__/getTimelineThreadLabel.test.ts b/packages/twenty-front/src/modules/activities/emails/utils/__tests__/getTimelineThreadLabel.test.ts
new file mode 100644
index 00000000000..870db374576
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/emails/utils/__tests__/getTimelineThreadLabel.test.ts
@@ -0,0 +1,31 @@
+import { getTimelineThreadLabel } from '@/activities/emails/utils/getTimelineThreadLabel';
+import { MessageChannelVisibility } from '~/generated/graphql';
+
+describe('getTimelineThreadLabel', () => {
+ it('should return the subject when it is shared', () => {
+ expect(
+ getTimelineThreadLabel({
+ subject: 'Renewal proposal',
+ visibility: MessageChannelVisibility.SUBJECT,
+ }),
+ ).toBe('Renewal proposal');
+ });
+
+ it('should hide the subject when only metadata is shared', () => {
+ expect(
+ getTimelineThreadLabel({
+ subject: 'Renewal proposal',
+ visibility: MessageChannelVisibility.METADATA,
+ }),
+ ).toBe('Email thread');
+ });
+
+ it('should fall back when the subject is empty', () => {
+ expect(
+ getTimelineThreadLabel({
+ subject: '',
+ visibility: MessageChannelVisibility.SHARE_EVERYTHING,
+ }),
+ ).toBe('Email thread');
+ });
+});
diff --git a/packages/twenty-front/src/modules/activities/emails/utils/getTimelineThreadLabel.ts b/packages/twenty-front/src/modules/activities/emails/utils/getTimelineThreadLabel.ts
new file mode 100644
index 00000000000..4a154cc9d97
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/emails/utils/getTimelineThreadLabel.ts
@@ -0,0 +1,18 @@
+import { t } from '@lingui/core/macro';
+import { isNonEmptyString } from '@sniptt/guards';
+import {
+ MessageChannelVisibility,
+ type TimelineThread,
+} from '~/generated/graphql';
+
+export const getTimelineThreadLabel = (
+ thread: Pick<TimelineThread, 'subject' | 'visibility'>,
+) => {
+ const isSubjectVisible =
+ thread.visibility === MessageChannelVisibility.SUBJECT ||
+ thread.visibility === MessageChannelVisibility.SHARE_EVERYTHING;
+
+ return isSubjectVisible && isNonEmptyString(thread.subject)
+ ? thread.subject
+ : t`Email thread`;
+};
diff --git a/packages/twenty-front/src/modules/activities/hooks/__tests__/useToggleActivityLink.test.ts b/packages/twenty-front/src/modules/activities/hooks/__tests__/useToggleActivityLink.test.ts
new file mode 100644
index 00000000000..711f6423974
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/hooks/__tests__/useToggleActivityLink.test.ts
@@ -0,0 +1,111 @@
+import { act, renderHook } from '@testing-library/react';
+import { gql } from '@apollo/client';
+
+import { useToggleActivityLink } from '@/activities/hooks/useToggleActivityLink';
+import { CoreObjectNameSingular } from 'twenty-shared/types';
+
+const mockCreateOneRecord = jest.fn();
+const mockDeleteOneRecord = jest.fn();
+const mockRefetch = jest.fn();
+const mockRefetchQueries = jest.fn();
+const mockUseFindManyRecords = jest.fn();
+
+jest.mock('@/object-record/hooks/useFindManyRecords', () => ({
+ useFindManyRecords: (args: unknown) => mockUseFindManyRecords(args),
+}));
+
+jest.mock('@/object-record/hooks/useCreateOneRecord', () => ({
+ useCreateOneRecord: () => ({ createOneRecord: mockCreateOneRecord }),
+}));
+
+jest.mock('@/object-record/hooks/useDeleteOneRecord', () => ({
+ useDeleteOneRecord: () => ({ deleteOneRecord: mockDeleteOneRecord }),
+}));
+
+jest.mock('@/object-metadata/hooks/useApolloCoreClient', () => ({
+ useApolloCoreClient: () => ({ refetchQueries: mockRefetchQueries }),
+}));
+
+const TIMELINE_QUERY = gql`
+ query Timeline {
+ timeline
+ }
+`;
+
+const targetRecord = {
+ id: 'opportunity-id',
+ targetObjectNameSingular: CoreObjectNameSingular.Opportunity,
+};
+
+const renderToggleHook = () =>
+ renderHook(() =>
+ useToggleActivityLink({
+ targetRecord,
+ activityLinkConfig: {
+ junctionObjectNameSingular: CoreObjectNameSingular.MessageThreadTarget,
+ activityJoinColumnName: 'messageThreadId',
+ targetJoinColumnName: 'targetOpportunityId',
+ },
+ activityIds: ['linked-thread-id', 'unlinked-thread-id'],
+ timelineQuery: TIMELINE_QUERY,
+ }),
+ );
+
+describe('useToggleActivityLink', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+
+ mockUseFindManyRecords.mockReturnValue({
+ records: [{ id: 'target-id', messageThreadId: 'linked-thread-id' }],
+ refetch: mockRefetch,
+ });
+ });
+
+ it('should only look up links between this record and the displayed activities', () => {
+ renderToggleHook();
+
+ expect(mockUseFindManyRecords).toHaveBeenCalledWith(
+ expect.objectContaining({
+ objectNameSingular: CoreObjectNameSingular.MessageThreadTarget,
+ filter: {
+ targetOpportunityId: { eq: 'opportunity-id' },
+ messageThreadId: { in: ['linked-thread-id', 'unlinked-thread-id'] },
+ },
+ }),
+ );
+ });
+
+ it('should expose linked activities', () => {
+ const { result } = renderToggleHook();
+
+ expect(result.current.linkedActivityIds.has('linked-thread-id')).toBe(true);
+ expect(result.current.linkedActivityIds.has('unlinked-thread-id')).toBe(
+ false,
+ );
+ });
+
+ it('should link an unlinked activity to the record and refresh the timeline', async () => {
+ const { result } = renderToggleHook();
+
+ await act(() => result.current.toggleActivityLink('unlinked-thread-id'));
+
+ expect(mockCreateOneRecord).toHaveBeenCalledWith({
+ messageThreadId: 'unlinked-thread-id',
+ targetOpportunityId: 'opportunity-id',
+ });
+ expect(mockDeleteOneRecord).not.toHaveBeenCalled();
+ expect(mockRefetch).toHaveBeenCalled();
+ expect(mockRefetchQueries).toHaveBeenCalledWith({
+ include: [TIMELINE_QUERY],
+ });
+ });
+
+ it('should unlink a linked activity from the record', async () => {
+ const { result } = renderToggleHook();
+
+ await act(() => result.current.toggleActivityLink('linked-thread-id'));
+
+ expect(mockDeleteOneRecord).toHaveBeenCalledWith('target-id');
+ expect(mockCreateOneRecord).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-front/src/modules/activities/hooks/useActivityLinkConfig.ts b/packages/twenty-front/src/modules/activities/hooks/useActivityLinkConfig.ts
new file mode 100644
index 00000000000..576bd7edd5f
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/hooks/useActivityLinkConfig.ts
@@ -0,0 +1,93 @@
+import { type ActivityTargetableObject } from '@/activities/types/ActivityTargetableEntity';
+import { useObjectMetadataItem } from '@/object-metadata/hooks/useObjectMetadataItem';
+import { useObjectMetadataItems } from '@/object-metadata/hooks/useObjectMetadataItems';
+import { useFindOneRecord } from '@/object-record/hooks/useFindOneRecord';
+import { useObjectPermissionsForObject } from '@/object-record/hooks/useObjectPermissionsForObject';
+import { useObjectMorphJunctionConfig } from '@/object-record/record-field/ui/hooks/useObjectMorphJunctionConfig';
+import { findTargetFieldInfo } from '@/object-record/record-field/ui/utils/junction/findTargetFieldInfo';
+import { CoreObjectNameSingular } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+import { RelationType } from '~/generated-metadata/graphql';
+
+export type ActivityLinkConfig = {
+ relatedCompany: { id: string; name: string };
+ junctionObjectNameSingular: string;
+ activityJoinColumnName: string;
+ targetJoinColumnName: string;
+};
+
+export const useActivityLinkConfig = ({
+ targetRecord,
+ activityObjectNameSingular,
+}: {
+ targetRecord: Pick<
+ ActivityTargetableObject,
+ 'id' | 'targetObjectNameSingular'
+ >;
+ activityObjectNameSingular:
+ | CoreObjectNameSingular.MessageThread
+ | CoreObjectNameSingular.CalendarEvent;
+}): ActivityLinkConfig | null => {
+ const { objectMetadataItem } = useObjectMetadataItem({
+ objectNameSingular: targetRecord.targetObjectNameSingular,
+ });
+ const { objectMetadataItems } = useObjectMetadataItems();
+ const junctionConfig = useObjectMorphJunctionConfig({
+ objectNameSingular: activityObjectNameSingular,
+ });
+ const { canUpdateObjectRecords: canLinkActivities } =
+ useObjectPermissionsForObject(
+ junctionConfig?.junctionObjectMetadata.id ?? '',
+ );
+
+ const companyRelationField = objectMetadataItem.fields.find(
+ (field) =>
+ field.isActive &&
+ field.relation?.type === RelationType.MANY_TO_ONE &&
+ field.relation.targetObjectMetadata.nameSingular ===
+ CoreObjectNameSingular.Company,
+ );
+
+ const targetJoinColumnName = isDefined(junctionConfig)
+ ? findTargetFieldInfo(
+ junctionConfig.targetFields,
+ objectMetadataItem.id,
+ objectMetadataItems,
+ )?.joinColumnName
+ : undefined;
+
+ const companyRelationFieldName = companyRelationField?.name ?? '';
+
+ const { record } = useFindOneRecord({
+ objectNameSingular: targetRecord.targetObjectNameSingular,
+ objectRecordId: targetRecord.id,
+ recordGqlFields: {
+ id: true,
+ [companyRelationFieldName]: { id: true, name: true },
+ },
+ skip:
+ !isDefined(companyRelationField) ||
+ !isDefined(targetJoinColumnName) ||
+ !canLinkActivities,
+ });
+
+ const relatedCompany: ActivityLinkConfig['relatedCompany'] | undefined =
+ record?.[companyRelationFieldName];
+
+ if (
+ !isDefined(relatedCompany) ||
+ !isDefined(junctionConfig) ||
+ !isDefined(targetJoinColumnName) ||
+ !canLinkActivities
+ ) {
+ return null;
+ }
+
+ return {
+ relatedCompany,
+ junctionObjectNameSingular:
+ junctionConfig.junctionObjectMetadata.nameSingular,
+ activityJoinColumnName: junctionConfig.sourceJoinColumnName,
+ targetJoinColumnName,
+ };
+};
diff --git a/packages/twenty-front/src/modules/activities/hooks/useToggleActivityLink.ts b/packages/twenty-front/src/modules/activities/hooks/useToggleActivityLink.ts
new file mode 100644
index 00000000000..6c35430d271
--- /dev/null
+++ b/packages/twenty-front/src/modules/activities/hooks/useToggleActivityLink.ts
@@ -0,0 +1,93 @@
+import { type ActivityLinkConfig } from '@/activities/hooks/useActivityLinkConfig';
+import { type ActivityTargetableObject } from '@/activities/types/ActivityTargetableEntity';
+import { useApolloCoreClient } from '@/object-metadata/hooks/useApolloCoreClient';
+import { useCreateOneRecord } from '@/object-record/hooks/useCreateOneRecord';
+import { useDeleteOneRecord } from '@/object-record/hooks/useDeleteOneRecord';
+import { useFindManyRecords } from '@/object-record/hooks/useFindManyRecords';
+import { type DocumentNode } from '@apollo/client';
+import { useState } from 'react';
+import { isDefined } from 'twenty-shared/utils';
+
+export const useToggleActivityLink = ({
+ targetRecord,
+ activityLinkConfig,
+ activityIds,
+ timelineQuery,
+}: {
+ targetRecord: Pick<ActivityTargetableObject, 'id'>;
+ activityLinkConfig: Pick<
+ ActivityLinkConfig,
+ | 'junctionObjectNameSingular'
+ | 'activityJoinColumnName'
+ | 'targetJoinColumnName'
+ >;
+ activityIds: string[];
+ timelineQuery: DocumentNode;
+}) => {
+ const apolloCoreClient = useApolloCoreClient();
+ const [pendingActivityIds, setPendingActivityIds] = useState<string[]>([]);
+
+ const {
+ junctionObjectNameSingular,
+ activityJoinColumnName,
+ targetJoinColumnName,
+ } = activityLinkConfig;
+
+ const { records: junctionRecords, refetch } = useFindManyRecords({
+ objectNameSingular: junctionObjectNameSingular,
+ filter: {
+ [targetJoinColumnName]: { eq: targetRecord.id },
+ [activityJoinColumnName]: { in: activityIds },
+ },
+ recordGqlFields: { id: true, [activityJoinColumnName]: true },
+ skip: activityIds.length === 0,
+ });
+
+ const { createOneRecord } = useCreateOneRecord({
+ objectNameSingular: junctionObjectNameSingular,
+ });
+ const { deleteOneRecord } = useDeleteOneRecord({
+ objectNameSingular: junctionObjectNameSingular,
+ });
+
+ const linkedActivityIds = new Set<string>(
+ junctionRecords.map(
+ (junctionRecord) => junctionRecord[activityJoinColumnName],
+ ),
+ );
+
+ const toggleActivityLink = async (activityId: string) => {
+ if (pendingActivityIds.includes(activityId)) {
+ return;
+ }
+
+ setPendingActivityIds((currentIds) => [...currentIds, activityId]);
+
+ try {
+ const existingJunctionRecord = junctionRecords.find(
+ (junctionRecord) =>
+ junctionRecord[activityJoinColumnName] === activityId,
+ );
+
+ if (isDefined(existingJunctionRecord)) {
+ await deleteOneRecord(existingJunctionRecord.id);
+ } else {
+ await createOneRecord({
+ [activityJoinColumnName]: activityId,
+ [targetJoinColumnName]: targetRecord.id,
+ });
+ }
+
+ await Promise.all([
+ refetch(),
+ apolloCoreClient.refetchQueries({ include: [timelineQuery] }),
+ ]);
+ } finally {
+ setPendingActivityIds((currentIds) =>
+ currentIds.filter((id) => id !== activityId),
+ );
+ }
+ };
+
+ return { linkedActivityIds, pendingActivityIds, toggleActivityLink };
+};
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/calendar/components/WidgetActionCalendar.tsx b/packages/twenty-front/src/modules/page-layout/widgets/calendar/components/WidgetActionCalendar.tsx
new file mode 100644
index 00000000000..56f13ab676a
--- /dev/null
+++ b/packages/twenty-front/src/modules/page-layout/widgets/calendar/components/WidgetActionCalendar.tsx
@@ -0,0 +1,24 @@
+import { LinkCalendarEventsDropdown } from '@/activities/calendar/components/LinkCalendarEventsDropdown';
+import { WidgetActionCalendarEventCreate } from '@/page-layout/widgets/calendar/components/WidgetActionCalendarEventCreate';
+import { WidgetCardHeaderActionButton } from '@/page-layout/widgets/widget-card/components/WidgetCardHeaderActionButton';
+import { useLingui } from '@lingui/react/macro';
+import { IconLink } from 'twenty-ui/icon';
+
+export const WidgetActionCalendar = () => {
+ const { t } = useLingui();
+
+ return (
+ <>
+ <LinkCalendarEventsDropdown
+ dropdownIdPrefix="widget-action-calendar-link-events"
+ trigger={
+ <WidgetCardHeaderActionButton
+ Icon={IconLink}
+ label={t`Link events`}
+ />
+ }
+ />
+ <WidgetActionCalendarEventCreate />
+ </>
+ );
+};
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/emails/components/WidgetActionEmails.tsx b/packages/twenty-front/src/modules/page-layout/widgets/emails/components/WidgetActionEmails.tsx
new file mode 100644
index 00000000000..618f7d09c28
--- /dev/null
+++ b/packages/twenty-front/src/modules/page-layout/widgets/emails/components/WidgetActionEmails.tsx
@@ -0,0 +1,24 @@
+import { LinkEmailThreadsDropdown } from '@/activities/emails/components/LinkEmailThreadsDropdown';
+import { WidgetActionEmailCompose } from '@/page-layout/widgets/emails/components/WidgetActionEmailCompose';
+import { WidgetCardHeaderActionButton } from '@/page-layout/widgets/widget-card/components/WidgetCardHeaderActionButton';
+import { useLingui } from '@lingui/react/macro';
+import { IconLink } from 'twenty-ui/icon';
+
+export const WidgetActionEmails = () => {
+ const { t } = useLingui();
+
+ return (
+ <>
+ <LinkEmailThreadsDropdown
+ dropdownIdPrefix="widget-action-email-link-threads"
+ trigger={
+ <WidgetCardHeaderActionButton
+ Icon={IconLink}
+ label={t`Link email threads`}
+ />
+ }
+ />
+ <WidgetActionEmailCompose />
+ </>
+ );
+};
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/utils/getWidgetHeaderActionDefinition.ts b/packages/twenty-front/src/modules/page-layout/widgets/utils/getWidgetHeaderActionDefinition.ts
index 7bbcdfd2e82..d3dc26ba793 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/utils/getWidgetHeaderActionDefinition.ts
+++ b/packages/twenty-front/src/modules/page-layout/widgets/utils/getWidgetHeaderActionDefinition.ts
@@ -3,8 +3,8 @@ import { WidgetActionCallRecordingSummary } from '@/page-layout/widgets/call-rec
import { WidgetActionCallRecordingTranscript } from '@/page-layout/widgets/call-recording-transcript/components/WidgetActionCallRecordingTranscript';
import { WidgetActionChatThreadCreate } from '@/page-layout/widgets/chat-threads/components/WidgetActionChatThreadCreate';
import { WidgetFieldActions } from '@/page-layout/widgets/components/WidgetFieldActions';
-import { WidgetActionCalendarEventCreate } from '@/page-layout/widgets/calendar/components/WidgetActionCalendarEventCreate';
-import { WidgetActionEmailCompose } from '@/page-layout/widgets/emails/components/WidgetActionEmailCompose';
+import { WidgetActionCalendar } from '@/page-layout/widgets/calendar/components/WidgetActionCalendar';
+import { WidgetActionEmails } from '@/page-layout/widgets/emails/components/WidgetActionEmails';
import { WidgetActionFileAttach } from '@/page-layout/widgets/files/components/WidgetActionFileAttach';
import { WidgetActionNoteCreate } from '@/page-layout/widgets/notes/components/WidgetActionNoteCreate';
import { WidgetActionTaskCreate } from '@/page-layout/widgets/tasks/components/WidgetActionTaskCreate';
@@ -32,8 +32,8 @@ const widgetHeaderActionComponentByWidgetType: Partial<
Record<WidgetType, ComponentType<WidgetHeaderActionComponentProps>>
> = {
[WidgetType.FIELD]: WidgetFieldActions,
- [WidgetType.CALENDAR]: WidgetActionCalendarEventCreate,
- [WidgetType.EMAILS]: WidgetActionEmailCompose,
+ [WidgetType.CALENDAR]: WidgetActionCalendar,
+ [WidgetType.EMAILS]: WidgetActionEmails,
[WidgetType.TASKS]: WidgetActionTaskCreate,
[WidgetType.NOTES]: WidgetActionNoteCreate,
[WidgetType.FILES]: WidgetActionFileAttach,
diff --git a/packages/twenty-front/src/modules/ui/feedback/empty-state/components/EmptyState.tsx b/packages/twenty-front/src/modules/ui/feedback/empty-state/components/EmptyState.tsx
index a764d362f6f..a5885effd0f 100644
--- a/packages/twenty-front/src/modules/ui/feedback/empty-state/components/EmptyState.tsx
+++ b/packages/twenty-front/src/modules/ui/feedback/empty-state/components/EmptyState.tsx
@@ -48,9 +48,17 @@ const StyledDescription = styled.div`
width: 50%;
`;
+const StyledActions = styled.div`
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--t-spacing-2);
+ justify-content: center;
+`;
+
export const EmptyState = {
Root: StyledRoot,
Content: StyledContent,
Title: StyledTitle,
Description: StyledDescription,
+ Actions: StyledActions,
};
diff --git a/packages/twenty-server/src/engine/core-modules/calendar/constants/calendar.constants.ts b/packages/twenty-server/src/engine/core-modules/calendar/constants/calendar.constants.ts
index 3a0d0be05fd..d4552f6c0aa 100644
--- a/packages/twenty-server/src/engine/core-modules/calendar/constants/calendar.constants.ts
+++ b/packages/twenty-server/src/engine/core-modules/calendar/constants/calendar.constants.ts
@@ -1,2 +1,3 @@
export const TIMELINE_CALENDAR_EVENTS_DEFAULT_PAGE_SIZE = 20;
export const TIMELINE_CALENDAR_EVENTS_MAX_PAGE_SIZE = 50;
+export const TIMELINE_CALENDAR_EVENTS_SEARCH_INPUT_MAX_LENGTH = 200;
diff --git a/packages/twenty-server/src/engine/core-modules/calendar/dtos/timeline-calendar-event-search-result.dto.ts b/packages/twenty-server/src/engine/core-modules/calendar/dtos/timeline-calendar-event-search-result.dto.ts
new file mode 100644
index 00000000000..7e50b0aedc4
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/calendar/dtos/timeline-calendar-event-search-result.dto.ts
@@ -0,0 +1,12 @@
+import { Field, ObjectType } from '@nestjs/graphql';
+
+import { TimelineCalendarEventDTO } from 'src/engine/core-modules/calendar/dtos/timeline-calendar-event.dto';
+
+@ObjectType('TimelineCalendarEventSearchResult')
+export class TimelineCalendarEventSearchResultDTO {
+ @Field(() => [TimelineCalendarEventDTO])
+ recordTimelineCalendarEvents: TimelineCalendarEventDTO[];
+
+ @Field(() => [TimelineCalendarEventDTO])
+ otherTimelineCalendarEvents: TimelineCalendarEventDTO[];
+}
diff --git a/packages/twenty-server/src/engine/core-modules/calendar/timeline-calendar-event.module.ts b/packages/twenty-server/src/engine/core-modules/calendar/timeline-calendar-event.module.ts
index 5bf12b284bd..37add2b0d11 100644
--- a/packages/twenty-server/src/engine/core-modules/calendar/timeline-calendar-event.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/calendar/timeline-calendar-event.module.ts
@@ -4,7 +4,6 @@ import { TypeOrmModule } from '@nestjs/typeorm';
import { FileUrlModule } from 'src/engine/core-modules/file/file-url/file-url.module';
import { TimelineCalendarEventResolver } from 'src/engine/core-modules/calendar/timeline-calendar-event.resolver';
import { TimelineCalendarEventService } from 'src/engine/core-modules/calendar/timeline-calendar-event.service';
-import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { RelatedPersonIdsModule } from 'src/engine/core-modules/related-person-ids/related-person-ids.module';
import { CalendarChannelEntity } from 'src/engine/metadata-modules/calendar-channel/entities/calendar-channel.entity';
import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
@@ -15,11 +14,7 @@ import { TargetModule } from 'src/engine/core-modules/target/target.module';
FileUrlModule,
RelatedPersonIdsModule,
TargetModule,
- TypeOrmModule.forFeature([
- CalendarChannelEntity,
- ConnectedAccountEntity,
- UserWorkspaceEntity,
- ]),
+ TypeOrmModule.forFeature([CalendarChannelEntity, ConnectedAccountEntity]),
],
exports: [],
providers: [TimelineCalendarEventResolver, TimelineCalendarEventService],
diff --git a/packages/twenty-server/src/engine/core-modules/calendar/timeline-calendar-event.resolver.ts b/packages/twenty-server/src/engine/core-modules/calendar/timeline-calendar-event.resolver.ts
index bd56a9f8dc6..e4dddb6b291 100644
--- a/packages/twenty-server/src/engine/core-modules/calendar/timeline-calendar-event.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/calendar/timeline-calendar-event.resolver.ts
@@ -1,15 +1,19 @@
import { UseGuards, UseFilters } from '@nestjs/common';
import { Args, ArgsType, Field, Int, Query } from '@nestjs/graphql';
-import { Max } from 'class-validator';
+import { Max, MaxLength } from 'class-validator';
import { CoreObjectNameSingular } from 'twenty-shared/types';
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
-import { TIMELINE_CALENDAR_EVENTS_MAX_PAGE_SIZE } from 'src/engine/core-modules/calendar/constants/calendar.constants';
+import {
+ TIMELINE_CALENDAR_EVENTS_MAX_PAGE_SIZE,
+ TIMELINE_CALENDAR_EVENTS_SEARCH_INPUT_MAX_LENGTH,
+} from 'src/engine/core-modules/calendar/constants/calendar.constants';
+import { TimelineCalendarEventSearchResultDTO } from 'src/engine/core-modules/calendar/dtos/timeline-calendar-event-search-result.dto';
import { TimelineCalendarEventsWithTotalDTO } from 'src/engine/core-modules/calendar/dtos/timeline-calendar-events-with-total.dto';
import { TimelineCalendarEventService } from 'src/engine/core-modules/calendar/timeline-calendar-event.service';
import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
-import { AuthWorkspaceMemberId } from 'src/engine/decorators/auth/auth-workspace-member-id.decorator';
+import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';
import { CoreResolver } from 'src/engine/api/graphql/graphql-config/decorators/core-resolver.decorator';
import { CustomPermissionGuard } from 'src/engine/guards/custom-permission.guard';
import { AuthPrincipalGuard } from 'src/engine/guards/auth-principal.guard';
@@ -32,6 +36,19 @@ class GetTimelineCalendarEventsFromObjectRecordArgs {
pageSize: number;
}
+@ArgsType()
+class SearchTimelineCalendarEventsArgs {
+ @Field(() => String)
+ objectNameSingular: string;
+
+ @Field(() => UUIDScalarType)
+ recordId: string;
+
+ @Field(() => String, { nullable: true })
+ @MaxLength(TIMELINE_CALENDAR_EVENTS_SEARCH_INPUT_MAX_LENGTH)
+ searchInput?: string;
+}
+
@ArgsType()
class GetTimelineCalendarEventsFromPersonIdArgs {
@Field(() => UUIDScalarType)
@@ -101,11 +118,11 @@ export class TimelineCalendarEventResolver {
page,
pageSize,
}: GetTimelineCalendarEventsFromObjectRecordArgs,
- @AuthWorkspaceMemberId() workspaceMemberId: string,
+ @AuthUserWorkspaceId() userWorkspaceId: string,
@AuthWorkspace() workspace: WorkspaceEntity,
) {
return this.timelineCalendarEventService.getCalendarEventsFromObjectRecord({
- currentWorkspaceMemberId: workspaceMemberId,
+ userWorkspaceId,
objectNameSingular,
recordId,
workspaceId: workspace.id,
@@ -114,17 +131,39 @@ export class TimelineCalendarEventResolver {
});
}
+ @Query(() => TimelineCalendarEventSearchResultDTO)
+ async searchTimelineCalendarEvents(
+ @Args()
+ {
+ objectNameSingular,
+ recordId,
+ searchInput,
+ }: SearchTimelineCalendarEventsArgs,
+ @AuthUserWorkspaceId() userWorkspaceId: string,
+ @AuthWorkspace() workspace: WorkspaceEntity,
+ ) {
+ return this.timelineCalendarEventService.searchCalendarEventsFromObjectRecord(
+ {
+ userWorkspaceId,
+ objectNameSingular,
+ recordId,
+ workspaceId: workspace.id,
+ searchInput,
+ },
+ );
+ }
+
@Query(() => TimelineCalendarEventsWithTotalDTO, {
deprecationReason: 'Use getTimelineCalendarEventsFromObjectRecord instead',
})
async getTimelineCalendarEventsFromPersonId(
@Args()
{ personId, page, pageSize }: GetTimelineCalendarEventsFromPersonIdArgs,
- @AuthWorkspaceMemberId() workspaceMemberId: string,
+ @AuthUserWorkspaceId() userWorkspaceId: string,
@AuthWorkspace() workspace: WorkspaceEntity,
) {
return this.timelineCalendarEventService.getCalendarEventsFromObjectRecord({
- currentWorkspaceMemberId: workspaceMemberId,
+ userWorkspaceId,
objectNameSingular: CoreObjectNameSingular.Person,
recordId: personId,
workspaceId: workspace.id,
@@ -139,11 +178,11 @@ export class TimelineCalendarEventResolver {
async getTimelineCalendarEventsFromCompanyId(
@Args()
{ companyId, page, pageSize }: GetTimelineCalendarEventsFromCompanyIdArgs,
- @AuthWorkspaceMemberId() workspaceMemberId: string,
+ @AuthUserWorkspaceId() userWorkspaceId: string,
@AuthWorkspace() workspace: WorkspaceEntity,
) {
return this.timelineCalendarEventService.getCalendarEventsFromObjectRecord({
- currentWorkspaceMemberId: workspaceMemberId,
+ userWorkspaceId,
objectNameSingular: CoreObjectNameSingular.Company,
recordId: companyId,
workspaceId: workspace.id,
@@ -162,11 +201,11 @@ export class TimelineCalendarEventResolver {
page,
pageSize,
}: GetTimelineCalendarEventsFromOpportunityIdArgs,
- @AuthWorkspaceMemberId() workspaceMemberId: string,
+ @AuthUserWorkspaceId() userWorkspaceId: string,
@AuthWorkspace() workspace: WorkspaceEntity,
) {
return this.timelineCalendarEventService.getCalendarEventsFromObjectRecord({
- currentWorkspaceMemberId: workspaceMemberId,
+ userWorkspaceId,
objectNameSingular: CoreObjectNameSingular.Opportunity,
recordId: opportunityId,
workspaceId: workspace.id,
diff --git a/packages/twenty-server/src/engine/core-modules/calendar/timeline-calendar-event.service.ts b/packages/twenty-server/src/engine/core-modules/calendar/timeline-calendar-event.service.ts
index 9d1544f8ab4..aceb0ca68b2 100644
--- a/packages/twenty-server/src/engine/core-modules/calendar/timeline-calendar-event.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/calendar/timeline-calendar-event.service.ts
@@ -3,25 +3,31 @@ import { InjectRepository } from '@nestjs/typeorm';
import omit from 'lodash.omit';
import { FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED } from 'twenty-shared/constants';
-import { isDefined } from 'twenty-shared/utils';
+import { isNonEmptyString } from '@sniptt/guards';
+import {
+ escapeForIlike,
+ isDefined,
+ isNonEmptyArray,
+} from 'twenty-shared/utils';
import { Any, In, type Repository } from 'typeorm';
import { CalendarChannelVisibility } from 'twenty-shared/types';
import { TIMELINE_CALENDAR_EVENTS_DEFAULT_PAGE_SIZE } from 'src/engine/core-modules/calendar/constants/calendar.constants';
+import { type TimelineCalendarEventSearchResultDTO } from 'src/engine/core-modules/calendar/dtos/timeline-calendar-event-search-result.dto';
+import { type TimelineCalendarEventDTO } from 'src/engine/core-modules/calendar/dtos/timeline-calendar-event.dto';
import { type TimelineCalendarEventsWithTotalDTO } from 'src/engine/core-modules/calendar/dtos/timeline-calendar-events-with-total.dto';
+import { isCalendarChannelFullyVisible } from 'src/engine/core-modules/calendar/utils/is-calendar-channel-fully-visible.util';
import { FileUrlService } from 'src/engine/core-modules/file/file-url/file-url.service';
import { RelatedPersonIdsService } from 'src/engine/core-modules/related-person-ids/services/related-person-ids.service';
import { type TargetFilter } from 'src/engine/core-modules/target/utils/get-target-field-name-for-object-record.util';
import { MessageCalendarTargetReadinessService } from 'src/engine/core-modules/target/services/message-calendar-target-readiness.service';
import { CalendarChannelEntity } from 'src/engine/metadata-modules/calendar-channel/entities/calendar-channel.entity';
import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
-import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
import { type CalendarEventWorkspaceEntity } from 'src/modules/calendar/common/standard-objects/calendar-event.workspace-entity';
import { type CallRecordingStatus } from 'src/modules/call-recording/common/enums/call-recording-status.enum';
import { type CallRecordingWorkspaceEntity } from 'src/modules/call-recording/standard-objects/call-recording.workspace-entity';
-import { type WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-member/standard-objects/workspace-member.workspace-entity';
@Injectable()
export class TimelineCalendarEventService {
@@ -31,22 +37,20 @@ export class TimelineCalendarEventService {
private readonly calendarChannelRepository: Repository<CalendarChannelEntity>,
@InjectRepository(ConnectedAccountEntity)
private readonly connectedAccountRepository: Repository<ConnectedAccountEntity>,
- @InjectRepository(UserWorkspaceEntity)
- private readonly userWorkspaceRepository: Repository<UserWorkspaceEntity>,
private readonly relatedPersonIdsService: RelatedPersonIdsService,
private readonly fileUrlService: FileUrlService,
private readonly messageCalendarTargetReadinessService: MessageCalendarTargetReadinessService,
) {}
async getCalendarEventsFromPersonIds({
- currentWorkspaceMemberId,
+ userWorkspaceId,
personIds,
workspaceId,
page = 1,
pageSize = TIMELINE_CALENDAR_EVENTS_DEFAULT_PAGE_SIZE,
targetFilter,
}: {
- currentWorkspaceMemberId: string;
+ userWorkspaceId: string;
personIds: string[];
workspaceId: string;
page: number;
@@ -105,239 +109,27 @@ export class TimelineCalendarEventService {
};
}
- const [events] = await calendarEventRepository.findAndCount({
- where: {
- id: Any(ids),
- },
- relations: {
- calendarEventParticipants: {
- person: true,
- workspaceMember: true,
- },
- calendarChannelEventAssociations: true,
- },
- });
-
- const callRecordingRepository =
- this.workspaceOrmManager.getRepository<CallRecordingWorkspaceEntity>(
- 'callRecording',
- { shouldBypassPermissionChecks: true },
- );
-
- const callRecordings = await callRecordingRepository.find({
- where: {
- calendarEventId: Any(ids),
- },
- select: {
- id: true,
- status: true,
- applicationId: true,
- calendarEventId: true,
- },
- });
-
- const callRecordingsByCalendarEventId = callRecordings.reduce<
- Map<
- string,
- {
- id: string;
- status: CallRecordingStatus;
- applicationId: string | null;
- }[]
- >
- >((acc, callRecording) => {
- if (!isDefined(callRecording.calendarEventId)) {
- return acc;
- }
-
- const existing = acc.get(callRecording.calendarEventId) ?? [];
-
- existing.push({
- id: callRecording.id,
- status: callRecording.status,
- applicationId: callRecording.applicationId ?? null,
- });
- acc.set(callRecording.calendarEventId, existing);
-
- return acc;
- }, new Map());
-
- const allCalendarChannelIds = [
- ...new Set(
- events.flatMap((event) =>
- event.calendarChannelEventAssociations.map(
- (association) => association.calendarChannelId,
- ),
- ),
- ),
- ];
-
- const calendarChannels =
- allCalendarChannelIds.length > 0
- ? await this.calendarChannelRepository.find({
- where: { id: In(allCalendarChannelIds), workspaceId },
- })
- : [];
-
- const workspaceMemberRepo =
- this.workspaceOrmManager.getRepository<WorkspaceMemberWorkspaceEntity>(
- 'workspaceMember',
- { shouldBypassPermissionChecks: true },
- );
-
- const currentMember = await workspaceMemberRepo.findOne({
- where: { id: currentWorkspaceMemberId },
- select: { userId: true },
- });
-
- const currentUserWorkspaceId = currentMember
- ? ((
- await this.userWorkspaceRepository.findOne({
- where: { userId: currentMember.userId, workspaceId },
- select: { id: true },
- })
- )?.id ?? null)
- : null;
-
- const connectedAccountIds = [
- ...new Set(
- calendarChannels.map((channel) => channel.connectedAccountId),
- ),
- ];
-
- const ownedAccountIds =
- connectedAccountIds.length > 0 && currentUserWorkspaceId
- ? new Set(
- (
- await this.connectedAccountRepository.find({
- where: {
- id: In(connectedAccountIds),
- userWorkspaceId: currentUserWorkspaceId,
- },
- select: { id: true },
- })
- ).map((a) => a.id),
- )
- : new Set<string>();
-
- const calendarChannelMap = new Map(
- calendarChannels.map((channel) => [
- channel.id,
- {
- visibility: channel.visibility,
- isOwnedByCurrentUser: ownedAccountIds.has(
- channel.connectedAccountId,
- ),
- },
- ]),
- );
-
- const orderedEvents = events.sort(
- (a, b) => ids.indexOf(a.id) - ids.indexOf(b.id),
- );
-
- const timelineCalendarEventPromises = orderedEvents.map(async (event) => {
- const participantPromises = event.calendarEventParticipants.map(
- async (participant) => {
- const personAvatarFileUrl =
- await this.fileUrlService.signFirstFilesFieldFileUrl({
- filesFieldValue: participant.person?.avatarFile,
- workspaceId,
- });
-
- return {
- calendarEventId: event.id,
- personId: participant.personId ?? null,
- workspaceMemberId: participant.workspaceMemberId ?? null,
- firstName:
- participant.person?.name?.firstName ||
- participant.workspaceMember?.name.firstName ||
- '',
- lastName:
- participant.person?.name?.lastName ||
- participant.workspaceMember?.name.lastName ||
- '',
- displayName:
- participant.person?.name?.firstName ||
- participant.person?.name?.lastName ||
- participant.workspaceMember?.name.firstName ||
- participant.workspaceMember?.name.lastName ||
- participant.displayName ||
- participant.handle ||
- '',
- avatarUrl:
- personAvatarFileUrl ||
- participant.person?.avatarUrl ||
- participant.workspaceMember?.avatarUrl ||
- '',
- handle: participant.handle ?? '',
- };
- },
- );
-
- const participants = await Promise.all(participantPromises);
-
- const hasFullAccess = event.calendarChannelEventAssociations.some(
- (association) => {
- const channel = calendarChannelMap.get(
- association.calendarChannelId,
- );
-
- return (
- channel?.visibility === 'SHARE_EVERYTHING' ||
- channel?.isOwnedByCurrentUser
- );
- },
- );
-
- const visibility = hasFullAccess
- ? CalendarChannelVisibility.SHARE_EVERYTHING
- : CalendarChannelVisibility.METADATA;
-
- return {
- ...omit(event, [
- 'calendarEventParticipants',
- 'calendarChannelEventAssociations',
- ]),
- title:
- visibility === CalendarChannelVisibility.METADATA
- ? FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED
- : (event.title ?? ''),
- description:
- visibility === CalendarChannelVisibility.METADATA
- ? FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED
- : (event.description ?? ''),
- startsAt: event.startsAt as unknown as Date,
- endsAt: event.endsAt as unknown as Date,
- participants,
- callRecordings: callRecordingsByCalendarEventId.get(event.id) ?? [],
- visibility,
- location: event.location ?? '',
- conferenceSolution: event.conferenceSolution ?? '',
- };
- });
-
- const timelineCalendarEvents = await Promise.all(
- timelineCalendarEventPromises,
- );
-
return {
totalNumberOfCalendarEvents,
- timelineCalendarEvents,
+ timelineCalendarEvents: await this.formatTimelineCalendarEvents({
+ calendarEventIds: ids,
+ userWorkspaceId,
+ workspaceId,
+ }),
relatedPersonIds: personIds,
};
}, authContext);
}
async getCalendarEventsFromObjectRecord({
- currentWorkspaceMemberId,
+ userWorkspaceId,
objectNameSingular,
recordId,
workspaceId,
page = 1,
pageSize = TIMELINE_CALENDAR_EVENTS_DEFAULT_PAGE_SIZE,
}: {
- currentWorkspaceMemberId: string;
+ userWorkspaceId: string;
objectNameSingular: string;
recordId: string;
workspaceId: string;
@@ -365,7 +157,7 @@ export class TimelineCalendarEventService {
}
return this.getCalendarEventsFromPersonIds({
- currentWorkspaceMemberId,
+ userWorkspaceId,
personIds,
workspaceId,
page,
@@ -373,4 +165,429 @@ export class TimelineCalendarEventService {
...(isDefined(targetFilter) && { targetFilter }),
});
}
+
+ async searchCalendarEventsFromObjectRecord({
+ userWorkspaceId,
+ objectNameSingular,
+ recordId,
+ workspaceId,
+ searchInput,
+ }: {
+ userWorkspaceId: string;
+ objectNameSingular: string;
+ recordId: string;
+ workspaceId: string;
+ searchInput?: string;
+ }): Promise<TimelineCalendarEventSearchResultDTO> {
+ if (!isNonEmptyString(searchInput?.trim())) {
+ const { timelineCalendarEvents } =
+ await this.getCalendarEventsFromObjectRecord({
+ userWorkspaceId,
+ objectNameSingular,
+ recordId,
+ workspaceId,
+ page: 1,
+ pageSize: TIMELINE_CALENDAR_EVENTS_DEFAULT_PAGE_SIZE,
+ });
+
+ return {
+ recordTimelineCalendarEvents: timelineCalendarEvents,
+ otherTimelineCalendarEvents: [],
+ };
+ }
+
+ const [
+ personIds,
+ targetFilter,
+ { ownedCalendarChannelIds, titleVisibleCalendarChannelIds },
+ ] = await Promise.all([
+ this.relatedPersonIdsService.getRelatedPersonIds({
+ workspaceId,
+ objectNameSingular,
+ recordId,
+ }),
+ this.messageCalendarTargetReadinessService.resolveTargetFilter({
+ objectNameSingular,
+ recordId,
+ workspaceId,
+ }),
+ this.getSearchableCalendarChannelIds({ userWorkspaceId, workspaceId }),
+ ]);
+
+ return this.workspaceOrmManager.executeInWorkspaceContext(async () => {
+ // Only channels sharing everything are searched, so a match never reveals a hidden title
+ const recordCalendarEventIds = await this.searchCalendarEventIds({
+ searchInput,
+ calendarChannelIds: titleVisibleCalendarChannelIds,
+ recordFilter: { targetFilter, personIds },
+ });
+
+ // The fallback searches only the viewer's own calendars, as nothing else narrows it down
+ const otherCalendarEventIds = await this.searchCalendarEventIds({
+ searchInput,
+ calendarChannelIds: ownedCalendarChannelIds,
+ excludedCalendarEventIds: recordCalendarEventIds,
+ });
+
+ const recordCalendarEventIdSet = new Set(recordCalendarEventIds);
+
+ const timelineCalendarEvents = await this.formatTimelineCalendarEvents({
+ calendarEventIds: [...recordCalendarEventIds, ...otherCalendarEventIds],
+ userWorkspaceId,
+ workspaceId,
+ });
+
+ return {
+ recordTimelineCalendarEvents: timelineCalendarEvents.filter(({ id }) =>
+ recordCalendarEventIdSet.has(id),
+ ),
+ otherTimelineCalendarEvents: timelineCalendarEvents.filter(
+ ({ id }) => !recordCalendarEventIdSet.has(id),
+ ),
+ };
+ }, buildSystemAuthContext(workspaceId));
+ }
+
+ private async searchCalendarEventIds({
+ searchInput,
+ calendarChannelIds,
+ recordFilter,
+ excludedCalendarEventIds = [],
+ }: {
+ searchInput: string;
+ calendarChannelIds: string[];
+ recordFilter?: { targetFilter?: TargetFilter; personIds: string[] };
+ excludedCalendarEventIds?: string[];
+ }): Promise<string[]> {
+ const searchWords = searchInput
+ .trim()
+ .split(/\s+/)
+ .filter(isNonEmptyString);
+
+ if (searchWords.length === 0 || calendarChannelIds.length === 0) {
+ return [];
+ }
+
+ if (
+ isDefined(recordFilter) &&
+ !isDefined(recordFilter.targetFilter) &&
+ recordFilter.personIds.length === 0
+ ) {
+ return [];
+ }
+
+ const calendarEventRepository =
+ this.workspaceOrmManager.getRepository<CalendarEventWorkspaceEntity>(
+ 'calendarEvent',
+ { shouldBypassPermissionChecks: true },
+ );
+
+ const queryBuilder = calendarEventRepository
+ .createQueryBuilder('calendarEvent')
+ .select('calendarEvent.id', 'id')
+ .addSelect('calendarEvent.startsAt', 'startsAt')
+ .innerJoin(
+ 'calendarEvent.calendarChannelEventAssociations',
+ 'calendarChannelEventAssociations',
+ )
+ .where(
+ 'calendarChannelEventAssociations.calendarChannelId IN (:...calendarChannelIds)',
+ { calendarChannelIds },
+ );
+
+ searchWords.forEach((searchWord, index) => {
+ const parameterName = `searchWord${index}`;
+
+ queryBuilder.andWhere(`calendarEvent.title ILIKE :${parameterName}`, {
+ [parameterName]: `%${escapeForIlike(searchWord)}%`,
+ });
+ });
+
+ if (isDefined(recordFilter?.targetFilter)) {
+ queryBuilder
+ .innerJoin('calendarEvent.calendarEventTargets', 'calendarEventTargets')
+ .andWhere(
+ `calendarEventTargets.${recordFilter.targetFilter.fieldName} = :targetRecordId`,
+ { targetRecordId: recordFilter.targetFilter.recordId },
+ );
+ } else if (isDefined(recordFilter)) {
+ queryBuilder
+ .innerJoin(
+ 'calendarEvent.calendarEventParticipants',
+ 'calendarEventParticipants',
+ )
+ .andWhere('calendarEventParticipants.personId IN (:...personIds)', {
+ personIds: recordFilter.personIds,
+ });
+ }
+
+ if (excludedCalendarEventIds.length > 0) {
+ queryBuilder.andWhere(
+ 'calendarEvent.id NOT IN (:...excludedCalendarEventIds)',
+ { excludedCalendarEventIds },
+ );
+ }
+
+ const calendarEvents = await queryBuilder
+ .groupBy('calendarEvent.id')
+ .addGroupBy('calendarEvent.startsAt')
+ .orderBy('calendarEvent.startsAt', 'DESC')
+ .limit(TIMELINE_CALENDAR_EVENTS_DEFAULT_PAGE_SIZE)
+ .getRawMany<{ id: string }>();
+
+ return calendarEvents.map(({ id }) => id);
+ }
+
+ private async getSearchableCalendarChannelIds({
+ userWorkspaceId,
+ workspaceId,
+ }: {
+ userWorkspaceId: string;
+ workspaceId: string;
+ }): Promise<{
+ ownedCalendarChannelIds: string[];
+ titleVisibleCalendarChannelIds: string[];
+ }> {
+ const [ownedConnectedAccounts, calendarChannels] = await Promise.all([
+ this.connectedAccountRepository.find({
+ where: { userWorkspaceId, workspaceId },
+ select: { id: true },
+ }),
+ this.calendarChannelRepository.find({
+ where: { workspaceId },
+ select: { id: true, visibility: true, connectedAccountId: true },
+ }),
+ ]);
+
+ const ownedConnectedAccountIds = new Set(
+ ownedConnectedAccounts.map((connectedAccount) => connectedAccount.id),
+ );
+
+ const ownedCalendarChannelIds: string[] = [];
+ const titleVisibleCalendarChannelIds: string[] = [];
+
+ for (const calendarChannel of calendarChannels) {
+ const isOwnedByCurrentUser = ownedConnectedAccountIds.has(
+ calendarChannel.connectedAccountId,
+ );
+
+ if (isOwnedByCurrentUser) {
+ ownedCalendarChannelIds.push(calendarChannel.id);
+ }
+
+ if (
+ isCalendarChannelFullyVisible({
+ visibility: calendarChannel.visibility,
+ isOwnedByCurrentUser,
+ })
+ ) {
+ titleVisibleCalendarChannelIds.push(calendarChannel.id);
+ }
+ }
+
+ return { ownedCalendarChannelIds, titleVisibleCalendarChannelIds };
+ }
+
+ private async formatTimelineCalendarEvents({
+ calendarEventIds: ids,
+ userWorkspaceId,
+ workspaceId,
+ }: {
+ calendarEventIds: string[];
+ userWorkspaceId: string;
+ workspaceId: string;
+ }): Promise<TimelineCalendarEventDTO[]> {
+ if (ids.length === 0) {
+ return [];
+ }
+
+ const calendarEventRepository =
+ this.workspaceOrmManager.getRepository<CalendarEventWorkspaceEntity>(
+ 'calendarEvent',
+ { shouldBypassPermissionChecks: true },
+ );
+
+ const [events] = await calendarEventRepository.findAndCount({
+ where: {
+ id: Any(ids),
+ },
+ relations: {
+ calendarEventParticipants: {
+ person: true,
+ workspaceMember: true,
+ },
+ calendarChannelEventAssociations: true,
+ },
+ });
+
+ const callRecordingRepository =
+ this.workspaceOrmManager.getRepository<CallRecordingWorkspaceEntity>(
+ 'callRecording',
+ { shouldBypassPermissionChecks: true },
+ );
+
+ const callRecordings = await callRecordingRepository.find({
+ where: {
+ calendarEventId: Any(ids),
+ },
+ select: {
+ id: true,
+ status: true,
+ applicationId: true,
+ calendarEventId: true,
+ },
+ });
+
+ const callRecordingsByCalendarEventId = callRecordings.reduce<
+ Map<
+ string,
+ {
+ id: string;
+ status: CallRecordingStatus;
+ applicationId: string | null;
+ }[]
+ >
+ >((acc, callRecording) => {
+ if (!isDefined(callRecording.calendarEventId)) {
+ return acc;
+ }
+
+ const existing = acc.get(callRecording.calendarEventId) ?? [];
+
+ existing.push({
+ id: callRecording.id,
+ status: callRecording.status,
+ applicationId: callRecording.applicationId ?? null,
+ });
+ acc.set(callRecording.calendarEventId, existing);
+
+ return acc;
+ }, new Map());
+
+ const allCalendarChannelIds = [
+ ...new Set(
+ events.flatMap((event) =>
+ event.calendarChannelEventAssociations.map(
+ (association) => association.calendarChannelId,
+ ),
+ ),
+ ),
+ ];
+
+ const calendarChannels = isNonEmptyArray(allCalendarChannelIds)
+ ? await this.calendarChannelRepository.find({
+ where: { id: In(allCalendarChannelIds), workspaceId },
+ })
+ : [];
+
+ const connectedAccountIds = [
+ ...new Set(calendarChannels.map((channel) => channel.connectedAccountId)),
+ ];
+
+ const ownedAccountIds = isNonEmptyArray(connectedAccountIds)
+ ? new Set(
+ (
+ await this.connectedAccountRepository.find({
+ where: {
+ id: In(connectedAccountIds),
+ userWorkspaceId,
+ },
+ select: { id: true },
+ })
+ ).map((a) => a.id),
+ )
+ : new Set<string>();
+
+ const calendarChannelMap = new Map(
+ calendarChannels.map((channel) => [
+ channel.id,
+ {
+ visibility: channel.visibility,
+ isOwnedByCurrentUser: ownedAccountIds.has(channel.connectedAccountId),
+ },
+ ]),
+ );
+
+ const orderedEvents = events.sort(
+ (a, b) => ids.indexOf(a.id) - ids.indexOf(b.id),
+ );
+
+ const timelineCalendarEventPromises = orderedEvents.map(async (event) => {
+ const participantPromises = event.calendarEventParticipants.map(
+ async (participant) => {
+ const personAvatarFileUrl =
+ await this.fileUrlService.signFirstFilesFieldFileUrl({
+ filesFieldValue: participant.person?.avatarFile,
+ workspaceId,
+ });
+
+ return {
+ calendarEventId: event.id,
+ personId: participant.personId ?? null,
+ workspaceMemberId: participant.workspaceMemberId ?? null,
+ firstName:
+ participant.person?.name?.firstName ||
+ participant.workspaceMember?.name.firstName ||
+ '',
+ lastName:
+ participant.person?.name?.lastName ||
+ participant.workspaceMember?.name.lastName ||
+ '',
+ displayName:
+ participant.person?.name?.firstName ||
+ participant.person?.name?.lastName ||
+ participant.workspaceMember?.name.firstName ||
+ participant.workspaceMember?.name.lastName ||
+ participant.displayName ||
+ participant.handle ||
+ '',
+ avatarUrl:
+ personAvatarFileUrl ||
+ participant.person?.avatarUrl ||
+ participant.workspaceMember?.avatarUrl ||
+ '',
+ handle: participant.handle ?? '',
+ };
+ },
+ );
+
+ const participants = await Promise.all(participantPromises);
+
+ const hasFullAccess = event.calendarChannelEventAssociations.some(
+ (association) => {
+ const channel = calendarChannelMap.get(association.calendarChannelId);
+
+ return isDefined(channel) && isCalendarChannelFullyVisible(channel);
+ },
+ );
+
+ const visibility = hasFullAccess
+ ? CalendarChannelVisibility.SHARE_EVERYTHING
+ : CalendarChannelVisibility.METADATA;
+
+ return {
+ ...omit(event, [
+ 'calendarEventParticipants',
+ 'calendarChannelEventAssociations',
+ ]),
+ title:
+ visibility === CalendarChannelVisibility.METADATA
+ ? FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED
+ : (event.title ?? ''),
+ description:
+ visibility === CalendarChannelVisibility.METADATA
+ ? FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED
+ : (event.description ?? ''),
+ startsAt: event.startsAt as unknown as Date,
+ endsAt: event.endsAt as unknown as Date,
+ participants,
+ callRecordings: callRecordingsByCalendarEventId.get(event.id) ?? [],
+ visibility,
+ location: event.location ?? '',
+ conferenceSolution: event.conferenceSolution ?? '',
+ };
+ });
+
+ return Promise.all(timelineCalendarEventPromises);
+ }
}
diff --git a/packages/twenty-server/src/engine/core-modules/calendar/utils/is-calendar-channel-fully-visible.util.ts b/packages/twenty-server/src/engine/core-modules/calendar/utils/is-calendar-channel-fully-visible.util.ts
new file mode 100644
index 00000000000..f788fbdf210
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/calendar/utils/is-calendar-channel-fully-visible.util.ts
@@ -0,0 +1,11 @@
+import { CalendarChannelVisibility } from 'twenty-shared/types';
+
+export const isCalendarChannelFullyVisible = ({
+ visibility,
+ isOwnedByCurrentUser,
+}: {
+ visibility: CalendarChannelVisibility;
+ isOwnedByCurrentUser: boolean;
+}): boolean =>
+ isOwnedByCurrentUser ||
+ visibility === CalendarChannelVisibility.SHARE_EVERYTHING;
diff --git a/packages/twenty-server/src/engine/core-modules/messaging/constants/messaging.constants.ts b/packages/twenty-server/src/engine/core-modules/messaging/constants/messaging.constants.ts
index 4a75639236b..a9663a135ac 100644
--- a/packages/twenty-server/src/engine/core-modules/messaging/constants/messaging.constants.ts
+++ b/packages/twenty-server/src/engine/core-modules/messaging/constants/messaging.constants.ts
@@ -1,2 +1,3 @@
export const TIMELINE_THREADS_DEFAULT_PAGE_SIZE = 20;
export const TIMELINE_THREADS_MAX_PAGE_SIZE = 50;
+export const TIMELINE_THREADS_SEARCH_INPUT_MAX_LENGTH = 200;
diff --git a/packages/twenty-server/src/engine/core-modules/messaging/dtos/timeline-thread-search-result.dto.ts b/packages/twenty-server/src/engine/core-modules/messaging/dtos/timeline-thread-search-result.dto.ts
new file mode 100644
index 00000000000..33a7d2e0083
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/messaging/dtos/timeline-thread-search-result.dto.ts
@@ -0,0 +1,12 @@
+import { Field, ObjectType } from '@nestjs/graphql';
+
+import { TimelineThreadDTO } from 'src/engine/core-modules/messaging/dtos/timeline-thread.dto';
+
+@ObjectType('TimelineThreadSearchResult')
+export class TimelineThreadSearchResultDTO {
+ @Field(() => [TimelineThreadDTO])
+ recordTimelineThreads: TimelineThreadDTO[];
+
+ @Field(() => [TimelineThreadDTO])
+ otherTimelineThreads: TimelineThreadDTO[];
+}
diff --git a/packages/twenty-server/src/engine/core-modules/messaging/services/get-messages.service.ts b/packages/twenty-server/src/engine/core-modules/messaging/services/get-messages.service.ts
index d80297f291a..122bfc5bfce 100644
--- a/packages/twenty-server/src/engine/core-modules/messaging/services/get-messages.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/messaging/services/get-messages.service.ts
@@ -1,8 +1,11 @@
import { Injectable } from '@nestjs/common';
+import { isNonEmptyString } from '@sniptt/guards';
import { isDefined } from 'twenty-shared/utils';
import { TIMELINE_THREADS_DEFAULT_PAGE_SIZE } from 'src/engine/core-modules/messaging/constants/messaging.constants';
+import { type TimelineThreadSearchResultDTO } from 'src/engine/core-modules/messaging/dtos/timeline-thread-search-result.dto';
+import { type TimelineThreadDTO } from 'src/engine/core-modules/messaging/dtos/timeline-thread.dto';
import { type TimelineThreadsWithTotalDTO } from 'src/engine/core-modules/messaging/dtos/timeline-threads-with-total.dto';
import { TimelineMessagingService } from 'src/engine/core-modules/messaging/services/timeline-messaging.service';
import { formatThreads } from 'src/engine/core-modules/messaging/utils/format-threads.util';
@@ -18,14 +21,21 @@ export class GetMessagesService {
private readonly messageCalendarTargetReadinessService: MessageCalendarTargetReadinessService,
) {}
- async getMessagesFromPersonIds(
- workspaceMemberId: string,
- personIds: string[],
- workspaceId: string,
+ async getMessagesFromPersonIds({
+ userWorkspaceId,
+ personIds,
+ workspaceId,
page = 1,
- pageSize: number = TIMELINE_THREADS_DEFAULT_PAGE_SIZE,
- targetFilter?: TargetFilter,
- ): Promise<TimelineThreadsWithTotalDTO> {
+ pageSize = TIMELINE_THREADS_DEFAULT_PAGE_SIZE,
+ targetFilter,
+ }: {
+ userWorkspaceId: string;
+ personIds: string[];
+ workspaceId: string;
+ page?: number;
+ pageSize?: number;
+ targetFilter?: TargetFilter;
+ }): Promise<TimelineThreadsWithTotalDTO> {
const offset = (page - 1) * pageSize;
const { messageThreads, totalNumberOfThreads } =
@@ -45,6 +55,116 @@ export class GetMessagesService {
};
}
+ return {
+ totalNumberOfThreads,
+ timelineThreads: await this.formatTimelineThreads({
+ messageThreads,
+ userWorkspaceId,
+ workspaceId,
+ }),
+ relatedPersonIds: personIds,
+ };
+ }
+
+ async searchMessagesFromObjectRecord({
+ userWorkspaceId,
+ objectNameSingular,
+ recordId,
+ workspaceId,
+ searchInput,
+ }: {
+ userWorkspaceId: string;
+ objectNameSingular: string;
+ recordId: string;
+ workspaceId: string;
+ searchInput?: string;
+ }): Promise<TimelineThreadSearchResultDTO> {
+ if (!isNonEmptyString(searchInput?.trim())) {
+ const { timelineThreads } = await this.getMessagesFromObjectRecord({
+ userWorkspaceId,
+ objectNameSingular,
+ recordId,
+ workspaceId,
+ });
+
+ return {
+ recordTimelineThreads: timelineThreads,
+ otherTimelineThreads: [],
+ };
+ }
+
+ const [
+ personIds,
+ targetFilter,
+ { ownedMessageChannelIds, subjectVisibleMessageChannelIds },
+ ] = await Promise.all([
+ this.relatedPersonIdsService.getRelatedPersonIds({
+ workspaceId,
+ objectNameSingular,
+ recordId,
+ }),
+ this.messageCalendarTargetReadinessService.resolveTargetFilter({
+ objectNameSingular,
+ recordId,
+ workspaceId,
+ }),
+ this.timelineMessagingService.getSearchableMessageChannelIds({
+ userWorkspaceId,
+ workspaceId,
+ }),
+ ]);
+
+ // Only channels sharing at least the subject are searched, so a match never reveals a hidden subject
+ const recordMessageThreads =
+ await this.timelineMessagingService.searchMessageThreads({
+ workspaceId,
+ searchInput,
+ messageChannelIds: subjectVisibleMessageChannelIds,
+ recordFilter: { targetFilter, personIds },
+ });
+
+ // The fallback searches only the viewer's own mailboxes, as nothing else narrows it down
+ const otherMessageThreads =
+ await this.timelineMessagingService.searchMessageThreads({
+ workspaceId,
+ searchInput,
+ messageChannelIds: ownedMessageChannelIds,
+ excludedMessageThreadIds: recordMessageThreads.map(({ id }) => id),
+ });
+
+ const recordMessageThreadIds = new Set(
+ recordMessageThreads.map(({ id }) => id),
+ );
+
+ const timelineThreads = await this.formatTimelineThreads({
+ messageThreads: [...recordMessageThreads, ...otherMessageThreads],
+ userWorkspaceId,
+ workspaceId,
+ });
+
+ return {
+ recordTimelineThreads: timelineThreads.filter(({ id }) =>
+ recordMessageThreadIds.has(id),
+ ),
+ otherTimelineThreads: timelineThreads.filter(
+ ({ id }) => !recordMessageThreadIds.has(id),
+ ),
+ };
+ }
+
+ private async formatTimelineThreads({
+ messageThreads,
+ userWorkspaceId,
+ workspaceId,
+ }: {
+ messageThreads: Parameters<typeof formatThreads>[0];
+ userWorkspaceId: string;
+ workspaceId: string;
+ }): Promise<TimelineThreadDTO[]> {
+ if (messageThreads.length === 0) {
+ return [];
+ }
+
const messageThreadIds = messageThreads.map(
(messageThread) => messageThread.id,
);
@@ -56,31 +176,34 @@ export class GetMessagesService {
);
const threadVisibilityByThreadId =
- await this.timelineMessagingService.getThreadVisibilityByThreadId(
+ await this.timelineMessagingService.getThreadVisibilityByThreadId({
messageThreadIds,
- workspaceMemberId,
+ userWorkspaceId,
workspaceId,
- );
+ });
- return {
- totalNumberOfThreads,
- timelineThreads: formatThreads(
- messageThreads,
- threadParticipantsByThreadId,
- threadVisibilityByThreadId,
- ),
- relatedPersonIds: personIds,
- };
+ return formatThreads(
+ messageThreads,
+ threadParticipantsByThreadId,
+ threadVisibilityByThreadId,
+ );
}
- async getMessagesFromObjectRecord(
- workspaceMemberId: string,
- objectNameSingular: string,
- recordId: string,
- workspaceId: string,
+ async getMessagesFromObjectRecord({
+ userWorkspaceId,
+ objectNameSingular,
+ recordId,
+ workspaceId,
page = 1,
- pageSize: number = TIMELINE_THREADS_DEFAULT_PAGE_SIZE,
- ): Promise<TimelineThreadsWithTotalDTO> {
+ pageSize = TIMELINE_THREADS_DEFAULT_PAGE_SIZE,
+ }: {
+ userWorkspaceId: string;
+ objectNameSingular: string;
+ recordId: string;
+ workspaceId: string;
+ page?: number;
+ pageSize?: number;
+ }): Promise<TimelineThreadsWithTotalDTO> {
const personIds = await this.relatedPersonIdsService.getRelatedPersonIds({
workspaceId,
objectNameSingular,
@@ -101,13 +224,13 @@ export class GetMessagesService {
};
}
- return this.getMessagesFromPersonIds(
- workspaceMemberId,
+ return this.getMessagesFromPersonIds({
+ userWorkspaceId,
personIds,
workspaceId,
page,
pageSize,
targetFilter,
- );
+ });
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/messaging/services/timeline-messaging.service.ts b/packages/twenty-server/src/engine/core-modules/messaging/services/timeline-messaging.service.ts
index d96d81bc7f7..d86d2d841c1 100644
--- a/packages/twenty-server/src/engine/core-modules/messaging/services/timeline-messaging.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/messaging/services/timeline-messaging.service.ts
@@ -5,12 +5,14 @@ import {
MessageChannelVisibility,
MessageParticipantRole,
} from 'twenty-shared/types';
-import { isDefined } from 'twenty-shared/utils';
+import { isNonEmptyString } from '@sniptt/guards';
+import { escapeForIlike, isDefined } from 'twenty-shared/utils';
import { In, type Repository } from 'typeorm';
import { FileUrlService } from 'src/engine/core-modules/file/file-url/file-url.service';
+import { TIMELINE_THREADS_DEFAULT_PAGE_SIZE } from 'src/engine/core-modules/messaging/constants/messaging.constants';
import { type TimelineThreadDTO } from 'src/engine/core-modules/messaging/dtos/timeline-thread.dto';
-import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
+import { getEffectiveMessageChannelVisibility } from 'src/engine/core-modules/messaging/utils/get-effective-message-channel-visibility.util';
import { type TargetFilter } from 'src/engine/core-modules/target/utils/get-target-field-name-for-object-record.util';
import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
@@ -19,7 +21,15 @@ import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
import { type MessageParticipantWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-participant.workspace-entity';
import { type MessageThreadWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-thread.workspace-entity';
-import { type WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-member/standard-objects/workspace-member.workspace-entity';
+
+type TimelineMessageThread = Omit<
+ TimelineThreadDTO,
+ | 'firstParticipant'
+ | 'lastTwoParticipants'
+ | 'participantCount'
+ | 'read'
+ | 'visibility'
+>;
@Injectable()
export class TimelineMessagingService {
@@ -29,8 +39,6 @@ export class TimelineMessagingService {
private readonly messageChannelRepository: Repository<MessageChannelEntity>,
@InjectRepository(ConnectedAccountEntity)
private readonly connectedAccountRepository: Repository<ConnectedAccountEntity>,
- @InjectRepository(UserWorkspaceEntity)
- private readonly userWorkspaceRepository: Repository<UserWorkspaceEntity>,
private readonly fileUrlService: FileUrlService,
) {}
@@ -41,14 +49,7 @@ export class TimelineMessagingService {
pageSize: number,
targetFilter?: TargetFilter,
): Promise<{
- messageThreads: Omit<
- TimelineThreadDTO,
- | 'firstParticipant'
- | 'lastTwoParticipants'
- | 'participantCount'
- | 'read'
- | 'visibility'
- >[];
+ messageThreads: TimelineMessageThread[];
totalNumberOfThreads: number;
}> {
const authContext = buildSystemAuthContext(workspaceId);
@@ -74,70 +75,239 @@ export class TimelineMessagingService {
.offset(offset)
.limit(pageSize);
- const applyRecordFilter = (
- queryBuilder: WorkspaceSelectQueryBuilder,
- ): void => {
- if (isDefined(targetFilter)) {
- queryBuilder
- .innerJoin(
- 'messageThread.messageThreadTargets',
- 'messageThreadTargets',
- )
- .where(
- `messageThreadTargets.${targetFilter.fieldName} = :targetRecordId`,
- { targetRecordId: targetFilter.recordId },
- );
-
- return;
- }
-
- queryBuilder
- .innerJoin('messages.messageParticipants', 'messageParticipants')
- .where('messageParticipants.personId IN(:...personIds)', {
- personIds,
- });
- };
-
- applyRecordFilter(totalQueryBuilder);
- applyRecordFilter(threadIdsQueryBuilder);
+ this.applyRecordFilter(totalQueryBuilder, { targetFilter, personIds });
+ this.applyRecordFilter(threadIdsQueryBuilder, {
+ targetFilter,
+ personIds,
+ });
const totalNumberOfThreads = await totalQueryBuilder.getCount();
- const threadIdsQuery = await threadIdsQueryBuilder.getRawMany();
+ const threadIdsQuery = await threadIdsQueryBuilder.getRawMany<{
+ id: string;
+ }>();
const messageThreadIds = threadIdsQuery.map((thread) => thread.id);
- const messageThreads = await messageThreadRepository.find({
- where: {
- id: In(messageThreadIds),
- },
- order: {
- messages: {
- receivedAt: 'DESC',
- },
- },
- relations: ['messages'],
- });
-
return {
- messageThreads: messageThreads.map((messageThread) => {
- const lastMessage = messageThread.messages[0];
- const firstMessage =
- messageThread.messages[messageThread.messages.length - 1];
-
- return {
- id: messageThread.id,
- subject: firstMessage.subject ?? '',
- lastMessageBody: lastMessage.text ?? '',
- lastMessageReceivedAt: lastMessage.receivedAt ?? new Date(),
- numberOfMessagesInThread: messageThread.messages.length,
- lastMessageIsDraft: lastMessage.isDraft ?? false,
- };
- }),
+ messageThreads: await this.findMessageThreadsByIds(messageThreadIds),
totalNumberOfThreads,
};
}, authContext);
}
+ public async searchMessageThreads({
+ workspaceId,
+ searchInput,
+ messageChannelIds,
+ recordFilter,
+ excludedMessageThreadIds = [],
+ }: {
+ workspaceId: string;
+ searchInput: string;
+ messageChannelIds: string[];
+ recordFilter?: { targetFilter?: TargetFilter; personIds: string[] };
+ excludedMessageThreadIds?: string[];
+ }): Promise<TimelineMessageThread[]> {
+ const searchWords = searchInput
+ .trim()
+ .split(/\s+/)
+ .filter(isNonEmptyString);
+
+ if (searchWords.length === 0 || messageChannelIds.length === 0) {
+ return [];
+ }
+
+ if (
+ isDefined(recordFilter) &&
+ !isDefined(recordFilter.targetFilter) &&
+ recordFilter.personIds.length === 0
+ ) {
+ return [];
+ }
+
+ return this.workspaceOrmManager.executeInWorkspaceContext(async () => {
+ const messageThreadRepository =
+ this.workspaceOrmManager.getRepository<MessageThreadWorkspaceEntity>(
+ 'messageThread',
+ { shouldBypassPermissionChecks: true },
+ );
+
+ const queryBuilder = messageThreadRepository
+ .createQueryBuilder('messageThread')
+ .select('messageThread.id', 'id')
+ .addSelect('MAX(messages.receivedAt)', 'max_received_at')
+ .innerJoin('messageThread.messages', 'messages')
+ .innerJoin(
+ 'messages.messageChannelMessageAssociations',
+ 'messageChannelMessageAssociations',
+ )
+ .where(
+ 'messageChannelMessageAssociations.messageChannelId IN (:...messageChannelIds)',
+ { messageChannelIds },
+ );
+
+ searchWords.forEach((searchWord, index) => {
+ const parameterName = `searchWord${index}`;
+
+ queryBuilder.andWhere(`messages.subject ILIKE :${parameterName}`, {
+ [parameterName]: `%${escapeForIlike(searchWord)}%`,
+ });
+ });
+
+ if (isDefined(recordFilter)) {
+ this.applyRecordFilter(queryBuilder, recordFilter);
+ }
+
+ if (excludedMessageThreadIds.length > 0) {
+ queryBuilder.andWhere(
+ 'messageThread.id NOT IN (:...excludedMessageThreadIds)',
+ { excludedMessageThreadIds },
+ );
+ }
+
+ const threadIdsQuery = await queryBuilder
+ .groupBy('messageThread.id')
+ .orderBy('max_received_at', 'DESC')
+ .limit(TIMELINE_THREADS_DEFAULT_PAGE_SIZE)
+ .getRawMany<{ id: string }>();
+
+ return this.findMessageThreadsByIds(
+ threadIdsQuery.map((thread) => thread.id),
+ );
+ }, buildSystemAuthContext(workspaceId));
+ }
+
+ public async getSearchableMessageChannelIds({
+ userWorkspaceId,
+ workspaceId,
+ }: {
+ userWorkspaceId: string;
+ workspaceId: string;
+ }): Promise<{
+ ownedMessageChannelIds: string[];
+ subjectVisibleMessageChannelIds: string[];
+ }> {
+ const [ownedConnectedAccounts, messageChannels] = await Promise.all([
+ this.connectedAccountRepository.find({
+ where: { userWorkspaceId, workspaceId },
+ select: { id: true },
+ }),
+ this.messageChannelRepository.find({
+ where: { workspaceId },
+ select: { id: true, visibility: true, connectedAccountId: true },
+ }),
+ ]);
+
+ const ownedConnectedAccountIds = new Set(
+ ownedConnectedAccounts.map((connectedAccount) => connectedAccount.id),
+ );
+
+ const ownedMessageChannelIds: string[] = [];
+ const subjectVisibleMessageChannelIds: string[] = [];
+
+ for (const messageChannel of messageChannels) {
+ const isOwnedByCurrentUser = ownedConnectedAccountIds.has(
+ messageChannel.connectedAccountId,
+ );
+ const visibility = getEffectiveMessageChannelVisibility({
+ visibility: messageChannel.visibility,
+ isOwnedByCurrentUser,
+ });
+
+ if (isOwnedByCurrentUser) {
+ ownedMessageChannelIds.push(messageChannel.id);
+ }
+
+ if (
+ visibility === MessageChannelVisibility.SUBJECT ||
+ visibility === MessageChannelVisibility.SHARE_EVERYTHING
+ ) {
+ subjectVisibleMessageChannelIds.push(messageChannel.id);
+ }
+ }
+
+ return { ownedMessageChannelIds, subjectVisibleMessageChannelIds };
+ }
+
+ private applyRecordFilter(
+ queryBuilder: WorkspaceSelectQueryBuilder,
+ {
+ targetFilter,
+ personIds,
+ }: { targetFilter?: TargetFilter; personIds: string[] },
+ ): void {
+ if (isDefined(targetFilter)) {
+ queryBuilder
+ .innerJoin('messageThread.messageThreadTargets', 'messageThreadTargets')
+ .andWhere(
+ `messageThreadTargets.${targetFilter.fieldName} = :targetRecordId`,
+ { targetRecordId: targetFilter.recordId },
+ );
+
+ return;
+ }
+
+ queryBuilder
+ .innerJoin('messages.messageParticipants', 'messageParticipants')
+ .andWhere('messageParticipants.personId IN (:...personIds)', {
+ personIds,
+ });
+ }
+
+ private async findMessageThreadsByIds(
+ messageThreadIds: string[],
+ ): Promise<TimelineMessageThread[]> {
+ if (messageThreadIds.length === 0) {
+ return [];
+ }
+
+ const messageThreadRepository =
+ this.workspaceOrmManager.getRepository<MessageThreadWorkspaceEntity>(
+ 'messageThread',
+ { shouldBypassPermissionChecks: true },
+ );
+
+ const messageThreads = await messageThreadRepository.find({
+ where: {
+ id: In(messageThreadIds),
+ },
+ order: {
+ messages: {
+ receivedAt: 'DESC',
+ },
+ },
+ relations: ['messages'],
+ });
+
+ const messageThreadPositionById = new Map(
+ messageThreadIds.map((messageThreadId, index) => [
+ messageThreadId,
+ index,
+ ]),
+ );
+
+ return messageThreads
+ .sort(
+ (a, b) =>
+ (messageThreadPositionById.get(a.id) ?? 0) -
+ (messageThreadPositionById.get(b.id) ?? 0),
+ )
+ .map((messageThread) => {
+ const lastMessage = messageThread.messages[0];
+ const firstMessage =
+ messageThread.messages[messageThread.messages.length - 1];
+
+ return {
+ id: messageThread.id,
+ subject: firstMessage.subject ?? '',
+ lastMessageBody: lastMessage.text ?? '',
+ lastMessageReceivedAt: lastMessage.receivedAt ?? new Date(),
+ numberOfMessagesInThread: messageThread.messages.length,
+ lastMessageIsDraft: lastMessage.isDraft ?? false,
+ };
+ });
+ }
+
public async getThreadParticipantsByThreadId(
messageThreadIds: string[],
workspaceId: string,
@@ -248,42 +418,18 @@ export class TimelineMessagingService {
}, authContext);
}
- public async getThreadVisibilityByThreadId(
- messageThreadIds: string[],
- workspaceMemberId: string,
- workspaceId: string,
- ): Promise<{
+ public async getThreadVisibilityByThreadId({
+ messageThreadIds,
+ userWorkspaceId,
+ workspaceId,
+ }: {
+ messageThreadIds: string[];
+ userWorkspaceId: string;
+ workspaceId: string;
+ }): Promise<{
[key: string]: MessageChannelVisibility;
}> {
- const authContext = buildSystemAuthContext(workspaceId);
-
return this.workspaceOrmManager.executeInWorkspaceContext(async () => {
- const workspaceMemberRepository =
- this.workspaceOrmManager.getRepository<WorkspaceMemberWorkspaceEntity>(
- 'workspaceMember',
- { shouldBypassPermissionChecks: true },
- );
-
- const currentMember = await workspaceMemberRepository.findOne({
- where: { id: workspaceMemberId },
- select: { userId: true },
- });
-
- if (!currentMember) {
- return {};
- }
-
- const currentUserWorkspace = await this.userWorkspaceRepository.findOne({
- where: { userId: currentMember.userId, workspaceId },
- select: { id: true },
- });
-
- if (!currentUserWorkspace) {
- return {};
- }
-
- const currentUserWorkspaceId = currentUserWorkspace.id;
-
const messageThreadRepository =
this.workspaceOrmManager.getRepository<MessageThreadWorkspaceEntity>(
'messageThread',
@@ -335,7 +481,7 @@ export class TimelineMessagingService {
await this.connectedAccountRepository.find({
where: {
id: In(allConnectedAccountIds),
- userWorkspaceId: currentUserWorkspaceId,
+ userWorkspaceId,
},
select: { id: true },
})
@@ -345,9 +491,12 @@ export class TimelineMessagingService {
const channelVisibilityMap = new Map(
messageChannels.map((channel) => [
channel.id,
- ownedAccountIds.has(channel.connectedAccountId)
- ? MessageChannelVisibility.SHARE_EVERYTHING
- : channel.visibility,
+ getEffectiveMessageChannelVisibility({
+ visibility: channel.visibility,
+ isOwnedByCurrentUser: ownedAccountIds.has(
+ channel.connectedAccountId,
+ ),
+ }),
]),
);
@@ -377,6 +526,6 @@ export class TimelineMessagingService {
}
return threadVisibilityByThreadId;
- }, authContext);
+ }, buildSystemAuthContext(workspaceId));
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/messaging/timeline-messaging.module.ts b/packages/twenty-server/src/engine/core-modules/messaging/timeline-messaging.module.ts
index bd74f2b29f2..4142336a28c 100644
--- a/packages/twenty-server/src/engine/core-modules/messaging/timeline-messaging.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/messaging/timeline-messaging.module.ts
@@ -6,8 +6,6 @@ import { GetMessagesService } from 'src/engine/core-modules/messaging/services/g
import { TimelineMessagingService } from 'src/engine/core-modules/messaging/services/timeline-messaging.service';
import { TimelineMessagingResolver } from 'src/engine/core-modules/messaging/timeline-messaging.resolver';
import { RelatedPersonIdsModule } from 'src/engine/core-modules/related-person-ids/related-person-ids.module';
-import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
-import { UserModule } from 'src/engine/core-modules/user/user.module';
import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permissions.module';
@@ -17,16 +15,11 @@ import { TargetModule } from 'src/engine/core-modules/target/target.module';
@Module({
imports: [
FileUrlModule,
- UserModule,
ConnectedAccountModule,
PermissionsModule,
RelatedPersonIdsModule,
TargetModule,
- TypeOrmModule.forFeature([
- MessageChannelEntity,
- ConnectedAccountEntity,
- UserWorkspaceEntity,
- ]),
+ TypeOrmModule.forFeature([MessageChannelEntity, ConnectedAccountEntity]),
],
exports: [],
providers: [
diff --git a/packages/twenty-server/src/engine/core-modules/messaging/timeline-messaging.resolver.ts b/packages/twenty-server/src/engine/core-modules/messaging/timeline-messaging.resolver.ts
index 704c8514ad9..590f10799ca 100644
--- a/packages/twenty-server/src/engine/core-modules/messaging/timeline-messaging.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/messaging/timeline-messaging.resolver.ts
@@ -1,21 +1,25 @@
import { UseGuards, UseFilters } from '@nestjs/common';
import { Args, ArgsType, Field, Int, Mutation, Query } from '@nestjs/graphql';
-import { Max } from 'class-validator';
+import { Max, MaxLength } from 'class-validator';
import { PermissionFlagType } from 'twenty-shared/constants';
import { CoreObjectNameSingular } from 'twenty-shared/types';
import { CoreResolver } from 'src/engine/api/graphql/graphql-config/decorators/core-resolver.decorator';
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
-import { TIMELINE_THREADS_MAX_PAGE_SIZE } from 'src/engine/core-modules/messaging/constants/messaging.constants';
+import {
+ TIMELINE_THREADS_MAX_PAGE_SIZE,
+ TIMELINE_THREADS_SEARCH_INPUT_MAX_LENGTH,
+} from 'src/engine/core-modules/messaging/constants/messaging.constants';
import { DismissReconnectAccountBannerInput } from 'src/engine/core-modules/messaging/dtos/dismiss-reconnect-account-banner.input';
+import { TimelineThreadSearchResultDTO } from 'src/engine/core-modules/messaging/dtos/timeline-thread-search-result.dto';
import { TimelineThreadsWithTotalDTO } from 'src/engine/core-modules/messaging/dtos/timeline-threads-with-total.dto';
import { GetMessagesService } from 'src/engine/core-modules/messaging/services/get-messages.service';
-import { UserService } from 'src/engine/core-modules/user/services/user.service';
import { type AuthContextUser } from 'src/engine/core-modules/auth/types/auth-context.type';
import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filters/auth-graphql-api-exception.filter';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { AuthUser } from 'src/engine/decorators/auth/auth-user.decorator';
+import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';
import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
import { CustomPermissionGuard } from 'src/engine/guards/custom-permission.guard';
import { AuthPrincipalGuard } from 'src/engine/guards/auth-principal.guard';
@@ -38,6 +42,19 @@ class GetTimelineThreadsFromObjectRecordArgs {
pageSize: number;
}
+@ArgsType()
+class SearchTimelineThreadsArgs {
+ @Field(() => String)
+ objectNameSingular: string;
+
+ @Field(() => UUIDScalarType)
+ recordId: string;
+
+ @Field(() => String, { nullable: true })
+ @MaxLength(TIMELINE_THREADS_SEARCH_INPUT_MAX_LENGTH)
+ searchInput?: string;
+}
+
@ArgsType()
class GetTimelineThreadsFromPersonIdArgs {
@Field(() => UUIDScalarType)
@@ -96,13 +113,12 @@ class GetTimelineThreadsFromOpportunityIdArgs {
export class TimelineMessagingResolver {
constructor(
private readonly getMessagesFromPersonIdsService: GetMessagesService,
- private readonly userService: UserService,
private readonly accountsToReconnectService: AccountsToReconnectService,
) {}
@Query(() => TimelineThreadsWithTotalDTO)
async getTimelineThreadsFromObjectRecord(
- @AuthUser() user: AuthContextUser,
+ @AuthUserWorkspaceId() userWorkspaceId: string,
@AuthWorkspace() workspace: WorkspaceEntity,
@Args()
{
@@ -112,105 +128,85 @@ export class TimelineMessagingResolver {
pageSize,
}: GetTimelineThreadsFromObjectRecordArgs,
) {
- const workspaceMember = await this.userService.loadWorkspaceMember(
- user,
- workspace,
- );
-
- if (!workspaceMember) {
- return;
- }
-
- return this.getMessagesFromPersonIdsService.getMessagesFromObjectRecord(
- workspaceMember.id,
+ return this.getMessagesFromPersonIdsService.getMessagesFromObjectRecord({
+ userWorkspaceId,
objectNameSingular,
recordId,
- workspace.id,
+ workspaceId: workspace.id,
page,
pageSize,
- );
+ });
+ }
+
+ @Query(() => TimelineThreadSearchResultDTO)
+ async searchTimelineThreads(
+ @AuthUserWorkspaceId() userWorkspaceId: string,
+ @AuthWorkspace() workspace: WorkspaceEntity,
+ @Args()
+ { objectNameSingular, recordId, searchInput }: SearchTimelineThreadsArgs,
+ ) {
+ return this.getMessagesFromPersonIdsService.searchMessagesFromObjectRecord({
+ userWorkspaceId,
+ objectNameSingular,
+ recordId,
+ workspaceId: workspace.id,
+ searchInput,
+ });
}
@Query(() => TimelineThreadsWithTotalDTO, {
deprecationReason: 'Use getTimelineThreadsFromObjectRecord instead',
})
async getTimelineThreadsFromPersonId(
- @AuthUser() user: AuthContextUser,
+ @AuthUserWorkspaceId() userWorkspaceId: string,
@AuthWorkspace() workspace: WorkspaceEntity,
@Args() { personId, page, pageSize }: GetTimelineThreadsFromPersonIdArgs,
) {
- const workspaceMember = await this.userService.loadWorkspaceMember(
- user,
- workspace,
- );
-
- if (!workspaceMember) {
- return;
- }
-
- return this.getMessagesFromPersonIdsService.getMessagesFromObjectRecord(
- workspaceMember.id,
- CoreObjectNameSingular.Person,
- personId,
- workspace.id,
+ return this.getMessagesFromPersonIdsService.getMessagesFromObjectRecord({
+ userWorkspaceId,
+ objectNameSingular: CoreObjectNameSingular.Person,
+ recordId: personId,
+ workspaceId: workspace.id,
page,
pageSize,
- );
+ });
}
@Query(() => TimelineThreadsWithTotalDTO, {
deprecationReason: 'Use getTimelineThreadsFromObjectRecord instead',
})
async getTimelineThreadsFromCompanyId(
- @AuthUser() user: AuthContextUser,
+ @AuthUserWorkspaceId() userWorkspaceId: string,
@AuthWorkspace() workspace: WorkspaceEntity,
@Args() { companyId, page, pageSize }: GetTimelineThreadsFromCompanyIdArgs,
) {
- const workspaceMember = await this.userService.loadWorkspaceMember(
- user,
- workspace,
- );
-
- if (!workspaceMember) {
- return;
- }
-
- return this.getMessagesFromPersonIdsService.getMessagesFromObjectRecord(
- workspaceMember.id,
- CoreObjectNameSingular.Company,
- companyId,
- workspace.id,
+ return this.getMessagesFromPersonIdsService.getMessagesFromObjectRecord({
+ userWorkspaceId,
+ objectNameSingular: CoreObjectNameSingular.Company,
+ recordId: companyId,
+ workspaceId: workspace.id,
page,
pageSize,
- );
+ });
}
@Query(() => TimelineThreadsWithTotalDTO, {
deprecationReason: 'Use getTimelineThreadsFromObjectRecord instead',
})
async getTimelineThreadsFromOpportunityId(
- @AuthUser() user: AuthContextUser,
+ @AuthUserWorkspaceId() userWorkspaceId: string,
@AuthWorkspace() workspace: WorkspaceEntity,
@Args()
{ opportunityId, page, pageSize }: GetTimelineThreadsFromOpportunityIdArgs,
) {
- const workspaceMember = await this.userService.loadWorkspaceMember(
- user,
- workspace,
- );
-
- if (!workspaceMember) {
- return;
- }
-
- return this.getMessagesFromPersonIdsService.getMessagesFromObjectRecord(
- workspaceMember.id,
- CoreObjectNameSingular.Opportunity,
- opportunityId,
- workspace.id,
+ return this.getMessagesFromPersonIdsService.getMessagesFromObjectRecord({
+ userWorkspaceId,
+ objectNameSingular: CoreObjectNameSingular.Opportunity,
+ recordId: opportunityId,
+ workspaceId: workspace.id,
page,
pageSize,
- );
+ });
}
@UseGuards(SettingsPermissionGuard(PermissionFlagType.CONNECTED_ACCOUNTS))
diff --git a/packages/twenty-server/src/engine/core-modules/messaging/utils/get-effective-message-channel-visibility.util.ts b/packages/twenty-server/src/engine/core-modules/messaging/utils/get-effective-message-channel-visibility.util.ts
new file mode 100644
index 00000000000..bbc258e5a90
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/messaging/utils/get-effective-message-channel-visibility.util.ts
@@ -0,0 +1,10 @@
+import { MessageChannelVisibility } from 'twenty-shared/types';
+
+export const getEffectiveMessageChannelVisibility = ({
+ visibility,
+ isOwnedByCurrentUser,
+}: {
+ visibility: MessageChannelVisibility;
+ isOwnedByCurrentUser: boolean;
+}): MessageChannelVisibility =>
+ isOwnedByCurrentUser ? MessageChannelVisibility.SHARE_EVERYTHING : visibility;
diff --git a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
index 71968a01d85..2ca2182d383 100644
--- a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
+++ b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
@@ -522,11 +522,13 @@ exports[`endpoint permission declarations should match the AuthPrincipalGuard an
"TimelineCalendarEventResolver.getTimelineCalendarEventsFromObjectRecord {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
"TimelineCalendarEventResolver.getTimelineCalendarEventsFromOpportunityId {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
"TimelineCalendarEventResolver.getTimelineCalendarEventsFromPersonId {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
+ "TimelineCalendarEventResolver.searchTimelineCalendarEvents {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
"TimelineMessagingResolver.dismissReconnectAccountBanner {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
"TimelineMessagingResolver.getTimelineThreadsFromCompanyId {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
"TimelineMessagingResolver.getTimelineThreadsFromObjectRecord {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
"TimelineMessagingResolver.getTimelineThreadsFromOpportunityId {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
"TimelineMessagingResolver.getTimelineThreadsFromPersonId {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
+ "TimelineMessagingResolver.searchTimelineThreads {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
"ToolCallAnswerResolver.answerToolCall {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
"ToolIndexResolver.getToolIndex {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
"ToolIndexResolver.getToolInputSchema {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
diff --git a/packages/twenty-server/test/integration/graphql/suites/search-timeline-calendar-events.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/search-timeline-calendar-events.integration-spec.ts
new file mode 100644
index 00000000000..531ffeffef6
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/search-timeline-calendar-events.integration-spec.ts
@@ -0,0 +1,214 @@
+import gql from 'graphql-tag';
+import { createOneOperation } from 'test/integration/graphql/utils/create-one-operation.util';
+import { destroyOneOperationFactory } from 'test/integration/graphql/utils/destroy-one-operation-factory.util';
+import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
+import { deleteRecordsByIds } from 'test/integration/utils/delete-records-by-ids';
+import { isDefined } from 'twenty-shared/utils';
+
+import { CALENDAR_CHANNEL_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/constants/calendar-channel-seed-ids.constant';
+
+const SEARCH_TIMELINE_CALENDAR_EVENTS = gql`
+ query SearchTimelineCalendarEvents(
+ $objectNameSingular: String!
+ $recordId: UUID!
+ $searchInput: String
+ ) {
+ searchTimelineCalendarEvents(
+ objectNameSingular: $objectNameSingular
+ recordId: $recordId
+ searchInput: $searchInput
+ ) {
+ recordTimelineCalendarEvents {
+ id
+ }
+ otherTimelineCalendarEvents {
+ id
+ }
+ }
+ }
+`;
+
+const TEST_SCHEMA_NAME = 'workspace_1wgvd1injqtife6y4rvfbu3h5';
+
+const COMPANY_ID = '20202020-ca1e-4000-8000-000000000001';
+const SHARED_COMPANY_EVENT_ID = '20202020-ca1e-4000-8000-000000000002';
+const HIDDEN_COMPANY_EVENT_ID = '20202020-ca1e-4000-8000-000000000003';
+const OWN_EVENT_ID = '20202020-ca1e-4000-8000-000000000004';
+const COLLEAGUE_EVENT_ID = '20202020-ca1e-4000-8000-000000000005';
+
+const CALENDAR_EVENTS = [
+ {
+ calendarEventId: SHARED_COMPANY_EVENT_ID,
+ associationId: '20202020-ca1e-4000-8000-000000000012',
+ targetId: '20202020-ca1e-4000-8000-000000000022',
+ title: 'Larkspur renewal review',
+ calendarChannelId: CALENDAR_CHANNEL_DATA_SEED_IDS.JONY,
+ },
+ {
+ calendarEventId: HIDDEN_COMPANY_EVENT_ID,
+ associationId: '20202020-ca1e-4000-8000-000000000013',
+ targetId: '20202020-ca1e-4000-8000-000000000023',
+ title: 'Larkspur pricing on a private calendar',
+ calendarChannelId: CALENDAR_CHANNEL_DATA_SEED_IDS.TIM,
+ },
+ {
+ calendarEventId: OWN_EVENT_ID,
+ associationId: '20202020-ca1e-4000-8000-000000000014',
+ targetId: null,
+ title: 'Larkspur kickoff',
+ calendarChannelId: CALENDAR_CHANNEL_DATA_SEED_IDS.JANE,
+ },
+ {
+ calendarEventId: COLLEAGUE_EVENT_ID,
+ associationId: '20202020-ca1e-4000-8000-000000000015',
+ targetId: null,
+ title: 'Larkspur offsite planning',
+ calendarChannelId: CALENDAR_CHANNEL_DATA_SEED_IDS.JONY,
+ },
+];
+
+const createRecord = async ({
+ objectMetadataSingularName,
+ input,
+}: {
+ objectMetadataSingularName: string;
+ input: object;
+}) => {
+ const { errors } = await createOneOperation({
+ objectMetadataSingularName,
+ input,
+ });
+
+ expect(errors).toBeUndefined();
+};
+
+const destroyRecord = (objectMetadataSingularName: string, recordId: string) =>
+ makeGraphqlApiRequest(
+ destroyOneOperationFactory({
+ objectMetadataSingularName,
+ gqlFields: 'id',
+ recordId,
+ }),
+ );
+
+const searchTimelineCalendarEvents = async (searchInput?: string) => {
+ const response = await makeGraphqlApiRequest({
+ query: SEARCH_TIMELINE_CALENDAR_EVENTS,
+ variables: {
+ objectNameSingular: 'company',
+ recordId: COMPANY_ID,
+ searchInput,
+ },
+ });
+
+ expect(response.body.errors).toBeUndefined();
+
+ const { recordTimelineCalendarEvents, otherTimelineCalendarEvents } =
+ response.body.data.searchTimelineCalendarEvents;
+
+ return {
+ recordCalendarEventIds: recordTimelineCalendarEvents.map(
+ ({ id }: { id: string }) => id,
+ ),
+ otherCalendarEventIds: otherTimelineCalendarEvents.map(
+ ({ id }: { id: string }) => id,
+ ),
+ };
+};
+
+describe('searchTimelineCalendarEvents (integration)', () => {
+ beforeAll(async () => {
+ await createRecord({
+ objectMetadataSingularName: 'company',
+ input: {
+ id: COMPANY_ID,
+ name: 'Larkspur Search Company',
+ },
+ });
+
+ for (const calendarEvent of CALENDAR_EVENTS) {
+ await createRecord({
+ objectMetadataSingularName: 'calendarEvent',
+ input: {
+ id: calendarEvent.calendarEventId,
+ title: calendarEvent.title,
+ isFullDay: false,
+ startsAt: new Date().toISOString(),
+ endsAt: new Date(Date.now() + 60_000).toISOString(),
+ },
+ });
+
+ // Channel associations are not writable through the API
+ await global.testDataSource.query(
+ `INSERT INTO "${TEST_SCHEMA_NAME}"."calendarChannelEventAssociation" ("id", "calendarEventId", "calendarChannelId", "eventExternalId") VALUES ($1, $2, $3, $4)`,
+ [
+ calendarEvent.associationId,
+ calendarEvent.calendarEventId,
+ calendarEvent.calendarChannelId,
+ `larkspur-${calendarEvent.calendarEventId}`,
+ ],
+ );
+
+ if (isDefined(calendarEvent.targetId)) {
+ await createRecord({
+ objectMetadataSingularName: 'calendarEventTarget',
+ input: {
+ id: calendarEvent.targetId,
+ calendarEventId: calendarEvent.calendarEventId,
+ targetCompanyId: COMPANY_ID,
+ },
+ });
+ }
+ }
+ });
+
+ afterAll(async () => {
+ for (const calendarEvent of CALENDAR_EVENTS) {
+ if (isDefined(calendarEvent.targetId)) {
+ await destroyRecord('calendarEventTarget', calendarEvent.targetId);
+ }
+
+ await deleteRecordsByIds('calendarChannelEventAssociation', [
+ calendarEvent.associationId,
+ ]);
+ await destroyRecord('calendarEvent', calendarEvent.calendarEventId);
+ }
+
+ await destroyRecord('company', COMPANY_ID);
+ });
+
+ it('should list the record events without fallback when there is no search input', async () => {
+ const { recordCalendarEventIds, otherCalendarEventIds } =
+ await searchTimelineCalendarEvents();
+
+ expect(recordCalendarEventIds).toEqual(
+ expect.arrayContaining([
+ SHARED_COMPANY_EVENT_ID,
+ HIDDEN_COMPANY_EVENT_ID,
+ ]),
+ );
+ expect(otherCalendarEventIds).toEqual([]);
+ });
+
+ it('should return matching record events first and the viewer own matching events as fallback', async () => {
+ const { recordCalendarEventIds, otherCalendarEventIds } =
+ await searchTimelineCalendarEvents('larkspur');
+
+ expect(recordCalendarEventIds).toEqual([SHARED_COMPANY_EVENT_ID]);
+ expect(otherCalendarEventIds).toEqual([OWN_EVENT_ID]);
+ });
+
+ it('should not match events whose title is hidden from the viewer', async () => {
+ const { recordCalendarEventIds } =
+ await searchTimelineCalendarEvents('larkspur pricing');
+
+ expect(recordCalendarEventIds).toEqual([]);
+ });
+
+ it('should not search colleagues calendars in the fallback', async () => {
+ const { otherCalendarEventIds } =
+ await searchTimelineCalendarEvents('larkspur offsite');
+
+ expect(otherCalendarEventIds).toEqual([]);
+ });
+});
diff --git a/packages/twenty-server/test/integration/graphql/suites/search-timeline-threads.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/search-timeline-threads.integration-spec.ts
new file mode 100644
index 00000000000..bd15e8c5665
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/search-timeline-threads.integration-spec.ts
@@ -0,0 +1,250 @@
+import gql from 'graphql-tag';
+import { createOneOperation } from 'test/integration/graphql/utils/create-one-operation.util';
+import { destroyOneOperationFactory } from 'test/integration/graphql/utils/destroy-one-operation-factory.util';
+import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
+import { deleteRecordsByIds } from 'test/integration/utils/delete-records-by-ids';
+
+import { isDefined } from 'twenty-shared/utils';
+
+import { MESSAGE_CHANNEL_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/constants/message-channel-seed-ids.constant';
+
+const SEARCH_TIMELINE_THREADS = gql`
+ query SearchTimelineThreads(
+ $objectNameSingular: String!
+ $recordId: UUID!
+ $searchInput: String
+ ) {
+ searchTimelineThreads(
+ objectNameSingular: $objectNameSingular
+ recordId: $recordId
+ searchInput: $searchInput
+ ) {
+ recordTimelineThreads {
+ id
+ subject
+ }
+ otherTimelineThreads {
+ id
+ subject
+ }
+ }
+ }
+`;
+
+const TEST_SCHEMA_NAME = 'workspace_1wgvd1injqtife6y4rvfbu3h5';
+
+const COMPANY_ID = '20202020-5ea4-4000-8000-000000000001';
+const COMPANY_THREAD_ID = '20202020-5ea4-4000-8000-000000000002';
+const OTHER_THREAD_ID = '20202020-5ea4-4000-8000-000000000003';
+const UNSHARED_COMPANY_THREAD_ID = '20202020-5ea4-4000-8000-000000000004';
+const COLLEAGUE_THREAD_ID = '20202020-5ea4-4000-8000-000000000005';
+
+const THREADS = [
+ {
+ messageThreadId: COMPANY_THREAD_ID,
+ messageId: '20202020-5ea4-4000-8000-000000000012',
+ participantId: '20202020-5ea4-4000-8000-000000000022',
+ associationId: '20202020-5ea4-4000-8000-000000000032',
+ targetId: '20202020-5ea4-4000-8000-000000000042',
+ subject: 'Quillfeather renewal proposal',
+ messageChannelId: MESSAGE_CHANNEL_DATA_SEED_IDS.TIM,
+ },
+ {
+ messageThreadId: OTHER_THREAD_ID,
+ messageId: '20202020-5ea4-4000-8000-000000000013',
+ participantId: '20202020-5ea4-4000-8000-000000000023',
+ associationId: '20202020-5ea4-4000-8000-000000000033',
+ targetId: null,
+ subject: 'Quillfeather kickoff notes',
+ messageChannelId: MESSAGE_CHANNEL_DATA_SEED_IDS.JANE,
+ },
+ {
+ messageThreadId: UNSHARED_COMPANY_THREAD_ID,
+ messageId: '20202020-5ea4-4000-8000-000000000014',
+ participantId: '20202020-5ea4-4000-8000-000000000024',
+ associationId: null,
+ targetId: '20202020-5ea4-4000-8000-000000000044',
+ subject: 'Quillfeather pricing without a channel',
+ messageChannelId: null,
+ },
+ {
+ messageThreadId: COLLEAGUE_THREAD_ID,
+ messageId: '20202020-5ea4-4000-8000-000000000015',
+ participantId: '20202020-5ea4-4000-8000-000000000025',
+ associationId: '20202020-5ea4-4000-8000-000000000035',
+ targetId: null,
+ subject: 'Quillfeather offsite planning',
+ messageChannelId: MESSAGE_CHANNEL_DATA_SEED_IDS.TIM,
+ },
+];
+
+const createRecord = async ({
+ objectMetadataSingularName,
+ input,
+}: {
+ objectMetadataSingularName: string;
+ input: object;
+}) => {
+ const { errors } = await createOneOperation({
+ objectMetadataSingularName,
+ input,
+ });
+
+ expect(errors).toBeUndefined();
+};
+
+const destroyRecord = (objectMetadataSingularName: string, recordId: string) =>
+ makeGraphqlApiRequest(
+ destroyOneOperationFactory({
+ objectMetadataSingularName,
+ gqlFields: 'id',
+ recordId,
+ }),
+ );
+
+const searchTimelineThreads = async (searchInput?: string) => {
+ const response = await makeGraphqlApiRequest({
+ query: SEARCH_TIMELINE_THREADS,
+ variables: {
+ objectNameSingular: 'company',
+ recordId: COMPANY_ID,
+ searchInput,
+ },
+ });
+
+ expect(response.body.errors).toBeUndefined();
+
+ const { recordTimelineThreads, otherTimelineThreads } =
+ response.body.data.searchTimelineThreads;
+
+ return {
+ recordThreadIds: recordTimelineThreads.map(({ id }: { id: string }) => id),
+ otherThreadIds: otherTimelineThreads.map(({ id }: { id: string }) => id),
+ };
+};
+
+describe('searchTimelineThreads (integration)', () => {
+ beforeAll(async () => {
+ await createRecord({
+ objectMetadataSingularName: 'company',
+ input: {
+ id: COMPANY_ID,
+ name: 'Quillfeather Search Company',
+ },
+ });
+
+ for (const thread of THREADS) {
+ await createRecord({
+ objectMetadataSingularName: 'messageThread',
+ input: {
+ id: thread.messageThreadId,
+ subject: thread.subject,
+ },
+ });
+
+ await createRecord({
+ objectMetadataSingularName: 'message',
+ input: {
+ id: thread.messageId,
+ messageThreadId: thread.messageThreadId,
+ subject: thread.subject,
+ text: `${thread.subject} body`,
+ receivedAt: new Date().toISOString(),
+ },
+ });
+
+ await createRecord({
+ objectMetadataSingularName: 'messageParticipant',
+ input: {
+ id: thread.participantId,
+ messageId: thread.messageId,
+ role: 'FROM',
+ handle: '[email protected]',
+ displayName: 'Quillfeather Sender',
+ },
+ });
+
+ // Channel associations are not writable through the API
+ if (
+ isDefined(thread.associationId) &&
+ isDefined(thread.messageChannelId)
+ ) {
+ await global.testDataSource.query(
+ `INSERT INTO "${TEST_SCHEMA_NAME}"."messageChannelMessageAssociation" ("id", "messageId", "messageChannelId", "messageExternalId", "messageThreadExternalId") VALUES ($1, $2, $3, $4, $5)`,
+ [
+ thread.associationId,
+ thread.messageId,
+ thread.messageChannelId,
+ `quillfeather-${thread.messageId}`,
+ `quillfeather-${thread.messageThreadId}`,
+ ],
+ );
+ }
+
+ if (isDefined(thread.targetId)) {
+ await createRecord({
+ objectMetadataSingularName: 'messageThreadTarget',
+ input: {
+ id: thread.targetId,
+ messageThreadId: thread.messageThreadId,
+ targetCompanyId: COMPANY_ID,
+ },
+ });
+ }
+ }
+ });
+
+ afterAll(async () => {
+ for (const thread of THREADS) {
+ if (isDefined(thread.targetId)) {
+ await destroyRecord('messageThreadTarget', thread.targetId);
+ }
+
+ if (isDefined(thread.associationId)) {
+ await deleteRecordsByIds('messageChannelMessageAssociation', [
+ thread.associationId,
+ ]);
+ }
+
+ await destroyRecord('messageParticipant', thread.participantId);
+ await destroyRecord('message', thread.messageId);
+ await destroyRecord('messageThread', thread.messageThreadId);
+ }
+
+ await destroyRecord('company', COMPANY_ID);
+ });
+
+ it('should list the record threads without fallback when there is no search input', async () => {
+ const { recordThreadIds, otherThreadIds } = await searchTimelineThreads();
+
+ expect(recordThreadIds).toEqual(
+ expect.arrayContaining([COMPANY_THREAD_ID, UNSHARED_COMPANY_THREAD_ID]),
+ );
+ expect(otherThreadIds).toEqual([]);
+ });
+
+ it('should return matching record threads first and the viewer own matching threads as fallback', async () => {
+ const { recordThreadIds, otherThreadIds } =
+ await searchTimelineThreads('quillfeather');
+
+ expect(recordThreadIds).toEqual([COMPANY_THREAD_ID]);
+ expect(otherThreadIds).toEqual([OTHER_THREAD_ID]);
+ });
+
+ it('should not search colleagues mailboxes in the fallback', async () => {
+ const { otherThreadIds } = await searchTimelineThreads(
+ 'quillfeather offsite',
+ );
+
+ expect(otherThreadIds).not.toContain(COLLEAGUE_THREAD_ID);
+ });
+
+ it('should not match threads whose subject is not shared through any channel', async () => {
+ const { recordThreadIds, otherThreadIds } = await searchTimelineThreads(
+ 'quillfeather pricing',
+ );
+
+ expect(recordThreadIds).toEqual([]);
+ expect(otherThreadIds).not.toContain(UNSHARED_COMPANY_THREAD_ID);
+ });
+});