iva-studio-workspace/IVA-Wakeup/global/gvf_ConversationHistory.js

68 lines
2.4 KiB
JavaScript

return {
async fetchConversationHistory(conversationId, limit) {
let datahistory = await db.collection("analytics_transactions").aggregate([
{
$match: {
$and: [
{ "conversationId": conversationId },
{ "outputs.datacollect": true }
]
}
}
]).toArray();
console.log('10 line');
let lastElement = datahistory[datahistory.length - 1];
console.log(lastElement?.metadata?.actionType);
let messages = [];
const tx_msg = (direction, text, sentTime) => {
return {
conversationId: conversationId,
direction,
text,
dateSent: new Date(sentTime).toISOString(),
};
};
let counts = { agent: 0, ivas: 0 };
let agentName;
let is_async = null;
for (let msg of datahistory) {
if (msg?.answers.length) {
if (msg?.input !== "") {
messages.push(tx_msg("ToAgent", msg?.input, (msg?.metadata?.createdAt ?? Date.now())));
}
counts.ivas++;
for (let i = 0; i < msg?.answers.length; i++) {
let answer = msg.answers[i];
if (typeof answer !== "string") {
answer = JSON.stringify(answer ?? null);
}
messages.push(tx_msg("ToCustomer", answer, (msg?.metadata?.createdAt ?? Date.now()) + 50 + i));
counts.ivas++;
}
}
if (limit > 0 && messages.length >= limit) break;
}
const summary = {
conversationId: conversationId,
steps: []
};
messages.forEach(msg => {
summary.steps.push({
who: msg.direction === "ToAgent" ? "Customer" : "System",
text: msg.text,
time: new Date(msg.dateSent).toLocaleString()
});
});
let history = ``;
summary.steps.forEach((step, index) => {
history += `<strong>${step.who}:</strong> ${step.text}<br/>`;
});
history+= `<strong>ActionType:</strong> ${lastElement?.metadata?.actionType}`
return history;
}
};