| | | 1 | | namespace Services.StockSyncServices; |
| | | 2 | | |
| | | 3 | | public sealed class MatchResult<T> where T : class |
| | | 4 | | { |
| | | 5 | | public T Item { get; init; } = null!; |
| | | 6 | | public bool ManufacturerMatched { get; init; } |
| | | 7 | | } |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Сопоставление артикула заказа со строкой WarehouseStock (exact → prefix). |
| | | 11 | | /// </summary> |
| | | 12 | | public static class WarehouseStockLookupMatcher |
| | | 13 | | { |
| | | 14 | | public static string Normalize(string? s) => |
| | 62 | 15 | | string.IsNullOrEmpty(s) ? "" : |
| | 62 | 16 | | new string(s.Where(char.IsLetterOrDigit).ToArray()).ToUpperInvariant(); |
| | | 17 | | |
| | | 18 | | public static MatchResult<T>? FindMatch<T>( |
| | | 19 | | IEnumerable<T> candidates, |
| | | 20 | | string normalizedArticle, |
| | | 21 | | string normalizedManufacturer, |
| | | 22 | | Func<T, string?> getArticle, |
| | | 23 | | Func<T, string?> getManufacturer) where T : class |
| | | 24 | | { |
| | 16 | 25 | | var list = candidates.ToList(); |
| | 16 | 26 | | if (list.Count == 0 || string.IsNullOrEmpty(normalizedArticle)) |
| | 2 | 27 | | return null; |
| | | 28 | | |
| | | 29 | | bool ManufacturerMatches(T item) => |
| | | 30 | | string.IsNullOrEmpty(normalizedManufacturer) || |
| | | 31 | | Normalize(getManufacturer(item)) == normalizedManufacturer; |
| | | 32 | | |
| | 14 | 33 | | var scoped = list.Where(ManufacturerMatches).ToList(); |
| | 14 | 34 | | var manufacturerMatched = scoped.Count > 0; |
| | 14 | 35 | | if (scoped.Count == 0) |
| | 2 | 36 | | scoped = list; |
| | 14 | 37 | | if (scoped.Count == 0) |
| | 0 | 38 | | return null; |
| | | 39 | | |
| | 29 | 40 | | var exact = scoped.FirstOrDefault(x => Normalize(getArticle(x)) == normalizedArticle); |
| | 14 | 41 | | if (exact != null) |
| | 4 | 42 | | return new MatchResult<T> { Item = exact, ManufacturerMatched = manufacturerMatched }; |
| | | 43 | | |
| | 10 | 44 | | var prefixMatches = scoped |
| | 11 | 45 | | .Select(x => (Item: x, Norm: Normalize(getArticle(x)))) |
| | 11 | 46 | | .Where(t => t.Norm.StartsWith(normalizedArticle, StringComparison.Ordinal) || |
| | 11 | 47 | | normalizedArticle.StartsWith(t.Norm, StringComparison.Ordinal)) |
| | 11 | 48 | | .OrderBy(t => t.Norm.StartsWith(normalizedArticle, StringComparison.Ordinal) ? 0 : 1) |
| | 11 | 49 | | .ThenBy(t => Math.Abs(t.Norm.Length - normalizedArticle.Length)) |
| | 11 | 50 | | .ThenBy(t => t.Norm.Length) |
| | 11 | 51 | | .Select(t => t.Item) |
| | 10 | 52 | | .ToList(); |
| | | 53 | | |
| | 10 | 54 | | if (prefixMatches.Count == 1) |
| | 9 | 55 | | return new MatchResult<T> { Item = prefixMatches[0], ManufacturerMatched = manufacturerMatched }; |
| | | 56 | | |
| | 1 | 57 | | return null; |
| | | 58 | | } |
| | | 59 | | } |