DB-backed workspace + LangGraph agent

This commit is contained in:
Ruslan Bakiev
2026-02-18 13:56:35 +07:00
parent a8db021597
commit efa0b79c4c
36 changed files with 2125 additions and 468 deletions

View File

@@ -0,0 +1,41 @@
import { getQuery } from "h3";
import { prisma } from "../../utils/prisma";
import { getAuthContext } from "../../utils/auth";
export default defineEventHandler(async (event) => {
const auth = await getAuthContext(event);
const q = getQuery(event);
const threadId = typeof q.threadId === "string" ? q.threadId : "";
if (!threadId) throw createError({ statusCode: 400, statusMessage: "threadId is required" });
const thread = await prisma.omniThread.findFirst({
where: { id: threadId, teamId: auth.teamId, channel: "TELEGRAM" },
});
if (!thread) throw createError({ statusCode: 404, statusMessage: "thread not found" });
const items = await prisma.omniMessage.findMany({
where: { teamId: auth.teamId, threadId: thread.id, channel: "TELEGRAM" },
orderBy: { occurredAt: "asc" },
take: 200,
});
return {
thread: {
id: thread.id,
contactId: thread.contactId,
externalChatId: thread.externalChatId,
businessConnectionId: thread.businessConnectionId,
title: thread.title,
updatedAt: thread.updatedAt,
},
items: items.map((m) => ({
id: m.id,
direction: m.direction,
status: m.status,
text: m.text,
providerMessageId: m.providerMessageId,
occurredAt: m.occurredAt,
})),
};
});

View File

@@ -0,0 +1,36 @@
import { readBody } from "h3";
import { prisma } from "../../utils/prisma";
import { getAuthContext } from "../../utils/auth";
import { enqueueTelegramSend } from "../../queues/telegramSend";
export default defineEventHandler(async (event) => {
const auth = await getAuthContext(event);
const body = await readBody<{ threadId?: string; text?: string }>(event);
const threadId = (body?.threadId || "").trim();
const text = (body?.text || "").trim();
if (!threadId) throw createError({ statusCode: 400, statusMessage: "threadId is required" });
if (!text) throw createError({ statusCode: 400, statusMessage: "text is required" });
const thread = await prisma.omniThread.findFirst({
where: { id: threadId, teamId: auth.teamId, channel: "TELEGRAM" },
});
if (!thread) throw createError({ statusCode: 404, statusMessage: "thread not found" });
const msg = await prisma.omniMessage.create({
data: {
teamId: auth.teamId,
contactId: thread.contactId,
threadId: thread.id,
direction: "OUT",
channel: "TELEGRAM",
status: "PENDING",
text,
occurredAt: new Date(),
},
});
await enqueueTelegramSend({ omniMessageId: msg.id });
return { ok: true, messageId: msg.id };
});

View File

@@ -0,0 +1,37 @@
import { prisma } from "../../utils/prisma";
import { getAuthContext } from "../../utils/auth";
export default defineEventHandler(async (event) => {
const auth = await getAuthContext(event);
const threads = await prisma.omniThread.findMany({
where: { teamId: auth.teamId, channel: "TELEGRAM" },
orderBy: { updatedAt: "desc" },
take: 50,
include: {
contact: true,
messages: { orderBy: { occurredAt: "desc" }, take: 1 },
},
});
return {
items: threads.map((t) => ({
id: t.id,
contact: { id: t.contact.id, name: t.contact.name },
externalChatId: t.externalChatId,
businessConnectionId: t.businessConnectionId,
title: t.title,
updatedAt: t.updatedAt,
lastMessage: t.messages[0]
? {
id: t.messages[0].id,
direction: t.messages[0].direction,
status: t.messages[0].status,
text: t.messages[0].text,
occurredAt: t.messages[0].occurredAt,
}
: null,
})),
};
});

View File

