diff --git a/PARR.Core/Services/Shortcodes/Handlers/RelationshipUnitShortcodeHandler.cs b/PARR.Core/Services/Shortcodes/Handlers/RelationshipUnitShortcodeHandler.cs index df4cd1a9..a98b5ab8 100644 --- a/PARR.Core/Services/Shortcodes/Handlers/RelationshipUnitShortcodeHandler.cs +++ b/PARR.Core/Services/Shortcodes/Handlers/RelationshipUnitShortcodeHandler.cs @@ -54,7 +54,6 @@ internal class RelationshipUnitShortcodeHandler : IShortcodeHandler private async Task GetRelValueAsync(TemplateForShortcode template, string fieldName, string caller, CancellationToken ct) { - // Оркестратор гарантирует наличие данных согласно Requirements if (template.UnitsInTemplate.Count == 0) { logger.LogDebug("[{Caller}] %СВЯЗЬ:{Field}% пропущен: UnitsInTemplate пуст.", caller, fieldName); @@ -63,7 +62,6 @@ internal class RelationshipUnitShortcodeHandler : IShortcodeHandler var unitIds = template.UnitsInTemplate.Select(u => u.UnitId).Distinct().ToList(); - // Пакетный запрос вместо N+1 var allValues = await unitInValueRepo.Get() .AsNoTracking() .Include(uv => uv.Field) @@ -75,15 +73,15 @@ internal class RelationshipUnitShortcodeHandler : IShortcodeHandler .Select(uv => uv.Value!.Value) .ToListAsync(ct); - var distinctSorted = allValues.Distinct().OrderBy(v => v, StringComparer.OrdinalIgnoreCase).ToList(); - if (distinctSorted.Count == 0) return string.Empty; + if (allValues.Count == 0) return string.Empty; - if (distinctSorted.Count > 1) - { - logger.LogWarning("[{Caller}] %СВЯЗЬ:{Field}% нашёл {Count} значений. Используется первое: '{First}'", - caller, fieldName, distinctSorted.Count, distinctSorted[0]); - } + var mostPopular = allValues + .GroupBy(v => v, StringComparer.OrdinalIgnoreCase) + .Select(g => new { Value = g.Key, Count = g.Count() }) + .OrderByDescending(x => x.Count) + .ThenBy(x => x.Value, StringComparer.OrdinalIgnoreCase) + .FirstOrDefault(); - return distinctSorted[0]!; + return mostPopular?.Value ?? string.Empty; } } \ No newline at end of file