Skip to content

Commit b711ff9

Browse files
Merge pull request #2189 from AletheiaFact/adding-support-for-external-identifiers-to-history-module
refactor: optimize history module architecture and fix pagination
2 parents 3e4c662 + 9b27640 commit b711ff9

29 files changed

+790
-179
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import { Db, ObjectId } from "mongodb";
2+
3+
const HEX24 = /^[0-9a-fA-F]{24}$/;
4+
5+
export async function up(db: Db) {
6+
try {
7+
const historiesToChange = await db
8+
.collection("histories")
9+
.find({ user: { $type: "string", $regex: HEX24 } })
10+
.toArray();
11+
12+
if (historiesToChange.length === 0) {
13+
console.log("No histories with string users to change.");
14+
} else {
15+
const bulkOps = historiesToChange.map((history) => ({
16+
updateOne: {
17+
filter: { _id: history._id },
18+
update: {
19+
$set: {
20+
user: new ObjectId(history.user as string),
21+
migration_revert_flag: true,
22+
},
23+
},
24+
},
25+
}));
26+
27+
const result = await db.collection("histories").bulkWrite(bulkOps);
28+
console.log(`Converted ${result.modifiedCount} history.user fields to ObjectId.`);
29+
}
30+
} catch (error) {
31+
console.error("Migration UP failed:", error);
32+
throw error;
33+
}
34+
}
35+
36+
export async function down(db: Db) {
37+
try {
38+
const historiesToRedefine = await db
39+
.collection("histories")
40+
.find({ migration_revert_flag: true })
41+
.toArray();
42+
43+
if (historiesToRedefine.length === 0) return;
44+
45+
const bulkOps = historiesToRedefine.map((history) => {
46+
const userIdString = history.user ? String(history.user) : null;
47+
48+
return {
49+
updateOne: {
50+
filter: { _id: history._id },
51+
update: { $set: { user: userIdString } },
52+
$unset: { migration_revert_flag: "" },
53+
},
54+
};
55+
})
56+
57+
const result = await db.collection("histories").bulkWrite(bulkOps);
58+
console.log(`Reverted ${result.modifiedCount} fields back to strings.`);
59+
60+
} catch (error) {
61+
console.error("Migration DOWN failed:", error);
62+
throw error;
63+
}
64+
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import { Db } from "mongodb";
2+
3+
export async function up(db: Db) {
4+
const historyCollection = db.collection("histories");
5+
6+
const historiesFound = historyCollection.find({
7+
user: { $type: "string", $regex: "-" },
8+
});
9+
10+
let count = 0;
11+
12+
while (await historiesFound.hasNext()) {
13+
const history = await historiesFound.next();
14+
if (!history) continue;
15+
const oldUserValue = history.user as string;
16+
17+
const newUser = {
18+
isM2M: true,
19+
clientId: oldUserValue,
20+
subject: "chatbot-service",
21+
scopes: ["read", "write"],
22+
role: { main: "integration" },
23+
namespace: "main",
24+
};
25+
26+
await historyCollection.updateOne(
27+
{ _id: history._id },
28+
{ $set: { user: newUser } }
29+
);
30+
31+
count++;
32+
}
33+
34+
console.log(`Migration complete. Updated ${count} documents.`);
35+
}
36+
37+
export async function down(db: Db) {
38+
const historyCollection = db.collection("histories");
39+
40+
const historiesFound = historyCollection.find({
41+
"user.isM2M": true,
42+
"user.subject": "chatbot-service",
43+
"user.clientId": { $exists: true }
44+
});
45+
46+
let count = 0;
47+
48+
while (await historiesFound.hasNext()) {
49+
const history = await historiesFound.next();
50+
if (!history) continue;
51+
const clientId = history.user.clientId;
52+
53+
await historyCollection.updateOne(
54+
{ _id: history._id },
55+
{ $set: { user: clientId } }
56+
);
57+
58+
count++;
59+
}
60+
61+
console.log(`Rollback complete. Reverted ${count} documents.`);
62+
}

public/locales/en/history.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
{
22
"anonymousUserName": "Anonymous",
3+
"automatedMonitoring": "Automated Monitoring",
4+
"virtualAssistant": "Virtual Assistant",
35
"create": "created",
46
"update": "updated",
57
"delete": "deleted",
@@ -8,4 +10,4 @@
810
"personality": "profile",
911
"claim": "claim",
1012
"historyItem": "{{username}} {{type}} {{title}} {{targetModel}}"
11-
}
13+
}

