Backoffice stage 2: chats (support + concierge, files)

- ChatThread per client/provider and channel; messages get files, internal notes,
  source (bot/mini app) and delivery errors; reply templates. Migration moves old
  concierge messages into threads.
- Routing: subscribers write to the concierge, others to support; /support and
  /concierge in the client bot; staff can take, transfer, close and move threads.
- Telegram: photos/documents from clients and providers, replies with the channel
  header, files sent from storage, notifications only to the assignee or the
  channel's staff, "Reply" into a specific thread.
- New admin: /chats with list, conversation, notes, files, templates, client panel;
  "Message" button on the client card; dashboard counts threads awaiting reply.
- Client mini app: in-app chat screen sharing the same conversation.
- Old admin keeps working on the same data (notes hidden there).
- Tests for routing, notes, assign/close/move, lists, recipients; separate test DB
  via TEST_DB_NAME; dev:chats-demo script.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
zabudko-ruandClaude Opus 5.5 committed 2026-10-21 01:50:37 +04:00
1 parent d452824c62
commit 23ffb2bf1d
46 files changed
+4176 -144

No files matched your search

+114 -4
View File
@@ -1,16 +1,24 @@
import cookie from '@fastify/cookie';
import cors from '@fastify/cors';
import multipart from '@fastify/multipart';
import multipart, { type MultipartFile } from '@fastify/multipart';
import * as Sentry from '@sentry/node';
import { fastifyTRPCPlugin, type FastifyTRPCPluginOptions } from '@trpc/server/adapters/fastify';
import { getFlow } from '@barev/core';
import { DomainError, proIdentity, setChecklistItem } from '@barev/services';
import Fastify from 'fastify';
import { DomainError, getClientByTelegramId, proIdentity, receiveMessage, setChecklistItem, staffSend } from '@barev/services';
import { getFile, putFile } from '@barev/services/storage';
import { TelegramSender } from '@barev/services/telegram';
import Fastify, { type FastifyReply, type FastifyRequest } from 'fastify';
import { ADMIN_COOKIE, findSession } from './auth/admin.ts';
import { validateInitData } from './auth/telegram.ts';
import { env } from './env.ts';
import { ctx as svc, db, ensureBucket, putObject } from './infra.ts';
import { appRouter, type AppRouter } from './router.ts';
import { createContext } from './trpc.ts';
import { channelsFor } from './routers/backoffice/chats.ts';
import { createContext, type StaffRole } from './trpc.ts';
/** Скачивание файлов, присланных ботам, — по их токенам */
const clientBotFiles = new TelegramSender(env.CLIENT_BOT_TOKEN, 'client-bot');
const proBotFiles = new TelegramSender(env.PRO_BOT_TOKEN, 'pro-bot');
if (env.SENTRY_DSN) Sentry.init({ dsn: env.SENTRY_DSN, environment: env.NODE_ENV });
@@ -82,6 +90,108 @@ app.post('/files/pro/checklist-photo', async (req, reply) => {
return { fileId: file.id };
});
// ───── файлы в чатах ─────
/** Что можно прислать в чат: картинки, PDF, офисные документы, текст, архив */
const CHAT_TYPES = /^(image\/(jpeg|png|webp|gif|heic)|application\/pdf|application\/msword|application\/vnd\.openxmlformats-officedocument\.[\w.]+|application\/vnd\.ms-excel|text\/plain|application\/zip)$/;
/** Сотрудник новой админки по cookie-сессии и каналы, которые ему доступны */
async function staffFromCookie(req: FastifyRequest) {
const session = await findSession(db, req.cookies[ADMIN_COOKIE]);
if (!session?.verified || session.adminUser.roles.length === 0) return null;
const roles = session.adminUser.roles as StaffRole[];
return { admin: session.adminUser, channels: channelsFor(roles, roles.includes('SUPERADMIN')) };
}
function multipartField(part: MultipartFile, name: string) {
const f = part.fields[name];
return f && !Array.isArray(f) && f.type === 'field' ? String(f.value) : undefined;
}
/** Имя файла как пришло, но без путей и управляющих символов */
const safeName = (name: string | undefined) => (name ?? 'file').replace(/[\\/\u0000-\u001f]/g, '_').slice(-120) || 'file';
/** Команда отправляет файл в диалог (или во внутреннюю заметку) */
app.post<{ Params: { threadId: string } }>('/files/bo/chat/:threadId', async (req, reply) => {
const staff = await staffFromCookie(req);
if (!staff) return reply.code(401).send({ error: 'ADMIN_LOGIN_REQUIRED' });
const thread = await db.chatThread.findUnique({ where: { id: req.params.threadId } });
if (!thread) return reply.code(404).send({ error: 'NOT_FOUND' });
if (!staff.channels.includes(thread.channel)) return reply.code(403).send({ error: 'ROLE_FORBIDDEN' });
const part = await req.file();
if (!part) return reply.code(400).send({ error: 'NO_FILE' });
if (!CHAT_TYPES.test(part.mimetype)) return reply.code(400).send({ error: 'BAD_FILE_TYPE' });
const body = await part.toBuffer();
const fileName = safeName(part.filename);
const fileKey = await putFile(`chats/${thread.id}`, body, part.mimetype, fileName);
try {
const m = await staffSend(svc, {
threadId: thread.id,
adminUserId: staff.admin.id,
text: multipartField(part, 'text') ?? '',
internal: multipartField(part, 'internal') === 'true',
file: { fileKey, fileName, mime: part.mimetype, size: body.length },
});
await db.auditLog.create({ data: { adminUserId: staff.admin.id, action: 'bo.chats.sendFile', entity: 'chats', entityId: thread.id, data: { fileName, size: body.length } } });
return { id: m.id };
} catch (e) {
if (e instanceof DomainError) return reply.code(400).send({ error: e.code });
throw e;
}
});
/** Отдать файл сообщения: из нашего хранилища или из Telegram (бот скачивает по file_id) */
async function sendChatFile(reply: FastifyReply, m: { fileKey: string | null; tgFileId: string | null; tgBot: string | null; mime: string | null; fileName: string | null }) {
reply.header('cache-control', 'private, max-age=3600');
reply.header('content-type', m.mime ?? 'application/octet-stream');
reply.header('content-disposition', `inline; filename*=UTF-8''${encodeURIComponent(m.fileName ?? 'file')}`);
reply.header('x-content-type-options', 'nosniff');
if (m.fileKey) return reply.send(await getFile(m.fileKey));
if (m.tgFileId) {
const res = await (m.tgBot === 'pro' ? proBotFiles : clientBotFiles).download(m.tgFileId);
if (!res?.body) return reply.code(404).send({ error: 'FILE_UNAVAILABLE' });
return reply.send(Buffer.from(await res.arrayBuffer()));
}
return reply.code(404).send({ error: 'NOT_FOUND' });
}
app.get<{ Params: { messageId: string } }>('/files/bo/chat-file/:messageId', async (req, reply) => {
const staff = await staffFromCookie(req);
if (!staff) return reply.code(401).send({ error: 'ADMIN_LOGIN_REQUIRED' });
const m = await db.conciergeMessage.findUnique({ where: { id: req.params.messageId }, include: { thread: { select: { channel: true } } } });
if (!m?.thread || !staff.channels.includes(m.thread.channel)) return reply.code(404).send({ error: 'NOT_FOUND' });
return sendChatFile(reply, m);
});
/** Мини-апп клиента: клиент видит только файлы своей переписки (без заметок команды) */
function clientFromInit(req: FastifyRequest) {
const auth = req.headers.authorization?.startsWith('tma ') ? req.headers.authorization.slice(4) : undefined;
const init = validateInitData(auth, env.clientBotToken, env.TG_INIT_DATA_MAX_AGE);
return init.ok ? getClientByTelegramId(db, BigInt(init.user.id)) : Promise.resolve(null);
}
app.get<{ Params: { messageId: string } }>('/files/client/chat-file/:messageId', async (req, reply) => {
const client = await clientFromInit(req);
if (!client) return reply.code(401).send({ error: 'UNAUTHORIZED' });
const m = await db.conciergeMessage.findUnique({ where: { id: req.params.messageId } });
if (!m || m.clientId !== client.id || m.internal) return reply.code(404).send({ error: 'NOT_FOUND' });
return sendChatFile(reply, m);
});
app.post('/files/client/chat', async (req, reply) => {
const client = await clientFromInit(req);
if (!client) return reply.code(401).send({ error: 'UNAUTHORIZED' });
if (!client.consentAt) return reply.code(412).send({ error: 'CONSENT_REQUIRED' });
const part = await req.file();
if (!part) return reply.code(400).send({ error: 'NO_FILE' });
if (!CHAT_TYPES.test(part.mimetype)) return reply.code(400).send({ error: 'BAD_FILE_TYPE' });
const body = await part.toBuffer();
const fileName = safeName(part.filename);
const fileKey = await putFile(`chats/client-${client.id}`, body, part.mimetype, fileName);
const res = await receiveMessage(svc, { clientId: client.id }, { text: multipartField(part, 'text') ?? '', source: 'MINIAPP', file: { fileKey, fileName, mime: part.mimetype, size: body.length } });
return { id: res?.message.id ?? null };
});
/** Ошибки из Mini App и админки (sendBeacon) — только в лог, без хранения */
app.post('/client-log', { bodyLimit: 4096 }, async (req, reply) => {
const b = (typeof req.body === 'object' && req.body) || {};