| | | 1 | | using Microsoft.EntityFrameworkCore; |
| | | 2 | | using Microsoft.Extensions.Logging; |
| | | 3 | | using Newtonsoft.Json.Linq; |
| | | 4 | | using OzonDomains.Models; |
| | | 5 | | using OzonDomains.Models.SupplierStatuses; |
| | | 6 | | using OzonRepositories.Context; |
| | | 7 | | using Services.ApiServices.MotexApi; |
| | | 8 | | |
| | | 9 | | namespace Services.SupplierStatusServices.Providers; |
| | | 10 | | |
| | | 11 | | /// <summary> |
| | | 12 | | /// Статусы Motex (МоТехС). Корзина локальная — читается из MotexCartItems (<see cref="LocalCartStatusReader"/>). |
| | | 13 | | /// Статусы оформленных заказов опрашиваются через Motex API (POST /api/v1/Orders/GetOrdersByIds |
| | | 14 | | /// или GET /api/v1/Orders/GetOrderDetails). |
| | | 15 | | /// </summary> |
| | | 16 | | public sealed class MotexSupplierStatusProvider : ISupplierStatusProvider |
| | | 17 | | { |
| | | 18 | | private readonly ApplicationDbContext _db; |
| | | 19 | | private readonly MotexDataManager _motex; |
| | | 20 | | private readonly LocalCartStatusReader _localCart; |
| | | 21 | | private readonly ILogger<MotexSupplierStatusProvider> _logger; |
| | | 22 | | |
| | 3 | 23 | | public MotexSupplierStatusProvider( |
| | 3 | 24 | | ApplicationDbContext db, |
| | 3 | 25 | | MotexDataManager motex, |
| | 3 | 26 | | LocalCartStatusReader localCart, |
| | 3 | 27 | | ILogger<MotexSupplierStatusProvider> logger) |
| | | 28 | | { |
| | 3 | 29 | | _db = db; |
| | 3 | 30 | | _motex = motex; |
| | 3 | 31 | | _localCart = localCart; |
| | 3 | 32 | | _logger = logger; |
| | 3 | 33 | | } |
| | | 34 | | |
| | 1 | 35 | | public string ProviderKey => ApiSupplierSettings.MotexProviderKey; |
| | | 36 | | |
| | | 37 | | public Task<IReadOnlyList<SupplierStatusSnapshot>> FetchCartAsync( |
| | | 38 | | IReadOnlyList<OrderSupplierStateRef> states, CancellationToken ct) => |
| | 1 | 39 | | _localCart.ReadAsync(ProviderKey, states, ct); |
| | | 40 | | |
| | | 41 | | public async Task<IReadOnlyList<SupplierStatusSnapshot>> FetchOrderAsync( |
| | | 42 | | IReadOnlyList<OrderSupplierStateRef> states, CancellationToken ct) |
| | | 43 | | { |
| | 2 | 44 | | if (states.Count == 0) return []; |
| | | 45 | | |
| | 4 | 46 | | var orderIds = states.Select(x => x.OrderId).Distinct().ToList(); |
| | 2 | 47 | | var localItems = await _db.MotexOrderItems |
| | 2 | 48 | | .Include(x => x.MotexOrder) |
| | 2 | 49 | | .Where(x => orderIds.Contains(x.StudioOrderId)) |
| | 2 | 50 | | .ToListAsync(ct); |
| | | 51 | | |
| | 2 | 52 | | var latestItems = localItems |
| | 1 | 53 | | .GroupBy(x => x.StudioOrderId) |
| | 5 | 54 | | .ToDictionary(g => g.Key, g => g.OrderByDescending(x => x.Id).First()); |
| | | 55 | | |
| | 2 | 56 | | var externalIds = states |
| | 2 | 57 | | .Select(x => x.ExternalOrderId) |
| | 1 | 58 | | .Concat(latestItems.Values.Select(x => x.MotexOrder?.ExternalOrderId)) |
| | 3 | 59 | | .Where(id => !string.IsNullOrWhiteSpace(id)) |
| | 3 | 60 | | .Select(id => id!) |
| | 2 | 61 | | .Distinct(StringComparer.OrdinalIgnoreCase) |
| | 2 | 62 | | .ToList(); |
| | | 63 | | |
| | 2 | 64 | | var byId = new Dictionary<string, JObject>(StringComparer.OrdinalIgnoreCase); |
| | 2 | 65 | | var byClientNum = new Dictionary<string, JObject>(StringComparer.OrdinalIgnoreCase); |
| | | 66 | | |
| | 2 | 67 | | if (externalIds.Count > 0) |
| | | 68 | | { |
| | | 69 | | try |
| | | 70 | | { |
| | 2 | 71 | | var response = await _motex.GetOrdersByIdsAsync(externalIds, ct); |
| | 1 | 72 | | var ordersArray = (response["orders"] as JArray ?? response as JArray ?? new JArray()).OfType<JObject>() |
| | 4 | 73 | | foreach (var order in ordersArray) |
| | | 74 | | { |
| | 1 | 75 | | var id = order.Value<string>("id"); |
| | 2 | 76 | | if (!string.IsNullOrWhiteSpace(id)) byId[id] = order; |
| | 1 | 77 | | var cNum = order.Value<string>("clientOrderNum"); |
| | 2 | 78 | | if (!string.IsNullOrWhiteSpace(cNum)) byClientNum[cNum] = order; |
| | | 79 | | } |
| | 1 | 80 | | } |
| | 1 | 81 | | catch (Exception ex) when (ex is MotexApiException or HttpRequestException or TaskCanceledException) |
| | | 82 | | { |
| | 1 | 83 | | _logger.LogInformation("МоТехС: не удалось получить статусы заказов: {Error}", ex.Message); |
| | 2 | 84 | | return states.Select(x => new SupplierStatusSnapshot |
| | 2 | 85 | | { |
| | 2 | 86 | | OrderId = x.OrderId, |
| | 2 | 87 | | Kind = SupplierStatusKind.Order, |
| | 2 | 88 | | StatusName = string.Empty, |
| | 2 | 89 | | Error = $"МоТехС: {ex.Message}" |
| | 2 | 90 | | }).ToList(); |
| | | 91 | | } |
| | | 92 | | } |
| | | 93 | | |
| | | 94 | | // Если у каких-то заказов известен только clientOrderNum (без externalOrderId), пробуем GetOrderDetails |
| | 1 | 95 | | var missingClientNums = latestItems.Values |
| | 1 | 96 | | .Select(x => x.MotexOrder) |
| | 1 | 97 | | .Where(o => o is not null && string.IsNullOrWhiteSpace(o.ExternalOrderId) && !string.IsNullOrWhiteSpace(o.Cl |
| | 0 | 98 | | .Select(o => o!.ClientOrderNum) |
| | 1 | 99 | | .Distinct(StringComparer.OrdinalIgnoreCase) |
| | 0 | 100 | | .Where(num => !byClientNum.ContainsKey(num)) |
| | 1 | 101 | | .Take(10) |
| | 1 | 102 | | .ToList(); |
| | | 103 | | |
| | 2 | 104 | | foreach (var clientNum in missingClientNums) |
| | | 105 | | { |
| | | 106 | | try |
| | | 107 | | { |
| | 0 | 108 | | var details = await _motex.GetOrderDetailsAsync(null, clientNum, ct); |
| | 0 | 109 | | var orderObj = details["order"] as JObject ?? details as JObject; |
| | 0 | 110 | | if (orderObj is not null) |
| | | 111 | | { |
| | 0 | 112 | | var id = orderObj.Value<string>("id"); |
| | 0 | 113 | | if (!string.IsNullOrWhiteSpace(id)) byId[id] = orderObj; |
| | 0 | 114 | | byClientNum[clientNum] = orderObj; |
| | | 115 | | } |
| | 0 | 116 | | } |
| | 0 | 117 | | catch (Exception ex) when (ex is MotexApiException or HttpRequestException or TaskCanceledException) |
| | | 118 | | { |
| | 0 | 119 | | _logger.LogInformation("МоТехС: не удалось получить детали заказа {ClientOrderNum}: {Error}", clientNum, |
| | 0 | 120 | | } |
| | 0 | 121 | | } |
| | | 122 | | |
| | 1 | 123 | | var result = new List<SupplierStatusSnapshot>(); |
| | 1 | 124 | | var localOrdersChanged = false; |
| | | 125 | | |
| | 4 | 126 | | foreach (var state in states) |
| | | 127 | | { |
| | 1 | 128 | | latestItems.TryGetValue(state.OrderId, out var item); |
| | 1 | 129 | | var localOrder = item?.MotexOrder; |
| | | 130 | | |
| | 1 | 131 | | JObject? apiOrder = null; |
| | 1 | 132 | | if (!string.IsNullOrWhiteSpace(state.ExternalOrderId) && byId.TryGetValue(state.ExternalOrderId, out var f1) |
| | 1 | 133 | | apiOrder = f1; |
| | 0 | 134 | | else if (!string.IsNullOrWhiteSpace(state.ExternalOrderNumber)) |
| | | 135 | | { |
| | 0 | 136 | | if (byId.TryGetValue(state.ExternalOrderNumber, out var f2)) |
| | 0 | 137 | | apiOrder = f2; |
| | 0 | 138 | | else if (byClientNum.TryGetValue(state.ExternalOrderNumber, out var f3)) |
| | 0 | 139 | | apiOrder = f3; |
| | | 140 | | } |
| | | 141 | | |
| | 1 | 142 | | if (apiOrder is null && localOrder is not null) |
| | | 143 | | { |
| | 0 | 144 | | if (!string.IsNullOrWhiteSpace(localOrder.ExternalOrderId) && byId.TryGetValue(localOrder.ExternalOrderI |
| | 0 | 145 | | apiOrder = f4; |
| | 0 | 146 | | else if (!string.IsNullOrWhiteSpace(localOrder.ClientOrderNum) && byClientNum.TryGetValue(localOrder.Cli |
| | 0 | 147 | | apiOrder = f5; |
| | | 148 | | } |
| | | 149 | | |
| | 1 | 150 | | if (apiOrder is null) |
| | | 151 | | continue; |
| | | 152 | | |
| | 1 | 153 | | var externalId = apiOrder.Value<string>("id") ?? localOrder?.ExternalOrderId; |
| | 1 | 154 | | var clientNum = apiOrder.Value<string>("clientOrderNum") ?? localOrder?.ClientOrderNum; |
| | | 155 | | |
| | 1 | 156 | | var apiItems = (apiOrder["orderItems"] as JArray)?.OfType<JObject>().ToList(); |
| | 1 | 157 | | var matchedItem = item is not null && apiItems is not null |
| | 1 | 158 | | ? apiItems.FirstOrDefault(i => |
| | 1 | 159 | | string.Equals(i.Value<string>("code"), item.Code, StringComparison.OrdinalIgnoreCase) && |
| | 1 | 160 | | string.Equals(i.Value<string>("brand"), item.Brand, StringComparison.OrdinalIgnoreCase)) |
| | 1 | 161 | | ?? (apiItems.Count == 1 ? apiItems[0] : null) |
| | 1 | 162 | | : apiItems?.FirstOrDefault(); |
| | | 163 | | |
| | 1 | 164 | | var status = matchedItem?.Value<string>("status") |
| | 1 | 165 | | ?? apiOrder.Value<string>("status") |
| | 1 | 166 | | ?? localOrder?.Status |
| | 1 | 167 | | ?? "—"; |
| | | 168 | | |
| | 1 | 169 | | if (localOrder is not null) |
| | | 170 | | { |
| | 1 | 171 | | if (!string.IsNullOrWhiteSpace(externalId) && string.IsNullOrWhiteSpace(localOrder.ExternalOrderId)) |
| | | 172 | | { |
| | 0 | 173 | | localOrder.ExternalOrderId = externalId; |
| | 0 | 174 | | localOrdersChanged = true; |
| | | 175 | | } |
| | 1 | 176 | | if (!string.IsNullOrWhiteSpace(status) && localOrder.Status != status) |
| | | 177 | | { |
| | 1 | 178 | | localOrder.Status = status; |
| | 1 | 179 | | localOrdersChanged = true; |
| | | 180 | | } |
| | | 181 | | } |
| | | 182 | | |
| | 1 | 183 | | var lineId = matchedItem?.Value<string>("id"); |
| | 1 | 184 | | var qntConfirmed = matchedItem?.Value<decimal?>("qnt_ordered") ?? matchedItem?.Value<decimal?>("quantity"); |
| | | 185 | | |
| | 1 | 186 | | result.Add(new SupplierStatusSnapshot |
| | 1 | 187 | | { |
| | 1 | 188 | | OrderId = state.OrderId, |
| | 1 | 189 | | Kind = SupplierStatusKind.Order, |
| | 1 | 190 | | ExternalCode = status, |
| | 1 | 191 | | StatusName = status, |
| | 1 | 192 | | ExternalOrderNumber = externalId ?? clientNum ?? state.ExternalOrderNumber, |
| | 1 | 193 | | ExternalOrderId = externalId ?? state.ExternalOrderId, |
| | 1 | 194 | | ExternalLineId = lineId ?? state.ExternalLineId, |
| | 1 | 195 | | QuantityConfirmed = qntConfirmed |
| | 1 | 196 | | }); |
| | | 197 | | } |
| | | 198 | | |
| | 1 | 199 | | if (localOrdersChanged) |
| | | 200 | | { |
| | 1 | 201 | | await _db.SaveChangesAsync(ct); |
| | | 202 | | } |
| | | 203 | | |
| | 1 | 204 | | return result; |
| | 2 | 205 | | } |
| | | 206 | | } |