fix telegram contact identity context for in/out messages

This commit is contained in:
Ruslan Bakiev
2026-02-23 19:28:03 +07:00
parent 79f1012f41
commit 94d8d46693
2 changed files with 35 additions and 20 deletions

View File

@@ -60,6 +60,12 @@ function normalizeNumber(value: unknown) {
return null;
}
function normalizeId(value: unknown) {
if (value == null) return null;
const text = String(value).trim();
return text || null;
}
type TelegramMediaInfo = {
kind: "voice" | "audio" | "video_note" | null;
fileId: string | null;
@@ -159,8 +165,26 @@ export function parseTelegramBusinessUpdate(raw: unknown): OmniInboundEnvelopeV1
const chat = asObject(message.chat);
const from = asObject(message.from);
const direction = detectDirection(message, chat, from);
const contactSource = direction === "OUT" && Object.keys(chat).length > 0 ? chat : from;
const fallbackContactSource = direction === "OUT" ? from : chat;
const ownerChatId = normalizeId(businessConnection.user_chat_id);
const chatId = normalizeId(chat.id);
const fromId = normalizeId(from.id);
let contactSource: JsonObject | null = null;
if (ownerChatId) {
// Prefer the counterparty id/source (different from connected owner chat id).
if (chatId && chatId !== ownerChatId) contactSource = chat;
if (fromId && fromId !== ownerChatId) {
if (!contactSource || direction === "IN") {
contactSource = from;
}
}
}
if (!contactSource) {
contactSource = direction === "OUT" && Object.keys(chat).length > 0 ? chat : from;
}
const fallbackContactSource = contactSource === chat ? from : chat;
const threadExternalId =
chat.id != null
@@ -170,11 +194,9 @@ export function parseTelegramBusinessUpdate(raw: unknown): OmniInboundEnvelopeV1
: null;
const contactExternalId =
contactSource.id != null
? String(contactSource.id)
: fallbackContactSource.id != null
? String(fallbackContactSource.id)
: null;
normalizeId(contactSource?.id) ??
normalizeId(fallbackContactSource?.id) ??
null;
const media = pickTelegramMedia(message);
const text =