Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.
C# aspnet-corecsharpdockerdotnetecommerceecommerce-platformmongodbmulti-storemulti-vendornosqlonline-shopshoppingcart
feat(arch001): add Edit/PDF/search regions to BaseOrderController; wire FilterOrderItems and vendor field gating into OrderViewModelService
KrzysztofPajak248d14dbe2da
diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseOrderControllerTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseOrderControllerTests.csindex 64aaabcd8..58720b714 100644--- a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseOrderControllerTests.cs+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseOrderControllerTests.cs@@ -184,4 +184,96 @@ public class BaseOrderControllerTestsAssert.AreSame(order, resultOrder);Assert.IsNull(denied);}++ [TestMethod]+ public async Task EditGet_NotFound_RedirectsToList()+ {+ _orderServiceMock.Setup(s => s.GetOrderById("missing")).ReturnsAsync((Order)null);++ var result = await _controller.Edit("missing");++ var redirect = result as RedirectToActionResult;+ Assert.IsNotNull(redirect);+ Assert.AreEqual("List", redirect.ActionName);+ }++ [TestMethod]+ public async Task EditGet_Deleted_RedirectsToList()+ {+ var order = new Order { Id = "o1", Deleted = true };+ _orderServiceMock.Setup(s => s.GetOrderById("o1")).ReturnsAsync(order);+ _scopeMock.Setup(s => s.HasAccess(order)).ReturnsAsync(true);++ var result = await _controller.Edit("o1");++ var redirect = result as RedirectToActionResult;+ Assert.IsNotNull(redirect);+ Assert.AreEqual("List", redirect.ActionName);+ }++ [TestMethod]+ public async Task EditGet_ScopeDenies_RedirectsToList()+ {+ var order = new Order { Id = "o1" };+ _orderServiceMock.Setup(s => s.GetOrderById("o1")).ReturnsAsync(order);+ _scopeMock.Setup(s => s.HasAccess(order)).ReturnsAsync(false);++ var result = await _controller.Edit("o1");++ var redirect = result as RedirectToActionResult;+ Assert.IsNotNull(redirect);+ Assert.AreEqual("List", redirect.ActionName);+ }++ [TestMethod]+ public async Task EditGet_Authorized_ReturnsViewAndCallsPrepareOrderDetailsModel()+ {+ var order = new Order { Id = "o1" };+ _orderServiceMock.Setup(s => s.GetOrderById("o1")).ReturnsAsync(order);+ _scopeMock.Setup(s => s.HasAccess(order)).ReturnsAsync(true);++ var result = await _controller.Edit("o1");++ Assert.IsInstanceOfType(result, typeof(ViewResult));+ _orderViewModelServiceMock.Verify(v => v.PrepareOrderDetailsModel(It.IsAny<OrderModel>(), order), Times.Once);+ }++ [TestMethod]+ public async Task ProductSearchAutoComplete_VendorScope_ForcesVendorIdIntoSearch()+ {+ _scopeMock.Setup(s => s.DefaultVendorId).Returns("vendor-A");+ // NOTE: brief's test used named-argument Setup/Verify calls (storeId:/vendorId:/keywords:/+ // pageSize:/showHidden:), which don't compile: (1) named arguments inside a Moq Setup+ // expression tree must appear in the same relative order as the method's declared parameter+ // list - the brief's order (storeId, vendorId, keywords, pageSize, showHidden) puts pageSize+ // (declared 3rd) after storeId/vendorId/keywords (declared 7th/8th/18th), which the compiler+ // rejects as CS9307 "named argument specification out of position"; and (2) IProductService.+ // SearchProducts actually returns Task<(IPagedList<Product>, IList<string>)>, not+ // Task<(List<Product>, int)> as the brief's ReturnsAsync assumed. Rewritten below as a fully+ // positional call (all 27 parameters, It.IsAny<T>() for the ones this test doesn't care+ // about) to test the same behavior: the controller forces scope.DefaultVendorId into the+ // vendorId slot alongside the caller-supplied term/pageSize/showHidden.+ var productServiceMock = new Mock<Grand.Business.Core.Interfaces.Catalog.Products.IProductService>();+ var pagedProducts = (Grand.Domain.IPagedList<Grand.Domain.Catalog.Product>)+ new Grand.Domain.PagedList<Grand.Domain.Catalog.Product>(new List<Grand.Domain.Catalog.Product>(), 0, 15);+ productServiceMock+ .Setup(p => p.SearchProducts(+ It.IsAny<bool>(), It.IsAny<int>(), 15, It.IsAny<IList<string>>(), It.IsAny<string>(), It.IsAny<string>(),+ null, "vendor-A", It.IsAny<string>(), It.IsAny<Grand.Domain.Catalog.ProductType?>(), It.IsAny<bool>(),+ It.IsAny<bool>(), It.IsAny<bool?>(), It.IsAny<bool?>(), It.IsAny<double?>(), It.IsAny<double?>(),+ It.IsAny<string>(), "abc", It.IsAny<bool>(), It.IsAny<bool>(), It.IsAny<bool>(), It.IsAny<string>(),+ It.IsAny<IList<string>>(), It.IsAny<IList<string>>(), It.IsAny<Grand.Domain.Catalog.ProductSortingEnum>(),+ true, It.IsAny<bool?>()))+ .ReturnsAsync((pagedProducts, (IList<string>)new List<string>()));++ await _controller.ProductSearchAutoComplete("abc", productServiceMock.Object);++ productServiceMock.Verify(p => p.SearchProducts(+ It.IsAny<bool>(), It.IsAny<int>(), 15, It.IsAny<IList<string>>(), It.IsAny<string>(), It.IsAny<string>(),+ null, "vendor-A", It.IsAny<string>(), It.IsAny<Grand.Domain.Catalog.ProductType?>(), It.IsAny<bool>(),+ It.IsAny<bool>(), It.IsAny<bool?>(), It.IsAny<bool?>(), It.IsAny<double?>(), It.IsAny<double?>(),+ It.IsAny<string>(), "abc", It.IsAny<bool>(), It.IsAny<bool>(), It.IsAny<bool>(), It.IsAny<string>(),+ It.IsAny<IList<string>>(), It.IsAny<IList<string>>(), It.IsAny<Grand.Domain.Catalog.ProductSortingEnum>(),+ true, It.IsAny<bool?>()), Times.Once);+ }}diff --git a/src/Web/Grand.Web.AdminShared/Controllers/BaseOrderController.cs b/src/Web/Grand.Web.AdminShared/Controllers/BaseOrderController.csindex 7e44505b0..7f768be24 100644--- a/src/Web/Grand.Web.AdminShared/Controllers/BaseOrderController.cs+++ b/src/Web/Grand.Web.AdminShared/Controllers/BaseOrderController.cs@@ -76,4 +76,140 @@ public abstract class BaseOrderController(}#endregion++ #region Order details (view-only)++ [PermissionAuthorizeAction(PermissionActionName.Preview)]+ public async Task<IActionResult> Edit(string id)+ {+ var order = await orderService.GetOrderById(id);+ if (order == null || order.Deleted) return RedirectToAction("List");+ if (!await scope.HasAccess(order)) return RedirectToAction("List");++ var model = new OrderModel();+ await orderViewModelService.PrepareOrderDetailsModel(model, order);++ return View(model);+ }++ public async Task<IActionResult> PdfInvoice(string orderId)+ {+ var (order, denied) = await LoadAuthorizedOrder(orderId);+ if (denied != null) return denied;++ var orders = new List<Order> { order };+ byte[] bytes;+ using (var stream = new MemoryStream())+ {+ await pdfService.PrintOrdersToPdf(stream, orders, contextAccessor.WorkContext.WorkingLanguage.Id,+ scope.DefaultVendorId);+ bytes = stream.ToArray();+ }++ return File(bytes, "application/pdf", $"order_{order.Id}.pdf");+ }++ [PermissionAuthorizeAction(PermissionActionName.Export)]+ [HttpPost]+ public async Task<IActionResult> PdfInvoiceAll(OrderListModel model)+ {+ var orders = await orderViewModelService.PrepareOrders(model);+ // Store's original code post-filtered by StoreId here even though PrepareOrders already+ // takes model.StoreId as a search filter - keep the extra filter for defense in depth,+ // matching Store's original exactly; harmless no-op for Admin/Vendor (DefaultStoreId null).+ if (scope.DefaultStoreId is not null)+ orders = orders.Where(x => x.StoreId == scope.DefaultStoreId).ToList();++ byte[] bytes;+ using (var stream = new MemoryStream())+ {+ await pdfService.PrintOrdersToPdf(stream, orders, contextAccessor.WorkContext.WorkingLanguage.Id,+ scope.DefaultVendorId ?? model.VendorId);+ bytes = stream.ToArray();+ }++ return File(bytes, "application/pdf", "orders.pdf");+ }++ [PermissionAuthorizeAction(PermissionActionName.Export)]+ [HttpPost]+ public async Task<IActionResult> PdfInvoiceSelected(string selectedIds)+ {+ var orders = new List<Order>();+ if (selectedIds != null)+ {+ var ids = selectedIds.Split([','], StringSplitOptions.RemoveEmptyEntries).ToArray();+ orders.AddRange(await orderService.GetOrdersByIds(ids));+ }++ // Store filters by StoreId; Vendor's original filtered by HasAccessToOrder (any-item+ // vendor match); Admin's original has no filter here at all. scope.HasAccess already+ // expresses all three checks per-host - safe to apply unconditionally, it's a true no-op+ // for Admin (AdminOrderDataScope.HasAccess is the Sales-Manager check, which Admin's+ // *original* PdfInvoiceSelected never applied - see plan risk note below).+ var accessible = new List<Order>();+ foreach (var order in orders)+ if (await scope.HasAccess(order))+ accessible.Add(order);+ orders = accessible;++ if (orders.Count == 0)+ {+ Error(translationService.GetResource($"{scope.ResourceKeyPrefix}.Orders.PdfInvoice.NoOrders"));+ return RedirectToAction("List");+ }++ byte[] bytes;+ using (var stream = new MemoryStream())+ {+ await pdfService.PrintOrdersToPdf(stream, orders, contextAccessor.WorkContext.WorkingLanguage.Id);+ bytes = stream.ToArray();+ }++ return File(bytes, "application/pdf", "orders.pdf");+ }++ public async Task<IActionResult> ProductSearchAutoComplete(string term,+ [FromServices] Grand.Business.Core.Interfaces.Catalog.Products.IProductService productService)+ {+ const int searchTermMinimumLength = 3;+ if (string.IsNullOrWhiteSpace(term) || term.Length < searchTermMinimumLength)+ return Content("");++ const int productNumber = 15;+ var products = (await productService.SearchProducts(+ storeId: scope.DefaultStoreId,+ vendorId: scope.DefaultVendorId,+ keywords: term,+ pageSize: productNumber,+ showHidden: true)).products;++ var result = products.Select(p => new { label = p.Name, productid = p.Id }).ToList();+ return Json(result);+ }++ [PermissionAuthorizeAction(PermissionActionName.Preview)]+ [HttpPost]+ public async Task<IActionResult> GoToOrderId(OrderListModel model)+ {+ Order order = null;+ int.TryParse(model.GoDirectlyToNumber, out var orderNumber);+ if (orderNumber > 0) order = await orderService.GetOrderByNumber(orderNumber);+ else+ {+ var orders = await orderService.GetOrdersByCode(model.GoDirectlyToNumber);+ switch (orders.Count)+ {+ case > 1: return RedirectToAction("List", new { Code = model.GoDirectlyToNumber });+ case 1: order = orders.FirstOrDefault(); break;+ case 0: return RedirectToAction("List", new { Code = model.GoDirectlyToNumber });+ }+ }++ if (order == null || !await scope.HasAccess(order)) return RedirectToAction("List");++ return RedirectToAction("Edit", "Order", new { id = order.Id });+ }++ #endregion}diff --git a/src/Web/Grand.Web.AdminShared/Services/OrderViewModelService.cs b/src/Web/Grand.Web.AdminShared/Services/OrderViewModelService.csindex 3b86f2975..68d085796 100644--- a/src/Web/Grand.Web.AdminShared/Services/OrderViewModelService.cs+++ b/src/Web/Grand.Web.AdminShared/Services/OrderViewModelService.cs@@ -77,6 +77,7 @@ public class OrderViewModelService : IOrderViewModelServiceprivate readonly IOrderStatusService _orderStatusService;private readonly IMediator _mediator;private readonly IEnumTranslationService _enumTranslationService;+ private readonly IAdminDataScope<Order> _scope;#endregion@@ -116,7 +117,8 @@ public class OrderViewModelService : IOrderViewModelServiceIOrderTagService orderTagService,IOrderStatusService orderStatusService,IMediator mediator,- IProductAttributeFormatter productAttributeFormatter, IEnumTranslationService enumTranslationService)+ IProductAttributeFormatter productAttributeFormatter, IEnumTranslationService enumTranslationService,+ IAdminDataScope<Order> scope){_orderService = orderService;_pricingService = priceCalculationService;@@ -154,6 +156,7 @@ public class OrderViewModelService : IOrderViewModelService_mediator = mediator;_productAttributeFormatter = productAttributeFormatter;_enumTranslationService = enumTranslationService;+ _scope = scope;}#endregion@@ -345,58 +348,70 @@ public class OrderViewModelService : IOrderViewModelServicemodel.OrderGuid = order.OrderGuid;var status = await _orderStatusService.GetAll();- model.OrderStatuses =- status.Select(x => new SelectListItem { Value = x.StatusId.ToString(), Text = x.Name }).ToList();+ if (_scope.DefaultVendorId is null)+ model.OrderStatuses =+ status.Select(x => new SelectListItem { Value = x.StatusId.ToString(), Text = x.Name }).ToList();model.OrderStatus = status.FirstOrDefault(x => x.StatusId == order.OrderStatusId)?.Name;var store = await _storeService.GetStoreById(order.StoreId);model.StoreName = store != null ? store.Shortcut : "Unknown";- model.CustomerId = order.CustomerId;+ if (_scope.DefaultVendorId is null)+ model.CustomerId = order.CustomerId;model.UserFields = order.UserFields;var customer = await _customerService.GetCustomerById(order.CustomerId);if (customer != null)model.CustomerInfo = !string.IsNullOrEmpty(customer.Email)? customer.Email- : _translationService.GetResource("Admin.Customers.Guest");+ : _translationService.GetResource($"{_scope.ResourceKeyPrefix}.Customers.Guest");- model.CustomerIp = order.CustomerIp;+ if (_scope.DefaultVendorId is null)+ model.CustomerIp = order.CustomerIp;model.VatNumber = order.VatNumber;model.CreatedOn = _dateTimeService.ConvertToUserTime(order.CreatedOnUtc, DateTimeKind.Utc);model.TaxDisplayType = _taxSettings.TaxDisplayType;- if (!string.IsNullOrEmpty(order.AffiliateId))+ if (_scope.DefaultVendorId is null){- var affiliate = await _affiliateService.GetAffiliateById(order.AffiliateId);- if (affiliate != null)+ if (!string.IsNullOrEmpty(order.AffiliateId)){- model.AffiliateId = affiliate.Id;- model.AffiliateName = affiliate.GetFullName();+ var affiliate = await _affiliateService.GetAffiliateById(order.AffiliateId);+ if (affiliate != null)+ {+ model.AffiliateId = affiliate.Id;+ model.AffiliateName = affiliate.GetFullName();+ }}}- if (!string.IsNullOrEmpty(order.SeId))+ if (_scope.DefaultVendorId is null){- var salesEmployee = await _salesEmployeeService.GetSalesEmployeeById(order.SeId);- if (salesEmployee != null)+ if (!string.IsNullOrEmpty(order.SeId)){- model.SalesEmployeeId = salesEmployee.Id;- model.SalesEmployeeName = salesEmployee.Name;+ var salesEmployee = await _salesEmployeeService.GetSalesEmployeeById(order.SeId);+ if (salesEmployee != null)+ {+ model.SalesEmployeeId = salesEmployee.Id;+ model.SalesEmployeeName = salesEmployee.Name;+ }}}//order's tags- if (order.OrderTags.Any())+ if (_scope.DefaultVendorId is null){- var tagsName = new List<string>();- foreach (var item in order.OrderTags)+ if (order.OrderTags.Any()){- var tag = await _orderTagService.GetOrderTagById(item);- if (tag != null)- tagsName.Add(tag.Name);- }+ var tagsName = new List<string>();+ foreach (var item in order.OrderTags)+ {+ var tag = await _orderTagService.GetOrderTagById(item);+ if (tag != null)+ tagsName.Add(tag.Name);+ }- model.OrderTags = string.Join(",", tagsName);+ model.OrderTags = string.Join(",", tagsName);+ }}#region Order totals@@ -693,7 +708,7 @@ public class OrderViewModelService : IOrderViewModelServicemodel.CheckoutAttributeInfo = order.CheckoutAttributeDescription;var hasDownloadableItems = false;- var products = order.OrderItems;+ var products = _scope.FilterOrderItems(order.OrderItems);foreach (var orderItem in products){var product = await _productService.GetProductByIdIncludeArch(orderItem.ProductId);