@@ -0,0 +1,163 @@
import { readBody, getQuery, getHeader } from "h3";
import { prisma } from "../../utils/prisma";
function teamIdFromWebhook(event: any) {
const q = getQuery(event);
const fromQuery = typeof q.teamId === "string" ? q.teamId : null;
return fromQuery || process.env.TELEGRAM_DEFAULT_TEAM_ID || "demo-team";
}
function assertSecret(event: any) {
const expected = process.env.TELEGRAM_WEBHOOK_SECRET;
if (!expected) return;
const got = getHeader(event, "x-telegram-bot-api-secret-token");
if (!got || got !== expected) {
throw createError({ statusCode: 401, statusMessage: "invalid telegram secret token" });
}
}
function displayNameFromTelegram(obj: any) {
const first = obj?.first_name || "";
const last = obj?.last_name || "";
const u = obj?.username ? `@${obj.username}` : "";
const full = `${first} ${last}`.trim();
return (full || u || "Telegram user").trim();
}
async function upsertBusinessConnection(teamId: string, bc: any) {
if (!bc?.id) return;
const businessConnectionId = String(bc.id);
await prisma.telegramBusinessConnection.upsert({
where: { teamId_businessConnectionId: { teamId, businessConnectionId } },
update: {
isEnabled: typeof bc.is_enabled === "boolean" ? bc.is_enabled : undefined,
canReply: typeof bc.can_reply === "boolean" ? bc.can_reply : undefined,
rawJson: bc,
},
create: {
teamId,
businessConnectionId,
isEnabled: typeof bc.is_enabled === "boolean" ? bc.is_enabled : null,
canReply: typeof bc.can_reply === "boolean" ? bc.can_reply : null,
rawJson: bc,
},
});
}
async function ensureContactForTelegramChat(teamId: string, externalChatId: string, tgUser: any) {
const existing = await prisma.omniContactIdentity.findUnique({
where: { teamId_channel_externalId: { teamId, channel: "TELEGRAM", externalId: externalChatId } },
include: { contact: true },
});
if (existing) return existing.contact;
const contact = await prisma.contact.create({
data: {
teamId,
name: displayNameFromTelegram(tgUser),
},
});
await prisma.omniContactIdentity.create({
data: {
teamId,
contactId: contact.id,
channel: "TELEGRAM",
externalId: externalChatId,
},
});
return contact;
}
async function ensureThread(input: {
teamId: string;
contactId: string;
externalChatId: string;
businessConnectionId?: string | null;
title?: string | null;
}) {
return prisma.omniThread.upsert({
where: {
teamId_channel_externalChatId_businessConnectionId: {
teamId: input.teamId,
channel: "TELEGRAM",
externalChatId: input.externalChatId,
businessConnectionId: input.businessConnectionId ?? null,
},
},
update: {
contactId: input.contactId,
title: input.title ?? undefined,
},
create: {
teamId: input.teamId,
contactId: input.contactId,
channel: "TELEGRAM",
externalChatId: input.externalChatId,
businessConnectionId: input.businessConnectionId ?? null,
title: input.title ?? null,
},
});
}
export default defineEventHandler(async (event) => {
assertSecret(event);
const teamId = teamIdFromWebhook(event);
const update = (await readBody<any>(event)) || {};
// business_connection updates (user connected/disconnected bot)
if (update.business_connection) {
await upsertBusinessConnection(teamId, update.business_connection);
return { ok: true };
}
const msg = update.business_message || update.edited_business_message;
if (!msg) return { ok: true };
const businessConnectionId = msg.business_connection_id ? String(msg.business_connection_id) : null;
const chatId = msg.chat?.id != null ? String(msg.chat.id) : null;
const providerMessageId = msg.message_id != null ? String(msg.message_id) : null;
if (!chatId || !providerMessageId) return { ok: true };
const text = typeof msg.text === "string" ? msg.text : typeof msg.caption === "string" ? msg.caption : "";
const occurredAt = msg.date ? new Date(Number(msg.date) * 1000) : new Date();
const contact = await ensureContactForTelegramChat(teamId, chatId, msg.from || msg.chat);
const thread = await ensureThread({
teamId,
contactId: contact.id,
externalChatId: chatId,
businessConnectionId,
title: msg.chat?.title ? String(msg.chat.title) : null,
});
// Dedupe on (threadId, providerMessageId). If duplicate, ignore.
try {
await prisma.omniMessage.create({
data: {
teamId,
contactId: contact.id,
threadId: thread.id,
direction: "IN",
channel: "TELEGRAM",
status: "DELIVERED",
text: text || "",
providerMessageId,
providerUpdateId: update.update_id != null ? String(update.update_id) : null,
rawJson: update,
occurredAt,
},
});
} catch (e: any) {
// Prisma unique constraint violation => duplicate delivery
if (e?.code !== "P2002") throw e;
}
return { ok: true };
});