NEKReport/addin/commands.html

286 lines
7.2 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://appsforoffice.microsoft.com/lib/1.1/hosted/office.js"></script>
</head>
<body>
<script>
Office.onReady(function () {
Office.actions.associate("analyzeSelectedEmails", analyzeSelectedEmails);
});
/* ----------------------------------------------------------
ВСТАВКА ПИСЬМА И ВЛОЖЕНИЙ В OUTLOOK
---------------------------------------------------------- */
window.addEventListener("message", async function(event) {
if (!event.data || event.data.type !== "insert_to_outlook") {
return;
}
try {
const payload = event.data.payload;
const letterText = payload.letter;
const sessionId = payload.session_id;
const item = Office.context.mailbox.item;
/* вставляем текст письма */
item.body.setAsync(
letterText,
{ coercionType: Office.CoercionType.Text }
);
/* получаем вложения */
const response = await fetch(
`https://nec.clients.septem.pro/llm/email-attachments/${sessionId}`
);
const attachments = await response.json();
for (const file of attachments) {
if (!file.content_base64) continue;
const ext = file.filename.split('.').pop().toLowerCase();
// полностью игнорируем изображения
if (['png','gif','bmp','tiff','webp'].includes(ext)) {
continue;
}
Office.context.mailbox.item.addFileAttachmentFromBase64Async(
file.content_base64,
file.filename
);
}
} catch (error) {
console.error("Insert to Outlook error:", error);
}
});
/* ----------------------------------------------------------
ПОЛУЧЕНИЕ ТЕКСТА И HTML ТЕЛА ПИСЬМА (ДОБАВЛЕНО)
---------------------------------------------------------- */
function getBodyAsync(item) {
return new Promise((resolve) => {
const result = { text: '', html: '' };
let pending = 2;
item.body.getAsync(Office.MailboxEnums.BodyType.Text, (res) => {
result.text = res.value || '';
if (--pending === 0) resolve(result);
});
item.body.getAsync(Office.MailboxEnums.BodyType.Html, (res) => {
result.html = res.value || '';
if (--pending === 0) resolve(result);
});
});
}
/* ----------------------------------------------------------
ПОЛУЧЕНИЕ ВЛОЖЕНИЙ
---------------------------------------------------------- */
function getAttachmentsWithContent(item) {
return new Promise((resolve) => {
if (!item.attachments || item.attachments.length === 0) {
resolve([]);
return;
}
const attachmentPromises = item.attachments.map(att => {
return new Promise((resolveAttachment) => {
item.getAttachmentContentAsync(att.id, function (result) {
if (result.status === Office.AsyncResultStatus.Succeeded) {
const attachmentContent = result.value;
let contentBase64 = null;
if (attachmentContent.format === Office.MailboxEnums.AttachmentContentFormat.Base64) {
contentBase64 = attachmentContent.content;
}
else if (attachmentContent.format === Office.MailboxEnums.AttachmentContentFormat.String) {
contentBase64 = btoa(attachmentContent.content);
}
resolveAttachment({
filename: att.name,
size: att.size,
content: contentBase64
});
}
else {
console.error("Failed to get attachment:", result.error);
resolveAttachment({
filename: att.name,
size: att.size,
content: null
});
}
});
});
});
Promise.all(attachmentPromises).then(resolve);
});
}
/* ----------------------------------------------------------
ОСНОВНАЯ ФУНКЦИЯ АНАЛИЗА ПИСЕМ
---------------------------------------------------------- */
async function analyzeSelectedEmails(event) {
try {
const item = Office.context.mailbox.item;
// Получаем и текст, и HTML (добавлено)
const body = await getBodyAsync(item);
const attachments = await getAttachmentsWithContent(item);
const emailData = {
id: item.itemId,
subject: item.subject,
sender: item.from?.emailAddress || "",
senderName: item.from?.displayName || "",
body: body.text, // текст
body_html: body.html, // HTML (новое поле)
receivedTime: item.dateTimeReceived?.toISOString() || "",
to: item.to?.map(t => t.emailAddress).join(", ") || "",
cc: item.cc?.map(c => c.emailAddress).join(", ") || "",
attachments: attachments
};
let sessionId = Office.context.roamingSettings.get("cargoSessionId");
const response = await fetch(
"https://nec.clients.septem.pro/llm/process-outlook-emails",
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
emails: [emailData],
session_id: sessionId
})
}
);
if (!response.ok) {
throw new Error("Server error: " + response.status);
}
const result = await response.json();
const newSessionId = result.session_id;
Office.context.roamingSettings.set("cargoSessionId", newSessionId);
Office.context.roamingSettings.saveAsync(function (asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Failed) {
console.error("Failed to save roamingSettings:", asyncResult.error);
}
});
Office.context.ui.displayDialogAsync(
`https://nec.clients.septem.pro/llm/addin/taskpane.html?session_id=${newSessionId}`,
{
height: 70,
width: 50,
displayInIframe: true
},
function (asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Failed) {
console.error("Dialog failed:", asyncResult.error);
window.open(
`https://nec.clients.septem.pro?session_id=${newSessionId}`,
"_blank"
);
}
event.completed();
}
);
} catch (error) {
console.error("Unexpected error:", error);
event.completed();
}
}
</script>
</body>
</html>