| | | 1 | | using System.Net; |
| | | 2 | | using Microsoft.EntityFrameworkCore; |
| | | 3 | | using OzonDomains; |
| | | 4 | | using OzonDomains.Models; |
| | | 5 | | using OzonRepositories.Context; |
| | | 6 | | using Services.ApiServices.OzonApi; |
| | | 7 | | using Services.ApiServices.OzonApi.Filters; |
| | | 8 | | using Services.DataServices; |
| | | 9 | | using Services.LabelServices; |
| | | 10 | | using Services.ParserServices.HelpDictEnum; |
| | | 11 | | |
| | | 12 | | namespace OzonOrdersWeb.TransactionServices; |
| | | 13 | | |
| | | 14 | | public sealed class OrderToSupplierOzonShipService |
| | | 15 | | { |
| | | 16 | | private readonly ApplicationDbContext _context; |
| | | 17 | | private readonly OzonApiDataManager _ozonApiDataManager; |
| | | 18 | | private readonly OzonClientServices _ozonClientServices; |
| | | 19 | | |
| | 0 | 20 | | public OrderToSupplierOzonShipService( |
| | 0 | 21 | | ApplicationDbContext context, |
| | 0 | 22 | | OzonApiDataManager ozonApiDataManager, |
| | 0 | 23 | | OzonClientServices ozonClientServices) |
| | | 24 | | { |
| | 0 | 25 | | _context = context; |
| | 0 | 26 | | _ozonApiDataManager = ozonApiDataManager; |
| | 0 | 27 | | _ozonClientServices = ozonClientServices; |
| | 0 | 28 | | } |
| | | 29 | | |
| | | 30 | | public async Task<OrderToSupplierOzonShipResult> ShipAsync( |
| | | 31 | | IReadOnlyCollection<int> orderIds, |
| | | 32 | | CancellationToken cancellationToken = default) |
| | | 33 | | { |
| | 0 | 34 | | if (orderIds.Count == 0) |
| | | 35 | | { |
| | 0 | 36 | | return OrderToSupplierOzonShipResult.Empty(); |
| | | 37 | | } |
| | | 38 | | |
| | 0 | 39 | | var dbOrders = await _context.Orders |
| | 0 | 40 | | .AsNoTracking() |
| | 0 | 41 | | .Include(o => o.ProductInfo) |
| | 0 | 42 | | .Where(o => orderIds.Contains(o.Id) && |
| | 0 | 43 | | o.OzonClientId.HasValue) |
| | 0 | 44 | | .ToListAsync(cancellationToken); |
| | | 45 | | |
| | 0 | 46 | | var entries = new List<OrderToSupplierOzonShipEntry>(); |
| | | 47 | | |
| | 0 | 48 | | foreach (var order in dbOrders) |
| | | 49 | | { |
| | 0 | 50 | | entries.Add(await ShipSingleOrderAsync(order).ConfigureAwait(false)); |
| | | 51 | | } |
| | | 52 | | |
| | 0 | 53 | | return new OrderToSupplierOzonShipResult(entries); |
| | 0 | 54 | | } |
| | | 55 | | |
| | | 56 | | private async Task<OrderToSupplierOzonShipEntry> ShipSingleOrderAsync(Order order) |
| | | 57 | | { |
| | 0 | 58 | | var shipment = order.ShipmentNumber ?? $"ID {order.Id}"; |
| | | 59 | | try |
| | | 60 | | { |
| | 0 | 61 | | if (!order.OzonClientId.HasValue) |
| | | 62 | | { |
| | 0 | 63 | | return OrderToSupplierOzonShipEntry.Skipped(order.Id, shipment, "Пропущено: у заказа не указан Ozon клие |
| | | 64 | | } |
| | | 65 | | |
| | 0 | 66 | | var ozonClient = await _ozonClientServices.GetOzonClientAsync(order.OzonClientId.Value).ConfigureAwait(false |
| | 0 | 67 | | if (ozonClient == null || ozonClient.ClientType != ClientType.OZON) |
| | | 68 | | { |
| | 0 | 69 | | return OrderToSupplierOzonShipEntry.Skipped(order.Id, shipment, "Пропущено: заказ не относится к Ozon кл |
| | | 70 | | } |
| | | 71 | | |
| | 0 | 72 | | if (string.IsNullOrWhiteSpace(ozonClient.DecryptClientId) || |
| | 0 | 73 | | string.IsNullOrWhiteSpace(ozonClient.DecryptApiKey)) |
| | | 74 | | { |
| | 0 | 75 | | return OrderToSupplierOzonShipEntry.Skipped(order.Id, shipment, "Пропущено: не найдены ключи Ozon клиент |
| | | 76 | | } |
| | | 77 | | |
| | 0 | 78 | | if (order.Quantity.GetValueOrDefault() <= 0) |
| | | 79 | | { |
| | 0 | 80 | | return OrderToSupplierOzonShipEntry.Skipped(order.Id, shipment, "Пропущено: количество равно 0."); |
| | | 81 | | } |
| | | 82 | | |
| | 0 | 83 | | var ozonPostingNumber = OzonPostingNumberHelper.GetOzonApiPostingNumber(order.ShipmentNumber); |
| | 0 | 84 | | _ozonApiDataManager.SetClient(ozonClient.DecryptClientId, ozonClient.DecryptApiKey); |
| | | 85 | | |
| | 0 | 86 | | var orderStatus = await _ozonApiDataManager.GetProductSatatus(ozonPostingNumber).ConfigureAwait(false); |
| | 0 | 87 | | var statusName = OzonLabelStatusHelper.GetOzonStatusDisplayName(orderStatus); |
| | | 88 | | |
| | 0 | 89 | | if (OzonLabelStatusHelper.IsOzonStatusPastShipping(orderStatus)) |
| | | 90 | | { |
| | 0 | 91 | | return OrderToSupplierOzonShipEntry.Skipped( |
| | 0 | 92 | | order.Id, shipment, |
| | 0 | 93 | | $"Пропущено: статус Ozon «{statusName}», повторная отгрузка не требуется."); |
| | | 94 | | } |
| | | 95 | | |
| | 0 | 96 | | if (orderStatus == "not_accepted") |
| | | 97 | | { |
| | 0 | 98 | | var toAwaitingDeliver = await _ozonApiDataManager |
| | 0 | 99 | | .SetAwaitingDelivery([ozonPostingNumber]) |
| | 0 | 100 | | .ConfigureAwait(false); |
| | 0 | 101 | | return toAwaitingDeliver.Result |
| | 0 | 102 | | ? OrderToSupplierOzonShipEntry.Success(order.Id, shipment, "Спорный заказ передан к отгрузке.") |
| | 0 | 103 | | : OrderToSupplierOzonShipEntry.Failed(order.Id, shipment, "Не удалось передать спорный заказ к отгру |
| | | 104 | | } |
| | | 105 | | |
| | | 106 | | // Несколько разных SKU в отправлении — отгружаем все товары, иначе Ozon отвечает |
| | | 107 | | // HAS_INCORRECT_PRODUCT_QUANTITY. |
| | | 108 | | List<FbsShipPackage> packages; |
| | 0 | 109 | | var postingProducts = await _ozonApiDataManager |
| | 0 | 110 | | .GetPostingShipProductsAsync(ozonPostingNumber) |
| | 0 | 111 | | .ConfigureAwait(false); |
| | 0 | 112 | | if (postingProducts.Count > 1) |
| | | 113 | | { |
| | 0 | 114 | | packages = OzonFbsShipPackageBuilder.Build(postingProducts, packagePerUnit: false); |
| | | 115 | | } |
| | | 116 | | else |
| | | 117 | | { |
| | 0 | 118 | | var realProductId = await _ozonApiDataManager.GetProductId(ozonPostingNumber).ConfigureAwait(false); |
| | 0 | 119 | | if (!long.TryParse(realProductId, out var realProductIdValue) || realProductIdValue <= 0) |
| | | 120 | | { |
| | 0 | 121 | | return OrderToSupplierOzonShipEntry.Failed( |
| | 0 | 122 | | order.Id, shipment, |
| | 0 | 123 | | $"Не удалось определить product_id для отправления {ozonPostingNumber}."); |
| | | 124 | | } |
| | | 125 | | |
| | 0 | 126 | | var shipQuantity = Math.Max(1, order.Quantity.GetValueOrDefault()); |
| | 0 | 127 | | var ozonShipQuantity = await _ozonApiDataManager |
| | 0 | 128 | | .GetPostingProductQuantityAsync(ozonPostingNumber, realProductIdValue) |
| | 0 | 129 | | .ConfigureAwait(false); |
| | 0 | 130 | | if (ozonShipQuantity > 0 && shipQuantity != ozonShipQuantity) |
| | | 131 | | { |
| | 0 | 132 | | shipQuantity = ozonShipQuantity; |
| | | 133 | | } |
| | | 134 | | |
| | 0 | 135 | | packages = new List<FbsShipPackage> |
| | 0 | 136 | | { |
| | 0 | 137 | | new() |
| | 0 | 138 | | { |
| | 0 | 139 | | Products = |
| | 0 | 140 | | [ |
| | 0 | 141 | | new FbsShipProduct |
| | 0 | 142 | | { |
| | 0 | 143 | | ProductId = realProductIdValue, |
| | 0 | 144 | | Quantity = shipQuantity |
| | 0 | 145 | | } |
| | 0 | 146 | | ] |
| | 0 | 147 | | } |
| | 0 | 148 | | }; |
| | | 149 | | } |
| | | 150 | | |
| | 0 | 151 | | await _ozonApiDataManager |
| | 0 | 152 | | .ShipFbsPosting(ozonPostingNumber, packages, withAdditionalData: true) |
| | 0 | 153 | | .ConfigureAwait(false); |
| | 0 | 154 | | await Task.Delay(2000).ConfigureAwait(false); |
| | | 155 | | |
| | 0 | 156 | | var newStatus = await _ozonApiDataManager.GetProductSubSatatus(ozonPostingNumber).ConfigureAwait(false); |
| | 0 | 157 | | if (newStatus == "ship_failed") |
| | | 158 | | { |
| | 0 | 159 | | await _ozonApiDataManager |
| | 0 | 160 | | .ShipFbsPosting(ozonPostingNumber, packages, withAdditionalData: true) |
| | 0 | 161 | | .ConfigureAwait(false); |
| | 0 | 162 | | await Task.Delay(2000).ConfigureAwait(false); |
| | 0 | 163 | | newStatus = await _ozonApiDataManager.GetProductSubSatatus(ozonPostingNumber).ConfigureAwait(false); |
| | | 164 | | } |
| | | 165 | | |
| | 0 | 166 | | if (newStatus == "ship_failed") |
| | | 167 | | { |
| | 0 | 168 | | return OrderToSupplierOzonShipEntry.Failed( |
| | 0 | 169 | | order.Id, shipment, |
| | 0 | 170 | | $"Ошибка отгрузки: {OzonStatus.GetSubStatus(newStatus)}."); |
| | | 171 | | } |
| | | 172 | | |
| | 0 | 173 | | return OrderToSupplierOzonShipEntry.Success( |
| | 0 | 174 | | order.Id, shipment, |
| | 0 | 175 | | $"{OzonStatus.GetSubStatus(newStatus)}."); |
| | | 176 | | } |
| | 0 | 177 | | catch (Exception ex) |
| | | 178 | | { |
| | | 179 | | // Ozon иногда успевает провести отправление между проверкой статуса и ShipFbsPosting. |
| | | 180 | | // Это не ошибка оформления: повторная отгрузка не нужна, закупку у поставщика можно продолжать. |
| | 0 | 181 | | if (ex.Message.Contains("POSTING_ALREADY_SHIPPED", StringComparison.OrdinalIgnoreCase)) |
| | | 182 | | { |
| | 0 | 183 | | return OrderToSupplierOzonShipEntry.Skipped(order.Id, shipment, |
| | 0 | 184 | | "Отправление уже отгружено в Ozon, повторная отгрузка не требуется."); |
| | | 185 | | } |
| | | 186 | | |
| | | 187 | | // Для HAS_INCORRECT_STATUS пользователю важно увидеть, в каком статусе сейчас отправление. |
| | 0 | 188 | | string? ozonStatusName = null; |
| | 0 | 189 | | if (OzonLabelPrintErrorHelper.NeedsCurrentOzonStatus(ex.Message)) |
| | | 190 | | { |
| | | 191 | | try |
| | | 192 | | { |
| | 0 | 193 | | var current = await _ozonApiDataManager |
| | 0 | 194 | | .GetProductSatatus(OzonPostingNumberHelper.GetOzonApiPostingNumber(order.ShipmentNumber)) |
| | 0 | 195 | | .ConfigureAwait(false); |
| | 0 | 196 | | ozonStatusName = OzonLabelStatusHelper.GetOzonStatusDisplayName(current); |
| | 0 | 197 | | } |
| | 0 | 198 | | catch |
| | | 199 | | { |
| | | 200 | | // Статус нужен только для текста ошибки. |
| | 0 | 201 | | } |
| | | 202 | | } |
| | | 203 | | |
| | 0 | 204 | | return OrderToSupplierOzonShipEntry.Failed(order.Id, shipment, ex.Message, ozonStatusName); |
| | | 205 | | } |
| | 0 | 206 | | } |
| | | 207 | | } |
| | | 208 | | |
| | | 209 | | public sealed class OrderToSupplierOzonShipResult |
| | | 210 | | { |
| | | 211 | | public IReadOnlyCollection<OrderToSupplierOzonShipEntry> Entries { get; } |
| | | 212 | | |
| | | 213 | | public int SuccessCount => Entries.Count(e => e.IsSuccess); |
| | | 214 | | public int FailedCount => Entries.Count(e => !e.IsSuccess && !e.IsSkipped); |
| | | 215 | | public int SkippedCount => Entries.Count(e => e.IsSkipped); |
| | | 216 | | |
| | | 217 | | /// <summary>Заказы, для которых можно продолжать оформление у поставщика: успешно отгруженные |
| | | 218 | | /// либо уже отгруженные в Ozon. Ошибка отгрузки не должна создавать новую закупку.</summary> |
| | | 219 | | public IReadOnlySet<int> EligibleOrderIds => Entries |
| | | 220 | | .Where(e => e.IsSuccess || e.IsSkipped) |
| | | 221 | | .Select(e => e.OrderId) |
| | | 222 | | .ToHashSet(); |
| | | 223 | | |
| | | 224 | | public OrderToSupplierOzonShipResult(IReadOnlyCollection<OrderToSupplierOzonShipEntry> entries) |
| | | 225 | | { |
| | | 226 | | Entries = entries; |
| | | 227 | | } |
| | | 228 | | |
| | | 229 | | public static OrderToSupplierOzonShipResult Empty() => new(Array.Empty<OrderToSupplierOzonShipEntry>()); |
| | | 230 | | |
| | | 231 | | public string ToHtmlBlock() |
| | | 232 | | { |
| | | 233 | | if (Entries.Count == 0) |
| | | 234 | | { |
| | | 235 | | return string.Empty; |
| | | 236 | | } |
| | | 237 | | |
| | | 238 | | var rows = Entries |
| | | 239 | | .Take(20) |
| | | 240 | | .Select(e => |
| | | 241 | | $"<li><b>{WebUtility.HtmlEncode(e.ShipmentNumber)}</b>: {WebUtility.HtmlEncode(e.Message)}</li>"); |
| | | 242 | | |
| | | 243 | | var hiddenCount = Math.Max(0, Entries.Count - 20); |
| | | 244 | | var hiddenTail = hiddenCount > 0 ? $"<li>... и еще {hiddenCount}</li>" : string.Empty; |
| | | 245 | | |
| | | 246 | | var alertClass = FailedCount > 0 ? "alert-warning border-warning-subtle" : "alert-info border-primary-subtle"; |
| | | 247 | | return $"<div class='alert {alertClass} mb-0'>" + |
| | | 248 | | "<div class='fw-semibold mb-1'><i class='fas fa-truck me-1 text-primary'></i>Отгрузка в Ozon</div>" + |
| | | 249 | | $"<div class='small mb-1'>Успешно: <b>{SuccessCount}</b>, с ошибками: <b>{FailedCount}</b>, пропущено: <b |
| | | 250 | | $"<ul class='mb-0 small'>{string.Join(string.Empty, rows)}{hiddenTail}</ul>" + |
| | | 251 | | "</div>"; |
| | | 252 | | } |
| | | 253 | | } |
| | | 254 | | |
| | | 255 | | public sealed record OrderToSupplierOzonShipEntry( |
| | | 256 | | int OrderId, |
| | | 257 | | string ShipmentNumber, |
| | | 258 | | bool IsSuccess, |
| | | 259 | | bool IsSkipped, |
| | | 260 | | string Message, |
| | | 261 | | string? OzonStatusName = null) |
| | | 262 | | { |
| | | 263 | | public static OrderToSupplierOzonShipEntry Success(int orderId, string shipmentNumber, string message) => |
| | | 264 | | new(orderId, shipmentNumber, true, false, message); |
| | | 265 | | |
| | | 266 | | public static OrderToSupplierOzonShipEntry Failed(int orderId, string shipmentNumber, string message, string? ozonSt |
| | | 267 | | new(orderId, shipmentNumber, false, false, message, ozonStatusName); |
| | | 268 | | |
| | | 269 | | public static OrderToSupplierOzonShipEntry Skipped(int orderId, string shipmentNumber, string message) => |
| | | 270 | | new(orderId, shipmentNumber, false, true, message); |
| | | 271 | | } |