Skip to content

Commit 18ff304

Browse files
committed
create 0-24-set-message-direction.command
1 parent 0d0af96 commit 18ff304

File tree

5 files changed

+183
-3
lines changed

5 files changed

+183
-3
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
import { Logger } from '@nestjs/common';
2+
import { InjectRepository } from '@nestjs/typeorm';
3+
4+
import chalk from 'chalk';
5+
import { Command, CommandRunner, Option } from 'nest-commander';
6+
import { Any, Repository } from 'typeorm';
7+
8+
import {
9+
Workspace,
10+
WorkspaceActivationStatus,
11+
} from 'src/engine/core-modules/workspace/workspace.entity';
12+
import { WorkspaceMetadataVersionService } from 'src/engine/metadata-modules/workspace-metadata-version/workspace-metadata-version.service';
13+
import { TwentyORMGlobalManager } from 'src/engine/twenty-orm/twenty-orm-global.manager';
14+
import { MessageChannelMessageAssociationWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-channel-message-association.workspace-entity';
15+
16+
interface SetMessageDirectionCommandOptions {
17+
workspaceId?: string;
18+
}
19+
20+
@Command({
21+
name: 'upgrade-0.24:migrate-message-direction',
22+
description: 'Migrate message direction',
23+
})
24+
export class SetMessageDirectionCommand extends CommandRunner {
25+
private readonly logger = new Logger(SetMessageDirectionCommand.name);
26+
constructor(
27+
private readonly workspaceMetadataVersionService: WorkspaceMetadataVersionService,
28+
private readonly twentyORMGlobalManager: TwentyORMGlobalManager,
29+
@InjectRepository(Workspace, 'core')
30+
private readonly workspaceRepository: Repository<Workspace>,
31+
) {
32+
super();
33+
}
34+
35+
@Option({
36+
flags: '-w, --workspace-id [workspace_id]',
37+
description: 'workspace id. Command runs on all workspaces if not provided',
38+
required: false,
39+
})
40+
parseWorkspaceId(value: string): string {
41+
return value;
42+
}
43+
44+
async run(
45+
_passedParam: string[],
46+
options: SetMessageDirectionCommandOptions,
47+
): Promise<void> {
48+
let activeWorkspaceIds: string[] = [];
49+
50+
if (options.workspaceId) {
51+
activeWorkspaceIds = [options.workspaceId];
52+
} else {
53+
const activeWorkspaces = await this.workspaceRepository.find({
54+
where: {
55+
activationStatus: WorkspaceActivationStatus.ACTIVE,
56+
...(options.workspaceId && { id: options.workspaceId }),
57+
},
58+
});
59+
60+
activeWorkspaceIds = activeWorkspaces.map((workspace) => workspace.id);
61+
}
62+
63+
if (!activeWorkspaceIds.length) {
64+
this.logger.log(chalk.yellow('No workspace found'));
65+
66+
return;
67+
} else {
68+
this.logger.log(
69+
chalk.green(
70+
`Running command on ${activeWorkspaceIds.length} workspaces`,
71+
),
72+
);
73+
}
74+
75+
for (const workspaceId of activeWorkspaceIds) {
76+
try {
77+
const messageChannelMessageAssociationRepository =
78+
await this.twentyORMGlobalManager.getRepositoryForWorkspace<MessageChannelMessageAssociationWorkspaceEntity>(
79+
workspaceId,
80+
'messageChannelMessageAssociation',
81+
);
82+
83+
const messageChannelMessageAssociations =
84+
await messageChannelMessageAssociationRepository.find({
85+
where: {
86+
message: {
87+
messageParticipants: {
88+
role: 'from',
89+
},
90+
},
91+
},
92+
relations: {
93+
message: {
94+
messageParticipants: true,
95+
},
96+
messageChannel: {
97+
connectedAccount: true,
98+
},
99+
},
100+
});
101+
102+
try {
103+
const { incoming, outgoing } =
104+
messageChannelMessageAssociations.reduce(
105+
(
106+
acc: {
107+
incoming: string[];
108+
outgoing: string[];
109+
},
110+
messageChannelMessageAssociation,
111+
) => {
112+
const connectedAccountHandle =
113+
messageChannelMessageAssociation?.messageChannel
114+
?.connectedAccount?.handle;
115+
const connectedAccountHanldeAliases =
116+
messageChannelMessageAssociation?.messageChannel
117+
?.connectedAccount?.handleAliases;
118+
const fromHandle =
119+
messageChannelMessageAssociation?.message
120+
?.messageParticipants?.[0]?.handle ?? '';
121+
122+
if (
123+
connectedAccountHandle === fromHandle ||
124+
connectedAccountHanldeAliases?.includes(fromHandle)
125+
) {
126+
acc.outgoing.push(messageChannelMessageAssociation.id);
127+
} else {
128+
acc.incoming.push(messageChannelMessageAssociation.id);
129+
}
130+
131+
return acc;
132+
},
133+
{ incoming: [], outgoing: [] },
134+
);
135+
136+
await messageChannelMessageAssociationRepository.update(
137+
{
138+
id: Any(incoming),
139+
},
140+
{
141+
direction: 'incoming',
142+
},
143+
);
144+
145+
await messageChannelMessageAssociationRepository.update(
146+
{
147+
id: Any(outgoing),
148+
},
149+
{
150+
direction: 'outgoing',
151+
},
152+
);
153+
} catch (error) {
154+
this.logger.log(
155+
chalk.red(`Running command on workspace ${workspaceId} failed`),
156+
);
157+
throw error;
158+
}
159+
160+
await this.workspaceMetadataVersionService.incrementMetadataVersion(
161+
workspaceId,
162+
);
163+
164+
this.logger.log(
165+
chalk.green(`Running command on workspace ${workspaceId} done`),
166+
);
167+
} catch (error) {
168+
this.logger.error(
169+
`Migration failed for workspace ${workspaceId}: ${error.message}`,
170+
);
171+
}
172+
}
173+
174+
this.logger.log(chalk.green(`Command completed!`));
175+
}
176+
}

packages/twenty-server/src/database/commands/upgrade-version/0-24/0-24-upgrade-version.command.ts

+3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { Command, CommandRunner, Option } from 'nest-commander';
22

3+
import { SetMessageDirectionCommand } from 'src/database/commands/upgrade-version/0-24/0-24-set-message-direction.command';
34
import { SyncWorkspaceMetadataCommand } from 'src/engine/workspace-manager/workspace-sync-metadata/commands/sync-workspace-metadata.command';
45

56
interface UpdateTo0_24CommandOptions {
@@ -13,6 +14,7 @@ interface UpdateTo0_24CommandOptions {
1314
export class UpgradeTo0_24Command extends CommandRunner {
1415
constructor(
1516
private readonly syncWorkspaceMetadataCommand: SyncWorkspaceMetadataCommand,
17+
private readonly setMessagesDirectionCommand: SetMessageDirectionCommand,
1618
) {
1719
super();
1820
}
@@ -35,5 +37,6 @@ export class UpgradeTo0_24Command extends CommandRunner {
3537
...options,
3638
force: true,
3739
});
40+
await this.setMessagesDirectionCommand.run(_passedParam, options);
3841
}
3942
}

packages/twenty-server/src/database/commands/upgrade-version/0-24/0-24-upgrade-version.module.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { Module } from '@nestjs/common';
22
import { TypeOrmModule } from '@nestjs/typeorm';
33

4+
import { SetMessageDirectionCommand } from 'src/database/commands/upgrade-version/0-24/0-24-set-message-direction.command';
45
import { UpgradeTo0_24Command } from 'src/database/commands/upgrade-version/0-24/0-24-upgrade-version.command';
56
import { TypeORMModule } from 'src/database/typeorm/typeorm.module';
67
import { KeyValuePair } from 'src/engine/core-modules/key-value-pair/key-value-pair.entity';
@@ -33,6 +34,6 @@ import { WorkspaceSyncMetadataCommandsModule } from 'src/engine/workspace-manage
3334
),
3435
TypeORMModule,
3536
],
36-
providers: [UpgradeTo0_24Command],
37+
providers: [UpgradeTo0_24Command, SetMessageDirectionCommand],
3738
})
3839
export class UpgradeTo0_24CommandModule {}

packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-message.service.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,6 @@ export class MessagingMessageService {
115115
headerMessageId: message.headerMessageId,
116116
subject: message.subject,
117117
receivedAt: new Date(parseInt(message.internalDate)),
118-
direction: messageDirection,
119118
text: message.text,
120119
messageThreadId: newOrExistingMessageThreadId,
121120
},
@@ -130,6 +129,7 @@ export class MessagingMessageService {
130129
messageId: newMessageId,
131130
messageExternalId: message.externalId,
132131
messageThreadExternalId: message.messageThreadExternalId,
132+
direction: messageDirection,
133133
},
134134
transactionManager,
135135
);

packages/twenty-server/src/modules/messaging/message-participant-manager/jobs/messaging-create-company-and-contact-after-sync.job.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -89,8 +89,8 @@ export class MessagingCreateCompanyAndContactAfterSyncJob {
8989
message: {
9090
messageChannelMessageAssociations: {
9191
messageChannelId,
92+
direction: directionFilter,
9293
},
93-
direction: directionFilter,
9494
},
9595
personId: IsNull(),
9696
workspaceMemberId: IsNull(),

0 commit comments

Comments
 (0)