| | | 1 | | using Microsoft.AspNetCore.Authorization; |
| | | 2 | | using Microsoft.AspNetCore.Mvc; |
| | | 3 | | using OzonOrdersWeb.Areas.Studio2.ViewModels.OneCStock; |
| | | 4 | | using OzonOrdersWeb.Authorization; |
| | | 5 | | using OzonRepositories.Data; |
| | | 6 | | using Services.ApiServices._1CApi.OData; |
| | | 7 | | using Services.ApiServices._1CApi.Stock; |
| | | 8 | | |
| | | 9 | | namespace OzonOrdersWeb.Areas.Studio2.Controllers; |
| | | 10 | | |
| | | 11 | | /// <summary> |
| | | 12 | | /// Раздел «Остатки 1С по складам»: номенклатура на выбранном складе с фильтром по сроку поступления. |
| | | 13 | | /// Данные читаются из 1С онлайн, поэтому страница отдаётся сразу, а таблица приходит отдельным AJAX. |
| | | 14 | | /// </summary> |
| | | 15 | | [Area("Studio2")] |
| | | 16 | | [Authorize(Roles = "User,Admin")] |
| | | 17 | | [Route("Studio2/OneCStock")] |
| | | 18 | | [Route("OneCStock")] |
| | | 19 | | public sealed class OneCStockController : Controller |
| | | 20 | | { |
| | | 21 | | private const int DefaultPageSize = 25; |
| | | 22 | | private const int MinPageSize = 10; |
| | | 23 | | private const int MaxPageSize = 100; |
| | | 24 | | private const int MaxOlderThanDays = 3650; |
| | | 25 | | private const int MaxRangeDays = 1095; |
| | | 26 | | |
| | | 27 | | private readonly IOneCWarehouseStockService _stockService; |
| | | 28 | | private readonly IOneCWarehouseStockExcelExporter _excelExporter; |
| | | 29 | | private readonly ProductRepository _productRepository; |
| | | 30 | | private readonly IOneCODataReferenceService _referenceService; |
| | | 31 | | |
| | 0 | 32 | | public OneCStockController( |
| | 0 | 33 | | IOneCWarehouseStockService stockService, |
| | 0 | 34 | | IOneCWarehouseStockExcelExporter excelExporter, |
| | 0 | 35 | | ProductRepository productRepository, |
| | 0 | 36 | | IOneCODataReferenceService referenceService) |
| | | 37 | | { |
| | 0 | 38 | | _stockService = stockService; |
| | 0 | 39 | | _excelExporter = excelExporter; |
| | 0 | 40 | | _productRepository = productRepository; |
| | 0 | 41 | | _referenceService = referenceService; |
| | 0 | 42 | | } |
| | | 43 | | |
| | | 44 | | [HttpGet("")] |
| | | 45 | | public async Task<IActionResult> Index(Guid? warehouse, CancellationToken cancellationToken = default) |
| | | 46 | | { |
| | 0 | 47 | | var warehousesTask = _stockService.GetWarehousesAsync(cancellationToken); |
| | 0 | 48 | | var suppliersTask = _referenceService.GetCounterpartiesAsync(); |
| | 0 | 49 | | await Task.WhenAll(warehousesTask, suppliersTask); |
| | 0 | 50 | | var warehouses = await warehousesTask; |
| | 0 | 51 | | var suppliers = await suppliersTask; |
| | | 52 | | |
| | 0 | 53 | | return View(new OneCStockIndexViewModel |
| | 0 | 54 | | { |
| | 0 | 55 | | Warehouses = warehouses, |
| | 0 | 56 | | Suppliers = suppliers |
| | 0 | 57 | | .Where(supplier => !string.IsNullOrWhiteSpace(supplier.Description)) |
| | 0 | 58 | | .OrderBy(supplier => supplier.Description, StringComparer.CurrentCulture) |
| | 0 | 59 | | .ToList(), |
| | 0 | 60 | | SelectedWarehouse = warehouse, |
| | 0 | 61 | | OneCUnavailable = warehouses.Count == 0 |
| | 0 | 62 | | }); |
| | 0 | 63 | | } |
| | | 64 | | |
| | | 65 | | /// <summary> |
| | | 66 | | /// Данные таблицы. Помечен <see cref="ServiceEndpointAttribute"/>: иначе авто-регистрация страниц |
| | | 67 | | /// заведёт псевдостраницу Studio2.OneCStock.Data и не-Admin получит 403 на запрос таблицы. |
| | | 68 | | /// </summary> |
| | | 69 | | [ServiceEndpoint] |
| | | 70 | | [HttpGet("data")] |
| | | 71 | | public async Task<IActionResult> Data( |
| | | 72 | | Guid warehouse, |
| | | 73 | | string mode = "none", |
| | | 74 | | int? olderThanDays = null, |
| | | 75 | | DateTime? receiptFrom = null, |
| | | 76 | | DateTime? receiptTo = null, |
| | | 77 | | string? article = null, |
| | | 78 | | string? producer = null, |
| | | 79 | | string documentType = "all", |
| | | 80 | | Guid? supplier = null, |
| | | 81 | | decimal minQty = 0m, |
| | | 82 | | string sort = "article", |
| | | 83 | | bool desc = false, |
| | | 84 | | int page = 1, |
| | | 85 | | int pageSize = DefaultPageSize, |
| | | 86 | | bool refresh = false, |
| | | 87 | | CancellationToken cancellationToken = default) |
| | | 88 | | { |
| | 0 | 89 | | var query = BuildQuery(warehouse, mode, olderThanDays, receiptFrom, receiptTo, |
| | 0 | 90 | | article, producer, documentType, supplier, minQty, sort, desc, page, pageSize, refresh); |
| | | 91 | | |
| | 0 | 92 | | var result = await _stockService.QueryAsync(query, cancellationToken); |
| | 0 | 93 | | var imageUrls = result.Failed |
| | 0 | 94 | | ? new Dictionary<string, string>() |
| | 0 | 95 | | : await _productRepository.GetImageUrlsByArticlesAsync( |
| | 0 | 96 | | result.Rows.Select(row => row.Article ?? string.Empty)); |
| | | 97 | | |
| | 0 | 98 | | return Ok(new |
| | 0 | 99 | | { |
| | 0 | 100 | | ok = !result.Failed, |
| | 0 | 101 | | error = result.Failed ? result.Warning : null, |
| | 0 | 102 | | warning = result.Failed ? null : result.Warning, |
| | 0 | 103 | | warehouseName = result.WarehouseName, |
| | 0 | 104 | | totalCount = result.TotalCount, |
| | 0 | 105 | | totalPositions = result.TotalPositions, |
| | 0 | 106 | | totalQuantity = result.TotalQuantityFiltered, |
| | 0 | 107 | | page = result.Page, |
| | 0 | 108 | | pageSize = result.PageSize, |
| | 0 | 109 | | snapshotAtUtc = result.SnapshotAtUtc, |
| | 0 | 110 | | items = result.Rows.Select(row => new |
| | 0 | 111 | | { |
| | 0 | 112 | | article = row.Article, |
| | 0 | 113 | | name = row.Name, |
| | 0 | 114 | | producer = row.Producer, |
| | 0 | 115 | | imageUrl = row.Article != null && imageUrls.TryGetValue(row.Article, out var imageUrl) |
| | 0 | 116 | | ? imageUrl |
| | 0 | 117 | | : null, |
| | 0 | 118 | | quantity = row.Quantity, |
| | 0 | 119 | | lastReceiptDate = row.LastReceiptDate, |
| | 0 | 120 | | daysOnStock = row.DaysOnStock, |
| | 0 | 121 | | lastReceiptDoc = row.LastReceiptDocNumber, |
| | 0 | 122 | | lastReceiptKind = row.LastReceiptDocKind, |
| | 0 | 123 | | lastReceiptSupplier = row.LastReceiptSupplier, |
| | 0 | 124 | | ageLabel = row.AgeBucket.HasValue |
| | 0 | 125 | | ? OneCWarehouseStockQueryBuilder.BucketLabel(row.AgeBucket.Value) |
| | 0 | 126 | | : null |
| | 0 | 127 | | }) |
| | 0 | 128 | | }); |
| | 0 | 129 | | } |
| | | 130 | | |
| | | 131 | | [HttpGet("export/excel")] |
| | | 132 | | public async Task<IActionResult> ExportExcel( |
| | | 133 | | Guid warehouse, |
| | | 134 | | string mode = "none", |
| | | 135 | | int? olderThanDays = null, |
| | | 136 | | DateTime? receiptFrom = null, |
| | | 137 | | DateTime? receiptTo = null, |
| | | 138 | | string? article = null, |
| | | 139 | | string? producer = null, |
| | | 140 | | string documentType = "all", |
| | | 141 | | Guid? supplier = null, |
| | | 142 | | decimal minQty = 0m, |
| | | 143 | | string sort = "article", |
| | | 144 | | bool desc = false, |
| | | 145 | | bool refresh = false, |
| | | 146 | | CancellationToken cancellationToken = default) |
| | | 147 | | { |
| | 0 | 148 | | var query = BuildQuery(warehouse, mode, olderThanDays, receiptFrom, receiptTo, |
| | 0 | 149 | | article, producer, documentType, supplier, minQty, sort, desc, page: 1, pageSize: MaxPageSize, refresh); |
| | 0 | 150 | | var export = await _excelExporter.ExportAsync(query, cancellationToken); |
| | 0 | 151 | | if (!export.Succeeded) |
| | 0 | 152 | | return BadRequest(new { error = export.Error }); |
| | | 153 | | |
| | 0 | 154 | | var fileName = $"onec-stock-{DateTime.Now:yyyyMMdd-HHmm}.xlsx"; |
| | 0 | 155 | | return File(export.Bytes!, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName); |
| | 0 | 156 | | } |
| | | 157 | | |
| | | 158 | | /// <summary>Приводит параметры запроса к безопасным границам — контроллер отвечает за валидацию входа.</summary> |
| | | 159 | | private static OneCWarehouseStockQuery BuildQuery( |
| | | 160 | | Guid warehouse, |
| | | 161 | | string mode, |
| | | 162 | | int? olderThanDays, |
| | | 163 | | DateTime? receiptFrom, |
| | | 164 | | DateTime? receiptTo, |
| | | 165 | | string? article, |
| | | 166 | | string? producer, |
| | | 167 | | string documentType, |
| | | 168 | | Guid? supplier, |
| | | 169 | | decimal minQty, |
| | | 170 | | string sort, |
| | | 171 | | bool desc, |
| | | 172 | | int page, |
| | | 173 | | int pageSize, |
| | | 174 | | bool refresh) |
| | | 175 | | { |
| | 0 | 176 | | var filterMode = mode switch |
| | 0 | 177 | | { |
| | 0 | 178 | | "older" => StockAgeFilterMode.OlderThanDays, |
| | 0 | 179 | | "range" => StockAgeFilterMode.ReceiptBetween, |
| | 0 | 180 | | _ => StockAgeFilterMode.None |
| | 0 | 181 | | }; |
| | | 182 | | |
| | 0 | 183 | | var days = olderThanDays.HasValue |
| | 0 | 184 | | ? Math.Clamp(olderThanDays.Value, 1, MaxOlderThanDays) |
| | 0 | 185 | | : (int?)null; |
| | | 186 | | |
| | 0 | 187 | | var to = receiptTo; |
| | 0 | 188 | | var from = receiptFrom; |
| | 0 | 189 | | if (filterMode == StockAgeFilterMode.ReceiptBetween) |
| | | 190 | | { |
| | 0 | 191 | | to ??= DateTime.Today; |
| | 0 | 192 | | from ??= to.Value.AddMonths(-1); |
| | | 193 | | // Слишком широкий диапазон превращает обороты в многостраничную выгрузку — режем сверху. |
| | 0 | 194 | | if ((to.Value - from.Value).TotalDays > MaxRangeDays) |
| | 0 | 195 | | from = to.Value.AddDays(-MaxRangeDays); |
| | | 196 | | } |
| | | 197 | | |
| | 0 | 198 | | var normalizedSort = sort switch |
| | 0 | 199 | | { |
| | 0 | 200 | | "qty" or "producer" or "age" => sort, |
| | 0 | 201 | | _ => "article" |
| | 0 | 202 | | }; |
| | | 203 | | |
| | 0 | 204 | | var normalizedDocumentType = documentType switch |
| | 0 | 205 | | { |
| | 0 | 206 | | "receipt" => ReceiptDocumentFilter.ReceiptInvoice, |
| | 0 | 207 | | "transfer" => ReceiptDocumentFilter.StockTransfer, |
| | 0 | 208 | | _ => ReceiptDocumentFilter.All |
| | 0 | 209 | | }; |
| | | 210 | | |
| | | 211 | | // У перемещения нет реквизита поставщика — не передаём несогласованную комбинацию в сервис. |
| | 0 | 212 | | if (normalizedDocumentType == ReceiptDocumentFilter.StockTransfer) |
| | 0 | 213 | | supplier = null; |
| | | 214 | | |
| | 0 | 215 | | return new OneCWarehouseStockQuery( |
| | 0 | 216 | | warehouse, |
| | 0 | 217 | | filterMode, |
| | 0 | 218 | | days, |
| | 0 | 219 | | from, |
| | 0 | 220 | | to, |
| | 0 | 221 | | string.IsNullOrWhiteSpace(article) ? null : article.Trim(), |
| | 0 | 222 | | string.IsNullOrWhiteSpace(producer) ? null : producer.Trim(), |
| | 0 | 223 | | minQty < 0 ? 0m : minQty, |
| | 0 | 224 | | normalizedSort, |
| | 0 | 225 | | desc, |
| | 0 | 226 | | Math.Max(1, page), |
| | 0 | 227 | | Math.Clamp(pageSize, MinPageSize, MaxPageSize), |
| | 0 | 228 | | refresh, |
| | 0 | 229 | | normalizedDocumentType, |
| | 0 | 230 | | supplier); |
| | | 231 | | } |
| | | 232 | | } |