| | | 1 | | using Newtonsoft.Json.Linq; |
| | | 2 | | |
| | | 3 | | namespace Services.LabelServices; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// Одно поле-требование Ozon по конкретному экземпляру товара в отправлении. |
| | | 7 | | /// Экземпляры разворачиваются по <c>quantity</c>: у каждого свой код маркировки. |
| | | 8 | | /// </summary> |
| | | 9 | | public sealed class OzonExemplarRequirement |
| | | 10 | | { |
| | | 11 | | public long ProductId { get; init; } |
| | | 12 | | |
| | | 13 | | public long ExemplarId { get; init; } |
| | | 14 | | |
| | | 15 | | /// <summary>Порядковый номер экземпляра в рамках товара (1..quantity) — для подписи в UI.</summary> |
| | | 16 | | public int Index { get; init; } |
| | | 17 | | |
| | | 18 | | public int Quantity { get; init; } |
| | | 19 | | |
| | | 20 | | public bool NeedsMandatoryMark { get; init; } |
| | | 21 | | |
| | | 22 | | public bool NeedsGtd { get; init; } |
| | | 23 | | |
| | | 24 | | public bool NeedsRnpt { get; init; } |
| | | 25 | | |
| | | 26 | | /// <summary>Требования, которые форма не закрывает: вес, IMEI, ювелирный УИН.</summary> |
| | | 27 | | public IReadOnlyList<string> Unsupported { get; init; } = []; |
| | | 28 | | |
| | | 29 | | public bool HasAnyRequirement => |
| | | 30 | | NeedsMandatoryMark || NeedsGtd || NeedsRnpt || Unsupported.Count > 0; |
| | | 31 | | } |
| | | 32 | | |
| | | 33 | | /// <summary>Итог сохранения данных экземпляров: готово ли отправление к сборке.</summary> |
| | | 34 | | public sealed class OzonExemplarSaveResult |
| | | 35 | | { |
| | | 36 | | public bool ShipAvailable { get; init; } |
| | | 37 | | |
| | | 38 | | public IReadOnlyList<string> Reasons { get; init; } = []; |
| | | 39 | | } |
| | | 40 | | |
| | | 41 | | /// <summary> |
| | | 42 | | /// Разбор ответов Ozon exemplar API (v6 create-or-get / v6 set / v5 status). |
| | | 43 | | /// Чистые функции без обращений к сети — покрываются юнит-тестами. |
| | | 44 | | /// </summary> |
| | | 45 | | public static class OzonExemplarHelper |
| | | 46 | | { |
| | | 47 | | public const string ShipAvailableStatus = "ship_available"; |
| | | 48 | | public const string ValidationInProgressStatus = "validation_in_progress"; |
| | | 49 | | |
| | 1 | 50 | | private static readonly Dictionary<string, string> UnsupportedRequirementNames = |
| | 1 | 51 | | new(StringComparer.OrdinalIgnoreCase) |
| | 1 | 52 | | { |
| | 1 | 53 | | ["weight"] = "фактический вес экземпляра", |
| | 1 | 54 | | ["imei"] = "IMEI", |
| | 1 | 55 | | ["jw_uin"] = "УИН ювелирного изделия" |
| | 1 | 56 | | }; |
| | | 57 | | |
| | 1 | 58 | | private static readonly Dictionary<string, string> CheckStatusNames = |
| | 1 | 59 | | new(StringComparer.OrdinalIgnoreCase) |
| | 1 | 60 | | { |
| | 1 | 61 | | ["processing"] = "проверяется", |
| | 1 | 62 | | ["failed"] = "проверка не пройдена", |
| | 1 | 63 | | ["passed"] = "проверка пройдена" |
| | 1 | 64 | | }; |
| | | 65 | | |
| | | 66 | | /// <summary> |
| | | 67 | | /// Разворачивает ответ /v6/fbs/posting/product/exemplar/create-or-get в плоский список |
| | | 68 | | /// требований по экземплярам. Возвращает только экземпляры, по которым что-то нужно заполнить. |
| | | 69 | | /// </summary> |
| | | 70 | | public static List<OzonExemplarRequirement> ParseRequirements(JObject? createOrGetResponse) |
| | | 71 | | { |
| | 5 | 72 | | var result = new List<OzonExemplarRequirement>(); |
| | 5 | 73 | | if (createOrGetResponse?["products"] is not JArray products) |
| | | 74 | | { |
| | 1 | 75 | | return result; |
| | | 76 | | } |
| | | 77 | | |
| | 14 | 78 | | foreach (var product in products.OfType<JObject>()) |
| | | 79 | | { |
| | 3 | 80 | | var productId = product["product_id"]?.Value<long>() ?? 0; |
| | 3 | 81 | | if (productId <= 0) |
| | | 82 | | { |
| | | 83 | | continue; |
| | | 84 | | } |
| | | 85 | | |
| | 3 | 86 | | var needsMandatoryMark = product["is_mandatory_mark_needed"]?.Value<bool>() ?? false; |
| | 3 | 87 | | var needsGtd = product["is_gtd_needed"]?.Value<bool>() ?? false; |
| | 3 | 88 | | var needsRnpt = product["is_rnpt_needed"]?.Value<bool>() ?? false; |
| | | 89 | | |
| | 3 | 90 | | var unsupported = new List<string>(); |
| | 3 | 91 | | if (product["is_weight_needed"]?.Value<bool>() ?? false) |
| | 1 | 92 | | unsupported.Add(UnsupportedRequirementNames["weight"]); |
| | 3 | 93 | | if (product["is_jw_uin_needed"]?.Value<bool>() ?? false) |
| | 0 | 94 | | unsupported.Add(UnsupportedRequirementNames["jw_uin"]); |
| | 3 | 95 | | if (product["has_imei"]?.Value<bool>() ?? false) |
| | 1 | 96 | | unsupported.Add(UnsupportedRequirementNames["imei"]); |
| | | 97 | | |
| | 3 | 98 | | if (!needsMandatoryMark && !needsGtd && !needsRnpt && unsupported.Count == 0) |
| | | 99 | | { |
| | | 100 | | continue; |
| | | 101 | | } |
| | | 102 | | |
| | 2 | 103 | | var exemplarIds = (product["exemplars"] as JArray)? |
| | 2 | 104 | | .OfType<JObject>() |
| | 3 | 105 | | .Select(exemplar => exemplar["exemplar_id"]?.Value<long>() ?? 0) |
| | 3 | 106 | | .Where(id => id > 0) |
| | 2 | 107 | | .ToList() ?? []; |
| | | 108 | | |
| | 2 | 109 | | var quantity = product["quantity"]?.Value<int>() ?? exemplarIds.Count; |
| | 2 | 110 | | if (quantity <= 0) |
| | | 111 | | { |
| | 0 | 112 | | quantity = Math.Max(exemplarIds.Count, 1); |
| | | 113 | | } |
| | | 114 | | |
| | 10 | 115 | | for (var index = 0; index < Math.Max(quantity, exemplarIds.Count); index++) |
| | | 116 | | { |
| | 3 | 117 | | result.Add(new OzonExemplarRequirement |
| | 3 | 118 | | { |
| | 3 | 119 | | ProductId = productId, |
| | 3 | 120 | | ExemplarId = index < exemplarIds.Count ? exemplarIds[index] : 0, |
| | 3 | 121 | | Index = index + 1, |
| | 3 | 122 | | Quantity = quantity, |
| | 3 | 123 | | NeedsMandatoryMark = needsMandatoryMark, |
| | 3 | 124 | | NeedsGtd = needsGtd, |
| | 3 | 125 | | NeedsRnpt = needsRnpt, |
| | 3 | 126 | | Unsupported = unsupported |
| | 3 | 127 | | }); |
| | | 128 | | } |
| | | 129 | | } |
| | | 130 | | |
| | 4 | 131 | | return result; |
| | | 132 | | } |
| | | 133 | | |
| | | 134 | | /// <summary> |
| | | 135 | | /// Разбирает ответ /v5/fbs/posting/product/exemplar/status. Готовность к сборке — |
| | | 136 | | /// <c>status = ship_available</c>; иначе собирает причины отказа по каждому экземпляру. |
| | | 137 | | /// </summary> |
| | | 138 | | public static bool IsShipAvailable(JObject? statusResponse, out IReadOnlyList<string> reasons) |
| | | 139 | | { |
| | 4 | 140 | | var status = statusResponse?["status"]?.Value<string>() ?? string.Empty; |
| | 4 | 141 | | if (status.Equals(ShipAvailableStatus, StringComparison.OrdinalIgnoreCase)) |
| | | 142 | | { |
| | 1 | 143 | | reasons = []; |
| | 1 | 144 | | return true; |
| | | 145 | | } |
| | | 146 | | |
| | 3 | 147 | | var collected = new List<string>(); |
| | | 148 | | |
| | 8 | 149 | | foreach (var product in (statusResponse?["products"] as JArray)?.OfType<JObject>() ?? []) |
| | | 150 | | { |
| | 1 | 151 | | var productId = product["product_id"]?.Value<long>() ?? 0; |
| | | 152 | | |
| | 4 | 153 | | foreach (var exemplar in (product["exemplars"] as JArray)?.OfType<JObject>() ?? []) |
| | | 154 | | { |
| | 4 | 155 | | foreach (var mark in (exemplar["marks"] as JArray)?.OfType<JObject>() ?? []) |
| | | 156 | | { |
| | 1 | 157 | | AddIfFailed(collected, productId, "код маркировки", |
| | 1 | 158 | | mark["check_status"]?.Value<string>(), mark["error_codes"] as JArray); |
| | | 159 | | } |
| | | 160 | | |
| | 1 | 161 | | AddIfFailed(collected, productId, "ГТД", |
| | 1 | 162 | | exemplar["gtd_check_status"]?.Value<string>(), exemplar["gtd_error_codes"] as JArray); |
| | 1 | 163 | | AddIfFailed(collected, productId, "РНПТ", |
| | 1 | 164 | | exemplar["rnpt_check_status"]?.Value<string>(), exemplar["rnpt_error_codes"] as JArray); |
| | 1 | 165 | | AddIfFailed(collected, productId, "вес", |
| | 1 | 166 | | exemplar["weight_check_status"]?.Value<string>(), exemplar["weight_error_codes"] as JArray); |
| | | 167 | | } |
| | | 168 | | } |
| | | 169 | | |
| | 3 | 170 | | if (collected.Count == 0) |
| | | 171 | | { |
| | 2 | 172 | | collected.Add(status.Equals(ValidationInProgressStatus, StringComparison.OrdinalIgnoreCase) |
| | 2 | 173 | | ? "Ozon ещё проверяет данные экземпляров. Подождите несколько секунд и повторите печать." |
| | 2 | 174 | | : "Ozon не подтвердил готовность отправления к сборке. Проверьте данные экземпляров."); |
| | | 175 | | } |
| | | 176 | | |
| | 3 | 177 | | reasons = collected; |
| | 3 | 178 | | return false; |
| | | 179 | | } |
| | | 180 | | |
| | | 181 | | private static void AddIfFailed(List<string> target, long productId, string fieldName, |
| | | 182 | | string? checkStatus, JArray? errorCodes) |
| | | 183 | | { |
| | 4 | 184 | | if (string.IsNullOrWhiteSpace(checkStatus) || |
| | 4 | 185 | | checkStatus.Equals("passed", StringComparison.OrdinalIgnoreCase)) |
| | | 186 | | { |
| | 3 | 187 | | return; |
| | | 188 | | } |
| | | 189 | | |
| | 1 | 190 | | var statusName = CheckStatusNames.TryGetValue(checkStatus, out var friendly) ? friendly : checkStatus; |
| | 1 | 191 | | var codes = errorCodes?.Values<string>() |
| | 1 | 192 | | .Where(code => !string.IsNullOrWhiteSpace(code)) |
| | 1 | 193 | | .ToList() ?? []; |
| | | 194 | | |
| | 1 | 195 | | var message = $"Товар {productId}, {fieldName}: {statusName}"; |
| | 1 | 196 | | if (codes.Count > 0) |
| | | 197 | | { |
| | 1 | 198 | | message += $" ({string.Join(", ", codes)})"; |
| | | 199 | | } |
| | | 200 | | |
| | 1 | 201 | | target.Add(message + "."); |
| | 1 | 202 | | } |
| | | 203 | | } |