import type { ComposeContext } from "./api"; /** Promesse autour des API asynchrones Office (callback AsyncResult). */ export function officeAsync(call: (cb: (r: Office.AsyncResult) => void) => void): Promise { return new Promise((resolve, reject) => { call((r) => (r.status === Office.AsyncResultStatus.Succeeded ? resolve(r.value) : reject(r.error))); }); } type ComposeItem = Office.MessageCompose | Office.AppointmentCompose; export function currentItem(): ComposeItem { return Office.context.mailbox.item as ComposeItem; } export function isAppointment(item: ComposeItem): item is Office.AppointmentCompose { return item.itemType === Office.MailboxEnums.ItemType.Appointment; } /** new / reply / forward pour un message, appointment pour une invitation. */ export async function getComposeContext(item: ComposeItem): Promise { if (isAppointment(item)) return "appointment"; const msg = item as Office.MessageCompose; if (typeof msg.getComposeTypeAsync !== "function") return "new"; try { const v = await officeAsync<{ composeType: string }>((cb) => msg.getComposeTypeAsync(cb)); switch (v.composeType) { case Office.MailboxEnums.ComposeType.Reply: return "reply"; case Office.MailboxEnums.ComposeType.Forward: return "forward"; default: return "new"; } } catch { return "new"; } } /** Adresse de la boîte émettrice (boîte partagée si l'agent a changé le champ De). */ export async function getMailbox(item: ComposeItem): Promise { try { if (isAppointment(item)) { const o = await officeAsync((cb) => item.organizer.getAsync(cb)); return o?.emailAddress?.toLowerCase() ?? null; } const f = await officeAsync((cb) => (item as Office.MessageCompose).from.getAsync(cb)); return f?.emailAddress?.toLowerCase() ?? null; } catch { return Office.context.mailbox.userProfile?.emailAddress?.toLowerCase() ?? null; } } export async function applySignature(item: ComposeItem, html: string): Promise { await officeAsync((cb) => item.body.setSignatureAsync(html, { coercionType: Office.CoercionType.Html }, cb)); // Neutralise la signature native d'Outlook (sinon doublon). Ignoré si non supporté. if (typeof item.disableClientSignatureAsync === "function") { try { await officeAsync((cb) => item.disableClientSignatureAsync(cb)); } catch { /* non bloquant */ } } } export function notify(item: ComposeItem, message: string): Promise { return new Promise((resolve) => { try { item.notificationMessages.replaceAsync( "cabm_signature", { type: Office.MailboxEnums.ItemNotificationMessageType.InformationalMessage, message, icon: "Icon.16x16", persistent: false, }, () => resolve(), ); } catch { resolve(); } }); }