| | | 1 | | using System.Diagnostics; |
| | | 2 | | using System.Security.Claims; |
| | | 3 | | using System.Text; |
| | | 4 | | using Microsoft.AspNetCore.Authorization; |
| | | 5 | | using Microsoft.AspNetCore.Http.Features; |
| | | 6 | | using Microsoft.AspNetCore.Mvc; |
| | | 7 | | using Newtonsoft.Json; |
| | | 8 | | using Newtonsoft.Json.Serialization; |
| | | 9 | | using OzonRepositories.Data; |
| | | 10 | | using Services.AiAssistant; |
| | | 11 | | using Services.ApiServices; |
| | | 12 | | using Services.ApiServices._1CApi; |
| | | 13 | | using Services.ApiServices.OpenRouterApi; |
| | | 14 | | using Services.ApiServices.OpenRouterApi.Models; |
| | | 15 | | using Services.DataServices; |
| | | 16 | | using Services.ParserServices.FielParsers; |
| | | 17 | | |
| | | 18 | | namespace OzonOrdersWeb.Areas.Studio2.Controllers; |
| | | 19 | | |
| | | 20 | | [Authorize(Roles = "User,Admin")] |
| | | 21 | | [Area("Studio2")] |
| | | 22 | | [Route("Studio2/AiAssistant")] |
| | | 23 | | public class AiAssistantController : Controller |
| | | 24 | | { |
| | | 25 | | private readonly AiOrderAnalysisService _analysisService; |
| | | 26 | | private readonly OpenRouterDataManager _dataManager; |
| | | 27 | | private readonly AiActionSuggestorAggregator _suggestorAggregator; |
| | | 28 | | private readonly AiOrderWriteService _writeService; |
| | | 29 | | private readonly SupplierDataServices _supplierDataServices; |
| | | 30 | | private readonly OneCDataManager _oneCDataManager; |
| | | 31 | | private readonly AiOrderSearchAgent _searchAgent; |
| | | 32 | | private readonly OrderRepository _orderRepository; |
| | | 33 | | private readonly ExcelExporter _excelExporter; |
| | | 34 | | private readonly ILogger<AiAssistantController> _logger; |
| | | 35 | | |
| | 0 | 36 | | public AiAssistantController( |
| | 0 | 37 | | AiOrderAnalysisService analysisService, |
| | 0 | 38 | | OpenRouterDataManager dataManager, |
| | 0 | 39 | | AiActionSuggestorAggregator suggestorAggregator, |
| | 0 | 40 | | AiOrderWriteService writeService, |
| | 0 | 41 | | SupplierDataServices supplierDataServices, |
| | 0 | 42 | | OneCDataManager oneCDataManager, |
| | 0 | 43 | | AiOrderSearchAgent searchAgent, |
| | 0 | 44 | | OrderRepository orderRepository, |
| | 0 | 45 | | ExcelExporter excelExporter, |
| | 0 | 46 | | ILogger<AiAssistantController> logger) |
| | | 47 | | { |
| | 0 | 48 | | _analysisService = analysisService; |
| | 0 | 49 | | _dataManager = dataManager; |
| | 0 | 50 | | _suggestorAggregator = suggestorAggregator; |
| | 0 | 51 | | _writeService = writeService; |
| | 0 | 52 | | _supplierDataServices = supplierDataServices; |
| | 0 | 53 | | _oneCDataManager = oneCDataManager; |
| | 0 | 54 | | _searchAgent = searchAgent; |
| | 0 | 55 | | _orderRepository = orderRepository; |
| | 0 | 56 | | _excelExporter = excelExporter; |
| | 0 | 57 | | _logger = logger; |
| | 0 | 58 | | } |
| | | 59 | | |
| | | 60 | | /// <summary>Список поставщиков для выпадающего списка в карточке proposal.</summary> |
| | | 61 | | [HttpGet("Suppliers")] |
| | | 62 | | public async Task<IActionResult> Suppliers() |
| | | 63 | | { |
| | 0 | 64 | | var list = await _supplierDataServices.GetSuppliers(); |
| | 0 | 65 | | return Ok(list |
| | 0 | 66 | | .Where(s => !string.IsNullOrWhiteSpace(s.Name)) |
| | 0 | 67 | | .OrderBy(s => s.Name) |
| | 0 | 68 | | .Select(s => new { id = s.Id, name = s.Name })); |
| | 0 | 69 | | } |
| | | 70 | | |
| | | 71 | | /// <summary>Список договоров 1С по ИНН поставщика (для ShippedBySupplier карточки).</summary> |
| | | 72 | | [HttpGet("Contracts")] |
| | | 73 | | public async Task<IActionResult> Contracts(string? supplierInn, CancellationToken ct) |
| | | 74 | | { |
| | 0 | 75 | | if (string.IsNullOrWhiteSpace(supplierInn)) |
| | 0 | 76 | | return Ok(Array.Empty<object>()); |
| | | 77 | | try |
| | | 78 | | { |
| | 0 | 79 | | var treaties = await _oneCDataManager.GetTreatyListAsync(supplierInn); |
| | 0 | 80 | | return Ok(treaties.Select(t => new { link = t.Link, name = t.Name, partner = t.Partner })); |
| | | 81 | | } |
| | 0 | 82 | | catch (Exception ex) |
| | | 83 | | { |
| | 0 | 84 | | _logger.LogWarning(ex, "AI Contracts: failed to load treaties for INN={Inn}", supplierInn); |
| | 0 | 85 | | return Ok(Array.Empty<object>()); |
| | | 86 | | } |
| | 0 | 87 | | } |
| | | 88 | | |
| | | 89 | | [HttpGet("")] |
| | 0 | 90 | | public IActionResult Index() => View(); |
| | | 91 | | |
| | | 92 | | [HttpPost("Prepare")] |
| | | 93 | | public async Task<IActionResult> Prepare([FromBody] AiChatRequest request, CancellationToken ct = default) |
| | | 94 | | { |
| | 0 | 95 | | if (string.IsNullOrWhiteSpace(request.Message)) |
| | 0 | 96 | | return BadRequest(new { error = "Сообщение не может быть пустым." }); |
| | | 97 | | |
| | 0 | 98 | | var intent = await _analysisService.DetectIntentAsync(request.Message, request.Context, ct); |
| | 0 | 99 | | return Ok(new AiChatPrepareResponse |
| | 0 | 100 | | { |
| | 0 | 101 | | Steps = AiThinkingStepsBuilder.BuildPending(intent, request.Message), |
| | 0 | 102 | | ToolLabel = AiOrderAnalysisService.GetToolLabel(intent?.ToolName), |
| | 0 | 103 | | ToolName = intent?.ToolName, |
| | 0 | 104 | | Phase = "intent" |
| | 0 | 105 | | }); |
| | 0 | 106 | | } |
| | | 107 | | |
| | | 108 | | /// <summary> |
| | | 109 | | /// Устанавливает cookie FilterData и открывает главную таблицу заказов с нужным фильтром. |
| | | 110 | | /// </summary> |
| | 0 | 111 | | private static readonly HashSet<string> FieldPresets = new(StringComparer.Ordinal) |
| | 0 | 112 | | { |
| | 0 | 113 | | "orders_today", |
| | 0 | 114 | | "cancelled_orders_today", |
| | 0 | 115 | | "unprofitable_orders", |
| | 0 | 116 | | "no_supplier_orders" |
| | 0 | 117 | | }; |
| | | 118 | | |
| | | 119 | | [HttpGet("OpenOrders")] |
| | | 120 | | public async Task<IActionResult> OpenOrders( |
| | | 121 | | string? preset, |
| | | 122 | | string? ids, |
| | | 123 | | CancellationToken ct = default) |
| | | 124 | | { |
| | 0 | 125 | | var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); |
| | | 126 | | OServices.FiltersServices.FilterModels.OrderFilterModel filter; |
| | | 127 | | |
| | 0 | 128 | | if (!string.IsNullOrWhiteSpace(preset) && FieldPresets.Contains(preset)) |
| | | 129 | | { |
| | 0 | 130 | | filter = AiOrdersFilterBuilder.FromPreset(preset); |
| | | 131 | | } |
| | 0 | 132 | | else if (!string.IsNullOrWhiteSpace(ids)) |
| | | 133 | | { |
| | 0 | 134 | | var rawIds = ids.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) |
| | 0 | 135 | | .Select(s => int.TryParse(s, out var id) ? id : 0) |
| | 0 | 136 | | .Where(id => id > 0); |
| | | 137 | | |
| | 0 | 138 | | var summaries = await _analysisService.GetSummariesByIdsAsync(rawIds, userId, ct); |
| | 0 | 139 | | filter = AiOrdersFilterBuilder.FromOrders(summaries); |
| | | 140 | | } |
| | 0 | 141 | | else if (!string.IsNullOrWhiteSpace(preset)) |
| | | 142 | | { |
| | 0 | 143 | | filter = AiOrdersFilterBuilder.FromPreset(preset); |
| | | 144 | | } |
| | | 145 | | else |
| | | 146 | | { |
| | 0 | 147 | | filter = new OServices.FiltersServices.FilterModels.OrderFilterModel { GroupByShipment = true }; |
| | | 148 | | } |
| | | 149 | | |
| | 0 | 150 | | Response.Cookies.Append("FilterData", Newtonsoft.Json.JsonConvert.SerializeObject(filter)); |
| | 0 | 151 | | return Redirect("/Orders/Index?page=1"); |
| | 0 | 152 | | } |
| | | 153 | | |
| | | 154 | | /// <summary>JSON фильтра для главной таблицы (без редиректа через OpenOrders).</summary> |
| | | 155 | | [HttpGet("OrderFilter")] |
| | | 156 | | public async Task<IActionResult> OrderFilter( |
| | | 157 | | string? preset, |
| | | 158 | | string? ids, |
| | | 159 | | CancellationToken ct = default) |
| | | 160 | | { |
| | 0 | 161 | | var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); |
| | | 162 | | OServices.FiltersServices.FilterModels.OrderFilterModel filter; |
| | | 163 | | |
| | 0 | 164 | | if (!string.IsNullOrWhiteSpace(preset) && FieldPresets.Contains(preset)) |
| | 0 | 165 | | filter = AiOrdersFilterBuilder.FromPreset(preset); |
| | 0 | 166 | | else if (!string.IsNullOrWhiteSpace(ids)) |
| | | 167 | | { |
| | 0 | 168 | | var rawIds = ids.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) |
| | 0 | 169 | | .Select(s => int.TryParse(s, out var id) ? id : 0) |
| | 0 | 170 | | .Where(id => id > 0); |
| | 0 | 171 | | var summaries = await _analysisService.GetSummariesByIdsAsync(rawIds, userId, ct); |
| | 0 | 172 | | filter = AiOrdersFilterBuilder.FromOrders(summaries); |
| | | 173 | | } |
| | 0 | 174 | | else if (!string.IsNullOrWhiteSpace(preset)) |
| | 0 | 175 | | filter = AiOrdersFilterBuilder.FromPreset(preset); |
| | | 176 | | else |
| | 0 | 177 | | return BadRequest(new { error = "Укажите ids или preset." }); |
| | | 178 | | |
| | 0 | 179 | | return Content(Newtonsoft.Json.JsonConvert.SerializeObject(filter), "application/json"); |
| | 0 | 180 | | } |
| | | 181 | | |
| | | 182 | | [HttpPost("Chat")] |
| | | 183 | | public async Task<IActionResult> Chat( |
| | | 184 | | [FromBody] AiChatRequest request, |
| | | 185 | | CancellationToken ct = default) |
| | | 186 | | { |
| | 0 | 187 | | if (string.IsNullOrWhiteSpace(request.Message)) |
| | 0 | 188 | | return BadRequest(new AiChatResponse |
| | 0 | 189 | | { |
| | 0 | 190 | | Success = false, |
| | 0 | 191 | | Error = "Сообщение не может быть пустым." |
| | 0 | 192 | | }); |
| | | 193 | | |
| | | 194 | | try |
| | | 195 | | { |
| | 0 | 196 | | var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); |
| | 0 | 197 | | var intent = await _analysisService.DetectIntentAsync(request.Message, request.Context, ct); |
| | | 198 | | |
| | 0 | 199 | | var dataContext = string.Empty; |
| | 0 | 200 | | var tableData = new List<OrderSummaryDto>(); |
| | 0 | 201 | | var enrichment = (AiChatEnrichmentDto?)null; |
| | 0 | 202 | | var dbRan = false; |
| | 0 | 203 | | string? dbQuery = null; |
| | | 204 | | |
| | 0 | 205 | | AiActionProposalDto? actionProposal = null; |
| | 0 | 206 | | List<AiActionProposalDto>? actionProposals = null; |
| | 0 | 207 | | bool isSearchResult = false; |
| | 0 | 208 | | string? appliedFiltersDescription = null; |
| | 0 | 209 | | int? totalFound = null; |
| | 0 | 210 | | if (intent != null) |
| | | 211 | | { |
| | 0 | 212 | | var queryResult = await _analysisService.RunQueryAsync(intent, userId, ct, request.Message); |
| | 0 | 213 | | dataContext = queryResult.Context; |
| | 0 | 214 | | tableData = queryResult.Orders; |
| | 0 | 215 | | enrichment = queryResult.Enrichment; |
| | 0 | 216 | | dbRan = true; |
| | 0 | 217 | | dbQuery = queryResult.SqlQuery; |
| | 0 | 218 | | actionProposal = queryResult.ActionProposal; |
| | 0 | 219 | | actionProposals = queryResult.ActionProposals; |
| | 0 | 220 | | isSearchResult = queryResult.IsSearchResult; |
| | 0 | 221 | | appliedFiltersDescription = queryResult.AppliedFiltersDescription; |
| | 0 | 222 | | totalFound = queryResult.TotalFound; |
| | 0 | 223 | | _logger.LogInformation("AI intent: {Tool}, rows: {Count}", intent.ToolName, tableData.Count); |
| | | 224 | | } |
| | | 225 | | |
| | 0 | 226 | | var answer = await _dataManager.AskWithContextAsync( |
| | 0 | 227 | | request.Message, |
| | 0 | 228 | | dataContext, |
| | 0 | 229 | | request.History, |
| | 0 | 230 | | request.Model, |
| | 0 | 231 | | ct); |
| | | 232 | | |
| | 0 | 233 | | var steps = AiThinkingStepsBuilder.BuildCompleted( |
| | 0 | 234 | | intent, |
| | 0 | 235 | | request.Message, |
| | 0 | 236 | | tableData.Count, |
| | 0 | 237 | | dbRan); |
| | | 238 | | |
| | 0 | 239 | | var actionLinks = _suggestorAggregator.Suggest(new AiSuggestionContext |
| | 0 | 240 | | { |
| | 0 | 241 | | ToolName = intent?.ToolName, |
| | 0 | 242 | | Article = intent?.Article, |
| | 0 | 243 | | ManufacturerPrefix = intent?.ManufacturerPrefix, |
| | 0 | 244 | | OrderId = intent?.OrderId, |
| | 0 | 245 | | Orders = tableData, |
| | 0 | 246 | | ConversationContext = request.Context |
| | 0 | 247 | | }); |
| | 0 | 248 | | var newContext = AiOrderAnalysisService.UpdateContext(request.Context, intent, tableData, actionProposal); |
| | 0 | 249 | | var palette = AiStatusPaletteBuilder.FromOrders(tableData); |
| | | 250 | | |
| | 0 | 251 | | return Ok(new AiChatResponse |
| | 0 | 252 | | { |
| | 0 | 253 | | Success = true, |
| | 0 | 254 | | Answer = answer, |
| | 0 | 255 | | ToolUsed = intent?.ToolName, |
| | 0 | 256 | | ToolLabel = AiOrderAnalysisService.GetToolLabel(intent?.ToolName), |
| | 0 | 257 | | Data = tableData.Count > 0 ? tableData : null, |
| | 0 | 258 | | Steps = steps, |
| | 0 | 259 | | ActionLinks = actionLinks.Count > 0 ? actionLinks : null, |
| | 0 | 260 | | Context = newContext, |
| | 0 | 261 | | StatusPalette = palette.Count > 0 ? palette : null, |
| | 0 | 262 | | Enrichment = enrichment, |
| | 0 | 263 | | DbQuery = dbQuery |
| | 0 | 264 | | }); |
| | | 265 | | } |
| | 0 | 266 | | catch (OperationCanceledException) |
| | | 267 | | { |
| | 0 | 268 | | return StatusCode(499, new AiChatResponse { Success = false, Error = "Запрос отменён." }); |
| | | 269 | | } |
| | 0 | 270 | | catch (Exception ex) |
| | | 271 | | { |
| | 0 | 272 | | _logger.LogError(ex, "AI assistant chat error"); |
| | 0 | 273 | | return StatusCode(500, new AiChatResponse |
| | 0 | 274 | | { |
| | 0 | 275 | | Success = false, |
| | 0 | 276 | | Error = "Произошла ошибка при обращении к AI. Попробуйте ещё раз." |
| | 0 | 277 | | }); |
| | | 278 | | } |
| | 0 | 279 | | } |
| | | 280 | | |
| | | 281 | | /// <summary> |
| | | 282 | | /// Выполняет write-действие агента (редактирование полей или создание транзакции). |
| | | 283 | | /// Вызывается фронтендом после подтверждения пользователем. |
| | | 284 | | /// </summary> |
| | | 285 | | [HttpPost("ExecuteAction")] |
| | | 286 | | public async Task<IActionResult> ExecuteAction( |
| | | 287 | | [FromBody] AiExecuteActionRequest request, |
| | | 288 | | CancellationToken ct = default) |
| | | 289 | | { |
| | 0 | 290 | | var userName = User.Identity?.Name ?? "AI Agent"; |
| | | 291 | | AiExecuteActionResponse result; |
| | | 292 | | |
| | | 293 | | try |
| | | 294 | | { |
| | 0 | 295 | | result = request.Kind switch |
| | 0 | 296 | | { |
| | 0 | 297 | | "edit_order" when request.EditDto != null => |
| | 0 | 298 | | await _writeService.ExecuteEditAsync(request.OrderId, request.EditDto, userName, ct, request.Model), |
| | 0 | 299 | | |
| | 0 | 300 | | "create_transaction" when request.TransactionDto != null => |
| | 0 | 301 | | await _writeService.ExecuteTransactionAsync(request.OrderId, request.TransactionDto, userName, ct, r |
| | 0 | 302 | | |
| | 0 | 303 | | _ => new AiExecuteActionResponse |
| | 0 | 304 | | { |
| | 0 | 305 | | Success = false, |
| | 0 | 306 | | Message = "Неизвестный тип действия или отсутствуют данные." |
| | 0 | 307 | | } |
| | 0 | 308 | | }; |
| | 0 | 309 | | } |
| | 0 | 310 | | catch (Exception ex) |
| | | 311 | | { |
| | 0 | 312 | | _logger.LogError(ex, "ExecuteAction failed: kind={Kind}, orderId={OrderId}", request.Kind, request.OrderId); |
| | 0 | 313 | | result = new AiExecuteActionResponse |
| | 0 | 314 | | { |
| | 0 | 315 | | Success = false, |
| | 0 | 316 | | Message = $"Ошибка: {ex.Message}" |
| | 0 | 317 | | }; |
| | 0 | 318 | | } |
| | | 319 | | |
| | | 320 | | // Генерируем AI-резюме на основе результата |
| | 0 | 321 | | if (result.Success) |
| | | 322 | | { |
| | | 323 | | try |
| | | 324 | | { |
| | 0 | 325 | | var summaryContext = BuildSummaryContext(request, result); |
| | 0 | 326 | | result.AiSummary = await _dataManager.AskWithContextAsync( |
| | 0 | 327 | | summaryContext, |
| | 0 | 328 | | string.Empty, |
| | 0 | 329 | | history: null, |
| | 0 | 330 | | modelOverride: request.Model, |
| | 0 | 331 | | ct); |
| | 0 | 332 | | } |
| | 0 | 333 | | catch (OperationCanceledException) |
| | | 334 | | { |
| | | 335 | | // Action already executed, user cancelled summary generation |
| | 0 | 336 | | } |
| | 0 | 337 | | catch (Exception ex) |
| | | 338 | | { |
| | 0 | 339 | | _logger.LogWarning(ex, "ExecuteAction: AI summary generation failed (non-blocking)"); |
| | 0 | 340 | | } |
| | | 341 | | } |
| | | 342 | | |
| | 0 | 343 | | return Ok(result); |
| | 0 | 344 | | } |
| | | 345 | | |
| | | 346 | | /// <summary> |
| | | 347 | | /// Формирует промпт для AI-резюме выполненного действия. |
| | | 348 | | /// </summary> |
| | | 349 | | private static string BuildSummaryContext(AiExecuteActionRequest request, AiExecuteActionResponse result) |
| | | 350 | | { |
| | 0 | 351 | | var parts = new System.Text.StringBuilder(); |
| | 0 | 352 | | parts.AppendLine("Ты — AI-агент Стас. Агент только что выполнил действие в системе управления заказами."); |
| | 0 | 353 | | parts.AppendLine("Напиши краткое резюме (2–3 предложения) от первого лица, обращаясь к пользователю."); |
| | 0 | 354 | | parts.AppendLine("Используй конкретные детали: номер заказа, тип транзакции, изменённые поля, новый статус."); |
| | 0 | 355 | | parts.AppendLine("Не используй markdown-заголовки и не повторяй технические детали дословно."); |
| | 0 | 356 | | parts.AppendLine(); |
| | 0 | 357 | | parts.Append("Тип действия: "); |
| | 0 | 358 | | parts.AppendLine(request.Kind == "create_transaction" ? "транзакция" : "редактирование заказа"); |
| | | 359 | | |
| | 0 | 360 | | var shipment = result.ShipmentNumber ?? $"#{request.OrderId}"; |
| | 0 | 361 | | parts.Append("Заказ: "); parts.AppendLine(shipment); |
| | | 362 | | |
| | 0 | 363 | | if (request.TransactionDto != null) |
| | | 364 | | { |
| | 0 | 365 | | parts.Append("Транзакция: "); parts.AppendLine(request.TransactionDto.TransactionLabel); |
| | 0 | 366 | | if (!string.IsNullOrWhiteSpace(request.TransactionDto.SupplierName)) |
| | | 367 | | { |
| | 0 | 368 | | parts.Append("Поставщик установлен: "); parts.AppendLine(request.TransactionDto.SupplierName); |
| | | 369 | | } |
| | 0 | 370 | | if (request.TransactionDto.PurchasePrice is > 0) |
| | | 371 | | { |
| | 0 | 372 | | parts.Append("Цена закупки: "); parts.Append(request.TransactionDto.PurchasePrice); parts.AppendLine(" ₽ |
| | | 373 | | } |
| | | 374 | | } |
| | 0 | 375 | | if (request.EditDto != null) |
| | | 376 | | { |
| | 0 | 377 | | if (!string.IsNullOrWhiteSpace(request.EditDto.AppStatusName)) |
| | 0 | 378 | | { parts.Append("Новый статус: "); parts.AppendLine(request.EditDto.AppStatusName); } |
| | 0 | 379 | | if (!string.IsNullOrWhiteSpace(request.EditDto.SupplierName)) |
| | 0 | 380 | | { parts.Append("Поставщик: "); parts.AppendLine(request.EditDto.SupplierName); } |
| | 0 | 381 | | if (request.EditDto.PurchasePrice.HasValue) |
| | 0 | 382 | | { parts.Append("Цена закупки: "); parts.Append(request.EditDto.PurchasePrice); parts.AppendLine(" ₽"); } |
| | | 383 | | } |
| | 0 | 384 | | if (!string.IsNullOrWhiteSpace(result.NewStatus)) |
| | 0 | 385 | | { parts.Append("Итоговый статус заказа: "); parts.AppendLine(result.NewStatus); } |
| | 0 | 386 | | if (!string.IsNullOrWhiteSpace(result.OneCResult)) |
| | 0 | 387 | | { parts.Append("Результат проводки в 1С: "); parts.AppendLine(result.OneCResult); } |
| | | 388 | | |
| | 0 | 389 | | parts.AppendLine(); |
| | 0 | 390 | | parts.Append("Системное сообщение о результате: "); parts.AppendLine(result.Message); |
| | 0 | 391 | | parts.AppendLine(); |
| | 0 | 392 | | parts.AppendLine("Напиши резюме:"); |
| | 0 | 393 | | return parts.ToString(); |
| | | 394 | | } |
| | | 395 | | |
| | | 396 | | /// <summary> |
| | | 397 | | /// SSE-стриминг ответа AI. События: meta → token → done. |
| | | 398 | | /// Клиент читает через fetch + ReadableStream. |
| | | 399 | | /// </summary> |
| | | 400 | | [HttpPost("Stream")] |
| | | 401 | | public async Task StreamChat([FromBody] AiChatRequest request, CancellationToken ct) |
| | | 402 | | { |
| | 0 | 403 | | if (string.IsNullOrWhiteSpace(request.Message)) |
| | | 404 | | { |
| | 0 | 405 | | Response.StatusCode = 400; |
| | 0 | 406 | | return; |
| | | 407 | | } |
| | | 408 | | |
| | 0 | 409 | | Response.ContentType = "text/event-stream; charset=utf-8"; |
| | 0 | 410 | | Response.Headers["Cache-Control"] = "no-cache, no-store"; |
| | 0 | 411 | | Response.Headers["X-Accel-Buffering"] = "no"; |
| | 0 | 412 | | HttpContext.Features.Get<IHttpResponseBodyFeature>()?.DisableBuffering(); |
| | | 413 | | |
| | 0 | 414 | | var serSettings = new JsonSerializerSettings |
| | 0 | 415 | | { |
| | 0 | 416 | | NullValueHandling = NullValueHandling.Ignore, |
| | 0 | 417 | | ContractResolver = new CamelCasePropertyNamesContractResolver() |
| | 0 | 418 | | }; |
| | | 419 | | |
| | | 420 | | async Task EmitAsync(string eventName, object data) |
| | | 421 | | { |
| | 0 | 422 | | var json = JsonConvert.SerializeObject(data, serSettings); |
| | 0 | 423 | | var line = $"event: {eventName}\ndata: {json}\n\n"; |
| | 0 | 424 | | await Response.WriteAsync(line, Encoding.UTF8, ct); |
| | 0 | 425 | | await Response.Body.FlushAsync(ct); |
| | 0 | 426 | | } |
| | | 427 | | |
| | 0 | 428 | | var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); |
| | 0 | 429 | | var intent = await _analysisService.DetectIntentAsync(request.Message, request.Context, ct); |
| | | 430 | | |
| | | 431 | | // Параллельные агенты order_detail пишут progress из пула потоков — сериализуем SSE. |
| | 0 | 432 | | var progressGate = new SemaphoreSlim(1, 1); |
| | | 433 | | async Task EmitProgressAsync(AiAgentProgressUpdate update) |
| | | 434 | | { |
| | 0 | 435 | | await progressGate.WaitAsync(ct); |
| | | 436 | | try |
| | | 437 | | { |
| | 0 | 438 | | if (!string.IsNullOrWhiteSpace(update.LogLine)) |
| | 0 | 439 | | await EmitAsync("log", new SseLogEvent { Line = update.LogLine, Icon = update.LogIcon }); |
| | 0 | 440 | | await EmitAsync("meta", new SseMetaEvent |
| | 0 | 441 | | { |
| | 0 | 442 | | ToolName = intent?.ToolName, |
| | 0 | 443 | | ToolLabel = AiOrderAnalysisService.GetToolLabel(intent?.ToolName), |
| | 0 | 444 | | Steps = update.Steps, |
| | 0 | 445 | | Phase = update.Phase, |
| | 0 | 446 | | FromCache = update.FromCache, |
| | 0 | 447 | | }); |
| | 0 | 448 | | } |
| | | 449 | | finally |
| | | 450 | | { |
| | 0 | 451 | | progressGate.Release(); |
| | | 452 | | } |
| | 0 | 453 | | } |
| | | 454 | | |
| | | 455 | | // ── 1. Мета: intent + ожидаемые шаги ───────────────────────────────── |
| | 0 | 456 | | var pendingSteps = AiThinkingStepsBuilder.BuildPending(intent, request.Message); |
| | 0 | 457 | | await EmitAsync("meta", new SseMetaEvent |
| | 0 | 458 | | { |
| | 0 | 459 | | ToolName = intent?.ToolName, |
| | 0 | 460 | | ToolLabel = AiOrderAnalysisService.GetToolLabel(intent?.ToolName), |
| | 0 | 461 | | Steps = pendingSteps, |
| | 0 | 462 | | Phase = "intent" |
| | 0 | 463 | | }); |
| | 0 | 464 | | await EmitAsync("log", new SseLogEvent |
| | 0 | 465 | | { |
| | 0 | 466 | | Line = intent != null |
| | 0 | 467 | | ? $"✓ Распознано: {AiOrderAnalysisService.GetToolLabel(intent.ToolName)}" |
| | 0 | 468 | | : "⟳ Анализ запроса…", |
| | 0 | 469 | | Icon = intent != null ? "check" : "spin" |
| | 0 | 470 | | }); |
| | | 471 | | |
| | | 472 | | // ── 2. Запрос к БД ──────────────────────────────────────────────────── |
| | 0 | 473 | | var dataContext = string.Empty; |
| | 0 | 474 | | var tableData = new List<OrderSummaryDto>(); |
| | 0 | 475 | | AiChatEnrichmentDto? enrichment = null; |
| | 0 | 476 | | AiActionProposalDto? actionProposal = null; |
| | 0 | 477 | | List<AiActionProposalDto>? actionProposals = null; |
| | 0 | 478 | | bool isSearchResult = false; |
| | 0 | 479 | | string? appliedFiltersDescription = null; |
| | 0 | 480 | | int? totalFound = null; |
| | 0 | 481 | | string? dbQuery = null; |
| | 0 | 482 | | long dbMs = 0; |
| | 0 | 483 | | AiOrderFilterCriteria? appliedCriteria = null; |
| | 0 | 484 | | string? suggestionQuery = null; |
| | 0 | 485 | | AiOrderFilterCriteria? relaxedSuggestion = null; |
| | 0 | 486 | | int? relaxedCount = null; |
| | 0 | 487 | | string? filterSpecification = null; |
| | | 488 | | |
| | 0 | 489 | | if (intent != null) |
| | | 490 | | { |
| | 0 | 491 | | var sw = Stopwatch.StartNew(); |
| | | 492 | | try |
| | | 493 | | { |
| | 0 | 494 | | var queryResult = await _analysisService.RunQueryAsync( |
| | 0 | 495 | | intent, userId, ct, request.Message, |
| | 0 | 496 | | onProgress: EmitProgressAsync); |
| | 0 | 497 | | sw.Stop(); |
| | 0 | 498 | | dbMs = sw.ElapsedMilliseconds; |
| | 0 | 499 | | dataContext = queryResult.Context; |
| | 0 | 500 | | tableData = queryResult.Orders; |
| | 0 | 501 | | enrichment = queryResult.Enrichment; |
| | 0 | 502 | | dbQuery = queryResult.SqlQuery; |
| | 0 | 503 | | actionProposal = queryResult.ActionProposal; |
| | 0 | 504 | | actionProposals = queryResult.ActionProposals; |
| | 0 | 505 | | isSearchResult = queryResult.IsSearchResult; |
| | 0 | 506 | | appliedFiltersDescription = queryResult.AppliedFiltersDescription; |
| | 0 | 507 | | totalFound = queryResult.TotalFound; |
| | 0 | 508 | | appliedCriteria = queryResult.AppliedCriteria; |
| | 0 | 509 | | suggestionQuery = queryResult.SuggestionQuery; |
| | 0 | 510 | | relaxedSuggestion = queryResult.RelaxedSuggestion; |
| | 0 | 511 | | relaxedCount = queryResult.RelaxedCount; |
| | 0 | 512 | | filterSpecification = queryResult.FilterSpecification; |
| | | 513 | | |
| | 0 | 514 | | if (queryResult.OzonLiveUi != null) |
| | | 515 | | { |
| | 0 | 516 | | enrichment ??= new AiChatEnrichmentDto(); |
| | 0 | 517 | | enrichment.OzonLive = queryResult.OzonLiveUi; |
| | | 518 | | } |
| | 0 | 519 | | } |
| | 0 | 520 | | catch (OperationCanceledException) { return; } |
| | 0 | 521 | | catch (Exception ex) |
| | | 522 | | { |
| | 0 | 523 | | sw.Stop(); |
| | 0 | 524 | | dbMs = sw.ElapsedMilliseconds; |
| | 0 | 525 | | _logger.LogError(ex, "Stream: DB query failed"); |
| | 0 | 526 | | } |
| | 0 | 527 | | sw.Stop(); |
| | | 528 | | |
| | 0 | 529 | | var completedSteps = AiThinkingStepsBuilder.BuildCompleted(intent, request.Message, tableData.Count, true); |
| | 0 | 530 | | await EmitAsync("meta", new SseMetaEvent |
| | 0 | 531 | | { |
| | 0 | 532 | | RowCount = tableData.Count, |
| | 0 | 533 | | DbMs = dbMs, |
| | 0 | 534 | | Sql = dbQuery, |
| | 0 | 535 | | Steps = completedSteps, |
| | 0 | 536 | | Phase = "db" |
| | 0 | 537 | | }); |
| | 0 | 538 | | await EmitAsync("log", new SseLogEvent |
| | 0 | 539 | | { |
| | 0 | 540 | | Line = tableData.Count > 0 |
| | 0 | 541 | | ? $"✓ Данные: {tableData.Count} записей ({dbMs} мс)" |
| | 0 | 542 | | : $"✓ Запрос к БД ({dbMs} мс)", |
| | 0 | 543 | | Icon = "check" |
| | 0 | 544 | | }); |
| | | 545 | | |
| | 0 | 546 | | } |
| | | 547 | | |
| | | 548 | | // ── 3. Стриминг токенов AI ──────────────────────────────────────────── |
| | | 549 | | { |
| | 0 | 550 | | var aiSteps = AiThinkingStepsBuilder.BuildCompleted( |
| | 0 | 551 | | intent, request.Message, tableData.Count, intent != null); |
| | 0 | 552 | | var aiStepIndex = intent?.ToolName == "orders_filter" ? 3 : 2; |
| | 0 | 553 | | if (aiSteps.Count > aiStepIndex) |
| | | 554 | | { |
| | 0 | 555 | | aiSteps[0].Status = "done"; |
| | 0 | 556 | | if (intent?.ToolName == "orders_filter" && aiSteps.Count > 1) |
| | | 557 | | { |
| | 0 | 558 | | aiSteps[1].Status = "done"; |
| | 0 | 559 | | aiSteps[1].Done = true; |
| | | 560 | | } |
| | 0 | 561 | | aiSteps[aiStepIndex - 1].Status = "done"; |
| | 0 | 562 | | aiSteps[aiStepIndex].Status = "active"; |
| | 0 | 563 | | aiSteps[aiStepIndex].Done = false; |
| | 0 | 564 | | aiSteps[aiStepIndex].Label = "Формирую ответ…"; |
| | | 565 | | } |
| | 0 | 566 | | await EmitAsync("meta", new SseMetaEvent { Steps = aiSteps, Phase = "ai" }); |
| | 0 | 567 | | await EmitAsync("log", new SseLogEvent { Line = "⟳ Генерация ответа…", Icon = "spin" }); |
| | | 568 | | } |
| | | 569 | | |
| | 0 | 570 | | UsageInfo? tokenUsage = null; |
| | 0 | 571 | | var answerBuilder = new StringBuilder(); |
| | 0 | 572 | | var cannedAnswer = AiAssistantResponseGuard.TryBuildCannedAnswer( |
| | 0 | 573 | | intent?.ToolName, dataContext, actionProposal, tableData); |
| | | 574 | | |
| | 0 | 575 | | if (!string.IsNullOrWhiteSpace(cannedAnswer)) |
| | | 576 | | { |
| | 0 | 577 | | answerBuilder.Append(cannedAnswer); |
| | 0 | 578 | | await EmitAsync("token", new { t = cannedAnswer }); |
| | | 579 | | } |
| | | 580 | | else |
| | | 581 | | { |
| | | 582 | | try |
| | | 583 | | { |
| | 0 | 584 | | await foreach (var token in _dataManager.StreamWithContextAsync( |
| | 0 | 585 | | request.Message, dataContext, request.History, request.Model, |
| | 0 | 586 | | onUsage: u => tokenUsage = u, |
| | 0 | 587 | | ct)) |
| | | 588 | | { |
| | 0 | 589 | | answerBuilder.Append(token); |
| | 0 | 590 | | await EmitAsync("token", new { t = token }); |
| | | 591 | | } |
| | 0 | 592 | | } |
| | 0 | 593 | | catch (OperationCanceledException) { return; } |
| | 0 | 594 | | catch (Exception ex) |
| | | 595 | | { |
| | 0 | 596 | | _logger.LogError(ex, "Stream: AI token stream failed"); |
| | 0 | 597 | | await EmitAsync("error", new { message = "Ошибка при получении ответа от AI." }); |
| | 0 | 598 | | return; |
| | | 599 | | } |
| | | 600 | | } |
| | | 601 | | |
| | | 602 | | // ── 4. Финальные данные: enrichment, action links ───────────────────── |
| | 0 | 603 | | var actionLinks = _suggestorAggregator.Suggest(new AiSuggestionContext |
| | 0 | 604 | | { |
| | 0 | 605 | | ToolName = intent?.ToolName, |
| | 0 | 606 | | Article = intent?.Article, |
| | 0 | 607 | | ManufacturerPrefix = intent?.ManufacturerPrefix, |
| | 0 | 608 | | OrderId = intent?.OrderId, |
| | 0 | 609 | | Orders = tableData, |
| | 0 | 610 | | ConversationContext = request.Context |
| | 0 | 611 | | }); |
| | | 612 | | // Выбираем первый proposal для UpdateContext (для pending transaction) |
| | 0 | 613 | | var primaryProposal = actionProposal ?? actionProposals?.FirstOrDefault(); |
| | 0 | 614 | | var newContext = AiOrderAnalysisService.UpdateContext(request.Context, intent, tableData, primaryProposal); |
| | 0 | 615 | | var palette = AiStatusPaletteBuilder.FromOrders(tableData); |
| | | 616 | | |
| | 0 | 617 | | List<string>? suggestedFollowUps = null; |
| | 0 | 618 | | if (intent != null) |
| | | 619 | | { |
| | 0 | 620 | | suggestedFollowUps = await _dataManager.GenerateFollowUpChipsAsync( |
| | 0 | 621 | | request.Message, |
| | 0 | 622 | | intent.ToolName, |
| | 0 | 623 | | dataContext, |
| | 0 | 624 | | totalFound, |
| | 0 | 625 | | ct); |
| | 0 | 626 | | if (suggestedFollowUps.Count == 0) |
| | 0 | 627 | | suggestedFollowUps = null; |
| | | 628 | | } |
| | | 629 | | |
| | 0 | 630 | | var fullAnswer = answerBuilder.ToString(); |
| | 0 | 631 | | var usedFallback = false; |
| | 0 | 632 | | if (string.IsNullOrWhiteSpace(cannedAnswer) |
| | 0 | 633 | | && AiAssistantResponseGuard.ShouldReplaceLlmAnswer(fullAnswer, tableData, intent?.ToolName) |
| | 0 | 634 | | && (!string.IsNullOrWhiteSpace(dataContext) || tableData.Count > 0)) |
| | | 635 | | { |
| | 0 | 636 | | fullAnswer = AiAssistantResponseGuard.BuildDataFallback(dataContext, tableData, intent?.ToolName); |
| | 0 | 637 | | usedFallback = true; |
| | | 638 | | } |
| | | 639 | | |
| | 0 | 640 | | await EmitAsync("done", new SseDoneEvent |
| | 0 | 641 | | { |
| | 0 | 642 | | AnswerText = usedFallback || !string.IsNullOrWhiteSpace(cannedAnswer) ? fullAnswer : null, |
| | 0 | 643 | | Enrichment = enrichment, |
| | 0 | 644 | | ActionLinks = actionLinks.Count > 0 ? actionLinks : null, |
| | 0 | 645 | | Data = tableData.Count > 0 ? tableData : null, |
| | 0 | 646 | | StatusPalette = palette.Count > 0 ? palette : null, |
| | 0 | 647 | | Context = newContext, |
| | 0 | 648 | | ActionProposal = actionProposal, |
| | 0 | 649 | | ActionProposals = actionProposals, |
| | 0 | 650 | | IsSearchResult = isSearchResult, |
| | 0 | 651 | | AppliedFiltersDescription = appliedFiltersDescription, |
| | 0 | 652 | | TotalFound = totalFound, |
| | 0 | 653 | | AppliedCriteria = appliedCriteria, |
| | 0 | 654 | | SuggestionQuery = suggestionQuery, |
| | 0 | 655 | | RelaxedSuggestion = relaxedSuggestion, |
| | 0 | 656 | | RelaxedCount = relaxedCount, |
| | 0 | 657 | | DbQuery = dbQuery, |
| | 0 | 658 | | FilterSpecification = filterSpecification, |
| | 0 | 659 | | ToolLabel = AiOrderAnalysisService.GetToolLabel(intent?.ToolName), |
| | 0 | 660 | | SuggestedFollowUps = suggestedFollowUps, |
| | 0 | 661 | | TokenUsage = tokenUsage == null ? null : new AiTokenUsageDto |
| | 0 | 662 | | { |
| | 0 | 663 | | PromptTokens = tokenUsage.PromptTokens, |
| | 0 | 664 | | CompletionTokens = tokenUsage.CompletionTokens, |
| | 0 | 665 | | TotalTokens = tokenUsage.TotalTokens, |
| | 0 | 666 | | }, |
| | 0 | 667 | | }); |
| | 0 | 668 | | } |
| | | 669 | | |
| | | 670 | | /// <summary>Устанавливает cookie FilterData по критериям поиска и возвращает URL таблицы заказов.</summary> |
| | | 671 | | [HttpPost("BuildOrdersFilterUrl")] |
| | | 672 | | public IActionResult BuildOrdersFilterUrl([FromBody] AiOrderFilterCriteria? criteria) |
| | | 673 | | { |
| | 0 | 674 | | if (criteria == null) |
| | 0 | 675 | | return BadRequest(new { error = "criteria required" }); |
| | | 676 | | |
| | 0 | 677 | | var filter = AiFilterCriteriaMapper.ToOrderFilterModel(criteria); |
| | 0 | 678 | | var json = JsonConvert.SerializeObject(filter); |
| | 0 | 679 | | Response.Cookies.Append("FilterData", json, new CookieOptions |
| | 0 | 680 | | { |
| | 0 | 681 | | MaxAge = TimeSpan.FromMinutes(30), |
| | 0 | 682 | | Path = "/", |
| | 0 | 683 | | SameSite = SameSiteMode.Lax, |
| | 0 | 684 | | }); |
| | 0 | 685 | | return Ok(new { url = "/Orders/Index?page=1" }); |
| | | 686 | | } |
| | | 687 | | |
| | | 688 | | /// <summary>Экспортирует результаты AI-поиска в Excel-файл.</summary> |
| | | 689 | | [HttpPost("ExportSearchExcel")] |
| | | 690 | | public async Task<IActionResult> ExportSearchExcel( |
| | | 691 | | [FromBody] AiOrderFilterCriteria? criteria, |
| | | 692 | | CancellationToken ct = default) |
| | | 693 | | { |
| | 0 | 694 | | if (criteria == null) |
| | 0 | 695 | | return BadRequest(new { error = "criteria required" }); |
| | | 696 | | |
| | 0 | 697 | | var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); |
| | 0 | 698 | | var result = await _searchAgent.SearchAsync(criteria, userId, ct, maxResults: 5000); |
| | 0 | 699 | | var ids = result.Orders.Select(o => o.Id).ToList(); |
| | 0 | 700 | | if (ids.Count == 0) |
| | 0 | 701 | | return NotFound(new { error = "Заказы не найдены." }); |
| | | 702 | | |
| | 0 | 703 | | var orders = await _orderRepository.GetOrdersByIds(ids, criteria.IncludeArchived); |
| | 0 | 704 | | var bytes = _excelExporter.ExportToExcel(orders); |
| | | 705 | | |
| | 0 | 706 | | var filename = $"AI_поиск_{DateTime.Now:yyyyMMdd_HHmm}.xlsx"; |
| | 0 | 707 | | return File(bytes, |
| | 0 | 708 | | "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", |
| | 0 | 709 | | filename); |
| | 0 | 710 | | } |
| | | 711 | | |
| | | 712 | | } |