| | | 1 | | using Microsoft.EntityFrameworkCore; |
| | | 2 | | using OzonDomains.Models.OzonHandover; |
| | | 3 | | using OzonRepositories.Context; |
| | | 4 | | |
| | | 5 | | namespace OzonRepositories.Data; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Репозиторий для импорта актов выдачи/приёма-передачи Ozon (формат "Telegram Lite"). |
| | | 9 | | /// </summary> |
| | | 10 | | public class OzonHandoverRepository : MainRepository |
| | | 11 | | { |
| | 6 | 12 | | public OzonHandoverRepository(ApplicationDbContext context) : base(context) |
| | | 13 | | { |
| | 6 | 14 | | } |
| | | 15 | | |
| | | 16 | | /// <summary>Найти существующий батч по ключу идемпотентности closed.id.</summary> |
| | | 17 | | public async Task<OzonHandoverImportBatch?> GetByClosedIdAsync(string closedId, CancellationToken ct = default) |
| | | 18 | | { |
| | 7 | 19 | | return await _context.OzonHandoverImportBatches |
| | 7 | 20 | | .FirstOrDefaultAsync(b => b.ClosedId == closedId, ct); |
| | 7 | 21 | | } |
| | | 22 | | |
| | | 23 | | /// <summary> |
| | | 24 | | /// Сохраняет батч. Если батч с таким ClosedId уже существует, слияние идёт поштучно: |
| | | 25 | | /// акт сопоставляется по (ActNo, ActDate, Pvz, ActType), позиция внутри акта — по ReturnId |
| | | 26 | | /// (а если его нет — по ItemNo+RowNo). Совпавшая позиция обновляется на месте (EF не шлёт |
| | | 27 | | /// UPDATE, если данные не изменились), несовпавшая — добавляется как новая. Повторный импорт |
| | | 28 | | /// того же документа не плодит дублей и не пересоздаёт то, что не изменилось. |
| | | 29 | | /// </summary> |
| | | 30 | | public async Task<OzonHandoverImportBatch> UpsertBatchAsync(OzonHandoverImportBatch batch, CancellationToken ct = de |
| | | 31 | | { |
| | 8 | 32 | | OzonHandoverImportBatch? existing = null; |
| | 8 | 33 | | if (!string.IsNullOrEmpty(batch.ClosedId)) |
| | | 34 | | { |
| | 8 | 35 | | existing = await _context.OzonHandoverImportBatches |
| | 8 | 36 | | .Include(b => b.Acts) |
| | 8 | 37 | | .ThenInclude(a => a.Items) |
| | 8 | 38 | | .ThenInclude(i => i.Photos) |
| | 8 | 39 | | .AsSplitQuery() |
| | 8 | 40 | | .FirstOrDefaultAsync(b => b.ClosedId == batch.ClosedId, ct); |
| | | 41 | | } |
| | | 42 | | |
| | 8 | 43 | | if (existing == null) |
| | | 44 | | { |
| | 20 | 45 | | foreach (var act in batch.Acts) |
| | 5 | 46 | | RecomputeActSummary(act); |
| | | 47 | | |
| | 5 | 48 | | batch.ImportedAt = DateTime.UtcNow; |
| | 5 | 49 | | batch.UpdatedAt = DateTime.UtcNow; |
| | 5 | 50 | | await _context.OzonHandoverImportBatches.AddAsync(batch, ct); |
| | 5 | 51 | | await _context.SaveChangesAsync(ct); |
| | 5 | 52 | | return batch; |
| | | 53 | | } |
| | | 54 | | |
| | 3 | 55 | | existing.DocumentType = batch.DocumentType; |
| | 3 | 56 | | existing.GeneratedAt = batch.GeneratedAt; |
| | 3 | 57 | | existing.ReturnType = batch.ReturnType; |
| | 3 | 58 | | existing.ClosedKind = batch.ClosedKind; |
| | 3 | 59 | | existing.SummaryActsCount = batch.SummaryActsCount; |
| | 3 | 60 | | existing.SummaryItemsCount = batch.SummaryItemsCount; |
| | 3 | 61 | | existing.SummaryTotalValue = batch.SummaryTotalValue; |
| | 3 | 62 | | existing.SummaryAcceptedItemsCount = batch.SummaryAcceptedItemsCount; |
| | 3 | 63 | | existing.SummaryAcceptedValue = batch.SummaryAcceptedValue; |
| | 3 | 64 | | existing.SummaryRejectedItemsCount = batch.SummaryRejectedItemsCount; |
| | 3 | 65 | | existing.SummaryRejectedValue = batch.SummaryRejectedValue; |
| | 3 | 66 | | existing.SummaryPendingItemsCount = batch.SummaryPendingItemsCount; |
| | 3 | 67 | | existing.SummaryPendingValue = batch.SummaryPendingValue; |
| | 3 | 68 | | existing.SummaryDefectCount = batch.SummaryDefectCount; |
| | 3 | 69 | | existing.SummaryMissortCount = batch.SummaryMissortCount; |
| | 3 | 70 | | existing.MatchedItemsCount = batch.MatchedItemsCount; |
| | 3 | 71 | | existing.UnmatchedItemsCount = batch.UnmatchedItemsCount; |
| | 3 | 72 | | existing.RawJson = batch.RawJson; |
| | 3 | 73 | | existing.UpdatedAt = DateTime.UtcNow; |
| | | 74 | | |
| | 10 | 75 | | foreach (var incomingAct in batch.Acts) |
| | | 76 | | { |
| | 4 | 77 | | var existingAct = existing.Acts.FirstOrDefault(a => IsSameAct(a, incomingAct)); |
| | 2 | 78 | | if (existingAct == null) |
| | | 79 | | { |
| | 0 | 80 | | RecomputeActSummary(incomingAct); |
| | 0 | 81 | | existing.Acts.Add(incomingAct); |
| | 0 | 82 | | continue; |
| | | 83 | | } |
| | | 84 | | |
| | 2 | 85 | | existingAct.GroupKey = incomingAct.GroupKey; |
| | 2 | 86 | | existingAct.GroupName = incomingAct.GroupName; |
| | 2 | 87 | | existingAct.Source = incomingAct.Source; |
| | 2 | 88 | | existingAct.AccountLabel = incomingAct.AccountLabel; |
| | 2 | 89 | | existingAct.ReturnType = incomingAct.ReturnType; |
| | 2 | 90 | | existingAct.BoxBarcode = incomingAct.BoxBarcode; |
| | 2 | 91 | | existingAct.ReturnId = incomingAct.ReturnId; |
| | | 92 | | |
| | 8 | 93 | | foreach (var incomingItem in incomingAct.Items) |
| | | 94 | | { |
| | 4 | 95 | | var existingItem = existingAct.Items.FirstOrDefault(i => IsSameItem(i, incomingItem)); |
| | 2 | 96 | | if (existingItem == null) |
| | | 97 | | { |
| | 0 | 98 | | existingAct.Items.Add(incomingItem); |
| | 0 | 99 | | continue; |
| | | 100 | | } |
| | | 101 | | |
| | 2 | 102 | | existingItem.OrderId = incomingItem.OrderId; |
| | 2 | 103 | | existingItem.RowNo = incomingItem.RowNo; |
| | 2 | 104 | | existingItem.ItemNo = incomingItem.ItemNo; |
| | 2 | 105 | | existingItem.ProductName = incomingItem.ProductName; |
| | 2 | 106 | | existingItem.Barcode = incomingItem.Barcode; |
| | 2 | 107 | | existingItem.Value = incomingItem.Value; |
| | 2 | 108 | | existingItem.ValueApi = incomingItem.ValueApi; |
| | 2 | 109 | | existingItem.WeightG = incomingItem.WeightG; |
| | 2 | 110 | | existingItem.Status = incomingItem.Status; |
| | 2 | 111 | | existingItem.Defect = incomingItem.Defect; |
| | 2 | 112 | | existingItem.Missort = incomingItem.Missort; |
| | 2 | 113 | | existingItem.Comment = incomingItem.Comment; |
| | 2 | 114 | | existingItem.MarkedAt = incomingItem.MarkedAt; |
| | 2 | 115 | | existingItem.Sku = incomingItem.Sku; |
| | 2 | 116 | | existingItem.OfferId = incomingItem.OfferId; |
| | 2 | 117 | | existingItem.AccountLabel = incomingItem.AccountLabel; |
| | 2 | 118 | | existingItem.ReturnId = incomingItem.ReturnId; |
| | 2 | 119 | | existingItem.OzonStatus = incomingItem.OzonStatus; |
| | 2 | 120 | | existingItem.OzonStatusName = incomingItem.OzonStatusName; |
| | 2 | 121 | | existingItem.ReturnType = incomingItem.ReturnType; |
| | 2 | 122 | | existingItem.BoxBarcode = incomingItem.BoxBarcode; |
| | 2 | 123 | | existingItem.Reason = incomingItem.Reason; |
| | 2 | 124 | | existingItem.ReasonIsDefect = incomingItem.ReasonIsDefect; |
| | 2 | 125 | | existingItem.ClientComment = incomingItem.ClientComment; |
| | 2 | 126 | | existingItem.ClientPhotosExpiresAt = incomingItem.ClientPhotosExpiresAt; |
| | 2 | 127 | | existingItem.PhotosCount = incomingItem.PhotosCount; |
| | 2 | 128 | | existingItem.PhotosError = incomingItem.PhotosError; |
| | 2 | 129 | | existingItem.RejectionComment = incomingItem.RejectionComment; |
| | 2 | 130 | | existingItem.RejectionReason = incomingItem.RejectionReason; |
| | 2 | 131 | | existingItem.RuPostTracking = incomingItem.RuPostTracking; |
| | 2 | 132 | | existingItem.ReturnNumber = incomingItem.ReturnNumber; |
| | 2 | 133 | | existingItem.OrderNumber = incomingItem.OrderNumber; |
| | 2 | 134 | | existingItem.ClientReturnMethod = incomingItem.ClientReturnMethod; |
| | 2 | 135 | | existingItem.WarehouseId = incomingItem.WarehouseId; |
| | | 136 | | // При повторном импорте с уже истёкшими временными URL не теряем ранее |
| | | 137 | | // скачанные фотографии. Пустой список без ошибки означает, что источник |
| | | 138 | | // действительно больше не передал фото и должен очистить галерею. |
| | 2 | 139 | | if (incomingItem.Photos.Count > 0 || string.IsNullOrWhiteSpace(incomingItem.PhotosError)) |
| | | 140 | | { |
| | 1 | 141 | | _context.OzonHandoverActItemPhotos.RemoveRange(existingItem.Photos); |
| | 1 | 142 | | existingItem.Photos.Clear(); |
| | 1 | 143 | | existingItem.Photos.AddRange(incomingItem.Photos); |
| | | 144 | | } |
| | | 145 | | } |
| | | 146 | | |
| | 2 | 147 | | RecomputeActSummary(existingAct); |
| | | 148 | | } |
| | | 149 | | |
| | 3 | 150 | | await _context.SaveChangesAsync(ct); |
| | 3 | 151 | | return existing; |
| | 8 | 152 | | } |
| | | 153 | | |
| | | 154 | | /// <summary>Один и тот же акт при повторном импорте: совпадают номер, дата, ПВЗ и тип акта.</summary> |
| | | 155 | | private static bool IsSameAct(OzonHandoverAct existing, OzonHandoverAct incoming) => |
| | 2 | 156 | | string.Equals(existing.ActNo, incoming.ActNo, StringComparison.OrdinalIgnoreCase) && |
| | 2 | 157 | | existing.ActDate == incoming.ActDate && |
| | 2 | 158 | | string.Equals(existing.Pvz, incoming.Pvz, StringComparison.OrdinalIgnoreCase) && |
| | 2 | 159 | | string.Equals(existing.ActType, incoming.ActType, StringComparison.OrdinalIgnoreCase); |
| | | 160 | | |
| | | 161 | | /// <summary> |
| | | 162 | | /// Одна и та же позиция при повторном импорте: приоритет — ReturnId (идентификатор возврата |
| | | 163 | | /// в Ozon, стабилен между экспортами). Если его нет ни у той, ни у другой стороны — запасной |
| | | 164 | | /// ключ ItemNo+RowNo. |
| | | 165 | | /// </summary> |
| | | 166 | | private static bool IsSameItem(OzonHandoverActItem existing, OzonHandoverActItem incoming) |
| | | 167 | | { |
| | 2 | 168 | | if (existing.ReturnId.HasValue && incoming.ReturnId.HasValue) |
| | 2 | 169 | | return existing.ReturnId == incoming.ReturnId; |
| | | 170 | | |
| | 0 | 171 | | return string.Equals(existing.ItemNo, incoming.ItemNo, StringComparison.OrdinalIgnoreCase) && |
| | 0 | 172 | | existing.RowNo == incoming.RowNo; |
| | | 173 | | } |
| | | 174 | | |
| | | 175 | | /// <summary> |
| | | 176 | | /// Статус и денормализованную сводку акта пересчитываем из его текущего набора позиций — |
| | | 177 | | /// единообразно и для новых актов, и для слитых с уже существующими. |
| | | 178 | | /// </summary> |
| | | 179 | | private static void RecomputeActSummary(OzonHandoverAct act) |
| | | 180 | | { |
| | 7 | 181 | | act.ItemsCount = act.Items.Count; |
| | 14 | 182 | | act.TotalValue = act.Items.Sum(i => i.Value); |
| | 14 | 183 | | act.AcceptedCount = act.Items.Count(i => IsStatus(i, "accepted")); |
| | 14 | 184 | | act.RejectedCount = act.Items.Count(i => IsStatus(i, "rejected")); |
| | 14 | 185 | | act.PendingCount = act.Items.Count(i => IsStatus(i, "pending")); |
| | 14 | 186 | | act.DefectCount = act.Items.Count(i => i.Defect); |
| | 14 | 187 | | act.MissortCount = act.Items.Count(i => i.Missort); |
| | 7 | 188 | | act.Status = ComputeActStatus(act.Items); |
| | 7 | 189 | | } |
| | | 190 | | |
| | | 191 | | private static bool IsStatus(OzonHandoverActItem item, string status) => |
| | 35 | 192 | | string.Equals(item.Status, status, StringComparison.OrdinalIgnoreCase); |
| | | 193 | | |
| | | 194 | | /// <summary> |
| | | 195 | | /// Статус акта — только accepted / rejected / partially_accepted (как в источнике, |
| | | 196 | | /// см. _act_status()); "pending" на уровне акта не существует. Все позиции accepted → |
| | | 197 | | /// accepted; все rejected → rejected; любая иная смесь (включая pending) — partially_accepted. |
| | | 198 | | /// </summary> |
| | | 199 | | private static string ComputeActStatus(IReadOnlyCollection<OzonHandoverActItem> items) |
| | | 200 | | { |
| | 7 | 201 | | if (items.Count == 0) |
| | 0 | 202 | | return "partially_accepted"; |
| | | 203 | | |
| | 14 | 204 | | if (items.All(i => IsStatus(i, "accepted"))) |
| | 0 | 205 | | return "accepted"; |
| | | 206 | | |
| | 14 | 207 | | if (items.All(i => IsStatus(i, "rejected"))) |
| | 0 | 208 | | return "rejected"; |
| | | 209 | | |
| | 7 | 210 | | return "partially_accepted"; |
| | | 211 | | } |
| | | 212 | | |
| | | 213 | | public async Task<List<OzonHandoverActItem>> GetItemsByOrderIdsAsync(IEnumerable<int> orderIds, CancellationToken ct |
| | | 214 | | { |
| | 0 | 215 | | var ids = orderIds.Distinct().ToList(); |
| | 0 | 216 | | if (ids.Count == 0) |
| | 0 | 217 | | return new List<OzonHandoverActItem>(); |
| | | 218 | | |
| | 0 | 219 | | return await _context.OzonHandoverActItems |
| | 0 | 220 | | .AsNoTracking() |
| | 0 | 221 | | .Include(i => i.Act) |
| | 0 | 222 | | .Include(i => i.Photos) |
| | 0 | 223 | | .Where(i => i.OrderId != null && ids.Contains(i.OrderId.Value)) |
| | 0 | 224 | | .ToListAsync(ct); |
| | 0 | 225 | | } |
| | | 226 | | |
| | | 227 | | public async Task<OzonHandoverImportBatch?> GetByIdWithDetailsAsync(int id, CancellationToken ct = default) |
| | | 228 | | { |
| | 1 | 229 | | return await _context.OzonHandoverImportBatches |
| | 1 | 230 | | .AsNoTracking() |
| | 1 | 231 | | .Include(b => b.Acts) |
| | 1 | 232 | | .ThenInclude(a => a.Items) |
| | 1 | 233 | | .AsSplitQuery() |
| | 1 | 234 | | .FirstOrDefaultAsync(b => b.Id == id, ct); |
| | 1 | 235 | | } |
| | | 236 | | } |