Files
ChatBot/docs/development/project-structure.md
Leonid Pershin e5e69470f8
All checks were successful
SonarQube / Build and analyze (push) Successful in 3m22s
add docs
2025-10-21 05:08:40 +03:00

10 KiB
Raw Blame History

📁 Структура проекта

Подробное описание организации кода в ChatBot.

🌳 Дерево проекта

ChatBot/
├── .gitea/
│   └── workflows/
│       └── build.yml              # CI/CD pipeline (SonarQube)
├── ChatBot/                       # Основной проект
│   ├── Common/
│   │   └── Constants/
│   │       ├── AIResponseConstants.cs
│   │       └── ChatTypes.cs
│   ├── Data/
│   │   ├── Interfaces/
│   │   │   └── IChatSessionRepository.cs
│   │   ├── Repositories/
│   │   │   └── ChatSessionRepository.cs
│   │   └── ChatBotDbContext.cs
│   ├── Migrations/
│   │   └── [EF Core миграции]
│   ├── Models/
│   │   ├── Configuration/
│   │   │   ├── Validators/
│   │   │   ├── AISettings.cs
│   │   │   ├── DatabaseSettings.cs
│   │   │   ├── OllamaSettings.cs
│   │   │   └── TelegramBotSettings.cs
│   │   ├── Dto/
│   │   │   └── ChatMessage.cs
│   │   ├── Entities/
│   │   │   ├── ChatMessageEntity.cs
│   │   │   └── ChatSessionEntity.cs
│   │   └── ChatSession.cs
│   ├── Prompts/
│   │   └── system-prompt.txt      # AI промпт
│   ├── Properties/
│   │   └── launchSettings.json
│   ├── Services/
│   │   ├── HealthChecks/
│   │   │   ├── OllamaHealthCheck.cs
│   │   │   └── TelegramBotHealthCheck.cs
│   │   ├── Interfaces/
│   │   │   ├── IAIService.cs
│   │   │   ├── IHistoryCompressionService.cs
│   │   │   ├── IOllamaClient.cs
│   │   │   ├── ISessionStorage.cs
│   │   │   └── ITelegramBotClientWrapper.cs
│   │   ├── Telegram/
│   │   │   ├── Commands/
│   │   │   │   ├── ClearCommand.cs
│   │   │   │   ├── CommandAttribute.cs
│   │   │   │   ├── CommandRegistry.cs
│   │   │   │   ├── HelpCommand.cs
│   │   │   │   ├── ReplyInfo.cs
│   │   │   │   ├── SettingsCommand.cs
│   │   │   │   ├── StartCommand.cs
│   │   │   │   ├── StatusCommand.cs
│   │   │   │   ├── TelegramCommandBase.cs
│   │   │   │   ├── TelegramCommandContext.cs
│   │   │   │   └── TelegramCommandProcessor.cs
│   │   │   ├── Interfaces/
│   │   │   │   ├── ITelegramBotService.cs
│   │   │   │   ├── ITelegramCommand.cs
│   │   │   │   ├── ITelegramCommandProcessor.cs
│   │   │   │   ├── ITelegramErrorHandler.cs
│   │   │   │   └── ITelegramMessageHandler.cs
│   │   │   └── Services/
│   │   │       ├── BotInfoService.cs
│   │   │       ├── TelegramBotService.cs
│   │   │       ├── TelegramErrorHandler.cs
│   │   │       ├── TelegramMessageHandler.cs
│   │   │       └── TelegramMessageSender.cs
│   │   ├── AIService.cs
│   │   ├── ChatService.cs
│   │   ├── DatabaseInitializationService.cs
│   │   ├── DatabaseSessionStorage.cs
│   │   ├── HistoryCompressionService.cs
│   │   ├── InMemorySessionStorage.cs
│   │   ├── ModelService.cs
│   │   ├── OllamaClientAdapter.cs
│   │   ├── SystemPromptService.cs
│   │   └── TelegramBotClientWrapper.cs
│   ├── appsettings.json
│   ├── appsettings.Development.json
│   ├── ChatBot.csproj
│   └── Program.cs
├── ChatBot.Tests/                 # Тестовый проект
│   ├── Common/
│   ├── Configuration/
│   ├── Data/
│   ├── Integration/
│   ├── Models/
│   ├── Program/
│   ├── Services/
│   ├── Telegram/
│   └── ChatBot.Tests.csproj
├── docs/                          # Документация
├── .gitignore
├── .gitattributes
├── ChatBot.sln
├── LICENSE.txt
└── README.md