public/locales/pt/history.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
{
22
"anonymousUserName": "Anônimo",
3+
"automatedMonitoring": "Monitoramento Automatizado",
4+
"virtualAssistant": "Assistente Virtual",
35
"create": "criou",
46
"update": "atualizou",
57
"delete": "deletou",
@@ -8,4 +10,4 @@
810
"personality": "o perfil de",
911
"claim": "a afirmação",
1012
"historyItem": "{{username}} {{type}} {{targetModel}} {{title}}"
11-
}
13+
}

server/chat-bot/chat-bot.machine.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ export const createChatBotMachine = (
1414
verificationRequestStateMachineService: VerificationRequestStateMachineService,
1515
value?,
1616
context?,
17-
chatbotStateId?
17+
M2MUser?,
1818
) => {
1919
const chatBotMachine = createMachine<ChatBotContext>(
2020
{
@@ -199,7 +199,7 @@ export const createChatBotMachine = (
199199

200200
verificationRequestStateMachineService.request(
201201
verificationRequestBody,
202-
chatbotStateId
202+
M2MUser
203203
);
204204
},
205205
},

server/chat-bot/chat-bot.service.ts

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import { createChatBotMachine } from "./chat-bot.machine";
77
import { ConfigService } from "@nestjs/config";
88
import { ChatBotStateService } from "../chat-bot-state/chat-bot-state.service";
99
import { VerificationRequestStateMachineService } from "../verification-request/state-machine/verification-request.state-machine.service";
10+
import { Roles } from "../auth/ability/ability.factory";
11+
import { M2M } from "../entities/m2m.entity";
1012

1113
const diacriticsRegex = /[\u0300-\u036f]/g;
1214
const MESSAGE_MAP = {
@@ -22,6 +24,19 @@ interface ChatBotContext {
2224
sourceChannel?: string;
2325
}
2426

27+
function M2MUser(clientId): M2M {
28+
return {
29+
isM2M: true,
30+
clientId,
31+
subject: "chatbot-service",
32+
scopes: ["read", "write"],
33+
role: {
34+
main: Roles.Integration,
35+
},
36+
namespace: "main",
37+
};
38+
}
39+
2540
@Injectable({ scope: Scope.REQUEST })
2641
export class ChatbotService {
2742
constructor(
@@ -99,7 +114,7 @@ export class ChatbotService {
99114
...chatbotState.machine.context,
100115
sourceChannel: channel,
101116
},
102-
chatbotState._id
117+
M2MUser(chatbotState._id)
103118
);
104119

105120
chatBotMachineService.start(chatbotState.machine.value);

server/claim-review/claim-review.service.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -353,7 +353,7 @@ export class ClaimReviewService {
353353
const history = this.historyService.getHistoryParams(
354354
newReview._id,
355355
TargetModel.ClaimReview,
356-
this.req?.user,
356+
this.req.user?._id,
357357
hide ? HistoryType.Hide : HistoryType.Unhide,
358358
after,
359359
before

server/claim/claim.service.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ export class ClaimService {
140140
newClaim.latestRevision = newClaimRevision._id;
141141
newClaim.slug = newClaimRevision.slug;
142142

143-
const user = this.req.user;
143+
const user = this.req.user?._id;
144144

145145
const history = this.historyService.getHistoryParams(
146146
newClaim._id,
@@ -193,7 +193,7 @@ export class ClaimService {
193193
claim.latestRevision = newClaimRevision._id;
194194
claim.slug = newClaimRevision.slug;
195195

196-
const user = this.req.user;
196+
const user = this.req.user?._id;
197197

198198
const history = this.historyService.getHistoryParams(
199199
claimId,
@@ -218,7 +218,7 @@ export class ClaimService {
218218
* @returns Returns the claim with the param isDeleted equal to true
219219
*/
220220
async delete(claimId) {
221-
const user = this.req.user;
221+
const user = this.req.user?._id;
222222
const previousClaim = await this.getById(claimId);
223223
const history = this.historyService.getHistoryParams(
224224
claimId,
@@ -251,7 +251,7 @@ export class ClaimService {
251251
const history = this.historyService.getHistoryParams(
252252
newClaim._id,
253253
TargetModel.Claim,
254-
this.req?.user,
254+
this.req.user?._id,
255255
isHidden ? HistoryType.Hide : HistoryType.Unhide,
256256
after,
257257
before

server/claim/types/debate/debate.service.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ export class DebateService {
7575
const history = this.historyService.getHistoryParams(
7676
newDebate._id,
7777
TargetModel.Debate,
78-
this.req.user,
78+
this.req.user?._id,
7979
HistoryType.Update,
8080
newDebate,
8181
previousDebate

server/claim/types/image/image.service.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ export class ImageService {
4444
const history = this.historyService.getHistoryParams(
4545
newImage._id,
4646
TargetModel.Image,
47-
this.req.user,
47+
this.req.user?._id,
4848
HistoryType.Create,
4949
newImage
5050
);

0 commit comments

Comments
 (0)