| | | 1 | | using OzonDomains.Models; |
| | | 2 | | using OzonRepositories.Data; |
| | | 3 | | using Services.ApiServices.StudioApi; |
| | | 4 | | using Services.ApiServices.StudioApi.Models.Response; |
| | | 5 | | using System.Text.RegularExpressions; |
| | | 6 | | |
| | | 7 | | namespace Services.DataServices; |
| | | 8 | | |
| | | 9 | | public class EtProducerDataServices : IDataServices |
| | | 10 | | { |
| | | 11 | | private readonly EtProducerRepository _repository; |
| | | 12 | | private readonly InterpartsDataManager _interpartsDataManager; |
| | | 13 | | |
| | 32 | 14 | | public EtProducerDataServices(EtProducerRepository repository, |
| | 32 | 15 | | InterpartsDataManager interpartsDataManager) |
| | | 16 | | { |
| | 32 | 17 | | _repository = repository; |
| | 32 | 18 | | _interpartsDataManager = interpartsDataManager; |
| | 32 | 19 | | } |
| | | 20 | | |
| | | 21 | | public Task<int> AddEtProducer(EtProducer value) |
| | | 22 | | { |
| | 0 | 23 | | return _repository.Add(value); |
| | | 24 | | } |
| | | 25 | | |
| | | 26 | | public Task<int> DeleteEtProducer(EtProducer value) |
| | | 27 | | { |
| | 0 | 28 | | return _repository.Delete(value); |
| | | 29 | | } |
| | | 30 | | |
| | | 31 | | public async Task<List<EtProducer>> GetEtProducers() |
| | | 32 | | { |
| | 0 | 33 | | return await _repository.Get(); |
| | 0 | 34 | | } |
| | | 35 | | |
| | | 36 | | public List<EtProducer> GetEtProducersByRealId(int? realId) |
| | | 37 | | { |
| | 0 | 38 | | return _repository.GetByRealId(realId).ToList(); |
| | | 39 | | } |
| | | 40 | | |
| | | 41 | | public IQueryable<EtProducer> GetQueryableEtProducers() |
| | | 42 | | { |
| | 17 | 43 | | return _repository.GetQueryable(); |
| | | 44 | | } |
| | | 45 | | |
| | | 46 | | public async Task<EtProducer?> GetEtProducerAsync(int id) |
| | | 47 | | { |
| | 0 | 48 | | return await _repository.GetAsync(id); |
| | 0 | 49 | | } |
| | | 50 | | |
| | | 51 | | public EtProducer? GetEtProducer(int id) |
| | | 52 | | { |
| | 0 | 53 | | return _repository.Get(id); |
| | | 54 | | } |
| | | 55 | | |
| | | 56 | | public async Task<EtProducer?> GetEtProducerAsync(EtProducer value) |
| | | 57 | | { |
| | 0 | 58 | | return await _repository.GetAsync(value); |
| | 0 | 59 | | } |
| | | 60 | | |
| | | 61 | | public async Task<EtProducer?> GetRealIdAsyncByCode(string marketPrefix) |
| | | 62 | | { |
| | 0 | 63 | | return await _repository.GetRealIdAsyncByCode(marketPrefix); |
| | 0 | 64 | | } |
| | | 65 | | |
| | | 66 | | /// <summary> |
| | | 67 | | /// Производитель по префиксу из offer_id. Если префикс общий у нескольких брендов (HND — Honda и Hyundai), |
| | | 68 | | /// выбирается тот, чьё имя встречается в названии товара отдельным словом. |
| | | 69 | | /// Если бренд по названию определить нельзя, возвращается null: пустой производитель лучше чужого, |
| | | 70 | | /// из-за которого карточка в 1С не находится. |
| | | 71 | | /// </summary> |
| | | 72 | | public async Task<EtProducer?> GetRealIdAsyncByCode(string marketPrefix, string? productName) |
| | | 73 | | { |
| | 2 | 74 | | var candidates = await _repository.GetAllByCodeAsync(marketPrefix); |
| | 6 | 75 | | if (candidates.Select(c => c.RealId).Distinct().Count() <= 1) |
| | 0 | 76 | | return candidates.FirstOrDefault(); |
| | | 77 | | |
| | 2 | 78 | | if (string.IsNullOrWhiteSpace(productName)) |
| | 0 | 79 | | return null; |
| | | 80 | | |
| | 2 | 81 | | var name = productName.Trim(); |
| | 5 | 82 | | return candidates.FirstOrDefault(c => IsProducerNameInProductName(c.Name, name)); |
| | 2 | 83 | | } |
| | | 84 | | |
| | | 85 | | private static bool IsProducerNameInProductName(string? producerName, string productName) |
| | | 86 | | { |
| | 3 | 87 | | if (string.IsNullOrWhiteSpace(producerName)) return false; |
| | | 88 | | |
| | 3 | 89 | | var escapedName = Regex.Escape(producerName.Trim()); |
| | 3 | 90 | | return Regex.IsMatch(productName, $"(?<![\\p{{L}}\\p{{N}}]){escapedName}(?![\\p{{L}}\\p{{N}}])", |
| | 3 | 91 | | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); |
| | | 92 | | } |
| | | 93 | | |
| | | 94 | | public async Task<EtProducer?> GetRealIdAsyncByName(string name) |
| | | 95 | | { |
| | 0 | 96 | | return await _repository.GetRealIdAsyncByName(name); |
| | 0 | 97 | | } |
| | | 98 | | |
| | | 99 | | public async Task<int> UpdateEtProducer(EtProducer value) |
| | | 100 | | { |
| | 0 | 101 | | return await _repository.Update(value); |
| | 0 | 102 | | } |
| | | 103 | | |
| | | 104 | | /// <summary> |
| | | 105 | | /// Обновляет EtProducer из API по ID с условием Id eq RealId |
| | | 106 | | /// </summary> |
| | | 107 | | /// <param name="producerId">ID производителя для обновления</param> |
| | | 108 | | /// <returns>Обновленный EtProducer или null если не найден</returns> |
| | | 109 | | public async Task<EtProducer?> UpdateEtProducerFromApi(int producerId) |
| | | 110 | | { |
| | | 111 | | try |
| | | 112 | | { |
| | | 113 | | // Получаем данные из API |
| | 0 | 114 | | var apiProducer = await _interpartsDataManager.GetProducerByIdWithRealId(producerId); |
| | 0 | 115 | | if (apiProducer == null) |
| | | 116 | | { |
| | 0 | 117 | | return null; // Производитель не найден в API |
| | | 118 | | } |
| | | 119 | | |
| | | 120 | | // Ищем существующего производителя в базе |
| | 0 | 121 | | var existingProducer = await _repository.GetAsync(producerId); |
| | | 122 | | |
| | 0 | 123 | | if (existingProducer != null) |
| | | 124 | | { |
| | | 125 | | // Обновляем существующую запись |
| | 0 | 126 | | return await UpdateExistingProducer(existingProducer, apiProducer); |
| | | 127 | | } |
| | | 128 | | else |
| | | 129 | | { |
| | | 130 | | // Создаем новую запись |
| | 0 | 131 | | return await CreateNewProducer(apiProducer); |
| | | 132 | | } |
| | | 133 | | } |
| | 0 | 134 | | catch (Exception ex) |
| | | 135 | | { |
| | | 136 | | // Логируем ошибку |
| | 0 | 137 | | Console.WriteLine($"Ошибка при обновлении EtProducer из API: {ex.Message}"); |
| | 0 | 138 | | return null; |
| | | 139 | | } |
| | 0 | 140 | | } |
| | | 141 | | |
| | | 142 | | /// <summary> |
| | | 143 | | /// Обновляет существующего производителя данными из API |
| | | 144 | | /// </summary> |
| | | 145 | | private async Task<EtProducer?> UpdateExistingProducer(EtProducer existing, Producer apiData) |
| | | 146 | | { |
| | 0 | 147 | | existing.RealId = apiData.RealId; |
| | 0 | 148 | | existing.Prefix = apiData.Prefix ?? string.Empty; |
| | 0 | 149 | | existing.Name = apiData.Name ?? string.Empty; |
| | 0 | 150 | | existing.Address = apiData.Address ?? string.Empty; |
| | 0 | 151 | | existing.Www = apiData.Www ?? string.Empty; |
| | 0 | 152 | | existing.Rating = apiData.Rating; |
| | 0 | 153 | | existing.ExistName = apiData.ExistName ?? string.Empty; |
| | 0 | 154 | | existing.ExistId = apiData.ExistId; |
| | 0 | 155 | | existing.Domain = apiData.Domain ?? string.Empty; |
| | 0 | 156 | | existing.TecdocSupplierId = apiData.TecdocSupplierId; |
| | 0 | 157 | | existing.MarketPrefix = apiData.MarketPrefix ?? string.Empty; |
| | | 158 | | |
| | 0 | 159 | | await _repository.Update(existing); |
| | 0 | 160 | | await _repository.SaveChanges(); |
| | | 161 | | |
| | 0 | 162 | | return existing; |
| | 0 | 163 | | } |
| | | 164 | | |
| | | 165 | | /// <summary> |
| | | 166 | | /// Создает нового производителя из данных API |
| | | 167 | | /// </summary> |
| | | 168 | | private async Task<EtProducer?> CreateNewProducer(Producer apiData) |
| | | 169 | | { |
| | 0 | 170 | | var newProducer = new EtProducer |
| | 0 | 171 | | { |
| | 0 | 172 | | Id = apiData.Id, |
| | 0 | 173 | | RealId = apiData.RealId, |
| | 0 | 174 | | Prefix = apiData.Prefix ?? string.Empty, |
| | 0 | 175 | | Name = apiData.Name ?? string.Empty, |
| | 0 | 176 | | Address = apiData.Address ?? string.Empty, |
| | 0 | 177 | | Www = apiData.Www ?? string.Empty, |
| | 0 | 178 | | Rating = apiData.Rating, |
| | 0 | 179 | | ExistName = apiData.ExistName ?? string.Empty, |
| | 0 | 180 | | ExistId = apiData.ExistId, |
| | 0 | 181 | | Domain = apiData.Domain ?? string.Empty, |
| | 0 | 182 | | TecdocSupplierId = apiData.TecdocSupplierId, |
| | 0 | 183 | | MarketPrefix = apiData.MarketPrefix ?? string.Empty |
| | 0 | 184 | | }; |
| | | 185 | | |
| | 0 | 186 | | await _repository.Add(newProducer); |
| | 0 | 187 | | await _repository.SaveChanges(); |
| | | 188 | | |
| | 0 | 189 | | return newProducer; |
| | 0 | 190 | | } |
| | | 191 | | |
| | | 192 | | /// <summary> |
| | | 193 | | /// Пакетное обновление нескольких производителей из API |
| | | 194 | | /// </summary> |
| | | 195 | | /// <param name="producerIds">Список ID производителей для обновления</param> |
| | | 196 | | /// <returns>Список обновленных производителей</returns> |
| | | 197 | | public async Task<List<EtProducer>> UpdateMultipleEtProducersFromApi(List<int> producerIds) |
| | | 198 | | { |
| | 0 | 199 | | var results = new List<EtProducer>(); |
| | | 200 | | |
| | 0 | 201 | | foreach (var producerId in producerIds) |
| | | 202 | | { |
| | 0 | 203 | | var updatedProducer = await UpdateEtProducerFromApi(producerId); |
| | 0 | 204 | | if (updatedProducer != null) |
| | | 205 | | { |
| | 0 | 206 | | results.Add(updatedProducer); |
| | | 207 | | } |
| | | 208 | | |
| | | 209 | | // Небольшая задержка чтобы не перегружать API |
| | 0 | 210 | | await Task.Delay(100); |
| | | 211 | | } |
| | | 212 | | |
| | 0 | 213 | | return results; |
| | 0 | 214 | | } |
| | | 215 | | |
| | | 216 | | /// <summary> |
| | | 217 | | /// Обновляет производителя по MarketPrefix (поиск + обновление из API) |
| | | 218 | | /// </summary> |
| | | 219 | | public async Task<EtProducer?> UpdateEtProducerByMarketPrefixFromApi(string marketPrefix) |
| | | 220 | | { |
| | | 221 | | // Сначала ищем в базе по MarketPrefix |
| | 0 | 222 | | var existingProducer = await _repository.GetRealIdAsyncByCode(marketPrefix); |
| | 0 | 223 | | if (existingProducer != null) |
| | | 224 | | { |
| | | 225 | | // Обновляем найденного производителя по его ID |
| | 0 | 226 | | return await UpdateEtProducerFromApi(existingProducer.Id); |
| | | 227 | | } |
| | | 228 | | |
| | 0 | 229 | | return null; |
| | 0 | 230 | | } |
| | | 231 | | |
| | | 232 | | /// <summary> |
| | | 233 | | /// Обновляет производителя по имени (поиск + обновление из API) |
| | | 234 | | /// </summary> |
| | | 235 | | public async Task<EtProducer?> UpdateEtProducerByNameFromApi(string name) |
| | | 236 | | { |
| | | 237 | | // Сначала ищем в базе по имени |
| | 0 | 238 | | var existingProducer = await _repository.GetRealIdAsyncByName(name); |
| | 0 | 239 | | if (existingProducer != null) |
| | | 240 | | { |
| | | 241 | | // Обновляем найденного производителя по его ID |
| | 0 | 242 | | return await UpdateEtProducerFromApi(existingProducer.Id); |
| | | 243 | | } |
| | | 244 | | |
| | 0 | 245 | | return null; |
| | 0 | 246 | | } |
| | | 247 | | |
| | | 248 | | public async Task<int> SaveChanges() |
| | | 249 | | { |
| | 0 | 250 | | return await _repository.SaveChanges(); |
| | 0 | 251 | | } |
| | | 252 | | } |