Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use twentyORM in Timeline messaging #6595

Merged
merged 33 commits into from
Aug 15, 2024
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
2f6bff3
wip
bosiraphael Aug 8, 2024
30336fd
wip
bosiraphael Aug 8, 2024
b7aea7f
wip
bosiraphael Aug 8, 2024
ad88682
fix
bosiraphael Aug 8, 2024
9391bba
fix and improve getMessageThreads
bosiraphael Aug 9, 2024
834d80c
fix invalid uuid
bosiraphael Aug 9, 2024
feacd03
fix participant display name
bosiraphael Aug 9, 2024
ee0da61
fix visibility
bosiraphael Aug 9, 2024
91a840a
fix participant count
bosiraphael Aug 9, 2024
cc4cbd7
remove old service
bosiraphael Aug 9, 2024
2cd9093
Merge branch 'main' into 6430-part-2
bosiraphael Aug 9, 2024
f3efdfb
remove unused type
bosiraphael Aug 9, 2024
0c3b97b
add select
bosiraphael Aug 9, 2024
baaa2d9
fix
bosiraphael Aug 9, 2024
f534ad7
remove comments
bosiraphael Aug 9, 2024
22b30d3
add braces
bosiraphael Aug 9, 2024
448f148
improve typing
bosiraphael Aug 9, 2024
3b9beab
fix
bosiraphael Aug 9, 2024
06ea254
fix thread visibility
bosiraphael Aug 9, 2024
ef624f3
fix
bosiraphael Aug 9, 2024
6092f3c
fix when workspaceMemberId is null
bosiraphael Aug 12, 2024
01ad72a
findAndCount instead of two separate queries
bosiraphael Aug 12, 2024
1ad6f43
rename
bosiraphael Aug 12, 2024
b545afd
fix imports
bosiraphael Aug 12, 2024
2086b5b
optimize and fix participants query
bosiraphael Aug 12, 2024
9185591
order thread participants
bosiraphael Aug 13, 2024
4ec4911
modify getThreadVisibilityByThreadId query
bosiraphael Aug 13, 2024
b1faccc
remove unused relation
bosiraphael Aug 13, 2024
b6f6783
Merge branch 'main' into 6430-part-2
bosiraphael Aug 13, 2024
ff076c7
Merge branch 'main' into 6430-part-2
bosiraphael Aug 13, 2024
439bb45
fix getAndCountMessageThreads
bosiraphael Aug 14, 2024
b18afe5
Merge branch 'main' into 6430-part-2
charlesBochet Aug 15, 2024
f248ada
Fix lint
charlesBochet Aug 15, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { ObjectType, Field } from '@nestjs/graphql';
import { Field, ObjectType } from '@nestjs/graphql';

import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';

