| | | 1 | | using Microsoft.EntityFrameworkCore; |
| | | 2 | | using MySqlConnector; |
| | | 3 | | using OzonDomains.Models; |
| | | 4 | | using OzonRepositories.Context; |
| | | 5 | | |
| | | 6 | | namespace OzonRepositories.Data; |
| | | 7 | | |
| | | 8 | | public class EtProducerRepository : IRepository<EtProducer> |
| | | 9 | | { |
| | 0 | 10 | | private sealed record ProducerPrefixRow(int Id, int RealId, string Prefix, string? MarketPrefix); |
| | | 11 | | |
| | | 12 | | private sealed class ProducerPrefixCacheEntry |
| | | 13 | | { |
| | 0 | 14 | | public List<ProducerPrefixRow> Rows { get; init; } = new(); |
| | 0 | 15 | | public DateTime LoadedAtUtc { get; init; } |
| | | 16 | | } |
| | | 17 | | |
| | 0 | 18 | | private static readonly object ProducerCacheLock = new(); |
| | | 19 | | private static ProducerPrefixCacheEntry? _producerCache; |
| | 0 | 20 | | private static readonly TimeSpan ProducerCacheTtl = TimeSpan.FromMinutes(30); |
| | | 21 | | |
| | | 22 | | ApplicationDbContext _context; |
| | | 23 | | |
| | 34 | 24 | | public EtProducerRepository(ApplicationDbContext context) |
| | | 25 | | { |
| | 34 | 26 | | _context = context; |
| | 34 | 27 | | } |
| | | 28 | | |
| | | 29 | | public async Task<int> Add(EtProducer value) |
| | | 30 | | { |
| | 0 | 31 | | await _context.EtProducers.AddAsync(value); |
| | 0 | 32 | | return await _context.SaveChangesAsync(); |
| | 0 | 33 | | } |
| | | 34 | | |
| | | 35 | | public async Task<int> Delete(EtProducer value) |
| | | 36 | | { |
| | 0 | 37 | | _context.EtProducers.Remove(value); |
| | 0 | 38 | | return await _context.SaveChangesAsync(); |
| | 0 | 39 | | } |
| | | 40 | | |
| | | 41 | | public async Task<List<EtProducer>> Get() |
| | | 42 | | { |
| | 0 | 43 | | return await _context.EtProducers.AsNoTracking().ToListAsync(); |
| | 0 | 44 | | } |
| | | 45 | | |
| | | 46 | | public IQueryable<EtProducer> GetByRealId(int? realId) |
| | | 47 | | { |
| | 0 | 48 | | return _context.EtProducers.AsNoTracking().Where(e => e.RealId == realId); |
| | | 49 | | } |
| | | 50 | | |
| | | 51 | | public IQueryable<EtProducer> GetQueryable() |
| | | 52 | | { |
| | 17 | 53 | | return _context.EtProducers.AsNoTracking().AsQueryable(); |
| | | 54 | | } |
| | | 55 | | |
| | | 56 | | public async Task<EtProducer?> GetAsync(int id) |
| | | 57 | | { |
| | 0 | 58 | | return await _context.EtProducers |
| | 0 | 59 | | .AsNoTracking() |
| | 0 | 60 | | .FirstOrDefaultAsync(e => e.Id == id); |
| | 0 | 61 | | } |
| | | 62 | | |
| | | 63 | | public EtProducer? Get(int id) |
| | | 64 | | { |
| | 0 | 65 | | return _context.EtProducers |
| | 0 | 66 | | .AsNoTracking() |
| | 0 | 67 | | .FirstOrDefault(e => e.Id == id); |
| | | 68 | | } |
| | | 69 | | |
| | | 70 | | |
| | | 71 | | public async Task<EtProducer?> GetAsync(EtProducer value) |
| | | 72 | | { |
| | 0 | 73 | | return await _context.EtProducers.AsNoTracking() |
| | 0 | 74 | | .FirstOrDefaultAsync(e => e.MarketPrefix == value.MarketPrefix); |
| | 0 | 75 | | } |
| | | 76 | | |
| | | 77 | | public async Task<EtProducer?> GetRealIdAsyncByCode(string marketPrefix) |
| | | 78 | | { |
| | 0 | 79 | | return await _context.EtProducers |
| | 0 | 80 | | .AsNoTracking() |
| | 0 | 81 | | .Where(r => r.MarketPrefix == marketPrefix || r.Prefix == marketPrefix) |
| | 0 | 82 | | .OrderBy(r => r.Id) |
| | 0 | 83 | | .FirstOrDefaultAsync(); |
| | 0 | 84 | | } |
| | | 85 | | |
| | | 86 | | /// <summary> |
| | | 87 | | /// Все производители с данным префиксом: один MarketPrefix бывает общим у разных брендов |
| | | 88 | | /// (HND — и Honda, и Hyundai). |
| | | 89 | | /// </summary> |
| | | 90 | | public async Task<List<EtProducer>> GetAllByCodeAsync(string marketPrefix) |
| | | 91 | | { |
| | 2 | 92 | | return await _context.EtProducers |
| | 2 | 93 | | .AsNoTracking() |
| | 2 | 94 | | .Where(r => r.MarketPrefix == marketPrefix || r.Prefix == marketPrefix) |
| | 2 | 95 | | .OrderBy(r => r.Id) |
| | 2 | 96 | | .ToListAsync(); |
| | 2 | 97 | | } |
| | | 98 | | |
| | | 99 | | |
| | | 100 | | public async Task<EtProducer?> GetRealIdAsyncByName(string name) |
| | | 101 | | { |
| | 0 | 102 | | if (string.IsNullOrEmpty(name)) |
| | 0 | 103 | | return null; |
| | | 104 | | |
| | | 105 | | // Получаем все и фильтруем в памяти |
| | 0 | 106 | | var allProducers = await _context.EtProducers |
| | 0 | 107 | | .Where(p => p.Name != null) |
| | 0 | 108 | | .AsNoTracking() |
| | 0 | 109 | | .ToListAsync(); |
| | | 110 | | |
| | 0 | 111 | | return allProducers.FirstOrDefault(p => |
| | 0 | 112 | | p.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); |
| | 0 | 113 | | } |
| | | 114 | | |
| | | 115 | | public async Task<int> Update(EtProducer value) |
| | | 116 | | { |
| | 0 | 117 | | _context.EtProducers.Attach(value); |
| | 0 | 118 | | _context.Entry(value).State = EntityState.Modified; |
| | | 119 | | |
| | 0 | 120 | | _context.Entry(value).Property(x => x.Name).IsModified = true; |
| | 0 | 121 | | _context.Entry(value).Property(x => x.MarketPrefix).IsModified = true; |
| | | 122 | | |
| | 0 | 123 | | return await _context.SaveChangesAsync(); |
| | 0 | 124 | | } |
| | | 125 | | |
| | | 126 | | /// <summary>Все непустые MarketPrefix из кэша EtProducers (cached).</summary> |
| | | 127 | | public async Task<HashSet<string>> GetAllMarketPrefixesAsync() |
| | | 128 | | { |
| | 0 | 129 | | var rows = await LoadProducerPrefixRowsAsync(); |
| | 0 | 130 | | return rows |
| | 0 | 131 | | .Where(r => !string.IsNullOrWhiteSpace(r.MarketPrefix)) |
| | 0 | 132 | | .Select(r => r.MarketPrefix!) |
| | 0 | 133 | | .ToHashSet(StringComparer.OrdinalIgnoreCase); |
| | 0 | 134 | | } |
| | | 135 | | |
| | | 136 | | public async Task<Dictionary<string, string?>> GetMarketPrefixesByNamesAsync(List<string> names) |
| | | 137 | | { |
| | 0 | 138 | | if (names == null || names.Count == 0) |
| | 0 | 139 | | return new Dictionary<string, string?>(); |
| | | 140 | | |
| | | 141 | | List<ProducerPrefixRow> allProducers; |
| | | 142 | | try |
| | | 143 | | { |
| | 0 | 144 | | allProducers = await LoadProducerPrefixRowsAsync(); |
| | 0 | 145 | | } |
| | 0 | 146 | | catch |
| | | 147 | | { |
| | 0 | 148 | | return names.Distinct().ToDictionary(n => n, _ => (string?)null); |
| | | 149 | | } |
| | | 150 | | |
| | 0 | 151 | | var producersByNormalizedPrefix = allProducers |
| | 0 | 152 | | .ToLookup(p => p.Prefix.Replace(" ", "").ToLower()); |
| | | 153 | | |
| | 0 | 154 | | var manufacturerRows = await LoadManufacturerRowsAsync(); |
| | 0 | 155 | | var resolverProducers = allProducers |
| | 0 | 156 | | .Select(p => new EtProducerMarketPrefixResolver.ProducerRow(p.Id, p.RealId, p.Prefix, p.MarketPrefix)) |
| | 0 | 157 | | .ToList(); |
| | | 158 | | |
| | 0 | 159 | | var result = new Dictionary<string, string?>(); |
| | | 160 | | |
| | 0 | 161 | | foreach (var originalName in names) |
| | | 162 | | { |
| | 0 | 163 | | if (string.IsNullOrEmpty(originalName)) |
| | | 164 | | { |
| | 0 | 165 | | result[originalName] = null; |
| | 0 | 166 | | continue; |
| | | 167 | | } |
| | | 168 | | |
| | 0 | 169 | | var normalized = originalName.Replace(" ", "").ToLower(); |
| | 0 | 170 | | var matches = producersByNormalizedPrefix[normalized].ToList(); |
| | | 171 | | |
| | 0 | 172 | | string? marketPrefix = null; |
| | | 173 | | |
| | 0 | 174 | | if (matches.Count > 0) |
| | | 175 | | { |
| | 0 | 176 | | var match = matches[0]; |
| | 0 | 177 | | marketPrefix = EtProducerMarketPrefixResolver.Resolve( |
| | 0 | 178 | | new EtProducerMarketPrefixResolver.ProducerRow(match.Id, match.RealId, match.Prefix, match.MarketPre |
| | 0 | 179 | | resolverProducers, |
| | 0 | 180 | | manufacturerRows); |
| | | 181 | | } |
| | | 182 | | |
| | 0 | 183 | | result[originalName] = marketPrefix; |
| | | 184 | | } |
| | | 185 | | |
| | 0 | 186 | | return result; |
| | 0 | 187 | | } |
| | | 188 | | |
| | | 189 | | /// <summary> |
| | | 190 | | /// Возвращает все алиасы производителя из той же группы <c>realId</c>, что и переданный Prefix. |
| | | 191 | | /// Нормализация намеренно убирает пробелы, кавычки и регистр: в ET встречаются варианты |
| | | 192 | | /// вроде LYNX, LYNXauto и "LYNX AUTO ". |
| | | 193 | | /// </summary> |
| | | 194 | | public async Task<IReadOnlyList<string>> GetAliasesByPrefixAsync(string prefix) |
| | | 195 | | { |
| | 0 | 196 | | if (string.IsNullOrWhiteSpace(prefix)) |
| | 0 | 197 | | return Array.Empty<string>(); |
| | | 198 | | |
| | 0 | 199 | | var normalizedPrefix = NormalizeProducerName(prefix); |
| | 0 | 200 | | if (normalizedPrefix.Length == 0) |
| | 0 | 201 | | return Array.Empty<string>(); |
| | | 202 | | |
| | 0 | 203 | | var rows = await LoadProducerPrefixRowsAsync(); |
| | 0 | 204 | | var match = rows.FirstOrDefault(row => |
| | 0 | 205 | | string.Equals(NormalizeProducerName(row.Prefix), normalizedPrefix, StringComparison.Ordinal)); |
| | 0 | 206 | | if (match is null) |
| | 0 | 207 | | return Array.Empty<string>(); |
| | | 208 | | |
| | 0 | 209 | | return rows |
| | 0 | 210 | | .Where(row => row.RealId == match.RealId) |
| | 0 | 211 | | .Select(row => row.Prefix) |
| | 0 | 212 | | .Where(value => !string.IsNullOrWhiteSpace(value)) |
| | 0 | 213 | | .Distinct(StringComparer.OrdinalIgnoreCase) |
| | 0 | 214 | | .ToArray(); |
| | 0 | 215 | | } |
| | | 216 | | |
| | | 217 | | private async Task<List<EtProducerMarketPrefixResolver.ManufacturerRow>> LoadManufacturerRowsAsync() |
| | | 218 | | { |
| | | 219 | | try |
| | | 220 | | { |
| | 0 | 221 | | return await _context.Manufacturers |
| | 0 | 222 | | .AsNoTracking() |
| | 0 | 223 | | .Where(m => m.Code != null && m.Code != "") |
| | 0 | 224 | | .Select(m => new EtProducerMarketPrefixResolver.ManufacturerRow( |
| | 0 | 225 | | m.EtProduserId, |
| | 0 | 226 | | m.Code!.Trim(), |
| | 0 | 227 | | m.Name)) |
| | 0 | 228 | | .ToListAsync(); |
| | | 229 | | } |
| | 0 | 230 | | catch |
| | | 231 | | { |
| | 0 | 232 | | return new List<EtProducerMarketPrefixResolver.ManufacturerRow>(); |
| | | 233 | | } |
| | 0 | 234 | | } |
| | | 235 | | |
| | | 236 | | private async Task<List<ProducerPrefixRow>> LoadProducerPrefixRowsAsync() |
| | | 237 | | { |
| | 0 | 238 | | lock (ProducerCacheLock) |
| | | 239 | | { |
| | 0 | 240 | | if (_producerCache != null && DateTime.UtcNow - _producerCache.LoadedAtUtc < ProducerCacheTtl) |
| | | 241 | | { |
| | 0 | 242 | | return _producerCache.Rows; |
| | | 243 | | } |
| | 0 | 244 | | } |
| | | 245 | | |
| | | 246 | | const int maxAttempts = 3; |
| | 0 | 247 | | Exception? last = null; |
| | 0 | 248 | | for (var attempt = 1; attempt <= maxAttempts; attempt++) |
| | | 249 | | { |
| | | 250 | | try |
| | | 251 | | { |
| | 0 | 252 | | var rows = await _context.EtProducers |
| | 0 | 253 | | .Where(p => p.Prefix != null) |
| | 0 | 254 | | .Select(p => new ProducerPrefixRow(p.Id, p.RealId, p.Prefix!, p.MarketPrefix)) |
| | 0 | 255 | | .AsNoTracking() |
| | 0 | 256 | | .ToListAsync(); |
| | | 257 | | |
| | 0 | 258 | | lock (ProducerCacheLock) |
| | | 259 | | { |
| | 0 | 260 | | _producerCache = new ProducerPrefixCacheEntry |
| | 0 | 261 | | { |
| | 0 | 262 | | Rows = rows, |
| | 0 | 263 | | LoadedAtUtc = DateTime.UtcNow |
| | 0 | 264 | | }; |
| | 0 | 265 | | } |
| | | 266 | | |
| | 0 | 267 | | return rows; |
| | | 268 | | } |
| | 0 | 269 | | catch (Exception ex) when (IsTransientDbError(ex) && attempt < maxAttempts) |
| | | 270 | | { |
| | 0 | 271 | | last = ex; |
| | 0 | 272 | | await Task.Delay(TimeSpan.FromMilliseconds(300 * attempt)); |
| | | 273 | | } |
| | | 274 | | } |
| | | 275 | | |
| | 0 | 276 | | lock (ProducerCacheLock) |
| | | 277 | | { |
| | 0 | 278 | | if (_producerCache?.Rows.Count > 0) |
| | | 279 | | { |
| | 0 | 280 | | return _producerCache.Rows; |
| | | 281 | | } |
| | 0 | 282 | | } |
| | | 283 | | |
| | 0 | 284 | | throw last ?? new InvalidOperationException("Не удалось загрузить EtProducers"); |
| | 0 | 285 | | } |
| | | 286 | | |
| | | 287 | | private static bool IsTransientDbError(Exception ex) |
| | | 288 | | { |
| | 0 | 289 | | for (var current = ex; current != null; current = current.InnerException) |
| | | 290 | | { |
| | 0 | 291 | | if (current is MySqlException or MySqlEndOfStreamException or TimeoutException or IOException) |
| | | 292 | | { |
| | 0 | 293 | | return true; |
| | | 294 | | } |
| | | 295 | | } |
| | | 296 | | |
| | 0 | 297 | | return false; |
| | | 298 | | } |
| | | 299 | | |
| | 0 | 300 | | private static string NormalizeProducerName(string value) => new(value |
| | 0 | 301 | | .Where(char.IsLetterOrDigit) |
| | 0 | 302 | | .Select(char.ToUpperInvariant) |
| | 0 | 303 | | .ToArray()); |
| | | 304 | | |
| | | 305 | | public async Task<int> SaveChanges() |
| | | 306 | | { |
| | 0 | 307 | | return await _context.SaveChangesAsync(); |
| | 0 | 308 | | } |
| | | 309 | | } |