// session.js import { PrismaClient } from '@prisma/client' const prisma = new PrismaClient() /** * Получить запись ChatState для пары (userId, externalBotId). * @param {string} userId * @param {string} externalBotId * @returns {Promise} */ export async function getSessionState(userId, externalBotId) { return prisma.chatState.findUnique({ where: { userId_externalBotId: { userId, externalBotId } } }) } /** * Узнать, какой внутренний бот сейчас держит сессию. * @param {string} userId * @param {string} externalBotId * @returns {Promise} — возвращает botId или null */ export async function getLockingBot(userId, externalBotId) { const state = await getSessionState(userId, externalBotId) return state ? state.lockedByBot : null } /** * Захватить внимание пользователя этим внутренним ботом. * Запишет в lockedByBot = botId. * @param {string} userId * @param {string} externalBotId * @param {string} botId — id внутреннего Bot */ export async function lockSessionToBot(userId, externalBotId, botId) { await prisma.chatState.upsert({ where: { userId_externalBotId: { userId, externalBotId } }, update: { lockedByBot: botId, updatedAt: new Date() }, create: { userId, externalBotId, stateJson: {}, lockedByBot: botId } }) } /** * Освободить сессию у пользователя для данного внешнего бота. * Запишет lockedByBot = null. * @param {string} userId * @param {string} externalBotId */ export async function unlockSession(userId, externalBotId) { await prisma.chatState.updateMany({ where: { userId, externalBotId, // только если была блокировка lockedByBot: { not: null } }, data: { lockedByBot: null } }) } /** * Проверить, захватил ли сессию конкретный внутренний бот. * @param {string} userId * @param {string} externalBotId * @param {string} botId * @returns {Promise} */ export async function isSessionLockedByBot(userId, externalBotId, botId) { const state = await getSessionState(userId, externalBotId) return !!state && state.lockedByBot === botId }