@ObjectType('TimelineThreadParticipant')
export class TimelineThreadParticipant {
@Field(() => UUIDScalarType, { nullable: true })
personId: string;
personId: string | null;

@Field(() => UUIDScalarType, { nullable: true })
workspaceMemberId: string;
workspaceMemberId: string | null;

@Field()
firstName: string;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { Injectable } from '@nestjs/common';

import { TIMELINE_THREADS_DEFAULT_PAGE_SIZE } from 'src/engine/core-modules/messaging/constants/messaging.constants';
import { TimelineThreadsWithTotal } from 'src/engine/core-modules/messaging/dtos/timeline-threads-with-total.dto';
import { GetMessagesFromPersonIdsService } from 'src/engine/core-modules/messaging/services/get-messages-from-person-ids.service';
import { TwentyORMManager } from 'src/engine/twenty-orm/twenty-orm.manager';
import { PersonWorkspaceEntity } from 'src/modules/person/standard-objects/person.workspace-entity';

@Injectable()
export class GetMessagesFromCompanyIdService {
constructor(
private readonly twentyORMManager: TwentyORMManager,
private readonly getMessagesFromPersonIdsService: GetMessagesFromPersonIdsService,
) {}

async getMessagesFromCompanyId(
workspaceMemberId: string,
companyId: string,
page = 1,
pageSize: number = TIMELINE_THREADS_DEFAULT_PAGE_SIZE,
): Promise<TimelineThreadsWithTotal> {
const personRepository =
await this.twentyORMManager.getRepository<PersonWorkspaceEntity>(
'person',
);
const personIds = (
await personRepository.find({
where: {
companyId,
},
select: {
id: true,
},
})
).map((person) => person.id);

if (!personIds) {
return {
totalNumberOfThreads: 0,
timelineThreads: [],
};
bosiraphael marked this conversation as resolved.
Show resolved Hide resolved
}

const messageThreads =
await this.getMessagesFromPersonIdsService.getMessagesFromPersonIds(
workspaceMemberId,
personIds,
page,
pageSize,
);

return messageThreads;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { Injectable } from '@nestjs/common';

import { Any } from 'typeorm';

import { TIMELINE_THREADS_DEFAULT_PAGE_SIZE } from 'src/engine/core-modules/messaging/constants/messaging.constants';
import { TimelineThreadsWithTotal } 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';
import { TwentyORMManager } from 'src/engine/twenty-orm/twenty-orm.manager';
import { MessageParticipantWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-participant.workspace-entity';
import { MessageThreadWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-thread.workspace-entity';

@Injectable()
export class GetMessagesFromPersonIdsService {
constructor(
private readonly twentyORMManager: TwentyORMManager,
private readonly timelineMessagingService: TimelineMessagingService,
) {}

async getMessagesFromPersonIds(
workspaceMemberId: string,
personIds: string[],
page = 1,
pageSize: number = TIMELINE_THREADS_DEFAULT_PAGE_SIZE,
): Promise<TimelineThreadsWithTotal> {
const offset = (page - 1) * pageSize;

const messageThreadRepository =
await this.twentyORMManager.getRepository<MessageThreadWorkspaceEntity>(
'messageThread',
);

const messageThreads =
await this.timelineMessagingService.getMessageThreads(
personIds,
offset,
pageSize,
);

if (!messageThreads) {
return {
totalNumberOfThreads: 0,
timelineThreads: [],
};
}

const messageThreadIds = messageThreads.map(
(messageThread) => messageThread.id,
);

const totalNumberOfThreads = await messageThreadRepository.count({
where: {
messages: {
messageParticipants: {
personId: Any(personIds),
},
},
},
});

const messageParticipantRepository =
await this.twentyORMManager.getRepository<MessageParticipantWorkspaceEntity>(
'messageParticipant',
);

const threadParticipants = await messageParticipantRepository.find({
where: {
message: {
messageThreadId: Any(messageThreadIds),
},
},
order: {
message: {
receivedAt: 'DESC',
},
},
relations: ['person', 'workspaceMember', 'message'],
});

const threadParticipantsByThreadId: {
[key: string]: MessageParticipantWorkspaceEntity[];
} = threadParticipants.reduce(
(threadParticipantsAcc, threadParticipant) => {
if (!threadParticipant.message.messageThreadId)
return threadParticipantsAcc;

if (!threadParticipantsAcc[threadParticipant.message.messageThreadId])
threadParticipantsAcc[threadParticipant.message.messageThreadId] = [];

threadParticipantsAcc[threadParticipant.message.messageThreadId].push(
threadParticipant,
);

return threadParticipantsAcc;
},
{},
);

const threadVisibilityByThreadId =
await this.timelineMessagingService.getThreadVisibilityByThreadId(
messageThreadIds,
threadParticipantsByThreadId,
workspaceMemberId,
);

return {
totalNumberOfThreads,
timelineThreads: formatThreads(
messageThreads,
threadParticipantsByThreadId,
threadVisibilityByThreadId,
),
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
import { Injectable } from '@nestjs/common';

import { Any } from 'typeorm';

import { TimelineThread } from 'src/engine/core-modules/messaging/dtos/timeline-thread.dto';
import { TwentyORMManager } from 'src/engine/twenty-orm/twenty-orm.manager';
import { MessageChannelVisibility } from 'src/modules/messaging/common/standard-objects/message-channel.workspace-entity';
import { MessageParticipantWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-participant.workspace-entity';
import { MessageThreadWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-thread.workspace-entity';

@Injectable()
export class TimelineMessagingService {
constructor(private readonly twentyORMManager: TwentyORMManager) {}

public async getMessageThreads(
personIds: string[],
offset: number,
pageSize: number,
): Promise<
Omit<
TimelineThread,
| 'firstParticipant'
| 'lastTwoParticipants'
| 'participantCount'
| 'read'
| 'visibility'
>[]
> {
const messageThreadRepository =
await this.twentyORMManager.getRepository<MessageThreadWorkspaceEntity>(
'messageThread',
);

const messageThreads = await messageThreadRepository.find({
select: {
id: true,
messages: {
receivedAt: true,
subject: true,
text: true,
},
},
where: {
messages: {
messageParticipants: {
personId: Any(personIds),
},
},
},
relations: ['messages', 'messages.messageParticipants'],
order: {
messages: {
receivedAt: 'DESC',
},
},
skip: offset,
take: pageSize,
});

return 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,
};
});
}

public async getThreadVisibilityByThreadId(
messageThreadIds: string[],
threadParticipantsByThreadId: {
[key: string]: MessageParticipantWorkspaceEntity[];
},
workspaceMemberId: string,
): Promise<{
[key: string]: MessageChannelVisibility;
}> {
const messageThreadIdsForWhichWorkspaceMemberIsNotInParticipants =
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: Consider optimizing the reduce function for better performance.

messageThreadIds.reduce(
(
messageThreadIdsForWhichWorkspaceMemberIsInNotParticipantsAcc: string[],
messageThreadId,
) => {
const threadMessagesWithWorkspaceMemberInParticipants =
threadParticipantsByThreadId[messageThreadId].filter(
(threadParticipant) =>
threadParticipant.workspaceMemberId === workspaceMemberId,
);

if (threadMessagesWithWorkspaceMemberInParticipants.length === 0)
messageThreadIdsForWhichWorkspaceMemberIsInNotParticipantsAcc.push(
messageThreadId,
);

return messageThreadIdsForWhichWorkspaceMemberIsInNotParticipantsAcc;
},
[],
);

const messageThreadRepository =
await this.twentyORMManager.getRepository<MessageThreadWorkspaceEntity>(
'messageThread',
);

const threadVisibility = await messageThreadRepository
.createQueryBuilder()
.select('messageThread.id', 'id')
.addSelect('messageChannel.visibility', 'visibility')
.leftJoin('messageThread.messages', 'message')
.leftJoin(
'message.messageChannelMessageAssociations',
'messageChannelMessageAssociation',
)
.leftJoin(
'messageChannelMessageAssociation.messageChannel',
'messageChannel',
)
.where('messageThread.id = ANY(:messageThreadIds)', {
messageThreadIds:
messageThreadIdsForWhichWorkspaceMemberIsNotInParticipants,
})
.getRawMany();

const visibilityValues = Object.values(MessageChannelVisibility);

const threadVisibilityByThreadIdForWhichWorkspaceMemberIsNotInParticipants:
| {
[key: string]: MessageChannelVisibility;
}
| undefined = threadVisibility?.reduce(
(threadVisibilityAcc, threadVisibility) => {
threadVisibilityAcc[threadVisibility.id] =
visibilityValues[
Math.max(
visibilityValues.indexOf(threadVisibility.visibility),
visibilityValues.indexOf(
threadVisibilityAcc[threadVisibility.id] ??
MessageChannelVisibility.METADATA,
),
)
];

return threadVisibilityAcc;
},
{},
);

const threadVisibilityByThreadId: {
[key: string]: MessageChannelVisibility;
} = messageThreadIds.reduce((threadVisibilityAcc, messageThreadId) => {
// If the workspace member is not in the participants of the thread, use the visibility value from the query
threadVisibilityAcc[messageThreadId] =
messageThreadIdsForWhichWorkspaceMemberIsNotInParticipants.includes(
messageThreadId,
)
? threadVisibilityByThreadIdForWhichWorkspaceMemberIsNotInParticipants?.[
messageThreadId
] ?? MessageChannelVisibility.METADATA
: MessageChannelVisibility.SHARE_EVERYTHING;

return threadVisibilityAcc;
}, {});

return threadVisibilityByThreadId;
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
import { Module } from '@nestjs/common';

import { GetMessagesFromCompanyIdService } from 'src/engine/core-modules/messaging/services/get-messages-from-company-id.service';
import { GetMessagesFromPersonIdsService } from 'src/engine/core-modules/messaging/services/get-messages-from-person-ids.service';
import { TimelineMessagingService } from 'src/engine/core-modules/messaging/services/timeline-messaging.service';
import { TimelineMessagingResolver } from 'src/engine/core-modules/messaging/timeline-messaging.resolver';
import { TimelineMessagingService } from 'src/engine/core-modules/messaging/timeline-messaging.service';
import { WorkspaceDataSourceModule } from 'src/engine/workspace-datasource/workspace-datasource.module';
import { UserModule } from 'src/engine/core-modules/user/user.module';
import { WorkspaceDataSourceModule } from 'src/engine/workspace-datasource/workspace-datasource.module';
@Module({
imports: [WorkspaceDataSourceModule, UserModule],
exports: [],
providers: [TimelineMessagingResolver, TimelineMessagingService],
providers: [
TimelineMessagingResolver,
TimelineMessagingService,
GetMessagesFromPersonIdsService,
GetMessagesFromCompanyIdService,
],
})
export class TimelineMessagingModule {}
Loading
Loading