| | | 1 | | using Microsoft.Extensions.Http; |
| | | 2 | | using OzonDomains.Models; |
| | | 3 | | using OzonDomains.Models.BitrixModels; |
| | | 4 | | using Services.ApiServices.OzonApi; |
| | | 5 | | using Services.ApiServices.OzonApi.Filters; |
| | | 6 | | using SlqStudio.Application.Services.EmailService; |
| | | 7 | | |
| | | 8 | | namespace Services.BitrixStockServices; |
| | | 9 | | |
| | | 10 | | public class BitrixOzonLinkedStockApiSyncService : IBitrixOzonLinkedStockApiSyncService |
| | | 11 | | { |
| | | 12 | | private const int MaxUpdatesPerLoad = 400; |
| | | 13 | | private const int BatchSize = 50; |
| | | 14 | | |
| | | 15 | | private readonly IHttpClientFactory _httpClientFactory; |
| | | 16 | | private readonly IEmailService? _emailService; |
| | | 17 | | |
| | 0 | 18 | | public BitrixOzonLinkedStockApiSyncService( |
| | 0 | 19 | | IHttpClientFactory httpClientFactory, |
| | 0 | 20 | | IEmailService? emailService = null) |
| | | 21 | | { |
| | 0 | 22 | | _httpClientFactory = httpClientFactory; |
| | 0 | 23 | | _emailService = emailService; |
| | 0 | 24 | | } |
| | | 25 | | |
| | | 26 | | public async Task<BitrixOzonStockSyncSummary> SyncPendingLinkedStocksAsync( |
| | | 27 | | IReadOnlyList<RemainingStockBitrix> items, |
| | | 28 | | IReadOnlyList<OzonClient> ozonClients, |
| | | 29 | | CancellationToken cancellationToken = default) |
| | | 30 | | { |
| | 0 | 31 | | var summary = new BitrixOzonStockSyncSummary(); |
| | 0 | 32 | | if (items.Count == 0 || ozonClients.Count == 0) |
| | | 33 | | { |
| | 0 | 34 | | return summary; |
| | | 35 | | } |
| | | 36 | | |
| | 0 | 37 | | var clientByName = ozonClients |
| | | 38 | | .Where(c => !string.IsNullOrWhiteSpace(c.Name)) |
| | | 39 | | .ToDictionary(c => c.Name.Trim(), c => c, StringComparer.OrdinalIgnoreCase); |
| | | 40 | | |
| | 0 | 41 | | var pending = CollectPending(items); |
| | 0 | 42 | | if (pending.Count == 0) |
| | | 43 | | { |
| | 0 | 44 | | return summary; |
| | | 45 | | } |
| | | 46 | | |
| | 0 | 47 | | if (pending.Count > MaxUpdatesPerLoad) |
| | | 48 | | { |
| | 0 | 49 | | summary.LimitReached = true; |
| | 0 | 50 | | pending = pending.Take(MaxUpdatesPerLoad).ToList(); |
| | | 51 | | } |
| | | 52 | | |
| | 0 | 53 | | foreach (var clientGroup in pending.GroupBy( |
| | | 54 | | p => p.Store.ClientName ?? string.Empty, |
| | 0 | 55 | | StringComparer.OrdinalIgnoreCase)) |
| | | 56 | | { |
| | 0 | 57 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 0 | 58 | | if (!clientByName.TryGetValue(clientGroup.Key, out var client)) |
| | | 59 | | { |
| | 0 | 60 | | foreach (var entry in clientGroup) |
| | | 61 | | { |
| | 0 | 62 | | summary.Skipped++; |
| | 0 | 63 | | summary.AddEntry(BuildDetail(entry, |
| | 0 | 64 | | (int)Math.Max(0, Math.Round(entry.Store.Amount)), |
| | 0 | 65 | | success: false, |
| | 0 | 66 | | error: $"Клиент Ozon «{entry.Store.ClientName}» не найден в настройках")); |
| | | 67 | | } |
| | | 68 | | |
| | | 69 | | continue; |
| | | 70 | | } |
| | | 71 | | |
| | 0 | 72 | | var apiManager = BitrixOzonApiFactory.Create(_httpClientFactory, _emailService, client); |
| | | 73 | | |
| | 0 | 74 | | var clientItems = clientGroup.ToList(); |
| | 0 | 75 | | for (var offset = 0; offset < clientItems.Count; offset += BatchSize) |
| | | 76 | | { |
| | 0 | 77 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 0 | 78 | | var batch = clientItems.Skip(offset).Take(BatchSize).ToList(); |
| | 0 | 79 | | await ProcessBatchAsync(apiManager, batch, summary, cancellationToken); |
| | | 80 | | } |
| | 0 | 81 | | } |
| | | 82 | | |
| | 0 | 83 | | foreach (var item in items) |
| | | 84 | | { |
| | 0 | 85 | | BitrixOzonStockLinkage.PruneUnlistedOzonProductStores(item); |
| | | 86 | | } |
| | | 87 | | |
| | 0 | 88 | | return summary; |
| | 0 | 89 | | } |
| | | 90 | | |
| | | 91 | | private static List<PendingOzonStockUpdate> CollectPending(IReadOnlyList<RemainingStockBitrix> items) |
| | | 92 | | { |
| | 0 | 93 | | var list = new List<PendingOzonStockUpdate>(); |
| | 0 | 94 | | foreach (var item in items) |
| | | 95 | | { |
| | 0 | 96 | | if (BitrixOzonStockLinkage.IsInactiveProduct(item)) |
| | | 97 | | { |
| | | 98 | | continue; |
| | | 99 | | } |
| | | 100 | | |
| | 0 | 101 | | lock (item.OzonStores) |
| | | 102 | | { |
| | 0 | 103 | | foreach (var store in item.OzonStores) |
| | | 104 | | { |
| | 0 | 105 | | if (!store.PendingOzonApiSync || |
| | 0 | 106 | | store.StoreId <= 0 || |
| | 0 | 107 | | string.IsNullOrWhiteSpace(store.OfferId) || |
| | 0 | 108 | | string.IsNullOrWhiteSpace(store.ClientName) || |
| | 0 | 109 | | store.LinkStores == null || |
| | 0 | 110 | | store.LinkStores.Count == 0) |
| | | 111 | | { |
| | | 112 | | continue; |
| | | 113 | | } |
| | | 114 | | |
| | 0 | 115 | | list.Add(new PendingOzonStockUpdate(item, store)); |
| | | 116 | | } |
| | | 117 | | } |
| | | 118 | | } |
| | | 119 | | |
| | 0 | 120 | | return list; |
| | | 121 | | } |
| | | 122 | | |
| | | 123 | | private async Task ProcessBatchAsync( |
| | | 124 | | OzonApiDataManager apiManager, |
| | | 125 | | List<PendingOzonStockUpdate> batch, |
| | | 126 | | BitrixOzonStockSyncSummary summary, |
| | | 127 | | CancellationToken cancellationToken) |
| | | 128 | | { |
| | 0 | 129 | | var resolved = new List<(PendingOzonStockUpdate Pending, StockItemForUpdate Payload)>(); |
| | 0 | 130 | | foreach (var entry in batch) |
| | | 131 | | { |
| | 0 | 132 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 133 | | |
| | 0 | 134 | | var store = entry.Store; |
| | 0 | 135 | | var productId = ParseProductId(store.ProductId); |
| | 0 | 136 | | if (productId <= 0) |
| | | 137 | | { |
| | 0 | 138 | | var articleBase = store.OfferId.Contains('=') |
| | 0 | 139 | | ? store.OfferId.Split('=')[0] |
| | 0 | 140 | | : store.OfferId; |
| | 0 | 141 | | productId = await apiManager.TryResolveProductIdByOfferIdAsync(store.OfferId, articleBase) |
| | 0 | 142 | | .ConfigureAwait(false); |
| | | 143 | | } |
| | | 144 | | |
| | 0 | 145 | | if (productId <= 0) |
| | | 146 | | { |
| | 0 | 147 | | RemoveStore(entry.Item, store); |
| | 0 | 148 | | continue; |
| | | 149 | | } |
| | | 150 | | |
| | 0 | 151 | | summary.Attempted++; |
| | | 152 | | |
| | 0 | 153 | | store.ProductId = productId.ToString(); |
| | 0 | 154 | | var stock = (int)Math.Max(0, Math.Round(store.Amount)); |
| | 0 | 155 | | entry.ResolvedProductId = productId; |
| | 0 | 156 | | entry.TargetStock = stock; |
| | 0 | 157 | | resolved.Add((entry, new StockItemForUpdate |
| | 0 | 158 | | { |
| | 0 | 159 | | OfferId = store.OfferId, |
| | 0 | 160 | | ProductId = productId, |
| | 0 | 161 | | Stock = stock, |
| | 0 | 162 | | WarehouseId = store.StoreId |
| | 0 | 163 | | })); |
| | 0 | 164 | | } |
| | | 165 | | |
| | 0 | 166 | | if (resolved.Count == 0) |
| | | 167 | | { |
| | 0 | 168 | | return; |
| | | 169 | | } |
| | | 170 | | |
| | | 171 | | try |
| | | 172 | | { |
| | 0 | 173 | | var result = await apiManager |
| | | 174 | | .UpdateProductStocks(resolved.Select(r => r.Payload).ToList()) |
| | 0 | 175 | | .ConfigureAwait(false); |
| | | 176 | | |
| | 0 | 177 | | var rows = result?.Result ?? new List<UpdateStockResult>(); |
| | 0 | 178 | | foreach (var (pending, payload) in resolved) |
| | | 179 | | { |
| | 0 | 180 | | var store = pending.Store; |
| | 0 | 181 | | var row = rows.FirstOrDefault(r => |
| | 0 | 182 | | string.Equals(r.OfferId, payload.OfferId, StringComparison.OrdinalIgnoreCase) && |
| | 0 | 183 | | r.WarehouseId == payload.WarehouseId); |
| | 0 | 184 | | if (row != null && row.Updated && (row.Errors == null || row.Errors.Count == 0)) |
| | | 185 | | { |
| | 0 | 186 | | summary.Succeeded++; |
| | 0 | 187 | | store.PendingOzonApiSync = false; |
| | 0 | 188 | | store.OzonPresentOnOzon = store.Amount; |
| | 0 | 189 | | store.LastOzonSyncError = null; |
| | 0 | 190 | | summary.AddEntry(BuildDetail(pending, pending.TargetStock, true, null, pending.ResolvedProductId)); |
| | 0 | 191 | | continue; |
| | | 192 | | } |
| | | 193 | | |
| | 0 | 194 | | summary.Failed++; |
| | 0 | 195 | | store.LastOzonSyncError = FormatStockErrors(row); |
| | 0 | 196 | | summary.AddEntry(BuildDetail(pending, pending.TargetStock, false, store.LastOzonSyncError, |
| | 0 | 197 | | pending.ResolvedProductId)); |
| | | 198 | | } |
| | 0 | 199 | | } |
| | 0 | 200 | | catch (Exception ex) |
| | | 201 | | { |
| | 0 | 202 | | foreach (var entry in resolved) |
| | | 203 | | { |
| | 0 | 204 | | summary.Failed++; |
| | 0 | 205 | | entry.Pending.Store.LastOzonSyncError = ex.Message; |
| | 0 | 206 | | summary.AddEntry(BuildDetail(entry.Pending, entry.Pending.TargetStock, false, ex.Message, |
| | 0 | 207 | | entry.Pending.ResolvedProductId)); |
| | | 208 | | } |
| | 0 | 209 | | } |
| | 0 | 210 | | } |
| | | 211 | | |
| | | 212 | | private static BitrixOzonStockSyncDetailEntry BuildDetail( |
| | | 213 | | PendingOzonStockUpdate pending, |
| | | 214 | | int stock, |
| | | 215 | | bool success, |
| | | 216 | | string? error, |
| | | 217 | | long? productId = null) |
| | | 218 | | { |
| | 0 | 219 | | var store = pending.Store; |
| | 0 | 220 | | var item = pending.Item; |
| | 0 | 221 | | int? previous = store.OzonPresentOnOzon.HasValue |
| | 0 | 222 | | ? (int)Math.Round(store.OzonPresentOnOzon.Value) |
| | 0 | 223 | | : null; |
| | | 224 | | |
| | 0 | 225 | | return new BitrixOzonStockSyncDetailEntry |
| | 0 | 226 | | { |
| | 0 | 227 | | Article = item.Article, |
| | 0 | 228 | | OfferId = store.OfferId, |
| | 0 | 229 | | OzonClient = store.ClientName ?? string.Empty, |
| | 0 | 230 | | WarehouseName = store.Title, |
| | 0 | 231 | | WarehouseId = store.StoreId, |
| | 0 | 232 | | BitrixStores = store.LinkStores != null ? string.Join(", ", store.LinkStores) : null, |
| | 0 | 233 | | PreviousOzonStock = previous, |
| | 0 | 234 | | NewStock = stock, |
| | 0 | 235 | | ProductId = productId ?? ParseProductId(store.ProductId), |
| | 0 | 236 | | Success = success, |
| | 0 | 237 | | ErrorMessage = error |
| | 0 | 238 | | }; |
| | | 239 | | } |
| | | 240 | | |
| | | 241 | | private static long ParseProductId(string? raw) => |
| | 0 | 242 | | long.TryParse(raw?.Trim(), out var id) ? id : 0; |
| | | 243 | | |
| | | 244 | | private static string FormatStockErrors(UpdateStockResult? row) |
| | | 245 | | { |
| | 0 | 246 | | if (row?.Errors == null || row.Errors.Count == 0) |
| | | 247 | | { |
| | 0 | 248 | | return row?.Updated == false ? "Ozon не обновил остаток" : "Неизвестная ошибка Ozon"; |
| | | 249 | | } |
| | | 250 | | |
| | 0 | 251 | | return string.Join("; ", row.Errors.Select(e => |
| | 0 | 252 | | string.IsNullOrWhiteSpace(e.Message) ? e.Code ?? "ошибка" : e.Message)); |
| | | 253 | | } |
| | | 254 | | |
| | | 255 | | private static void RemoveStore(RemainingStockBitrix item, StockByStore store) |
| | | 256 | | { |
| | 0 | 257 | | lock (item.OzonStores) |
| | | 258 | | { |
| | 0 | 259 | | item.OzonStores.RemoveAll(s => |
| | 0 | 260 | | ReferenceEquals(s, store) || |
| | 0 | 261 | | (s.StoreId == store.StoreId && |
| | 0 | 262 | | string.Equals(s.ClientName, store.ClientName, StringComparison.OrdinalIgnoreCase))); |
| | 0 | 263 | | } |
| | 0 | 264 | | } |
| | | 265 | | |
| | | 266 | | private sealed class PendingOzonStockUpdate |
| | | 267 | | { |
| | 0 | 268 | | public PendingOzonStockUpdate(RemainingStockBitrix item, StockByStore store) |
| | | 269 | | { |
| | 0 | 270 | | Item = item; |
| | 0 | 271 | | Store = store; |
| | 0 | 272 | | } |
| | | 273 | | |
| | 0 | 274 | | public RemainingStockBitrix Item { get; } |
| | 0 | 275 | | public StockByStore Store { get; } |
| | 0 | 276 | | public long ResolvedProductId { get; set; } |
| | 0 | 277 | | public int TargetStock { get; set; } |
| | | 278 | | } |
| | | 279 | | } |