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 32 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,101 @@
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 { 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 { PersonWorkspaceEntity } from 'src/modules/person/standard-objects/person.workspace-entity';

@Injectable()
export class GetMessagesService {
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 { messageThreads, totalNumberOfThreads } =
await this.timelineMessagingService.getAndCountMessageThreads(
personIds,
offset,
pageSize,
);

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

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

const threadParticipantsByThreadId =
await this.timelineMessagingService.getThreadParticipantsByThreadId(
messageThreadIds,
);

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

return {
totalNumberOfThreads,
timelineThreads: formatThreads(
messageThreads,
threadParticipantsByThreadId,
threadVisibilityByThreadId,
),
};
}

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.length === 0) {
return {
totalNumberOfThreads: 0,
timelineThreads: [],
};
}

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

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

import { Any, Not } 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 getAndCountMessageThreads(
personIds: string[],
offset: number,
pageSize: number,
): Promise<{
messageThreads: Omit<
TimelineThread,
| 'firstParticipant'
| 'lastTwoParticipants'
| 'participantCount'
| 'read'
| 'visibility'
>[];
totalNumberOfThreads: number;
}> {
const messageThreadRepository =
await this.twentyORMManager.getRepository<MessageThreadWorkspaceEntity>(
'messageThread',
);

const [messageThreadIds, totalNumberOfThreads] =
await messageThreadRepository.findAndCount({
select: {
id: true,
},
where: {
messages: {
messageParticipants: {
personId: Any(personIds),
},
},
},
skip: offset,
take: pageSize,
});

const messageThreads = await messageThreadRepository.find({
select: {
id: true,
},
where: {
id: Any(messageThreadIds.map((thread) => thread.id)),
},
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,
};
}),
totalNumberOfThreads,
};
}

public async getThreadParticipantsByThreadId(
messageThreadIds: string[],
): Promise<{
[key: string]: MessageParticipantWorkspaceEntity[];
}> {
const messageParticipantRepository =
await this.twentyORMManager.getRepository<MessageParticipantWorkspaceEntity>(
'messageParticipant',
);
const threadParticipants = await messageParticipantRepository
.createQueryBuilder()
.select('messageParticipant')
.addSelect('message.messageThreadId')
.addSelect('message.receivedAt')
.leftJoinAndSelect('messageParticipant.person', 'person')
.leftJoinAndSelect(
'messageParticipant.workspaceMember',
'workspaceMember',
)
.leftJoin('messageParticipant.message', 'message')
.where('message.messageThreadId = ANY(:messageThreadIds)', {
messageThreadIds,
})
.andWhere('messageParticipant.role = :role', { role: 'from' })
.orderBy('message.messageThreadId')
.distinctOn(['message.messageThreadId', 'messageParticipant.handle'])
.getMany();

// This is because subqueries are not handled by twentyORM
const orderedThreadParticipants = threadParticipants.sort(
(a, b) =>
(a.message.receivedAt ?? new Date()).getTime() -
(b.message.receivedAt ?? new Date()).getTime(),
);

// This is because composite fields are not handled correctly by the ORM
const threadParticipantsWithCompositeFields = orderedThreadParticipants.map(
(threadParticipant) => ({
...threadParticipant,
person: {
id: threadParticipant.person?.id,
name: {
//eslint-disable-next-line
//@ts-ignore
firstName: threadParticipant.person?.nameFirstName,
//eslint-disable-next-line
//@ts-ignore
lastName: threadParticipant.person?.nameLastName,
},
avatarUrl: threadParticipant.person?.avatarUrl,
},
workspaceMember: {
id: threadParticipant.workspaceMember?.id,
name: {
//eslint-disable-next-line
//@ts-ignore
firstName: threadParticipant.workspaceMember?.nameFirstName,
//eslint-disable-next-line
//@ts-ignore
lastName: threadParticipant.workspaceMember?.nameLastName,
},
avatarUrl: threadParticipant.workspaceMember?.avatarUrl,
},
}),
);

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

public async getThreadVisibilityByThreadId(
messageThreadIds: string[],
workspaceMemberId: string,
): Promise<{
[key: string]: MessageChannelVisibility;
}> {
const messageThreadRepository =
await this.twentyORMManager.getRepository<MessageThreadWorkspaceEntity>(
'messageThread',
);

const threadsWithoutWorkspaceMember = await messageThreadRepository.find({
select: {
id: true,
},
where: {
id: Any(messageThreadIds),
messages: {
messageChannelMessageAssociations: {
messageChannel: {
connectedAccount: {
accountOwnerId: Not(workspaceMemberId),
},
},
},
},
},
});

const threadIdsWithoutWorkspaceMember = threadsWithoutWorkspaceMember.map(
(thread) => thread.id,
);

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: threadIdsWithoutWorkspaceMember,
})
.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] =
threadIdsWithoutWorkspaceMember.includes(messageThreadId)
? (threadVisibilityByThreadIdForWhichWorkspaceMemberIsNotInParticipants?.[
messageThreadId
] ?? MessageChannelVisibility.METADATA)
: MessageChannelVisibility.SHARE_EVERYTHING;

return threadVisibilityAcc;
}, {});

return threadVisibilityByThreadId;
}
}
Loading
Loading