📂 Основные папки

/Common

Общие константы и утилиты.

Constants/

  • AIResponseConstants.cs - Константы для AI ответов
    • EmptyResponseMarker = "{empty}"
    • DefaultErrorMessage
  • ChatTypes.cs - Типы чатов
    • Private, Group, Supergroup, Channel

/Data

Слой доступа к данным.

Interfaces/

  • IChatSessionRepository.cs - Интерфейс репозитория

Repositories/

  • ChatSessionRepository.cs - Реализация репозитория

Root:

  • ChatBotDbContext.cs - EF Core контекст

/Models

Модели данных и конфигурация.

Configuration/

  • Settings классы для конфигурации
  • Validators/ - FluentValidation валидаторы

Dto/

  • ChatMessage.cs - DTO для сообщений

Entities/

  • ChatSessionEntity.cs - Сущность сессии
  • ChatMessageEntity.cs - Сущность сообщения

Root:

  • ChatSession.cs - Доменная модель сессии

/Services

Бизнес-логика приложения.

HealthChecks/

  • OllamaHealthCheck.cs - Проверка Ollama
  • TelegramBotHealthCheck.cs - Проверка Telegram

Interfaces/

  • Интерфейсы всех сервисов

Telegram/

  • Commands/ - Реализация команд бота
  • Interfaces/ - Интерфейсы Telegram сервисов
  • Services/ - Реализация Telegram сервисов

Root Services:

  • AIService.cs - Работа с AI
  • ChatService.cs - Управление чатами
  • HistoryCompressionService.cs - Сжатие истории
  • DatabaseSessionStorage.cs - Хранение в БД
  • InMemorySessionStorage.cs - Хранение в памяти
  • И другие...

/Migrations

EF Core миграции базы данных.

/Prompts

AI промпты.

  • system-prompt.txt - Системный промпт для AI

🎯 Naming Conventions

Файлы

  • Classes: PascalCase.cs (например, ChatService.cs)
  • Interfaces: IPascalCase.cs (например, IAIService.cs)
  • Tests: ClassNameTests.cs

Namespace

namespace ChatBot.Services
namespace ChatBot.Models.Configuration
namespace ChatBot.Data.Repositories

Структура namespace соответствует структуре папок.

Классы

public class ChatService          // Service classes
public interface IAIService       // Interfaces (I prefix)
public class ChatSession          // Models
public class ChatSessionEntity    // Entities (Entity suffix)

🔍 Зависимости между слоями

Program.cs
    ↓
Services/
    ↓
Data/Repositories
    ↓
Data/ChatBotDbContext
    ↓
Models/Entities

Правила:

  • Services зависят от Interfaces
  • Repositories зависят от Entities
  • Models независимы
  • Presentation зависит от Services

📦 NuGet пакеты

Основные

<PackageReference Include="Telegram.Bot" Version="22.7.2" />
<PackageReference Include="OllamaSharp" Version="5.4.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.10" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />

Логирование

<PackageReference Include="Serilog" Version="4.3.0" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="9.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />

Validation

<PackageReference Include="FluentValidation" Version="12.0.0" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="12.0.0" />

🧪 Тестовый проект

Структура

ChatBot.Tests/
├── Common/              # Тесты констант
├── Configuration/       # Тесты валидаторов
├── Data/               # Тесты репозиториев и DbContext
├── Integration/        # Интеграционные тесты
├── Models/             # Тесты моделей
├── Services/           # Тесты сервисов
└── Telegram/           # Тесты Telegram функций

Naming Convention

public class ChatServiceTests
{
    [Fact]
    public void ProcessMessage_ShouldReturnResponse()
    
    [Theory]
    [InlineData(...)]
    public void Method_Scenario_ExpectedBehavior()
}

🔧 Configuration Files

appsettings.json

Основная конфигурация приложения.

appsettings.Development.json

Переопределения для Development режима.

.env

Локальные переменные окружения (не в git).

launchSettings.json

Настройки запуска для Visual Studio/Rider.

📝 Special Files

Program.cs

Точка входа приложения:

  • Конфигурация DI
  • Регистрация сервисов
  • Инициализация логирования

ChatBot.csproj

Project file:

  • Target Framework: net9.0
  • Package References
  • Build configurations

ChatBot.sln

Solution file для Visual Studio.

🚀 Build Output

bin/
├── Debug/
│   └── net9.0/
├── Release/
│   └── net9.0/
obj/
└── [Промежуточные файлы]

📚 См. также