# 📁 Структура проекта
Подробное описание организации кода в 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
```csharp
namespace ChatBot.Services
namespace ChatBot.Models.Configuration
namespace ChatBot.Data.Repositories
```
Структура namespace соответствует структуре папок.
### Классы
```csharp
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 пакеты
### Основные
```xml
```
### Логирование
```xml
```
### Validation
```xml
```
## 🧪 Тестовый проект
### Структура
```
ChatBot.Tests/
├── Common/ # Тесты констант
├── Configuration/ # Тесты валидаторов
├── Data/ # Тесты репозиториев и DbContext
├── Integration/ # Интеграционные тесты
├── Models/ # Тесты моделей
├── Services/ # Тесты сервисов
└── Telegram/ # Тесты Telegram функций
```
### Naming Convention
```csharp
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/
└── [Промежуточные файлы]
```
## 📚 См. также
- [Сервисы](./services.md)
- [Архитектура](../architecture/overview.md)
- [Разработка команд](./telegram-integration.md)