| | | 1 | | using System.Linq.Expressions; |
| | | 2 | | using Hangfire; |
| | | 3 | | using Microsoft.AspNetCore.Mvc; |
| | | 4 | | using Microsoft.EntityFrameworkCore; |
| | | 5 | | using OzonDomains.Models.ArmtekEtp; |
| | | 6 | | using OzonDomains.Models.Authorization.Enums; |
| | | 7 | | using OzonOrdersWeb.Areas.Settlements.Models; |
| | | 8 | | using OzonOrdersWeb.Authorization; |
| | | 9 | | using OzonOrdersWeb.WebServices.ArmtekEtp; |
| | | 10 | | using OzonOrdersWeb.WebServices.Grid; |
| | | 11 | | using OzonRepositories.Context; |
| | | 12 | | using Services.ApiServices.ArmtekEtp; |
| | | 13 | | using Services.ArmtekEtpServices; |
| | | 14 | | |
| | | 15 | | namespace OzonOrdersWeb.Areas.Settlements.Controllers; |
| | | 16 | | |
| | | 17 | | /// <summary> |
| | | 18 | | /// Раздел «Взаиморасчёты Armtek»: данные из кабинета etp.armtek.ru, которые выгружает <see cref="ArmtekEtpSyncJob"/>. |
| | | 19 | | /// Три серверных грида (взаиморасчёты, фактуры, позиции фактур), страница фактуры и запуск загрузки за период. |
| | | 20 | | /// </summary> |
| | | 21 | | [Area("Settlements")] |
| | | 22 | | [Route("Settlements/Armtek")] |
| | 0 | 23 | | public sealed class ArmtekController( |
| | 0 | 24 | | ApplicationDbContext db, |
| | 0 | 25 | | IBackgroundJobClient jobs, |
| | 0 | 26 | | ArmtekEtpSyncService sync, |
| | 0 | 27 | | SettlementSuppliersOverview overview, |
| | 0 | 28 | | ILogger<ArmtekController> logger) : Controller |
| | | 29 | | { |
| | | 30 | | private const string PageCode = "Settlements.Armtek.Index"; |
| | 0 | 31 | | private static readonly string[] Tabs = ["settlements", "invoices", "items"]; |
| | | 32 | | |
| | | 33 | | [HttpGet("")] |
| | | 34 | | [PageAuthorize(PageCode, AccessType.View)] |
| | | 35 | | public async Task<IActionResult> Index(string? tab, CancellationToken ct) |
| | | 36 | | { |
| | 0 | 37 | | tab = Tabs.Contains(tab) ? tab! : "settlements"; |
| | 0 | 38 | | var summary = await overview.GetArmtekSummaryAsync(ct); |
| | 0 | 39 | | return View(new ArmtekSettlementsPageViewModel |
| | 0 | 40 | | { |
| | 0 | 41 | | Tab = tab, |
| | 0 | 42 | | SettlementsCount = summary.SettlementsCount, |
| | 0 | 43 | | InvoicesCount = summary.InvoicesCount, |
| | 0 | 44 | | ItemsCount = summary.ItemsCount, |
| | 0 | 45 | | LastUpdatedAtUtc = summary.LastUpdatedAtUtc, |
| | 0 | 46 | | LastError = summary.LastError, |
| | 0 | 47 | | LastErrorAtUtc = summary.LastErrorAtUtc, |
| | 0 | 48 | | Schedule = overview.ScheduleText, |
| | 0 | 49 | | Balance = summary.Balance, |
| | 0 | 50 | | BalanceCurrency = summary.BalanceCurrency, |
| | 0 | 51 | | BalanceDate = summary.BalanceDate, |
| | 0 | 52 | | CanSync = User.IsInRole("Admin") || User.IsInRole(Services.Authorization.AuthorizationConstants.SuperAdminRo |
| | 0 | 53 | | }); |
| | 0 | 54 | | } |
| | | 55 | | |
| | | 56 | | // ---------- Взаиморасчёты ---------- |
| | | 57 | | |
| | | 58 | | [HttpPost("settlements/grid")] |
| | | 59 | | [ValidateAntiForgeryToken] |
| | | 60 | | [PageAuthorize(PageCode, AccessType.View)] |
| | | 61 | | public async Task<IActionResult> SettlementsGrid([FromBody] ServerGridRequest? request, CancellationToken ct) |
| | | 62 | | { |
| | 0 | 63 | | var page = await PageAsync(db.ArmtekSettlements.AsNoTracking(), ArmtekEtpGridDefinitions.Settlements, request, c |
| | 0 | 64 | | if (page.Error != null) return BadRequest(new { success = false, error = page.Error }); |
| | | 65 | | |
| | 0 | 66 | | var vbelns = page.Rows.Select(x => x.Vbeln).Distinct().ToList(); |
| | 0 | 67 | | var invoices = await db.ArmtekInvoices.AsNoTracking() |
| | 0 | 68 | | .Where(x => vbelns.Contains(x.Vbeln)) |
| | 0 | 69 | | .Select(x => new { x.Id, x.Kunnr, x.Vbeln }) |
| | 0 | 70 | | .ToListAsync(ct); |
| | 0 | 71 | | var invoiceIds = invoices.ToDictionary(x => (x.Kunnr, x.Vbeln), x => x.Id); |
| | | 72 | | |
| | 0 | 73 | | var rows = page.Rows.Select(x => new |
| | 0 | 74 | | { |
| | 0 | 75 | | x.Id, x.Kunnr, x.ClientName, x.DocDate, x.Vbeln, x.DocType, x.DocTypeName, x.DocNumber, x.PrintNumber, |
| | 0 | 76 | | x.PaymentMethodName, x.Amount, x.PayUntil, x.ReturnAmount, x.PaymentAmount, x.RemainderAmount, x.Balance, |
| | 0 | 77 | | x.Contract, x.Currency, x.DivisionName, x.CompanyName, x.UpdatedAtUtc, |
| | 0 | 78 | | HasInvoicePage = x.DocType != null && ArmtekEtpSyncService.InvoiceDocTypes.Contains(x.DocType), |
| | 0 | 79 | | InvoiceId = invoiceIds.TryGetValue((x.Kunnr, x.Vbeln), out var id) ? id : (long?)null |
| | 0 | 80 | | }).ToList(); |
| | 0 | 81 | | return Ok(new { success = true, rows, totalCount = page.Total, lastRow = page.LastRow(rows.Count) }); |
| | 0 | 82 | | } |
| | | 83 | | |
| | | 84 | | [HttpPost("settlements/grid/facets")] |
| | | 85 | | [ValidateAntiForgeryToken] |
| | | 86 | | [PageAuthorize(PageCode, AccessType.View)] |
| | | 87 | | public Task<IActionResult> SettlementsFacets([FromBody] ServerGridRequest? request, CancellationToken ct) => |
| | 0 | 88 | | FacetsAsync(db.ArmtekSettlements.AsNoTracking(), ArmtekEtpGridDefinitions.Settlements, request, ct); |
| | | 89 | | |
| | | 90 | | // ---------- Фактуры ---------- |
| | | 91 | | |
| | | 92 | | [HttpPost("invoices/grid")] |
| | | 93 | | [ValidateAntiForgeryToken] |
| | | 94 | | [PageAuthorize(PageCode, AccessType.View)] |
| | | 95 | | public async Task<IActionResult> InvoicesGrid([FromBody] ServerGridRequest? request, CancellationToken ct) |
| | | 96 | | { |
| | 0 | 97 | | var page = await PageAsync(db.ArmtekInvoices.AsNoTracking(), ArmtekEtpGridDefinitions.Invoices, request, ct, |
| | 0 | 98 | | x => new ArmtekInvoice |
| | 0 | 99 | | { |
| | 0 | 100 | | Id = x.Id, Kunnr = x.Kunnr, Vbeln = x.Vbeln, InvoiceDate = x.InvoiceDate, CreatedAt = x.CreatedAt, |
| | 0 | 101 | | CreatedBy = x.CreatedBy, BuyerCode = x.BuyerCode, BuyerName = x.BuyerName, |
| | 0 | 102 | | UnloadingPointName = x.UnloadingPointName, DeliveryAddress = x.DeliveryAddress, Contact = x.Contact, |
| | 0 | 103 | | ReceiveMethod = x.ReceiveMethod, DeliveryStatus = x.DeliveryStatus, UpdNumber = x.UpdNumber, |
| | 0 | 104 | | TtnNumber = x.TtnNumber, TotalAmount = x.TotalAmount, TotalQuantity = x.TotalQuantity, |
| | 0 | 105 | | ReturnedQuantity = x.ReturnedQuantity, LoadedAtUtc = x.LoadedAtUtc, OrderNumber = x.OrderNumber, |
| | 0 | 106 | | OrderType = x.OrderType, OrderStatus = x.OrderStatus, ReturnReason = x.ReturnReason, |
| | 0 | 107 | | PickupPointName = x.PickupPointName, Payment = x.Payment, Contract = x.Contract, Currency = x.Currency, |
| | 0 | 108 | | MaxReturnSum = x.MaxReturnSum, Source = x.Source |
| | 0 | 109 | | }); |
| | 0 | 110 | | if (page.Error != null) return BadRequest(new { success = false, error = page.Error }); |
| | | 111 | | |
| | 0 | 112 | | var rows = page.Rows.Select(x => new |
| | 0 | 113 | | { |
| | 0 | 114 | | x.Id, x.Kunnr, x.Vbeln, x.InvoiceDate, x.CreatedAt, x.CreatedBy, x.BuyerCode, x.BuyerName, |
| | 0 | 115 | | x.UnloadingPointName, x.DeliveryAddress, x.Contact, x.ReceiveMethod, x.DeliveryStatus, x.UpdNumber, |
| | 0 | 116 | | x.TtnNumber, x.TotalAmount, x.TotalQuantity, x.ReturnedQuantity, x.LoadedAtUtc, x.OrderNumber, x.OrderType, |
| | 0 | 117 | | x.OrderStatus, x.ReturnReason, x.PickupPointName, x.Payment, x.Contract, x.Currency, x.MaxReturnSum, |
| | 0 | 118 | | Source = x.Source == ArmtekEtpSyncService.ApiSource ? "API" : "Кабинет" |
| | 0 | 119 | | }).ToList(); |
| | 0 | 120 | | return Ok(new { success = true, rows, totalCount = page.Total, lastRow = page.LastRow(rows.Count) }); |
| | 0 | 121 | | } |
| | | 122 | | |
| | | 123 | | [HttpPost("invoices/grid/facets")] |
| | | 124 | | [ValidateAntiForgeryToken] |
| | | 125 | | [PageAuthorize(PageCode, AccessType.View)] |
| | | 126 | | public Task<IActionResult> InvoicesFacets([FromBody] ServerGridRequest? request, CancellationToken ct) => |
| | 0 | 127 | | FacetsAsync(db.ArmtekInvoices.AsNoTracking(), ArmtekEtpGridDefinitions.Invoices, request, ct); |
| | | 128 | | |
| | | 129 | | // ---------- Позиции фактур ---------- |
| | | 130 | | |
| | | 131 | | [HttpPost("items/grid")] |
| | | 132 | | [ValidateAntiForgeryToken] |
| | | 133 | | [PageAuthorize(PageCode, AccessType.View)] |
| | | 134 | | public async Task<IActionResult> ItemsGrid([FromBody] ServerGridRequest? request, CancellationToken ct) |
| | | 135 | | { |
| | 0 | 136 | | var page = await PageAsync(ItemsSource(request), ArmtekEtpGridDefinitions.Items, request, ct, |
| | 0 | 137 | | x => new ArmtekInvoiceItem |
| | 0 | 138 | | { |
| | 0 | 139 | | Id = x.Id, InvoiceId = x.InvoiceId, Position = x.Position, ArmtekCode = x.ArmtekCode, Article = x.Articl |
| | 0 | 140 | | Brand = x.Brand, Name = x.Name, FullName = x.FullName, Price = x.Price, Quantity = x.Quantity, |
| | 0 | 141 | | Returned = x.Returned, Amount = x.Amount, OrderNumber = x.OrderNumber, OrderPosition = x.OrderPosition, |
| | 0 | 142 | | Note = x.Note, Gtd = x.Gtd, Country = x.Country, MaxReturnDate = x.MaxReturnDate, NoReturn = x.NoReturn, |
| | 0 | 143 | | ReturnDays = x.ReturnDays, VatRate = x.VatRate, VatAmount = x.VatAmount, Ean = x.Ean, Tnved = x.Tnved, W |
| | 0 | 144 | | Invoice = new ArmtekInvoice |
| | 0 | 145 | | { |
| | 0 | 146 | | Kunnr = x.Invoice!.Kunnr, Vbeln = x.Invoice.Vbeln, InvoiceDate = x.Invoice.InvoiceDate, |
| | 0 | 147 | | OrderType = x.Invoice.OrderType, ReturnReason = x.Invoice.ReturnReason |
| | 0 | 148 | | } |
| | 0 | 149 | | }); |
| | 0 | 150 | | if (page.Error != null) return BadRequest(new { success = false, error = page.Error }); |
| | | 151 | | |
| | 0 | 152 | | var rows = page.Rows.Select(x => new |
| | 0 | 153 | | { |
| | 0 | 154 | | x.Id, x.InvoiceId, x.Invoice!.Kunnr, x.Invoice.Vbeln, x.Invoice.InvoiceDate, x.Position, x.ArmtekCode, |
| | 0 | 155 | | x.Article, x.Brand, x.Name, x.FullName, x.Price, x.Quantity, x.Returned, x.Amount, x.OrderNumber, |
| | 0 | 156 | | x.OrderPosition, x.Note, x.Gtd, x.Country, x.MaxReturnDate, x.NoReturn, x.ReturnDays, x.VatRate, x.VatAmount |
| | 0 | 157 | | x.Ean, x.Tnved, x.Weight, x.Invoice.OrderType, x.Invoice.ReturnReason |
| | 0 | 158 | | }).ToList(); |
| | 0 | 159 | | return Ok(new { success = true, rows, totalCount = page.Total, lastRow = page.LastRow(rows.Count) }); |
| | 0 | 160 | | } |
| | | 161 | | |
| | | 162 | | [HttpPost("items/grid/facets")] |
| | | 163 | | [ValidateAntiForgeryToken] |
| | | 164 | | [PageAuthorize(PageCode, AccessType.View)] |
| | | 165 | | public Task<IActionResult> ItemsFacets([FromBody] ServerGridRequest? request, CancellationToken ct) => |
| | 0 | 166 | | FacetsAsync(ItemsSource(request), ArmtekEtpGridDefinitions.Items, request, ct); |
| | | 167 | | |
| | | 168 | | /// <summary>Позиции одной фактуры, если грид открыт со страницы фактуры (?invoiceId=).</summary> |
| | | 169 | | private IQueryable<ArmtekInvoiceItem> ItemsSource(ServerGridRequest? request) |
| | | 170 | | { |
| | 0 | 171 | | IQueryable<ArmtekInvoiceItem> source = db.ArmtekInvoiceItems.AsNoTracking(); |
| | 0 | 172 | | if (request != null && request.Params.TryGetValue("invoiceId", out var raw) && long.TryParse(raw, out var invoic |
| | 0 | 173 | | source = source.Where(x => x.InvoiceId == invoiceId); |
| | 0 | 174 | | return source; |
| | | 175 | | } |
| | | 176 | | |
| | | 177 | | // ---------- Фактура ---------- |
| | | 178 | | |
| | | 179 | | [HttpGet("Invoice/{kunnr}/{vbeln}")] |
| | | 180 | | [PageAuthorize(PageCode, AccessType.View)] |
| | | 181 | | public async Task<IActionResult> Invoice(string kunnr, string vbeln, CancellationToken ct) |
| | | 182 | | { |
| | 0 | 183 | | var invoice = await db.ArmtekInvoices.AsNoTracking() |
| | 0 | 184 | | .SingleOrDefaultAsync(x => x.Kunnr == kunnr && x.Vbeln == vbeln, ct); |
| | 0 | 185 | | var settlement = await db.ArmtekSettlements.AsNoTracking() |
| | 0 | 186 | | .SingleOrDefaultAsync(x => x.Kunnr == kunnr && x.Vbeln == vbeln, ct); |
| | 0 | 187 | | if (invoice == null && settlement == null) |
| | 0 | 188 | | return NotFound(); |
| | | 189 | | |
| | 0 | 190 | | return View(ArmtekInvoicePageViewModel.Build(kunnr, vbeln, invoice, settlement)); |
| | 0 | 191 | | } |
| | | 192 | | |
| | | 193 | | [HttpPost("Invoice/{kunnr}/{vbeln}/reload")] |
| | | 194 | | [ValidateAntiForgeryToken] |
| | | 195 | | [PageAuthorize(PageCode, AccessType.Edit)] |
| | | 196 | | public async Task<IActionResult> ReloadInvoice(string kunnr, string vbeln, CancellationToken ct) |
| | | 197 | | { |
| | | 198 | | try |
| | | 199 | | { |
| | 0 | 200 | | await sync.LoadInvoiceAsync(kunnr, vbeln, ct); |
| | 0 | 201 | | TempData["Success"] = $"Фактура {vbeln} загружена из кабинета Armtek."; |
| | 0 | 202 | | } |
| | 0 | 203 | | catch (Exception ex) when (ex is ArmtekEtpException or HttpRequestException or TaskCanceledException) |
| | | 204 | | { |
| | 0 | 205 | | logger.LogWarning(ex, "Armtek ETP: фактура {Kunnr}/{Vbeln} не загружена со страницы", kunnr, vbeln); |
| | 0 | 206 | | TempData["Error"] = $"Не удалось загрузить фактуру {vbeln}: {ex.Message}"; |
| | 0 | 207 | | } |
| | 0 | 208 | | return RedirectToAction(nameof(Invoice), new { kunnr, vbeln }); |
| | 0 | 209 | | } |
| | | 210 | | |
| | | 211 | | // ---------- Загрузка из кабинета ---------- |
| | | 212 | | |
| | | 213 | | public sealed class SyncRequest |
| | | 214 | | { |
| | 0 | 215 | | public DateTime? From { get; set; } |
| | 0 | 216 | | public DateTime? To { get; set; } |
| | | 217 | | } |
| | | 218 | | |
| | | 219 | | [HttpPost("sync")] |
| | | 220 | | [ValidateAntiForgeryToken] |
| | | 221 | | [PageAuthorize(PageCode, AccessType.Edit)] |
| | | 222 | | public IActionResult Sync([FromBody] SyncRequest? request) |
| | | 223 | | { |
| | 0 | 224 | | var to = (request?.To ?? DateTime.Today).Date; |
| | 0 | 225 | | var from = (request?.From ?? to.AddDays(-45)).Date; |
| | 0 | 226 | | if (from > to) return BadRequest(new { success = false, error = "Дата «с» позже даты «по»." }); |
| | | 227 | | |
| | | 228 | | // Период не ограничиваем: кабинет отдаёт взаиморасчёты за любой срок одним ответом. Долго идут только фактуры, |
| | | 229 | | // и то один раз — уже загруженные старые фактуры повторно не читаются. |
| | 0 | 230 | | var user = User.Identity?.Name; |
| | 0 | 231 | | var jobId = jobs.Enqueue<ArmtekEtpSyncJob>(j => j.ExecuteRangeAsync(from, to, user)); |
| | 0 | 232 | | logger.LogInformation("Armtek ETP: загрузка {From:dd.MM.yyyy}–{To:dd.MM.yyyy} поставлена ({JobId}) пользователем |
| | 0 | 233 | | from, to, jobId, User.Identity?.Name); |
| | 0 | 234 | | return Ok(new { success = true, jobId }); |
| | | 235 | | } |
| | | 236 | | |
| | | 237 | | /// <summary> |
| | | 238 | | /// Взаиморасчёты из Excel (кабинет → Взаиморасчёты → Выгрузить файл → .xlsx) — когда автозагрузка из кабинета |
| | | 239 | | /// упирается в капчу. dryRun=true только проверяет файл; иначе строки импортируются, а фактуры этих документов |
| | | 240 | | /// дочитываются через API фоновой задачей (связь документ ↔ фактура по коду документа). |
| | | 241 | | /// </summary> |
| | | 242 | | [HttpPost("import")] |
| | | 243 | | [ValidateAntiForgeryToken] |
| | | 244 | | [RequestSizeLimit(MaxImportBytes)] |
| | | 245 | | [PageAuthorize(PageCode, AccessType.Edit)] |
| | | 246 | | public async Task<IActionResult> Import(IFormFile? file, bool dryRun, CancellationToken ct) |
| | | 247 | | { |
| | 0 | 248 | | if (file == null || file.Length == 0) |
| | 0 | 249 | | return Ok(new { success = false, errors = new[] { "Выберите файл .xlsx с взаиморасчётами." } }); |
| | 0 | 250 | | if (!file.FileName.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase)) |
| | 0 | 251 | | return Ok(new { success = false, errors = new[] { $"Нужен файл .xlsx, а выбран «{file.FileName}»." } }); |
| | 0 | 252 | | if (file.Length > MaxImportBytes) |
| | 0 | 253 | | return Ok(new { success = false, errors = new[] { "Файл больше 10 МБ — это не выгрузка взаиморасчётов." } }) |
| | | 254 | | |
| | 0 | 255 | | await using var buffer = new MemoryStream(); |
| | 0 | 256 | | await file.CopyToAsync(buffer, ct); |
| | 0 | 257 | | buffer.Position = 0; |
| | 0 | 258 | | var parsed = ArmtekSettlementsExcelReader.Read(buffer); |
| | 0 | 259 | | var summary = new |
| | 0 | 260 | | { |
| | 0 | 261 | | rows = parsed.Rows.Count, |
| | 0 | 262 | | periodFrom = parsed.PeriodFrom, |
| | 0 | 263 | | periodTo = parsed.PeriodTo, |
| | 0 | 264 | | payers = parsed.Rows.Select(r => r.Kunnr).Distinct().ToArray(), |
| | 0 | 265 | | docTypes = parsed.Rows.GroupBy(r => r.DocTypeName).Select(g => new { name = g.Key, count = g.Count() }).Orde |
| | 0 | 266 | | lastBalance = parsed.Rows.OrderBy(r => r.DocDate).ThenBy(r => r.RowNumber).LastOrDefault()?.Balance, |
| | 0 | 267 | | parsed.Warnings |
| | 0 | 268 | | }; |
| | 0 | 269 | | if (!parsed.IsValid) |
| | 0 | 270 | | return Ok(new { success = false, errors = parsed.Errors, summary }); |
| | 0 | 271 | | if (dryRun) |
| | 0 | 272 | | return Ok(new { success = true, dryRun = true, summary }); |
| | | 273 | | |
| | 0 | 274 | | var user = User.Identity?.Name; |
| | 0 | 275 | | var imported = await sync.ImportSettlementsAsync(parsed.Rows, Path.GetFileName(file.FileName), user, ct); |
| | 0 | 276 | | var jobId = jobs.Enqueue<ArmtekEtpSyncJob>(j => j.ExecuteInvoicesAsync(imported.PeriodFrom, imported.PeriodTo, u |
| | 0 | 277 | | logger.LogInformation("Armtek: {Result} — пользователь {User}, фактуры к ним дочитывает задача {JobId}", importe |
| | 0 | 278 | | return Ok(new { success = true, summary, imported = imported.ToString(), created = imported.Created, updated = i |
| | 0 | 279 | | } |
| | | 280 | | |
| | | 281 | | private const int MaxImportBytes = 10 * 1024 * 1024; |
| | | 282 | | |
| | | 283 | | [HttpGet("sync/{jobId}")] |
| | | 284 | | [PageAuthorize(PageCode, AccessType.View)] |
| | | 285 | | public IActionResult SyncStatus(string jobId) |
| | | 286 | | { |
| | 0 | 287 | | var details = JobStorage.Current.GetMonitoringApi().JobDetails(jobId); |
| | 0 | 288 | | if (details == null) return NotFound(new { success = false, error = "Задача не найдена." }); |
| | | 289 | | |
| | 0 | 290 | | var last = details.History.FirstOrDefault(); |
| | 0 | 291 | | var state = last?.StateName ?? "Enqueued"; |
| | 0 | 292 | | string? message = null; |
| | 0 | 293 | | if (last?.Data != null) |
| | | 294 | | { |
| | 0 | 295 | | last.Data.TryGetValue("Result", out var result); |
| | 0 | 296 | | last.Data.TryGetValue("ExceptionMessage", out var error); |
| | 0 | 297 | | message = (error ?? result)?.Trim('"'); |
| | | 298 | | } |
| | 0 | 299 | | return Ok(new { success = true, state, message }); |
| | | 300 | | } |
| | | 301 | | |
| | | 302 | | // ---------- Общее ---------- |
| | | 303 | | |
| | 0 | 304 | | private sealed record GridPage<T>(IReadOnlyList<T> Rows, int Total, int Start, string? Error) |
| | | 305 | | { |
| | 0 | 306 | | public int LastRow(int count) => Start + count >= Total ? Total : -1; |
| | | 307 | | } |
| | | 308 | | |
| | | 309 | | private static async Task<GridPage<T>> PageAsync<T>(IQueryable<T> source, ServerGridDefinition<T> def, |
| | | 310 | | ServerGridRequest? request, CancellationToken ct, Expression<Func<T, T>>? projection = null) |
| | | 311 | | { |
| | 0 | 312 | | var error = ServerGridQuery.Validate(request); |
| | 0 | 313 | | if (error != null) return new GridPage<T>([], 0, 0, error); |
| | | 314 | | |
| | 0 | 315 | | var filtered = ServerGridQuery.ApplyFilters(source, def, request!); |
| | 0 | 316 | | var total = await filtered.CountAsync(ct); |
| | 0 | 317 | | var start = Math.Max(0, request!.StartRow); |
| | 0 | 318 | | var take = Math.Clamp(request.EndRow - start, 1, ServerGridQuery.MaxBlockSize); |
| | 0 | 319 | | if (start >= total) return new GridPage<T>([], total, start, null); |
| | | 320 | | |
| | 0 | 321 | | var sorted = ServerGridQuery.ApplySort(filtered, def, request.SortModel).Skip(start).Take(take); |
| | 0 | 322 | | var rows = projection == null ? await sorted.ToListAsync(ct) : await sorted.Select(projection).ToListAsync(ct); |
| | 0 | 323 | | return new GridPage<T>(rows, total, start, null); |
| | 0 | 324 | | } |
| | | 325 | | |
| | | 326 | | private static async Task<IActionResult> FacetsAsync<T>(IQueryable<T> source, ServerGridDefinition<T> def, |
| | | 327 | | ServerGridRequest? request, CancellationToken ct) |
| | | 328 | | { |
| | 0 | 329 | | if (request is null || string.IsNullOrWhiteSpace(request.ColId)) |
| | 0 | 330 | | return new BadRequestObjectResult(new { success = false, error = "colId обязателен" }); |
| | 0 | 331 | | request.StartRow = 0; |
| | 0 | 332 | | request.EndRow = 1; |
| | 0 | 333 | | var error = ServerGridQuery.Validate(request); |
| | 0 | 334 | | if (error != null) return new BadRequestObjectResult(new { success = false, error }); |
| | 0 | 335 | | var values = await ServerGridQuery.FacetsAsync(source, def, request, ct); |
| | 0 | 336 | | return new OkObjectResult(new { success = true, values }); |
| | 0 | 337 | | } |
| | | 338 | | } |