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
Enhancement wishlist feature (#96)
Krzysztof Pajak750c78edb7d4
diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AddRequiredProductsCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AddRequiredProductsCommandHandler.csindex 42af5f771..e154e1c50 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AddRequiredProductsCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AddRequiredProductsCommandHandler.cs@@ -2,6 +2,7 @@using Grand.Business.Checkout.Commands.Models.Orders;using Grand.Business.Checkout.Extensions;using Grand.Business.Checkout.Interfaces.Orders;+using Grand.Business.Checkout.Services.Orders;using Grand.Domain.Catalog;using Grand.Domain.Orders;using MediatR;@@ -67,13 +68,14 @@ namespace Grand.Business.Checkout.Commands.Handlers.Ordersif (product.AutoAddRequiredProducts){- var addToCartWarnings = await _shoppingCartService.AddToCart(customer: customer,+ var addToCart = await _shoppingCartService.AddToCart(customer: customer,productId: rp.Id,shoppingCartType: shoppingCartType,storeId: storeId,- automaticallyAddRequiredProductsIfEnabled: false, getRequiredProductWarnings: false);+ automaticallyAddRequiredProductsIfEnabled: false,+ validator: new ShoppingCartValidatorOptions() { GetRequiredProductWarnings = false });- if (rp.RequireOtherProducts && addToCartWarnings.Count == 0)+ if (rp.RequireOtherProducts && addToCart.warnings.Count == 0){await Handle(new AddRequiredProductsCommand{diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReOrderCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReOrderCommandHandler.csindex b863e5b99..7aea6b88f 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReOrderCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReOrderCommandHandler.cs@@ -1,6 +1,7 @@using Grand.Business.Catalog.Interfaces.Products;using Grand.Business.Checkout.Commands.Models.Orders;using Grand.Business.Checkout.Interfaces.Orders;+using Grand.Business.Checkout.Services.Orders;using Grand.Business.Customers.Interfaces;using Grand.Domain.Catalog;using Grand.Domain.Orders;@@ -47,14 +48,15 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders{if (product.ProductTypeId == ProductType.SimpleProduct){- warnings.AddRange(await _shoppingCartService.AddToCart(customer, orderItem.ProductId,+ warnings.AddRange((await _shoppingCartService.AddToCart(customer, orderItem.ProductId,ShoppingCartType.ShoppingCart, request.Order.StoreId, orderItem.WarehouseId,orderItem.Attributes,product.EnteredPrice ?_taxSettings.PricesIncludeTax ? orderItem.UnitPriceInclTax : orderItem.UnitPriceExclTax: (double?)default,orderItem.RentalStartDateUtc, orderItem.RentalEndDateUtc,- orderItem.Quantity, false, getRequiredProductWarnings: false));+ orderItem.Quantity, false,+ validator: new ShoppingCartValidatorOptions() { GetRequiredProductWarnings = false })).warnings);}}elsediff --git a/src/Business/Grand.Business.Checkout/Interfaces/Orders/IShoppingCartService.cs b/src/Business/Grand.Business.Checkout/Interfaces/Orders/IShoppingCartService.csindex 71a2f95e3..4cc84f9e5 100644--- a/src/Business/Grand.Business.Checkout/Interfaces/Orders/IShoppingCartService.cs+++ b/src/Business/Grand.Business.Checkout/Interfaces/Orders/IShoppingCartService.cs@@ -1,3 +1,4 @@+using Grand.Business.Checkout.Services.Orders;using Grand.Domain.Catalog;using Grand.Domain.Common;using Grand.Domain.Customers;@@ -59,13 +60,15 @@ namespace Grand.Business.Checkout.Interfaces.Orders/// <param name="reservationId">ReservationId</param>/// <param name="parameter">Parameter for reservation</param>/// <param name="duration">Duration for reservation</param>- /// <param name="getRequiredProductWarnings">GetRequiredProductWarnings</param>- /// <returns>Warnings</returns>- Task<IList<string>> AddToCart(Customer customer, string productId,+ /// <param name="validator">ShoppingCartValidatorOptions</param>+ /// <returns>(warnings, shoppingCartItem)</returns>+ Task<(IList<string> warnings, ShoppingCartItem shoppingCartItem)> AddToCart(Customer customer, string productId,ShoppingCartType shoppingCartType, string storeId, string warehouseId = null, IList<CustomAttribute> attributes = null,double? customerEnteredPrice = null,DateTime? rentalStartDate = null, DateTime? rentalEndDate = null,- int quantity = 1, bool automaticallyAddRequiredProductsIfEnabled = true, string reservationId = "", string parameter = "", string duration = "", bool getRequiredProductWarnings = true);+ int quantity = 1,+ bool automaticallyAddRequiredProductsIfEnabled = true, string reservationId = "", string parameter = "", string duration = "",+ ShoppingCartValidatorOptions validator = null);/// <summary>/// Updates the shopping cart itemdiff --git a/src/Business/Grand.Business.Checkout/Interfaces/Orders/IShoppingCartValidator.cs b/src/Business/Grand.Business.Checkout/Interfaces/Orders/IShoppingCartValidator.csindex d5b460a49..60318b238 100644--- a/src/Business/Grand.Business.Checkout/Interfaces/Orders/IShoppingCartValidator.cs+++ b/src/Business/Grand.Business.Checkout/Interfaces/Orders/IShoppingCartValidator.cs@@ -81,6 +81,15 @@ namespace Grand.Business.Checkout.Interfaces.Orders/// <returns>Warnings</returns>Task<IList<string>> GetReservationProductWarnings(Customer customer, Product product, ShoppingCartItem shoppingCartItem);+ /// <summary>+ /// Validates shopping cart item for inventory+ /// </summary>+ /// <param name="customer">Customer</param>+ /// <param name="Product">product</param>+ /// <param name="shoppingCartItem">ShoppingCartItem</param>+ /// <returns>Warnings</returns>+ Task<IList<string>> GetInventoryProductWarnings(Customer customer, Product product, ShoppingCartItem shoppingCartItem);+/// <summary>/// Validates common problems/// </summary>diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.csindex 5241e134d..b5d70fb0b 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.cs@@ -190,20 +190,23 @@ namespace Grand.Business.Checkout.Services.Orders/// <param name="reservationId">ReservationId</param>/// <param name="parameter">Parameter for reservation</param>/// <param name="duration">Duration for reservation</param>- /// <param name="getRequiredProductWarnings">GetRequiredProductWarnings</param>- /// <returns>Warnings</returns>- public virtual async Task<IList<string>> AddToCart(Customer customer, string productId,+ /// <param name="validator">ShoppingCartValidatorOptions</param>+ /// <returns>(warnings, shoppingCartItem)</returns>+ public virtual async Task<(IList<string> warnings, ShoppingCartItem shoppingCartItem)> AddToCart(Customer customer, string productId,ShoppingCartType shoppingCartType, string storeId,string warehouseId = null, IList<CustomAttribute> attributes = null,double? customerEnteredPrice = null,DateTime? rentalStartDate = null, DateTime? rentalEndDate = null,int quantity = 1, bool automaticallyAddRequiredProductsIfEnabled = true,string reservationId = "", string parameter = "", string duration = "",- bool getRequiredProductWarnings = true)+ ShoppingCartValidatorOptions validator = null){if (customer == null)throw new ArgumentNullException(nameof(customer));+ if (validator == null)+ validator = new ShoppingCartValidatorOptions();+var product = await _productService.GetProductById(productId);if (product == null)throw new ArgumentNullException(nameof(product));@@ -217,7 +220,7 @@ namespace Grand.Business.Checkout.Services.OrdersrentalEndDate, quantity, reservationId)).ToList();if (warnings.Any())- return warnings;+ return (warnings, null);var shoppingCartItem = await FindShoppingCartItem(cart,shoppingCartType, productId, warehouseId, attributes, customerEnteredPrice,@@ -229,7 +232,7 @@ namespace Grand.Business.Checkout.Services.Ordersif (update){shoppingCartItem.Quantity += quantity;- warnings.AddRange(await _shoppingCartValidator.GetShoppingCartItemWarnings(customer, shoppingCartItem, product, new ShoppingCartValidatorOptions() { GetRequiredProductWarnings = getRequiredProductWarnings }));+ warnings.AddRange(await _shoppingCartValidator.GetShoppingCartItemWarnings(customer, shoppingCartItem, product, validator));}else{@@ -258,9 +261,7 @@ namespace Grand.Business.Checkout.Services.Orders};warnings.AddRange(await _shoppingCartValidator.GetShoppingCartItemWarnings- (customer, shoppingCartItem, product,- new ShoppingCartValidatorOptions()- { GetRequiredProductWarnings = getRequiredProductWarnings }));+ (customer, shoppingCartItem, product, validator));}if (!warnings.Any())@@ -281,7 +282,7 @@ namespace Grand.Business.Checkout.Services.Ordersawait _customerService.ResetCheckoutData(customer, storeId);}- return warnings;+ return (warnings, shoppingCartItem);}private async Task UpdateExistingShoppingCartItem(ShoppingCartItem shoppingCartItem, Customer customer,@@ -560,7 +561,8 @@ namespace Grand.Business.Checkout.Services.Ordersvar sci = fromCart[i];await AddToCart(toCustomer, sci.ProductId, sci.ShoppingCartTypeId, sci.StoreId, sci.WarehouseId,sci.Attributes, sci.EnteredPrice,- sci.RentalStartDateUtc, sci.RentalEndDateUtc, sci.Quantity, false, sci.ReservationId, sci.Parameter, sci.Duration);+ sci.RentalStartDateUtc, sci.RentalEndDateUtc, sci.Quantity, false, sci.ReservationId, sci.Parameter, sci.Duration,+ new ShoppingCartValidatorOptions());}for (int i = 0; i < fromCart.Count; i++){diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.cs b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.csindex 5540207fe..15fa2edd5 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.cs@@ -149,151 +149,6 @@ namespace Grand.Business.Checkout.Services.Orders}}- //quantity validation- var hasQtyWarnings = false;- if (shoppingCartItem.Quantity < product.OrderMinimumQuantity)- {- warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.MinimumQuantity"), product.OrderMinimumQuantity));- hasQtyWarnings = true;- }- if (shoppingCartItem.Quantity > product.OrderMaximumQuantity)- {- warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.MaximumQuantity"), product.OrderMaximumQuantity));- hasQtyWarnings = true;- }- var allowedQuantities = product.ParseAllowedQuantities();- if (allowedQuantities.Length > 0 && !allowedQuantities.Contains(shoppingCartItem.Quantity))- {- warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.AllowedQuantities"), string.Join(", ", allowedQuantities)));- }-- if (_shoppingCartSettings.AllowToSelectWarehouse && string.IsNullOrEmpty(shoppingCartItem.WarehouseId))- {- warnings.Add(_translationService.GetResource("ShoppingCart.RequiredWarehouse"));- }-- var warehouseId = !string.IsNullOrEmpty(shoppingCartItem.WarehouseId) ? shoppingCartItem.WarehouseId : _workContext.CurrentStore?.DefaultWarehouseId;-- if (!string.IsNullOrEmpty(warehouseId))- {- var warehouse = await _warehouseService.GetWarehouseById(warehouseId);- if (warehouse == null)- warnings.Add(_translationService.GetResource("ShoppingCart.WarehouseNotExists"));- }-- var validateOutOfStock = shoppingCartItem.ShoppingCartTypeId == ShoppingCartType.ShoppingCart || !_shoppingCartSettings.AllowOutOfStockItemsToBeAddedToWishlist;- if (validateOutOfStock && !hasQtyWarnings)- {- switch (product.ManageInventoryMethodId)- {- case ManageInventoryMethod.DontManageStock:- {- //do nothing- }- break;- case ManageInventoryMethod.ManageStock:- {- if (product.BackorderModeId == BackorderMode.NoBackorders)- {- var qty = shoppingCartItem.Quantity;-- qty += customer.ShoppingCartItems- .Where(x => x.ShoppingCartTypeId == shoppingCartItem.ShoppingCartTypeId &&- x.WarehouseId == warehouseId &&- x.ProductId == shoppingCartItem.ProductId &&- x.StoreId == shoppingCartItem.StoreId &&- x.Id != shoppingCartItem.Id)- .Sum(x => x.Quantity);-- var maximumQuantityCanBeAdded = _stockQuantityService.GetTotalStockQuantity(product, warehouseId: warehouseId);- if (maximumQuantityCanBeAdded < qty)- {- if (maximumQuantityCanBeAdded <= 0)- warnings.Add(_translationService.GetResource("ShoppingCart.OutOfStock"));- else- warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.QuantityExceedsStock"), maximumQuantityCanBeAdded));- }- }- }- break;- case ManageInventoryMethod.ManageStockByBundleProducts:- {- foreach (var item in product.BundleProducts)- {- var _qty = shoppingCartItem.Quantity * item.Quantity;- var p1 = await _productService.GetProductById(item.ProductId);- if (p1 != null)- {- if (p1.BackorderModeId == BackorderMode.NoBackorders)- {- if (p1.ManageInventoryMethodId == ManageInventoryMethod.ManageStock)- {- int maximumQuantityCanBeAdded = _stockQuantityService.GetTotalStockQuantity(p1, warehouseId: warehouseId);- if (maximumQuantityCanBeAdded < _qty)- {- warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.OutOfStock.BundleProduct"), p1.Name));- }- }- if (p1.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByAttributes)- {- var combination = _productAttributeParser.FindProductAttributeCombination(p1, shoppingCartItem.Attributes);- if (combination != null)- {- //combination exists - check stock level- var stockquantity = _stockQuantityService.GetTotalStockQuantityForCombination(p1, combination, warehouseId: warehouseId);- if (!combination.AllowOutOfStockOrders && stockquantity < _qty)- {- if (stockquantity <= 0)- {- warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.OutOfStock.BundleProduct"), p1.Name));- }- else- {- warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.QuantityExceedsStock.BundleProduct"), p1.Name, stockquantity));- }- }- }- else- {- warnings.Add(_translationService.GetResource("ShoppingCart.Combination.NotExist"));- }- }- }- }- }- }- break;- case ManageInventoryMethod.ManageStockByAttributes:- {- var combination = _productAttributeParser.FindProductAttributeCombination(product, shoppingCartItem.Attributes);- if (combination != null)- {- //combination exists - check stock level- var stockquantity = _stockQuantityService.GetTotalStockQuantityForCombination(product, combination, warehouseId: warehouseId);- if (!combination.AllowOutOfStockOrders && stockquantity < shoppingCartItem.Quantity)- {- int maximumQuantityCanBeAdded = stockquantity;- if (maximumQuantityCanBeAdded <= 0)- {- warnings.Add(_translationService.GetResource("ShoppingCart.OutOfStock"));- }- else- {- warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.QuantityExceedsStock"), maximumQuantityCanBeAdded));- }- }- }- else- {- warnings.Add(_translationService.GetResource("ShoppingCart.Combination.NotExist"));- }- }- break;- default:- break;- }- }-//availability datesbool availableStartDateError = false;if (product.AvailableStartDateTimeUtc.HasValue)@@ -564,6 +419,158 @@ namespace Grand.Business.Checkout.Services.Ordersreturn warnings;}+ public virtual async Task<IList<string>> GetInventoryProductWarnings(Customer customer, Product product, ShoppingCartItem shoppingCartItem)+ {+ var warnings = new List<string>();++ //quantity validation+ var hasQtyWarnings = false;+ if (shoppingCartItem.Quantity < product.OrderMinimumQuantity)+ {+ warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.MinimumQuantity"), product.OrderMinimumQuantity));+ hasQtyWarnings = true;+ }+ if (shoppingCartItem.Quantity > product.OrderMaximumQuantity)+ {+ warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.MaximumQuantity"), product.OrderMaximumQuantity));+ hasQtyWarnings = true;+ }+ var allowedQuantities = product.ParseAllowedQuantities();+ if (allowedQuantities.Length > 0 && !allowedQuantities.Contains(shoppingCartItem.Quantity))+ {+ warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.AllowedQuantities"), string.Join(", ", allowedQuantities)));+ }++ if (_shoppingCartSettings.AllowToSelectWarehouse && string.IsNullOrEmpty(shoppingCartItem.WarehouseId))+ {+ warnings.Add(_translationService.GetResource("ShoppingCart.RequiredWarehouse"));+ }++ var warehouseId = !string.IsNullOrEmpty(shoppingCartItem.WarehouseId) ? shoppingCartItem.WarehouseId : _workContext.CurrentStore?.DefaultWarehouseId;++ if (!string.IsNullOrEmpty(warehouseId))+ {+ var warehouse = await _warehouseService.GetWarehouseById(warehouseId);+ if (warehouse == null)+ warnings.Add(_translationService.GetResource("ShoppingCart.WarehouseNotExists"));+ }++ if (!hasQtyWarnings)+ {+ switch (product.ManageInventoryMethodId)+ {+ case ManageInventoryMethod.DontManageStock:+ {+ //do nothing+ }+ break;+ case ManageInventoryMethod.ManageStock:+ {+ if (product.BackorderModeId == BackorderMode.NoBackorders)+ {+ var qty = shoppingCartItem.Quantity;++ qty += customer.ShoppingCartItems+ .Where(x => x.ShoppingCartTypeId == shoppingCartItem.ShoppingCartTypeId &&+ x.WarehouseId == warehouseId &&+ x.ProductId == shoppingCartItem.ProductId &&+ x.StoreId == shoppingCartItem.StoreId &&+ x.Id != shoppingCartItem.Id)+ .Sum(x => x.Quantity);++ var maximumQuantityCanBeAdded = _stockQuantityService.GetTotalStockQuantity(product, warehouseId: warehouseId);+ if (maximumQuantityCanBeAdded < qty)+ {+ if (maximumQuantityCanBeAdded <= 0)+ warnings.Add(_translationService.GetResource("ShoppingCart.OutOfStock"));+ else+ warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.QuantityExceedsStock"), maximumQuantityCanBeAdded));+ }+ }+ }+ break;+ case ManageInventoryMethod.ManageStockByBundleProducts:+ {+ foreach (var item in product.BundleProducts)+ {+ var _qty = shoppingCartItem.Quantity * item.Quantity;+ var p1 = await _productService.GetProductById(item.ProductId);+ if (p1 != null)+ {+ if (p1.BackorderModeId == BackorderMode.NoBackorders)+ {+ if (p1.ManageInventoryMethodId == ManageInventoryMethod.ManageStock)+ {+ int maximumQuantityCanBeAdded = _stockQuantityService.GetTotalStockQuantity(p1, warehouseId: warehouseId);+ if (maximumQuantityCanBeAdded < _qty)+ {+ warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.OutOfStock.BundleProduct"), p1.Name));+ }+ }+ if (p1.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByAttributes)+ {+ var combination = _productAttributeParser.FindProductAttributeCombination(p1, shoppingCartItem.Attributes);+ if (combination != null)+ {+ //combination exists - check stock level+ var stockquantity = _stockQuantityService.GetTotalStockQuantityForCombination(p1, combination, warehouseId: warehouseId);+ if (!combination.AllowOutOfStockOrders && stockquantity < _qty)+ {+ if (stockquantity <= 0)+ {+ warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.OutOfStock.BundleProduct"), p1.Name));+ }+ else+ {+ warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.QuantityExceedsStock.BundleProduct"), p1.Name, stockquantity));+ }+ }+ }+ else+ {+ warnings.Add(_translationService.GetResource("ShoppingCart.Combination.NotExist"));+ }+ }+ }+ }+ }+ }+ break;+ case ManageInventoryMethod.ManageStockByAttributes:+ {+ var combination = _productAttributeParser.FindProductAttributeCombination(product, shoppingCartItem.Attributes);+ if (combination != null)+ {+ //combination exists - check stock level+ var stockquantity = _stockQuantityService.GetTotalStockQuantityForCombination(product, combination, warehouseId: warehouseId);+ if (!combination.AllowOutOfStockOrders && stockquantity < shoppingCartItem.Quantity)+ {+ int maximumQuantityCanBeAdded = stockquantity;+ if (maximumQuantityCanBeAdded <= 0)+ {+ warnings.Add(_translationService.GetResource("ShoppingCart.OutOfStock"));+ }+ else+ {+ warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.QuantityExceedsStock"), maximumQuantityCanBeAdded));+ }+ }+ }+ else+ {+ warnings.Add(_translationService.GetResource("ShoppingCart.Combination.NotExist"));+ }+ }+ break;+ default:+ break;+ }+ }++ return warnings;+ }++public virtual IList<string> GetAuctionProductWarning(double bid, Product product, Customer customer){var warnings = new List<string>();@@ -909,6 +916,10 @@ namespace Grand.Business.Checkout.Services.Ordersif (options.GetStandardWarnings)warnings.AddRange(await GetStandardWarnings(customer, product, shoppingCartItem));+ //inventory properties+ if (options.GetInventoryWarnings)+ warnings.AddRange(await GetInventoryProductWarnings(customer, product, shoppingCartItem));+//selected attributesif (options.GetAttributesWarnings)warnings.AddRange(await GetShoppingCartItemAttributeWarnings(customer, product, shoppingCartItem));diff --git a/src/Business/Grand.Business.Checkout/Utilities/ShoppingCartValidatorOptions.cs b/src/Business/Grand.Business.Checkout/Utilities/ShoppingCartValidatorOptions.csindex 569d7fd0e..bea087974 100644--- a/src/Business/Grand.Business.Checkout/Utilities/ShoppingCartValidatorOptions.cs+++ b/src/Business/Grand.Business.Checkout/Utilities/ShoppingCartValidatorOptions.cs@@ -4,6 +4,7 @@{public bool GetStandardWarnings = true;public bool GetAttributesWarnings = true;+ public bool GetInventoryWarnings = true;public bool GetGiftVoucherWarnings = true;public bool GetRequiredProductWarnings = true;public bool GetRentalWarnings = true;diff --git a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/EndAuctionsTask.cs b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/EndAuctionsTask.csindex e00b7220c..b5c5d0e88 100644--- a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/EndAuctionsTask.cs+++ b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/EndAuctionsTask.cs@@ -1,5 +1,6 @@using Grand.Business.Catalog.Interfaces.Products;using Grand.Business.Checkout.Interfaces.Orders;+using Grand.Business.Checkout.Services.Orders;using Grand.Business.Common.Interfaces.Logging;using Grand.Business.Customers.Interfaces;using Grand.Business.Messages.Interfaces;@@ -50,8 +51,9 @@ namespace Grand.Business.System.Services.BackgroundServices.ScheduleTaskscontinue;}- var warnings = await _shoppingCartService.AddToCart(await _customerService.GetCustomerById(bid.CustomerId), bid.ProductId, Domain.Orders.ShoppingCartType.Auctions,- bid.StoreId, bid.WarehouseId, customerEnteredPrice: bid.Amount, getRequiredProductWarnings: false);+ var warnings = (await _shoppingCartService.AddToCart(await _customerService.GetCustomerById(bid.CustomerId), bid.ProductId, Domain.Orders.ShoppingCartType.Auctions,+ bid.StoreId, bid.WarehouseId, customerEnteredPrice: bid.Amount,+ validator: new ShoppingCartValidatorOptions() { GetRequiredProductWarnings = false })).warnings;if (!warnings.Any()){diff --git a/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/EndAuctionsTaskTests.cs b/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/EndAuctionsTaskTests.csindex badcc69bb..5180af3c9 100644--- a/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/EndAuctionsTaskTests.cs+++ b/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/EndAuctionsTaskTests.cs@@ -1,5 +1,6 @@using Grand.Business.Catalog.Interfaces.Products;using Grand.Business.Checkout.Interfaces.Orders;+using Grand.Business.Checkout.Services.Orders;using Grand.Business.Common.Interfaces.Logging;using Grand.Business.Customers.Interfaces;using Grand.Business.Messages.Interfaces;@@ -60,8 +61,9 @@ namespace Grand.Business.System.Tests.Services.BackgroundService_auctionMock.Setup(c => c.GetBidsByProductId(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>())).ReturnsAsync(() => new PagedList<Bid>() { new Bid() });_shoppingCartMock.Setup(c => c.AddToCart(It.IsAny<Customer>(), It.IsAny<string>(), It.IsAny<ShoppingCartType>(), It.IsAny<string>(),It.IsAny<string>(), It.IsAny<IList<CustomAttribute>>(), It.IsAny<double?>(), It.IsAny<DateTime?>(),- It.IsAny<DateTime?>(), It.IsAny<int>(), It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()))- .ReturnsAsync(new List<string>() { "warning" });+ It.IsAny<DateTime?>(), It.IsAny<int>(), It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),+ It.IsAny<ShoppingCartValidatorOptions>()))+ .ReturnsAsync((new List<string>() { "warning" }, null));await _task.Execute();_loggerMock.Verify(c => c.InsertLog(Domain.Logging.LogLevel.Error, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Customer>()), Times.Once);@@ -74,8 +76,8 @@ namespace Grand.Business.System.Tests.Services.BackgroundService_auctionMock.Setup(c => c.GetBidsByProductId(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>())).ReturnsAsync(() => new PagedList<Bid>() { new Bid() });_shoppingCartMock.Setup(c => c.AddToCart(It.IsAny<Customer>(), It.IsAny<string>(), It.IsAny<ShoppingCartType>(), It.IsAny<string>(),It.IsAny<string>(), It.IsAny<IList<CustomAttribute>>(), It.IsAny<double?>(), It.IsAny<DateTime?>(),- It.IsAny<DateTime?>(), It.IsAny<int>(), It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()))- .ReturnsAsync(new List<string>());+ It.IsAny<DateTime?>(), It.IsAny<int>(), It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ShoppingCartValidatorOptions>()))+ .ReturnsAsync((new List<string>(), null));await _task.Execute();_loggerMock.Verify(c => c.InsertLog(Domain.Logging.LogLevel.Error, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Customer>()), Times.Never);diff --git a/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml b/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xmlindex 5103fa5cd..4f6edc00c 100644--- a/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml+++ b/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml@@ -13374,6 +13374,9 @@<Resource Name="Common.Show"><Value>Show</Value></Resource>+ <Resource Name="Common.Success">+ <Value>Success</Value>+ </Resource><Resource Name="Common.Upload"><Value>Upload</Value></Resource>diff --git a/src/Web/Grand.Web/Controllers/ActionCartController.cs b/src/Web/Grand.Web/Controllers/ActionCartController.csindex 24f65fb25..1e50b3e99 100644--- a/src/Web/Grand.Web/Controllers/ActionCartController.cs+++ b/src/Web/Grand.Web/Controllers/ActionCartController.cs@@ -11,6 +11,7 @@ using Grand.Domain.Common;using Grand.Domain.Orders;using Grand.Infrastructure;using Grand.Web.Extensions;+using Grand.Web.Features.Models.Products;using Grand.Web.Features.Models.ShoppingCart;using MediatR;using Microsoft.AspNetCore.Http;@@ -71,23 +72,10 @@ namespace Grand.Web.Controllers#region Methods- [HttpPost]- public virtual async Task<IActionResult> AddProductCatalog(string productId, int shoppingCartTypeId,- int quantity, bool forceredirection = false)+ protected IActionResult RedirectToProduct(Product product, ShoppingCartType cartType, int quantity){- var cartType = (ShoppingCartType)shoppingCartTypeId;-- var product = await _productService.GetProductById(productId);- if (product == null)- //no product found- return Json(new- {- success = false,- message = "No product found with the specified ID"- });-- //we can add only simple products and- if (product.ProductTypeId != ProductType.SimpleProduct || _shoppingCartSettings.AllowToSelectWarehouse)+ //we can't add grouped products+ if (product.ProductTypeId == ProductType.GroupedProduct){return Json(new{@@ -96,17 +84,16 @@ namespace Grand.Web.Controllers}//products with "minimum order quantity" more than a specified qty- if (product.OrderMinimumQuantity > quantity)+ if (cartType == ShoppingCartType.ShoppingCart && product.OrderMinimumQuantity > quantity){//we cannot add to the cart such products from category pages- //it can confuse customers. That's why we redirect customers to the product details pagereturn Json(new{redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName(_workContext.WorkingLanguage.Id) }),});}- if (product.EnteredPrice)+ if (cartType == ShoppingCartType.ShoppingCart && product.EnteredPrice){//cannot be added to the cart (requires a customer to enter price)return Json(new@@ -114,9 +101,8 @@ namespace Grand.Web.Controllersredirect = Url.RouteUrl("Product", new { SeName = product.GetSeName(_workContext.WorkingLanguage.Id) }),});}-var allowedQuantities = product.ParseAllowedQuantities();- if (allowedQuantities.Length > 0)+ if (cartType == ShoppingCartType.ShoppingCart && allowedQuantities.Length > 0){//cannot be added to the cart (requires a customer to select a quantity from dropdownlist)return Json(new@@ -125,55 +111,92 @@ namespace Grand.Web.Controllers});}- if (product.ProductAttributeMappings.Any())+ if (cartType != ShoppingCartType.Wishlist && product.ProductAttributeMappings.Any()){- //product has some attributes. let a customer see them+ //product has some attributesreturn Json(new{redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName(_workContext.WorkingLanguage.Id) }),});}- var customer = _workContext.CurrentCustomer;+ return null;+ }- string warehouseId =- product.UseMultipleWarehouses ? _workContext.CurrentStore.DefaultWarehouseId :+ protected string GetWarehouse(Product product)+ {+ return product.UseMultipleWarehouses ? _workContext.CurrentStore.DefaultWarehouseId :(string.IsNullOrEmpty(_workContext.CurrentStore.DefaultWarehouseId) ? product.WarehouseId : _workContext.CurrentStore.DefaultWarehouseId);+ }- //get standard warnings without attribute validations- //first, try to find existing shopping cart item- var cart = _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, cartType);- var shoppingCartItem = await _shoppingCartService.FindShoppingCartItem(cart, cartType, product.Id, warehouseId);- //if we already have the same product in the cart, then use the total quantity to validate- var quantityToValidate = shoppingCartItem != null ? shoppingCartItem.Quantity + quantity : quantity;- var addToCartWarnings = await _shoppingCartValidator- .GetShoppingCartItemWarnings(customer, new ShoppingCartItem() {- ShoppingCartTypeId = cartType,- StoreId = _workContext.CurrentStore.Id,- WarehouseId = warehouseId,- Quantity = quantityToValidate- },- product, new ShoppingCartValidatorOptions() { GetRequiredProductWarnings = false });- if (addToCartWarnings.Any())- {- //cannot be added to the cart+ [HttpPost]+ public virtual async Task<IActionResult> AddProductCatalog(string productId, int shoppingCartTypeId,+ int quantity, bool forceredirection = false)+ {+ var cartType = (ShoppingCartType)shoppingCartTypeId;++ var product = await _productService.GetProductById(productId);+ if (product == null)+ //no product foundreturn Json(new{- redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName(_workContext.WorkingLanguage.Id) }),+ success = false,+ message = "No product found with the specified ID"});++ var redirect = RedirectToProduct(product, cartType, quantity);+ if (redirect != null)+ return redirect;++ var customer = _workContext.CurrentCustomer;++ string warehouseId = GetWarehouse(product);++ var cart = _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, cartType);++ if (cartType != ShoppingCartType.Wishlist)+ {+ var shoppingCartItem = await _shoppingCartService.FindShoppingCartItem(cart, cartType, product.Id, warehouseId);++ //if we already have the same product in the cart, then use the total quantity to validate+ var quantityToValidate = shoppingCartItem != null ? shoppingCartItem.Quantity + quantity : quantity;+ var addToCartWarnings = await _shoppingCartValidator+ .GetShoppingCartItemWarnings(customer, new ShoppingCartItem() {+ ShoppingCartTypeId = cartType,+ StoreId = _workContext.CurrentStore.Id,+ WarehouseId = warehouseId,+ Quantity = quantityToValidate+ }, product, new ShoppingCartValidatorOptions() {+ GetRequiredProductWarnings = false+ });++ if (addToCartWarnings.Any())+ {+ //cannot be added to the cart+ return Json(new+ {+ redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName(_workContext.WorkingLanguage.Id) }),+ });+ }}- //try adding product to the cart (now including product attribute validation, etc)- addToCartWarnings = await _shoppingCartService.AddToCart(customer: customer,+ //try adding product to the cart+ var addToCart = await _shoppingCartService.AddToCart(customer: customer,productId: productId,shoppingCartType: cartType,storeId: _workContext.CurrentStore.Id,warehouseId: warehouseId,- quantity: quantity, getRequiredProductWarnings: false);- if (addToCartWarnings.Any())+ quantity: quantity,+ validator: new ShoppingCartValidatorOptions() {+ GetRequiredProductWarnings = false,+ GetInventoryWarnings = (cartType == ShoppingCartType.ShoppingCart || !_shoppingCartSettings.AllowOutOfStockItemsToBeAddedToWishlist),+ GetAttributesWarnings = (cartType != ShoppingCartType.Wishlist),+ GetGiftVoucherWarnings = (cartType != ShoppingCartType.Wishlist)+ });++ if (addToCart.warnings.Any()){//cannot be added to the cart- //but we do not display attribute and gift voucher warnings here. do it on the product details pagereturn Json(new{redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName(_workContext.WorkingLanguage.Id) }),@@ -183,6 +206,7 @@ namespace Grand.Web.Controllersvar addtoCartModel = await _mediator.Send(new GetAddToCart() {Product = product,Customer = customer,+ ShoppingCartItem = addToCart.shoppingCartItem,Quantity = quantity,CartType = cartType,Currency = _workContext.WorkingCurrency,@@ -267,18 +291,8 @@ namespace Grand.Web.Controllers}}- [HttpPost]- public virtual async Task<IActionResult> AddProductDetails(string productId, int shoppingCartTypeId, IFormCollection form)+ protected IActionResult ReturnFailMessage(Product product, ShoppingCartType shoppingCartTypeId){- var product = await _productService.GetProductById(productId);- if (product == null)- {- return Json(new- {- redirect = Url.RouteUrl("HomePage"),- });- }-//you can't add group productsif (product.ProductTypeId == ProductType.GroupedProduct){@@ -318,52 +332,26 @@ namespace Grand.Web.Controllers});}+ return null;+ }- #region Update existing shopping cart item?- string updatecartitemid = "";- foreach (string formKey in form.Keys)- if (formKey.Equals(string.Format("addtocart_{0}.UpdatedShoppingCartItemId", productId), StringComparison.OrdinalIgnoreCase))- {- updatecartitemid = form[formKey];- break;- }-- ShoppingCartItem updatecartitem = null;- if (_shoppingCartSettings.AllowCartItemEditing && !string.IsNullOrEmpty(updatecartitemid))- {- var cart = _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, (ShoppingCartType)shoppingCartTypeId);- updatecartitem = cart.FirstOrDefault(x => x.Id == updatecartitemid);-- //is it this product?- if (updatecartitem != null && product.Id != updatecartitem.ProductId)- {- return Json(new- {- success = false,- message = "This product does not match a passed shopping cart item identifier"- });- }- }- #endregion-- #region Customer entered price+ private async Task<double?> GetCustomerEnteredPrice(IFormCollection form, string productId)+ {double? customerEnteredPriceConverted = null;- if (product.EnteredPrice)+ foreach (string formKey in form.Keys){- foreach (string formKey in form.Keys)+ if (formKey.Equals(string.Format("addtocart_{0}.CustomerEnteredPrice", productId), StringComparison.OrdinalIgnoreCase)){- if (formKey.Equals(string.Format("addtocart_{0}.CustomerEnteredPrice", productId), StringComparison.OrdinalIgnoreCase))- {- if (double.TryParse(form[formKey], out double customerEnteredPrice))- customerEnteredPriceConverted = await _currencyService.ConvertToPrimaryStoreCurrency(customerEnteredPrice, _workContext.WorkingCurrency);- break;- }+ if (double.TryParse(form[formKey], out double customerEnteredPrice))+ customerEnteredPriceConverted = await _currencyService.ConvertToPrimaryStoreCurrency(customerEnteredPrice, _workContext.WorkingCurrency);+ break;}}- #endregion-- #region Quantity+ return customerEnteredPriceConverted;+ }+ private int GetQuantity(IFormCollection form, string productId)+ {int quantity = 1;foreach (string formKey in form.Keys)if (formKey.Equals(string.Format("addtocart_{0}.EnteredQuantity", productId), StringComparison.OrdinalIgnoreCase))@@ -372,7 +360,31 @@ namespace Grand.Web.Controllersbreak;}- #endregion+ return quantity;+ }+ [HttpPost]+ public virtual async Task<IActionResult> AddProductDetails(string productId, int shoppingCartTypeId, IFormCollection form)+ {+ var product = await _productService.GetProductById(productId);+ if (product == null)+ {+ return Json(new+ {+ redirect = Url.RouteUrl("HomePage"),+ });+ }++ var message = ReturnFailMessage(product, (ShoppingCartType)shoppingCartTypeId);+ if (message != null)+ return message;++ double? customerEnteredPriceConverted = null;+ if (product.EnteredPrice)+ {+ customerEnteredPriceConverted = await GetCustomerEnteredPrice(form, productId);+ }++ var quantity = GetQuantity(form, productId);//product and gift voucher attributesvar attributes = await _mediator.Send(new GetParseProductAttributes() { Product = product, Form = form });@@ -454,9 +466,7 @@ namespace Grand.Web.Controllers}}- var cartType = updatecartitem == null ? (ShoppingCartType)shoppingCartTypeId :- //if the item to update is found, then we ignore the specified "shoppingCartTypeId" parameter- updatecartitem.ShoppingCartTypeId;+ var cartType = (ShoppingCartType)shoppingCartTypeId;//save itemvar addToCartWarnings = new List<string>();@@ -467,37 +477,19 @@ namespace Grand.Web.Controllersproduct.UseMultipleWarehouses ? _workContext.CurrentStore.DefaultWarehouseId :(string.IsNullOrEmpty(_workContext.CurrentStore.DefaultWarehouseId) ? product.WarehouseId : _workContext.CurrentStore.DefaultWarehouseId);- if (updatecartitem == null)- {- //add to the cart- addToCartWarnings.AddRange(await _shoppingCartService.AddToCart(_workContext.CurrentCustomer,- productId, cartType, _workContext.CurrentStore.Id, warehouseId,- attributes, customerEnteredPriceConverted,- rentalStartDate, rentalEndDate, quantity, true, reservationId, parameter, duration, getRequiredProductWarnings: false));- }- else- {- var cart = _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, (ShoppingCartType)shoppingCartTypeId);- var otherCartItemWithSameParameters = await _shoppingCartService.FindShoppingCartItem(- cart, updatecartitem.ShoppingCartTypeId, productId, warehouseId, attributes, customerEnteredPriceConverted,- rentalStartDate, rentalEndDate);- if (otherCartItemWithSameParameters != null &&- otherCartItemWithSameParameters.Id == updatecartitem.Id)- {- //ensure it's other shopping cart cart item- otherCartItemWithSameParameters = null;- }- //update existing item- addToCartWarnings.AddRange(await _shoppingCartService.UpdateShoppingCartItem(_workContext.CurrentCustomer,- updatecartitem.Id, warehouseId, attributes, customerEnteredPriceConverted,- rentalStartDate, rentalEndDate, quantity, true));- if (otherCartItemWithSameParameters != null && !addToCartWarnings.Any())- {- //delete the same shopping cart item (the other one)- await _shoppingCartService.DeleteShoppingCartItem(_workContext.CurrentCustomer, otherCartItemWithSameParameters);- }- }+ //add to the cart+ var (warnings, shoppingCartItem) = await _shoppingCartService.AddToCart(_workContext.CurrentCustomer,+ productId, cartType, _workContext.CurrentStore.Id, warehouseId,+ attributes, customerEnteredPriceConverted,+ rentalStartDate, rentalEndDate, quantity, true, reservationId, parameter, duration,+ new ShoppingCartValidatorOptions() {+ GetRequiredProductWarnings = false,+ GetInventoryWarnings = (cartType == ShoppingCartType.ShoppingCart || !_shoppingCartSettings.AllowOutOfStockItemsToBeAddedToWishlist),+ });++ addToCartWarnings.AddRange(warnings);+#region Return resultif (addToCartWarnings.Any())@@ -514,6 +506,7 @@ namespace Grand.Web.Controllersvar addtoCartModel = await _mediator.Send(new GetAddToCart() {Product = product,Customer = _workContext.CurrentCustomer,+ ShoppingCartItem = shoppingCartItem,Quantity = quantity,CartType = cartType,CustomerEnteredPrice = customerEnteredPriceConverted,@@ -714,6 +707,262 @@ namespace Grand.Web.Controllers}++ public virtual async Task<IActionResult> GetItemCart(string shoppingcartId)+ {+ var cart = _workContext.CurrentCustomer.ShoppingCartItems.FirstOrDefault(sci => sci.Id == shoppingcartId);+ if (cart == null)+ return Json(new+ {+ success = false,+ message = "No item cart found with the specified ID"+ });++ var product = await _productService.GetProductById(cart.ProductId);+ if (product == null)+ return Json(new+ {+ success = false,+ message = "No product found with the specified ID"+ });+++ //availability dates+ if (!product.IsAvailable() && !(product.ProductTypeId == ProductType.Auction))+ return Json(new+ {+ success = false,+ message = "No product found with the specified ID"+ });++ //visible individually?+ if (!product.VisibleIndividually)+ {+ //is this one an associated products?+ var parentGroupedProduct = await _productService.GetProductById(product.ParentGroupedProductId);+ if (parentGroupedProduct == null)+ {+ return Json(new+ {+ redirect = Url.RouteUrl("HomePage"),+ });+ }+ return Json(new+ {+ redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName(_workContext.WorkingLanguage.Id) }),+ });+ }++ //prepare the model+ var model = await _mediator.Send(new GetProductDetailsPage() {+ Store = _workContext.CurrentStore,+ Product = product,+ UpdateCartItem = cart+ });++ return Json(new+ {+ success = true,+ model = model,+ });+ }++ [HttpPost]+ public virtual async Task<IActionResult> UpdateItemCart(string shoppingCartItemId, IFormCollection form)+ {+ var cart = _workContext.CurrentCustomer.ShoppingCartItems.FirstOrDefault(sci => sci.Id == shoppingCartItemId);+ if (cart == null)+ return Json(new+ {+ success = false,+ message = "No item cart found with the specified ID"+ });++ var product = await _productService.GetProductById(cart.ProductId);+ if (product == null)+ {+ return Json(new+ {+ redirect = Url.RouteUrl("HomePage"),+ });+ }++ //you can't add group products+ if (product.ProductTypeId == ProductType.GroupedProduct)+ {+ return Json(new+ {+ success = false,+ message = "Grouped products couldn't be added to the cart"+ });+ }++ //you can't add reservation product to wishlist+ if (product.ProductTypeId == ProductType.Reservation && cart.ShoppingCartTypeId == ShoppingCartType.Wishlist)+ {+ return Json(new+ {+ success = false,+ message = "Reservation products couldn't be added to the wishlist"+ });+ }++ //you can't add auction product to wishlist+ if (product.ProductTypeId == ProductType.Auction)+ {+ return Json(new+ {+ success = false,+ message = "Auction products couldn't be added to the wishlist"+ });+ }+ //check available date+ if (product.AvailableEndDateTimeUtc.HasValue && product.AvailableEndDateTimeUtc.Value < DateTime.UtcNow)+ {+ return Json(new+ {+ success = false,+ message = _translationService.GetResource("ShoppingCart.NotAvailable")+ });+ }++ #region Customer entered price+ double? customerEnteredPriceConverted = null;+ if (product.EnteredPrice)+ {+ foreach (string formKey in form.Keys)+ {+ if (formKey.Equals(string.Format("addtocart_{0}.CustomerEnteredPrice", cart.ProductId), StringComparison.OrdinalIgnoreCase))+ {+ if (double.TryParse(form[formKey], out double customerEnteredPrice))+ customerEnteredPriceConverted = await _currencyService.ConvertToPrimaryStoreCurrency(customerEnteredPrice, _workContext.WorkingCurrency);+ break;+ }+ }+ }+ #endregion++ #region Quantity++ var quantity = cart.Quantity;+ foreach (string formKey in form.Keys)+ if (formKey.Equals(string.Format("addtocart_{0}.EnteredQuantity", cart.ProductId), StringComparison.OrdinalIgnoreCase))+ {+ int.TryParse(form[formKey], out quantity);+ break;+ }++ #endregion++ //product and gift voucher attributes+ var attributes = await _mediator.Send(new GetParseProductAttributes() { Product = product, Form = form });++ //rental attributes+ DateTime? rentalStartDate = cart.RentalStartDateUtc;+ DateTime? rentalEndDate = cart.RentalEndDateUtc;+ if (product.ProductTypeId == ProductType.Reservation)+ {+ product.ParseReservationDates(form, out rentalStartDate, out rentalEndDate);+ }++ //product reservation+ string reservationId = cart.ReservationId;+ string parameter = cart.Parameter;+ string duration = cart.Duration;+ if (product.ProductTypeId == ProductType.Reservation)+ {+ foreach (string formKey in form.Keys)+ {+ if (formKey.Contains("Reservation"))+ {+ reservationId = form["Reservation"].ToString();+ break;+ }+ }++ if (product.IntervalUnitId == IntervalUnit.Hour || product.IntervalUnitId == IntervalUnit.Minute)+ {+ if (string.IsNullOrEmpty(reservationId))+ {+ return Json(new+ {+ success = false,+ message = _translationService.GetResource("Product.Addtocart.Reservation.Required")+ });+ }+ var productReservationService = HttpContext.RequestServices.GetRequiredService<IProductReservationService>();+ var reservation = await productReservationService.GetProductReservation(reservationId);+ if (reservation == null)+ {+ return Json(new+ {+ success = false,+ message = "No reservation found"+ });+ }+ duration = reservation.Duration;+ rentalStartDate = reservation.Date;+ parameter = reservation.Parameter;+ }+ else if (product.IntervalUnitId == IntervalUnit.Day)+ {+ string datefrom = "";+ string dateto = "";+ foreach (var item in form)+ {+ if (item.Key == "reservationDatepickerFrom")+ {+ datefrom = item.Value;+ }++ if (item.Key == "reservationDatepickerTo")+ {+ dateto = item.Value;+ }+ }++ string datePickerFormat = "MM/dd/yyyy";+ if (!string.IsNullOrEmpty(datefrom))+ {+ rentalStartDate = DateTime.ParseExact(datefrom, datePickerFormat, CultureInfo.InvariantCulture);+ }++ if (!string.IsNullOrEmpty(dateto))+ {+ rentalEndDate = DateTime.ParseExact(dateto, datePickerFormat, CultureInfo.InvariantCulture);+ }+ }+ }++ //save item+ var addToCartWarnings = new List<string>();++ var warehouseId = _shoppingCartSettings.AllowToSelectWarehouse ?+ form["WarehouseId"].ToString() : cart.WarehouseId;++ //update existing item+ addToCartWarnings.AddRange(await _shoppingCartService.UpdateShoppingCartItem(_workContext.CurrentCustomer,+ cart.Id, warehouseId, attributes, customerEnteredPriceConverted,+ rentalStartDate, rentalEndDate, quantity, true));++ if (addToCartWarnings.Any())+ {+ //cannot be updated the cart/wishlist+ return Json(new+ {+ success = false,+ message = addToCartWarnings.ToArray()+ });+ }++ return Json(new+ {+ success = true,+ message = ""+ });++ }+#endregion}diff --git a/src/Web/Grand.Web/Controllers/ShoppingCartController.cs b/src/Web/Grand.Web/Controllers/ShoppingCartController.csindex 5c4bbebb3..08c78f4a5 100644--- a/src/Web/Grand.Web/Controllers/ShoppingCartController.cs+++ b/src/Web/Grand.Web/Controllers/ShoppingCartController.cs@@ -269,42 +269,43 @@ namespace Grand.Web.Controllers[AutoValidateAntiforgeryToken][HttpPost]- public virtual async Task<IActionResult> UpdateCart(IFormCollection form)+ public virtual async Task<IActionResult> UpdateQuantity(string shoppingcartId, int quantity){if (!await _permissionService.Authorize(StandardPermission.EnableShoppingCart))- return RedirectToRoute("HomePage");-- var shoppingCartTypes = new List<ShoppingCartType>();- shoppingCartTypes.Add(ShoppingCartType.ShoppingCart);- if (_shoppingCartSettings.AllowOnHoldCart)- shoppingCartTypes.Add(ShoppingCartType.OnHoldCart);-- var cart = _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, shoppingCartTypes.ToArray());+ return Json(new+ {+ success = false,+ warnings = "No permission",+ });- //current warnings <cart item identifier, warnings>- var innerWarnings = new Dictionary<string, IList<string>>();- foreach (var sci in cart)+ var cart = _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, PrepareCartTypes())+ .FirstOrDefault(x => x.Id == shoppingcartId);+ if (cart == null){- foreach (string formKey in form.Keys)- if (formKey.Equals(string.Format("itemquantity{0}", sci.Id), StringComparison.OrdinalIgnoreCase))- {- if (int.TryParse(form[formKey], out int newQuantity))- {- var currSciWarnings = await _shoppingCartService.UpdateShoppingCartItem(_workContext.CurrentCustomer,- sci.Id, sci.WarehouseId, sci.Attributes, sci.EnteredPrice,- sci.RentalStartDateUtc, sci.RentalEndDateUtc,- newQuantity, true, sci.ReservationId, sci.Id);- innerWarnings.Add(sci.Id, currSciWarnings);- }- break;- }+ return Json(new+ {+ success = false,+ warnings = "Shopping cart item not found",+ });+ }+ if (quantity <= 0)+ {+ return Json(new+ {+ success = false,+ warnings = "Wrong quantity",+ });}- cart = _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, PrepareCartTypes());+ var warnings = new List<string>();+ var currSciWarnings = await _shoppingCartService.UpdateShoppingCartItem(_workContext.CurrentCustomer,+ cart.Id, cart.WarehouseId, cart.Attributes, cart.EnteredPrice,+ cart.RentalStartDateUtc, cart.RentalEndDateUtc,+ quantity, true);+ warnings.AddRange(currSciWarnings);- var model = await _mediator.Send(new GetShoppingCart()- {- Cart = cart,+ var model = await _mediator.Send(new GetShoppingCart() {+ Cart = _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, PrepareCartTypes()),Customer = _workContext.CurrentCustomer,Currency = _workContext.WorkingCurrency,Language = _workContext.WorkingLanguage,@@ -312,24 +313,14 @@ namespace Grand.Web.ControllersTaxDisplayType = _workContext.TaxDisplayType});- //update current warnings- foreach (var kvp in innerWarnings)- {- //kvp = <cart item identifier, warnings>- var sciId = kvp.Key;- var warnings = kvp.Value;- //find model- var sciModel = model.Items.FirstOrDefault(x => x.Id == sciId);- if (sciModel != null)- foreach (var w in warnings)- if (!sciModel.Warnings.Contains(w))- sciModel.Warnings.Add(w);- }return Json(new{+ success = !warnings.Any(),+ warnings = string.Join(", ", warnings),totalproducts = string.Format(_translationService.GetResource("ShoppingCart.HeaderQuantity"), model.Items.Sum(x => x.Quantity)),model = model});+}public virtual async Task<IActionResult> ClearCart()diff --git a/src/Web/Grand.Web/Controllers/WishlistController.cs b/src/Web/Grand.Web/Controllers/WishlistController.csindex e7c671e9f..bfbfb5093 100644--- a/src/Web/Grand.Web/Controllers/WishlistController.cs+++ b/src/Web/Grand.Web/Controllers/WishlistController.cs@@ -1,5 +1,6 @@using Grand.Business.Checkout.Extensions;using Grand.Business.Checkout.Interfaces.Orders;+using Grand.Business.Checkout.Services.Orders;using Grand.Business.Common.Interfaces.Directory;using Grand.Business.Common.Interfaces.Localization;using Grand.Business.Common.Interfaces.Security;@@ -66,6 +67,7 @@ namespace Grand.Web.Controllers#region Wishlist+ [HttpGet]public virtual async Task<IActionResult> Index(Guid? customerGuid){if (!await _permissionService.Authorize(StandardPermission.EnableWishlist))@@ -82,8 +84,7 @@ namespace Grand.Web.Controllersif (!string.IsNullOrEmpty(_workContext.CurrentStore.Id))cart = cart.LimitPerStore(_shoppingCartSettings.SharedCartBetweenStores, _workContext.CurrentStore.Id);- var model = await _mediator.Send(new GetWishlist()- {+ var model = await _mediator.Send(new GetWishlist() {Cart = cart.ToList(),Customer = _workContext.CurrentCustomer,Language = _workContext.WorkingLanguage,@@ -96,113 +97,103 @@ namespace Grand.Web.Controllersreturn View(model);}+ [AutoValidateAntiforgeryToken][HttpPost]- public virtual async Task<IActionResult> UpdateWishlist(IFormCollection form)+ public virtual async Task<IActionResult> UpdateQuantity(string shoppingcartId, int quantity){if (!await _permissionService.Authorize(StandardPermission.EnableWishlist))return RedirectToRoute("HomePage");- var customer = _workContext.CurrentCustomer;+ var cart = _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, ShoppingCartType.Wishlist).FirstOrDefault(x => x.Id == shoppingcartId);+ if (cart == null)+ {+ return Json(new+ {+ success = false,+ warnings = "Shopping cart item not found",+ });+ }+ if (quantity <= 0)+ {+ return Json(new+ {+ success = false,+ warnings = "Wrong quantity ",+ });+ }- var cart = _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, ShoppingCartType.Wishlist);- var allIdsToRemove = !string.IsNullOrEmpty(form["removefromcart"].ToString())- ? form["removefromcart"].ToString().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)- .Select(x => x)- .ToList()- : new List<string>();+ var warnings = new List<string>();+ var currSciWarnings = await _shoppingCartService.UpdateShoppingCartItem(_workContext.CurrentCustomer,+ cart.Id, cart.WarehouseId, cart.Attributes, cart.EnteredPrice,+ cart.RentalStartDateUtc, cart.RentalEndDateUtc,+ quantity, true);+ warnings.AddRange(currSciWarnings);- //current warnings <cart item identifier, warnings>- var innerWarnings = new Dictionary<string, IList<string>>();- foreach (var sci in cart)+ return Json(new{- bool remove = allIdsToRemove.Contains(sci.Id);- if (remove)- await _shoppingCartService.DeleteShoppingCartItem(customer, sci);- else- {- foreach (string formKey in form.Keys)- if (formKey.Equals(string.Format("itemquantity{0}", sci.Id), StringComparison.OrdinalIgnoreCase))- {- if (int.TryParse(form[formKey], out int newQuantity))- {- var currSciWarnings = await _shoppingCartService.UpdateShoppingCartItem(_workContext.CurrentCustomer,- sci.Id, sci.WarehouseId, sci.Attributes, sci.EnteredPrice,- sci.RentalStartDateUtc, sci.RentalEndDateUtc,- newQuantity, true);- innerWarnings.Add(sci.Id, currSciWarnings);- }- break;- }- }- }+ success = !warnings.Any(),+ warnings = string.Join(", ", warnings),+ totalproducts = _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, ShoppingCartType.Wishlist).Sum(x => x.Quantity),+ });- return RedirectToAction("Index");}[HttpPost]- public virtual async Task<IActionResult> AddItemsToCartFromWishlist(Guid? customerGuid, IFormCollection form)+ public virtual async Task<IActionResult> AddItemToCartFromWishlist(string shoppingcartId){if (!await _permissionService.Authorize(StandardPermission.EnableShoppingCart))- return RedirectToRoute("HomePage");+ return Json(new { success = false, message = "No permission" });+if (!await _permissionService.Authorize(StandardPermission.EnableWishlist))- return RedirectToRoute("HomePage");+ return Json(new { success = false, message = "No permission" });- var pageCustomer = customerGuid.HasValue- ? await _customerService.GetCustomerByGuid(customerGuid.Value)- : _workContext.CurrentCustomer;- if (pageCustomer == null)- return RedirectToRoute("HomePage");- var pageCart = pageCustomer.ShoppingCartItems.Where(sci => sci.ShoppingCartTypeId == ShoppingCartType.Wishlist);- if (!string.IsNullOrEmpty(_workContext.CurrentStore.Id))- pageCart = pageCart.LimitPerStore(_shoppingCartSettings.SharedCartBetweenStores, _workContext.CurrentStore.Id);-- var allWarnings = new List<string>();- var numberOfAddedItems = 0;- var allIdsToAdd = form.ContainsKey("addtocart") ? form["addtocart"].ToString().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)- .Select(x => x)- .ToList()- : new List<string>();- foreach (var sci in pageCart.ToList())- {- if (allIdsToAdd.Contains(sci.Id))- {- var warnings = await _shoppingCartService.AddToCart(_workContext.CurrentCustomer,- sci.ProductId, ShoppingCartType.ShoppingCart,- _workContext.CurrentStore.Id, sci.WarehouseId,- sci.Attributes, sci.EnteredPrice,- sci.RentalStartDateUtc, sci.RentalEndDateUtc, sci.Quantity, true, getRequiredProductWarnings: false);- if (!warnings.Any())- numberOfAddedItems++;- if (_shoppingCartSettings.MoveItemsFromWishlistToCart && //settings enabled- !customerGuid.HasValue &&- !warnings.Any())- {- await _shoppingCartService.DeleteShoppingCartItem(_workContext.CurrentCustomer, sci);- }- allWarnings.AddRange(warnings);- }- }+ var itemCart = _workContext.CurrentCustomer.ShoppingCartItems+ .FirstOrDefault(sci => sci.ShoppingCartTypeId == ShoppingCartType.Wishlist && sci.Id == shoppingcartId);- if (numberOfAddedItems > 0)- {- //redirect to the shopping cart page+ if (itemCart == null)+ return Json(new { success = false, message = "Shopping cart ident not found" });- if (allWarnings.Any())- {- Error(_translationService.GetResource("Wishlist.AddToCart.Error"), true);- }+ var warnings = (await _shoppingCartService.AddToCart(_workContext.CurrentCustomer,+ itemCart.ProductId, ShoppingCartType.ShoppingCart,+ _workContext.CurrentStore.Id, itemCart.WarehouseId,+ itemCart.Attributes, itemCart.EnteredPrice,+ itemCart.RentalStartDateUtc, itemCart.RentalEndDateUtc, itemCart.Quantity, true,+ validator: new ShoppingCartValidatorOptions() { GetRequiredProductWarnings = false })).warnings;++ if (warnings.Any())+ return Json(new { success = false, message = string.Join(',', warnings) });++ if(_shoppingCartSettings.MoveItemsFromWishlistToCart)+ await _shoppingCartService.DeleteShoppingCartItem(_workContext.CurrentCustomer, itemCart);++ return Json(new { success = true, message = "" });- return RedirectToRoute("ShoppingCart");- }- else- {- return RedirectToAction("Index");- }}+ [HttpPost]+ public virtual async Task<IActionResult> DeleteItemFromWishlist(string shoppingcartId)+ {+ if (!await _permissionService.Authorize(StandardPermission.EnableShoppingCart))+ return Json(new { success = false, message = "No permission" });++ if (!await _permissionService.Authorize(StandardPermission.EnableWishlist))+ return Json(new { success = false, message = "No permission" });++ var itemCart = _workContext.CurrentCustomer.ShoppingCartItems+ .FirstOrDefault(sci => sci.ShoppingCartTypeId == ShoppingCartType.Wishlist && sci.Id == shoppingcartId);++ if (itemCart == null)+ return Json(new { success = false, message = "Shopping cart ident not found" });++ await _shoppingCartService.DeleteShoppingCartItem(_workContext.CurrentCustomer, itemCart);++ return Json(new { success = true, message = "" });++ }+ [HttpGet]public virtual async Task<IActionResult> EmailWishlist([FromServices] CaptchaSettings captchaSettings){if (!await _permissionService.Authorize(StandardPermission.EnableWishlist) || !_shoppingCartSettings.EmailWishlistEnabled)@@ -213,8 +204,7 @@ namespace Grand.Web.Controllersif (!cart.Any())return RedirectToRoute("HomePage");- var model = new WishlistEmailAFriendModel- {+ var model = new WishlistEmailAFriendModel {YourEmailAddress = _workContext.CurrentCustomer.Email,DisplayCaptcha = captchaSettings.Enabled && captchaSettings.ShowOnEmailWishlistToFriendPage};diff --git a/src/Web/Grand.Web/Endpoints/EndpointProvider.cs b/src/Web/Grand.Web/Endpoints/EndpointProvider.csindex c69922782..b185a2400 100644--- a/src/Web/Grand.Web/Endpoints/EndpointProvider.cs+++ b/src/Web/Grand.Web/Endpoints/EndpointProvider.cs@@ -567,10 +567,13 @@ namespace Grand.Web.Endpoints$"{pattern}removegiftvouchercode/",new { controller = "ShoppingCart", action = "RemoveGiftVoucherCode" });- endpointRouteBuilder.MapControllerRoute("UpdateCart",- $"{pattern}updatecart/",- new { controller = "ShoppingCart", action = "UpdateCart" });+ endpointRouteBuilder.MapControllerRoute("UpdateQuantityCart",+ $"{pattern}cart/updatequantity",+ new { controller = "ShoppingCart", action = "UpdateQuantity" });+ endpointRouteBuilder.MapControllerRoute("UpdateItemCart",+ $"{pattern}updateitemcart/",+ new { controller = "ActionCart", action = "UpdateItemCart" });//get state list by country ID (AJAX link)endpointRouteBuilder.MapControllerRoute("DeleteCartItem",pattern + "deletecartitem/{id?}",@@ -590,24 +593,35 @@ namespace Grand.Web.Endpointspattern + "uploadfilecheckoutattribute/{attributeId}",new { controller = "ShoppingCart", action = "UploadFileCheckoutAttribute" });+ //update item cart+ endpointRouteBuilder.MapControllerRoute("GetItemCart",+ pattern + "getitemcart/{shoppingcartId?}",+ new { controller = "ActionCart", action = "GetItemCart" });+//wishlistendpointRouteBuilder.MapControllerRoute("Wishlist",pattern + "wishlist/{customerGuid?}",new { controller = "Wishlist", action = "Index" });+ //update wishlist+ endpointRouteBuilder.MapControllerRoute("UpdateQuantityWishlist",+ $"{pattern}wishlist/updatequantity",+ new { controller = "Wishlist", action = "UpdateQuantity" });+//email wishlistendpointRouteBuilder.MapControllerRoute("EmailWishlist",pattern + "emailwishlist",new { controller = "Wishlist", action = "EmailWishlist" });- //email wishlist- endpointRouteBuilder.MapControllerRoute("UpdateWishlist",- pattern + "updatewishlist",- new { controller = "Wishlist", action = "UpdateWishlist" });- //email wishlist- endpointRouteBuilder.MapControllerRoute("AddItemsToCartFromWishlist",- pattern + "additemstocartwishlist",- new { controller = "Wishlist", action = "AddItemsToCartFromWishlist" });+ //add item to wishlist+ endpointRouteBuilder.MapControllerRoute("AddItemToCartFromWishlist",+ pattern + "wishlist/addItemtocartfromwishlist/{shoppingcartId?}",+ new { controller = "Wishlist", action = "AddItemToCartFromWishlist" });++ //delete item from wishlist+ endpointRouteBuilder.MapControllerRoute("DeleteItemFromWishlist",+ pattern + "wishlist/deleteitemfromwishlist/{shoppingcartId?}",+ new { controller = "Wishlist", action = "DeleteItemFromWishlist" });}private void RegisterOrderRoute(IEndpointRouteBuilder endpointRouteBuilder, string pattern)diff --git a/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetAddToCartHandler.cs b/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetAddToCartHandler.csindex 480e4a960..d9bc0e906 100644--- a/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetAddToCartHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetAddToCartHandler.cs@@ -109,19 +109,8 @@ namespace Grand.Web.Features.Handlers.ShoppingCartif (request.CartType != ShoppingCartType.Auctions){- var cartItems = request.Customer.ShoppingCartItems- .Where(x => x.ShoppingCartTypeId == request.CartType &&- x.ProductId == request.Product.Id &&- x.EnteredPrice == request.CustomerEnteredPrice);-- if (request.Attributes != null && request.Attributes.Any() && cartItems.Count() > 1)- {- cartItems = cartItems.Where(x => x.Attributes.All(y => request.Attributes.Any(z => z.Key == y.Key && z.Value == y.Value)));- }-- var sci = cartItems.FirstOrDefault();-- model.ItemQuantity = sci.Quantity;++ model.ItemQuantity = request.Quantity;//unit pricesif (request.Product.CallForPrice)@@ -130,11 +119,11 @@ namespace Grand.Web.Features.Handlers.ShoppingCart}else{- var productprices = await _taxService.GetProductPrice(request.Product, (await _pricingService.GetUnitPrice(sci, request.Product)).unitprice);+ var productprices = await _taxService.GetProductPrice(request.Product, (await _pricingService.GetUnitPrice(request.ShoppingCartItem, request.Product)).unitprice);double taxRate = productprices.taxRate;model.Price = !request.CustomerEnteredPrice.HasValue ? _priceFormatter.FormatPrice(productprices.productprice) : _priceFormatter.FormatPrice(request.CustomerEnteredPrice.Value);model.DecimalPrice = request.CustomerEnteredPrice ?? productprices.productprice;- model.TotalPrice = _priceFormatter.FormatPrice(productprices.productprice * sci.Quantity);+ model.TotalPrice = _priceFormatter.FormatPrice(productprices.productprice * request.ShoppingCartItem.Quantity);}//picturediff --git a/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetShoppingCartHandler.cs b/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetShoppingCartHandler.csindex 0afe728ff..7b2600b2a 100644--- a/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetShoppingCartHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetShoppingCartHandler.cs@@ -381,10 +381,7 @@ namespace Grand.Web.Features.Handlers.ShoppingCartAttributeInfo = await _productAttributeFormatter.FormatAttributes(product, sci.Attributes),};- cartItemModel.AllowItemEditing = _shoppingCartSettings.AllowCartItemEditing &&- product.ProductTypeId == ProductType.SimpleProduct &&- (!String.IsNullOrEmpty(cartItemModel.AttributeInfo) || product.IsGiftVoucher) &&- product.VisibleIndividually;+ cartItemModel.AllowItemEditing = _shoppingCartSettings.AllowCartItemEditing && product.VisibleIndividually;if (product.RequireOtherProducts)cartItemModel.DisableRemoval = product.RequireOtherProducts && product.ParseRequiredProductIds().Intersect(request.Cart.Select(x => x.ProductId)).Any();diff --git a/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetWishlistHandler.cs b/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetWishlistHandler.csindex e427c6274..836886ffc 100644--- a/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetWishlistHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetWishlistHandler.cs@@ -135,7 +135,7 @@ namespace Grand.Web.Features.Handlers.ShoppingCartAttributeInfo = await _productAttributeFormatter.FormatAttributes(product, sci.Attributes),};- cartItemModel.AllowItemEditing = _shoppingCartSettings.AllowCartItemEditing && product.ProductTypeId == ProductType.SimpleProduct && (!String.IsNullOrEmpty(cartItemModel.AttributeInfo) || product.IsGiftVoucher) && product.VisibleIndividually;+ cartItemModel.AllowItemEditing = _shoppingCartSettings.AllowCartItemEditing && product.VisibleIndividually;//allowed quantitiesvar allowedQuantities = product.ParseAllowedQuantities();diff --git a/src/Web/Grand.Web/Features/Models/ShoppingCart/GetAddToCart.cs b/src/Web/Grand.Web/Features/Models/ShoppingCart/GetAddToCart.csindex 929307094..1837b0b45 100644--- a/src/Web/Grand.Web/Features/Models/ShoppingCart/GetAddToCart.cs+++ b/src/Web/Grand.Web/Features/Models/ShoppingCart/GetAddToCart.cs@@ -20,6 +20,7 @@ namespace Grand.Web.Features.Models.ShoppingCartpublic Language Language { get; set; }public Currency Currency { get; set; }public Store Store { get; set; }+ public ShoppingCartItem ShoppingCartItem { get; set; }public TaxDisplayType TaxDisplayType { get; set; }public int Quantity { get; set; }public double? CustomerEnteredPrice { get; set; }diff --git a/src/Web/Grand.Web/Views/Shared/_AddToCartQV.cshtml b/src/Web/Grand.Web/Views/Shared/_AddToCartQV.cshtmlindex b5a9fbd60..4298dcfdc 100644--- a/src/Web/Grand.Web/Views/Shared/_AddToCartQV.cshtml+++ b/src/Web/Grand.Web/Views/Shared/_AddToCartQV.cshtml@@ -1,57 +1,76 @@@{var addtocart = @Url.RouteUrl("AddProductDetails");+ var updateitemcart = @Url.RouteUrl("UpdateItemCart");}-<template v-if="PopupQuickViewVueModal.AddToCart.EnteredPrice">- <div class="customer-entered-price mb-3 d-flex w-100 flex-column">- <div class="price-input">- <label :for="'addtocart_' + PopupQuickViewVueModal.AddToCart.ProductId + '_CustomerEnteredPrice'" class="enter-price-label">@Loc["Products.EnterProductPrice"]</label>- <input :id="'addtocart_' + PopupQuickViewVueModal.AddToCart.ProductId + '_CustomerEnteredPrice'" :name="'addtocart_' + PopupQuickViewVueModal.AddToCart.ProductId + '.CustomerEnteredPrice'" type="text" :value="PopupQuickViewVueModal.AddToCart.CustomerEnteredPrice" class="form-control enter-price-input" />- </div>- <div class="price-range pt-1">- {{PopupQuickViewVueModal.AddToCart.CustomerEnteredPriceRange}}+ <template v-if="PopupQuickViewVueModal.AddToCart.UpdatedShoppingCartItemId !== null">+ <input type="hidden" id="shoppingCartItemId" name="shoppingCartItemId" :value="UpdatedShoppingCartItemId" />+ </template>+ <template v-if="PopupQuickViewVueModal.AddToCart.EnteredPrice">+ <div class="customer-entered-price mb-3 d-flex w-100 flex-column">+ <div class="price-input">+ <label :for="'addtocart_' + PopupQuickViewVueModal.AddToCart.ProductId + '_CustomerEnteredPrice'" class="enter-price-label">@Loc["Products.EnterProductPrice"]</label>+ <input :id="'addtocart_' + PopupQuickViewVueModal.AddToCart.ProductId + '_CustomerEnteredPrice'" :name="'addtocart_' + PopupQuickViewVueModal.AddToCart.ProductId + '.CustomerEnteredPrice'" type="text" :value="PopupQuickViewVueModal.AddToCart.CustomerEnteredPrice" class="form-control enter-price-input" />+ </div>+ <div class="price-range pt-1">+ {{PopupQuickViewVueModal.AddToCart.CustomerEnteredPriceRange}}+ </div></div>- </div>-</template>-<div role="group" class="input-group product-add-to-cart flex-nowrap">- <template v-if="!PopupQuickViewVueModal.AddToCart.DisableBuyButton || PopupQuickViewVueModal.AddToCart.EnteredPrice">- <template v-if="PopupQuickViewVueModal.AddToCart.MinimumQuantityNotification !== null">- <div class="min-qty-notification text-danger w-100 mb-2">{{PopupQuickViewVueModal.AddToCart.MinimumQuantityNotification}}</div>- </template></template>- <template v-if="!PopupQuickViewVueModal.AddToCart.DisableBuyButton">- <template v-if="PopupQuickViewVueModal.AddToCart.AllowedQuantities.length > 0">- <select :id="'addtocart_' + PopupQuickViewVueModal.AddToCart.ProductId + '_EnteredQuantity'" :name="'addtocart_' + PopupQuickViewVueModal.AddToCart.ProductId + '.EnteredQuantity'" class="custom-select form-control qty-dropdown mr-2">- <template v-for="option in PopupQuickViewVueModal.AddToCart.AllowedQuantities">- <option :value="option.Value" :disabled="option.Disabled" :selected="option.Selected">{{option.Text}}</option>- </template>- </select>- </template>- <template v-else>- <label :for="'addtocart_' + PopupQuickViewVueModal.AddToCart.ProductId + '_EnteredQuantity'" class="sr-only">@Loc["ShoppingCart.AddToCart"]</label>- <input :value="PopupQuickViewVueModal.AddToCart.EnteredQuantity" :id="'addtocart_' + PopupQuickViewVueModal.AddToCart.ProductId + '_EnteredQuantity'" :name="'addtocart_' + PopupQuickViewVueModal.AddToCart.ProductId + '.EnteredQuantity'" value="" class="qty-input form-control text-center" type="number" inputmode="numeric" />- <template v-if="PopupQuickViewVueModal.AddToCart.MeasureUnit !== ''">- <span class="qty-unit d-flex align-items-center mr-2">- {{PopupQuickViewVueModal.AddToCart.MeasureUnit}}- </span>+ <div role="group" class="input-group product-add-to-cart flex-nowrap">+ <template v-if="!PopupQuickViewVueModal.AddToCart.DisableBuyButton || PopupQuickViewVueModal.AddToCart.EnteredPrice">+ <template v-if="PopupQuickViewVueModal.AddToCart.MinimumQuantityNotification !== null">+ <div class="min-qty-notification text-danger w-100 mb-2">{{PopupQuickViewVueModal.AddToCart.MinimumQuantityNotification}}</div></template></template>- <div class="input-group-append w-100">- <button type="button" :id="'add-to-cart-button-' + PopupQuickViewVueModal.AddToCart.ProductId" class="btn btn-info w-100 add-to-cart-button d-inline-flex" data-productid="PopupQuickViewVueModal.AddToCart.ProductId" :onclick="'AxiosCart.addproducttocart_details(`@addtocart/' + PopupQuickViewVueModal.AddToCart.ProductId + '/1`, `#product-details-form`);return false;'">- <span>- <template v-if="PopupQuickViewVueModal.AddToCart.IsAuction">- @Loc["ShoppingCart.BuyNow"]- </template>- <template v-else-if="PopupQuickViewVueModal.AddToCart.IsReservation">- @Loc["ShoppingCart.Reservation"]- </template>- <template v-else-if="PopupQuickViewVueModal.AddToCart.AvailableForPreOrder">- @Loc["ShoppingCart.PreOrder"]- </template>- <template v-else>- @Loc["ShoppingCart.AddToCart"]+ <template v-if="!PopupQuickViewVueModal.AddToCart.DisableBuyButton">+ <template v-if="PopupQuickViewVueModal.AddToCart.AllowedQuantities.length > 0">+ <select :id="'addtocart_' + PopupQuickViewVueModal.AddToCart.ProductId + '_EnteredQuantity'" :name="'addtocart_' + PopupQuickViewVueModal.AddToCart.ProductId + '.EnteredQuantity'" class="custom-select form-control qty-dropdown mr-2">+ <template v-for="option in PopupQuickViewVueModal.AddToCart.AllowedQuantities">+ <option :value="option.Value" :disabled="option.Disabled" :selected="option.Selected">{{option.Text}}</option></template>- </span>- </button>- </div>- </template>-</div>\ No newline at end of file+ </select>+ </template>+ <template v-else>+ <label :for="'addtocart_' + PopupQuickViewVueModal.AddToCart.ProductId + '_EnteredQuantity'" class="sr-only">@Loc["ShoppingCart.AddToCart"]</label>+ <input v-model.number="PopupQuickViewVueModal.AddToCart.EnteredQuantity" :id="'addtocart_' + PopupQuickViewVueModal.AddToCart.ProductId + '_EnteredQuantity'" :name="'addtocart_' + PopupQuickViewVueModal.AddToCart.ProductId + '.EnteredQuantity'" class="qty-input form-control text-center" type="number" inputmode="numeric" />+ <template v-if="PopupQuickViewVueModal.AddToCart.MeasureUnit !== ''">+ <span class="qty-unit d-flex align-items-center mr-2">+ {{PopupQuickViewVueModal.AddToCart.MeasureUnit}}+ </span>+ </template>+ </template>+ <div class="input-group-append w-100">+ <template v-if="typeof vmwishlist !== 'undefined' && PopupQuickViewVueModal.AddToCart.UpdatedShoppingCartItemId !== null">+ <button :id="'add-to-wishlist-button-' + PopupQuickViewVueModal.AddToCart.ProductId" class="btn btn-info w-100 d-inline-flex main-button" title="@Loc["ShoppingCart.AddToWishlist.Update"]" :data-productid="PopupQuickViewVueModal.AddToCart.ProductId" :onclick="'AxiosCart.updateitem(`@updateitemcart`, `#product-details-form`);return false;'" v-b-tooltip.hover.bottom>+ <span>+ @Loc["ShoppingCart.AddToWishlist.Update"]+ </span>+ </button>+ </template>+ <template v-else>+ <button type="button" :id="'add-to-cart-button-' + PopupQuickViewVueModal.AddToCart.ProductId" class="btn btn-info w-100 main-button d-inline-flex"+ data-productid="PopupQuickViewVueModal.AddToCart.ProductId" :onclick="PopupQuickViewVueModal.AddToCart.UpdatedShoppingCartItemId !== null ?+ 'AxiosCart.updateitem(`@updateitemcart`, `#product-details-form`);return false;' :+ 'AxiosCart.addproducttocart_details(`@addtocart/' + PopupQuickViewVueModal.AddToCart.ProductId + '/1`, `#product-details-form`);return false;'">+ <span>+ <template v-if="PopupQuickViewVueModal.AddToCart.IsAuction">+ @Loc["ShoppingCart.BuyNow"]+ </template>+ <template v-else-if="PopupQuickViewVueModal.AddToCart.IsReservation">+ @Loc["ShoppingCart.Reservation"]+ </template>+ <template v-else-if="PopupQuickViewVueModal.AddToCart.AvailableForPreOrder">+ @Loc["ShoppingCart.PreOrder"]+ </template>+ <template v-else-if="PopupQuickViewVueModal.AddToCart.UpdateShoppingCartItemType !== null">+ @Loc["ShoppingCart.AddToCart.Update"]+ </template>+ <template v-else>+ @Loc["ShoppingCart.AddToCart"]+ </template>+ </span>+ </button>+ </template>+ </div>+ </template>+ </div>\ No newline at end of filediff --git a/src/Web/Grand.Web/Views/Shared/_AddToWishlistQV.cshtml b/src/Web/Grand.Web/Views/Shared/_AddToWishlistQV.cshtmlindex 53b0e8120..ba14730c7 100644--- a/src/Web/Grand.Web/Views/Shared/_AddToWishlistQV.cshtml+++ b/src/Web/Grand.Web/Views/Shared/_AddToWishlistQV.cshtml@@ -2,15 +2,12 @@var addtowishlist = @Url.RouteUrl("AddProductDetails");}<template v-if="!PopupQuickViewVueModal.AddToCart.DisableWishlistButton">- <button id="'add-to-wishlist-button-' + PopupQuickViewVueModal.AddToCart.ProductId" class="btn btn-secondary add-to-wishlist-button mr-1" :data-productid="PopupQuickViewVueModal.AddToCart.ProductId" :onclick="'AxiosCart.addproducttocart_details(`@addtowishlist/' + PopupQuickViewVueModal.AddToCart.ProductId + '/2`, `#product-details-form`);return false;'" v-b-tooltip.hover.bottom>- <span class="sr-only">- <template v-if="PopupQuickViewVueModal.AddToCart.UpdatedShoppingCartItemId !== null && PopupQuickViewVueModal.AddToCart.UpdateShoppingCartItemType == 2">- @Loc["ShoppingCart.AddToWishlist.Update"];- </template>- <template v-else>- @Loc["ShoppingCart.AddToWishlist"];- </template>- </span>- <b-icon icon="heart"></b-icon>- </button>+ <template v-if="PopupQuickViewVueModal.AddToCart.UpdatedShoppingCartItemId == null">+ <button :id="'add-to-wishlist-button-' + PopupQuickViewVueModal.AddToCart.ProductId" class="btn btn-secondary add-to-wishlist-button mr-1" title="@Loc["ShoppingCart.AddToWishlist"]" :data-productid="PopupQuickViewVueModal.AddToCart.ProductId" :onclick="'AxiosCart.addproducttocart_details(`@addtowishlist/' + PopupQuickViewVueModal.AddToCart.ProductId + '/2`, `#product-details-form`);return false;'" v-b-tooltip.hover.bottom>+ <span class="sr-only">+ @Loc["ShoppingCart.AddToWishlist"]+ </span>+ <b-icon icon="heart"></b-icon>+ </button>+ </template></template>diff --git a/src/Web/Grand.Web/Views/Shared/_ProductLayout.QuickViewVue.cshtml b/src/Web/Grand.Web/Views/Shared/_ProductLayout.QuickViewVue.cshtmlindex 719b7e0d7..452dd0070 100644--- a/src/Web/Grand.Web/Views/Shared/_ProductLayout.QuickViewVue.cshtml+++ b/src/Web/Grand.Web/Views/Shared/_ProductLayout.QuickViewVue.cshtml@@ -5,13 +5,19 @@<div class="quick-view"><div class="col-12 px-0"><div class="form-row">- <div class="col-lg-5 col-12">+ <div class="col-lg-5 col-12 d-lg-block d-none"><div class="product-picture">- <img :src="PopupQuickViewVueModal.DefaultPictureModel.ImageUrl" :alt="PopupQuickViewVueModal.DefaultPictureModel.AlternateText" :title="PopupQuickViewVueModal.DefaultPictureModel.Title" class="img-fluid" id="main_qv_img" />+ <picture>+ <source media="(max-width: 991px)" sizes="1px" srcset="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7 1w" />+ <img :src="PopupQuickViewVueModal.DefaultPictureModel.ImageUrl" :alt="PopupQuickViewVueModal.DefaultPictureModel.AlternateText" :title="PopupQuickViewVueModal.DefaultPictureModel.Title" class="img-fluid" id="main_qv_img" />+ </picture></div><div v-if="PopupQuickViewVueModal.PictureModels.length > 1" class="product-gallery"><template v-for="picture in PopupQuickViewVueModal.PictureModels">- <img class="img-thumb" :src="picture.ThumbImageUrl" :alt="picture.AlternateText" :title="picture.Title" :data-img="picture.ImageUrl" @@click="document.getElementById('main_qv_img').src = $event.target.dataset.img" />+ <picture>+ <source media="(max-width: 991px)" sizes="1px" srcset="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7 1w" />+ <img class="img-thumb" :src="picture.ThumbImageUrl" :alt="picture.AlternateText" :title="picture.Title" :data-img="picture.ImageUrl" @@click="document.getElementById('main_qv_img').src = $event.target.dataset.img" />+ </picture></template></div></div>@@ -87,7 +93,7 @@<template v-if="PopupQuickViewVueModal.ProductType !== 10"><partial name="_AddToCartQV" />- <template v-if="!PopupQuickViewVueModal.AddToCart.DisableWishlistButton || PopupQuickViewVueModal.CompareProductsEnabled || PopupQuickViewVueModal.EmailAFriendEnabled">+ <template v-if="(!PopupQuickViewVueModal.AddToCart.DisableWishlistButton || PopupQuickViewVueModal.CompareProductsEnabled || PopupQuickViewVueModal.EmailAFriendEnabled) && PopupQuickViewVueModal.AddToCart.UpdatedShoppingCartItemId == null"><div class="btn-group mt-2 mb-3 w-100"><partial name="_AddToWishlistQV" /><partial name="_ProductsComparisonQV" />diff --git a/src/Web/Grand.Web/Views/ShoppingCart/CartSummary.cshtml b/src/Web/Grand.Web/Views/ShoppingCart/CartSummary.cshtmlindex 3a5722ef5..7049ec236 100644--- a/src/Web/Grand.Web/Views/ShoppingCart/CartSummary.cshtml+++ b/src/Web/Grand.Web/Views/ShoppingCart/CartSummary.cshtml@@ -51,7 +51,7 @@<tr v-for="item in vmorder.cart.Items"><td v-if="vmorder.cart.IsAllowOnHold && vmorder.cart.IsEditable" class="onhold-cart"><label class="custom-control custom-switch mb-0 pl-0">- <input :id="'checkbox_' + item.Id" type="checkbox" :checked="item.IsCart" class="custom-control-input changeshoppingcartitem" :data-href="'@Url.RouteUrl("ChangeTypeCartItem")/' + item.Id + '?status=' + !item.IsCart" v-on:change="vmorder.ChangeShoppingCart($event)" />+ <input :id="'checkbox_' + item.Id" type="checkbox" :checked="item.IsCart" class="custom-control-input changeshoppingcartitem" v-on:change="vmorder.updateCartType(item.Id, !item.IsCart)" /><span class="custom-control-label ml-5"></span></label></td>@@ -73,14 +73,14 @@<div v-if="item.AuctionInfo != ''" v-html="item.AuctionInfo" class="attributes small"></div><div v-if="item.RecurringInfo != null" v-html="item.RecurringInfo" class="recurring-info"></div><div v-if="item.ReservationInfo != null" v-html="item.ReservationInfo" class="rental-info attributes small"></div>- <div v-if="vmorder.cart.IsEditable && item.AllowItemEditing" class="edit-item mb-1 mt-1">- <a class="btn btn-sm btn-secondary" :href="'/' + item.ProductSeName + '?updatecartitemid=' + item.Id">@Loc["Common.Edit"]</a>- </div>- <div v-if="typeof item.Warnings !== 'undefined' && item.Warnings.length > 0" class="message-error alert alert-danger">+ <div v-if="typeof item.Warnings !== 'undefined' && item.Warnings.length > 0" class="message-error small alert alert-danger mt-2 mb-0"><ul v-for="warning in item.Warnings" class="mb-0 p-0"><li>{{warning}}</li></ul></div>+ <div v-if="vmorder.cart.IsEditable && item.AllowItemEditing" class="edit-item mt-2">+ <a class="btn btn-sm btn-secondary" @@click="vmorder.updateOnCart(item.Id)">@Loc["Common.Edit"]</a>+ </div></td><td class="unit-price"><span class="product-unit-price price">{{item.UnitPrice}}</span>@@ -91,12 +91,12 @@<td class="quantity"><div v-if="vmorder.cart.IsEditable"><div v-if="item.AllowedQuantities[0]">- <select :id="'itemquantity' + item.Id" :name="'itemquantity' + item.Id" class="custom-select form-control qty-dropdown" v-on:change="vmorder.ChangeShoppingCart($event)">+ <select :id="'itemquantity' + item.Id" :name="'itemquantity' + item.Id" class="custom-select form-control qty-dropdown" v-on:change="vmorder.updateQuantity('itemquantity', item.Id)"><option v-for="qty in item.AllowedQuantities" :selected="qty.Selected" :value="qty.Value">{{qty.Value}}</option></select></div><div v-else>- <input :id="'itemquantity' + item.Id" :name="'itemquantity' + item.Id" type="number" :value="item.Quantity" min="1" v-on:change="vmorder.ChangeShoppingCart($event)" class="qty-input form-control text-center" />+ <input :id="'itemquantity' + item.Id" :name="'itemquantity' + item.Id" type="number" v-model="item.Quantity" min="1" v-on:change="vmorder.updateQuantity('itemquantity', item.Id)" class="qty-input form-control text-center" /></div></div><div v-else>@@ -184,9 +184,9 @@}else{- <span class="read"+ <span class="read"onclick="window.open('@Url.RouteUrl("PagePopup", new { SystemName = PageSeNameConstants.Conditionsofuse })', 450, 500, true)">- @Loc["Checkout.TermsOfService.Read"]+ @Loc["Checkout.TermsOfService.Read"]</span>}</b-form-checkbox>@@ -239,167 +239,5 @@</div>@await Component.InvokeAsync("Widget", new { widgetZone = "order_summary_content_after" })</div>-<script asp-location="Header">- var Order = Vue.extend({- props: {- cart: null,- totals: null,- checkoutAsGuest: false,- // confirm order- MinOrderTotalWarning: null,- TermsOfServiceOnOrderConfirmPage: null,- ConfirmWarnings: null,- // terms of service- terms: false,- acceptTerms: false,- },- mounted() {- this.cart = @Json.Serialize(Model);- this.updateTotals();- this.cartView();- },- watch: {- terms: function () {- if (this.terms == true) {- this.acceptTerms = false;- }- }- },- methods: {- cartView() {- var body = document.body;- body.classList.add("cart-view");- },- updateCart() {- axios({- baseURL: '/Component/Index?Name=OrderSummary',- method: 'get',- data: null,- headers: {- 'Accept': 'application/json',- 'Content-Type': 'application/json',- 'X-Response-View': 'Json'- }- }).then(response => {- this.cart = response.data;- })- },- updateTotals() {- axios({- baseURL: '/Component/Index?Name=OrderTotals',- method: 'get',- data: null,- headers: {- 'Accept': 'application/json',- 'Content-Type': 'application/json',- 'X-Response-View': 'Json'- }- }).then(response => {- this.totals = response.data;- });- },- termsCheck(guest) {- if (vmorder.cart.MinOrderSubtotalWarning == null) {- if (this.terms) {- if (guest) {- window.location = '@Url.RouteUrl("Checkout")';- } else {- document.getElementById('shopping-cart-form').setAttribute('action', '@Url.RouteUrl("StartCheckout")');- document.getElementById('shopping-cart-form').submit();- }- vmorder.acceptTerms = false;- }- else {- vmorder.acceptTerms = true;- }- }- },- ApplyGiftVoucher(href) {- var bodyFormData = new FormData();- bodyFormData.append('giftvouchercouponcode', document.getElementById('giftvouchercouponcode').value);- bodyFormData.append('__RequestVerificationToken', document.querySelector('input[name=__RequestVerificationToken]').value);- axios({- method: 'post',- url: href,- data: bodyFormData,- headers: { 'Content-Type': 'multipart/form-data' }- }).then(function (response) {- vmorder.cart = response.data.model;- }).then(function () {- this.vmorder.updateTotals()- });- },- removeGiftVoucher(href) {- var bodyFormData = new FormData();- bodyFormData.append('__RequestVerificationToken', document.querySelector('input[name=__RequestVerificationToken]').value);- axios({- method: 'post',- url: href,- data: bodyFormData,- headers: { 'Content-Type': 'multipart/form-data' },- }).then(function (response) {- vmorder.cart = response.data.model;- }).catch(function (error) {- alert(error);- }).then(function () {- this.vmorder.updateTotals();- });- },- ChangeShoppingCart(event) {- if (event.target.getAttribute('data-href')) {- var href = event.target.getAttribute('data-href');- } else {- var href = '@Url.RouteUrl("UpdateCart")';- }-- var form = document.getElementById('shopping-cart-form');- var data = new FormData(form);- axios({- method: 'post',- data: data,- url: href,- }).then(function (response) {- vmorder.cart = response.data.model;- vm.updateFly();- }).then(function () {- this.vmorder.updateTotals();- });- },- deleteitem(href) {- axios({- method: 'post',- url: href,- }).then(function (response) {- vmorder.cart = response.data.model;- if (document.querySelector('.sidebar-cart')) {- var newfly = response.data.sidebarshoppingcartmodel;- vm.flycart = newfly;- vm.flycartitems = newfly.Items;- vm.flycartindicator = newfly.TotalProducts;- } else {- document.querySelector('.qty-indicator.cart-qty').innerText = response.data.totalproducts;- }- }).then(function () {- this.vmorder.updateTotals();- });- },- ApplyDiscountCode(href) {- var bodyFormData = new FormData();- bodyFormData.append('discountcouponcode', document.getElementById('discountcouponcode').value);- bodyFormData.append('__RequestVerificationToken', document.querySelector('input[name=__RequestVerificationToken]').value);- axios({- method: 'post',- url: href,- data: bodyFormData,- }).then(function (response) {- vmorder.cart = response.data.model;- }).then(function () {- this.vmorder.updateTotals();- });- }- }- });-- var vmorder = new Order().$mount('#ordersummarypagecart')-</script>\ No newline at end of file+<partial name="_ModelScript" model="Model" />\ No newline at end of filediff --git a/src/Web/Grand.Web/Views/ShoppingCart/_ModelScript.cshtml b/src/Web/Grand.Web/Views/ShoppingCart/_ModelScript.cshtmlnew file mode 100644index 000000000..bb3b286e4--- /dev/null+++ b/src/Web/Grand.Web/Views/ShoppingCart/_ModelScript.cshtml@@ -0,0 +1,232 @@+@model ShoppingCartModel+<script asp-location="Header">+ var Order = Vue.extend({+ props: {+ cart: null,+ totals: null,+ checkoutAsGuest: false,+ // confirm order+ MinOrderTotalWarning: null,+ TermsOfServiceOnOrderConfirmPage: null,+ ConfirmWarnings: null,+ // terms of service+ terms: false,+ acceptTerms: false,+ },+ mounted() {+ this.cart = @Json.Serialize(Model);+ this.updateTotals();+ this.cartView();+ },+ watch: {+ terms: function () {+ if (this.terms == true) {+ this.acceptTerms = false;+ }+ }+ },+ methods: {+ cartView() {+ var body = document.body;+ body.classList.add("cart-view");+ },+ updateCart() {+ axios({+ baseURL: '/Component/Index?Name=OrderSummary',+ method: 'get',+ data: null,+ headers: {+ 'Accept': 'application/json',+ 'Content-Type': 'application/json',+ 'X-Response-View': 'Json'+ }+ }).then(response => {+ this.cart = response.data;+ })+ },+ updateTotals() {+ axios({+ baseURL: '/Component/Index?Name=OrderTotals',+ method: 'get',+ data: null,+ headers: {+ 'Accept': 'application/json',+ 'Content-Type': 'application/json',+ 'X-Response-View': 'Json'+ }+ }).then(response => {+ this.totals = response.data;+ });+ },+ termsCheck(guest) {+ if (vmorder.cart.MinOrderSubtotalWarning == null) {+ if (this.terms) {+ if (guest) {+ window.location = '@Url.RouteUrl("Checkout")';+ } else {+ document.getElementById('shopping-cart-form').setAttribute('action', '@Url.RouteUrl("StartCheckout")');+ document.getElementById('shopping-cart-form').submit();+ }+ vmorder.acceptTerms = false;+ }+ else {+ vmorder.acceptTerms = true;+ }+ }+ },+ ApplyGiftVoucher(href) {+ var bodyFormData = new FormData();+ bodyFormData.append('giftvouchercouponcode', document.getElementById('giftvouchercouponcode').value);+ bodyFormData.append('__RequestVerificationToken', document.querySelector('input[name=__RequestVerificationToken]').value);+ axios({+ method: 'post',+ url: href,+ data: bodyFormData,+ headers: { 'Content-Type': 'multipart/form-data' }+ }).then(function (response) {+ vmorder.cart = response.data.model;+ }).then(function () {+ this.vmorder.updateTotals()+ });+ },+ removeGiftVoucher(href) {+ var bodyFormData = new FormData();+ bodyFormData.append('__RequestVerificationToken', document.querySelector('input[name=__RequestVerificationToken]').value);+ axios({+ method: 'post',+ url: href,+ data: bodyFormData,+ headers: { 'Content-Type': 'multipart/form-data' },+ }).then(function (response) {+ vmorder.cart = response.data.model;+ }).catch(function (error) {+ alert(error);+ }).then(function () {+ this.vmorder.updateTotals();+ });+ },+ getModel() {+ axios({+ method: 'get',+ url: '@Url.RouteUrl("ShoppingCart")',+ headers: {+ 'Accept': 'application/json',+ 'Content-Type': 'application/json',+ 'X-Response-View': 'Json'+ },+ }).then(function (response) {+ vmorder.cart = response.data;+ if (document.querySelector('.qty-indicator.cart-qty')) {+ let total = 0;+ for (var i = 0; i < vmorder.cart.Items.length; i++) {+ total = total + vmorder.cart.Items[i].Quantity;+ }+ document.querySelector('.qty-indicator.cart-qty').innerHTML = total;+ }+ }).then(function () {+ vmorder.updateTotals();+ });+ },+ updateQuantity(element, id) {+ var elementById = document.getElementById(element + id);+ var data = new FormData();+ data.append('shoppingcartId', id);+ data.append('quantity', elementById.value);+ data.append('__RequestVerificationToken',+ document.querySelector('input[name=__RequestVerificationToken]').value);+ axios({+ method: 'post',+ data: data,+ url: '@Url.RouteUrl("UpdateQuantityCart")',+ }).then(function (response) {+ if (response.data.success) {+ vmorder.cart = response.data.model;+ if (document.querySelector('.qty-indicator.cart-qty'))+ document.querySelector('.qty-indicator.cart-qty').innerText = response.data.totalproducts;+ }+ else {+ vmorder.displayWarning(response.data.warnings);+ }+ }).then(function () {+ this.vmorder.updateTotals();+ });+ },+ updateCartType(id, iscart) {+ var data = new FormData();+ data.append('id', id);+ data.append('status', iscart);+ data.append('__RequestVerificationToken',+ document.querySelector('input[name=__RequestVerificationToken]').value);+ axios({+ method: 'post',+ data: data,+ url: '@Url.RouteUrl("ChangeTypeCartItem")',+ }).then(function (response) {+ vmorder.cart = response.data.model;+ vm.updateFly();+ }).then(function () {+ this.vmorder.updateTotals();+ });+ },+ updateOnCart(id) {+ axios({+ url: '/GetItemCart/' + id + '',+ method: 'get',+ headers: { 'Content-Type': 'application/json' }+ }).then(function (response) {+ if (response.data.success) {+ vm.PopupQuickViewVueModal = response.data.model;+ vm.UpdatedShoppingCartItemId = id;+ vm.$refs['ModalQuickView'].show();+ } else {+ vmorder.displayWarning(response.data.message);+ }+ });+ },+ deleteitem(href) {+ axios({+ method: 'post',+ url: href,+ }).then(function (response) {+ vmorder.cart = response.data.model;+ if (document.querySelector('.sidebar-cart')) {+ var newfly = response.data.sidebarshoppingcartmodel;+ vm.flycart = newfly;+ vm.flycartitems = newfly.Items;+ vm.flycartindicator = newfly.TotalProducts;+ document.querySelector('.qty-indicator.cart-qty').innerText = response.data.totalproducts;+ } else {+ document.querySelector('.qty-indicator.cart-qty').innerText = response.data.totalproducts;+ }+ }).then(function () {+ this.vmorder.updateTotals();+ });+ },+ ApplyDiscountCode(href) {+ var bodyFormData = new FormData();+ bodyFormData.append('discountcouponcode', document.getElementById('discountcouponcode').value);+ bodyFormData.append('__RequestVerificationToken', document.querySelector('input[name=__RequestVerificationToken]').value);+ axios({+ method: 'post',+ url: href,+ data: bodyFormData,+ }).then(function (response) {+ vmorder.cart = response.data.model;+ }).then(function () {+ this.vmorder.updateTotals();+ });+ },+ displayWarning(message) {+ this.$bvToast.toast(message, {+ title: '@Loc["common.warning"]',+ variant: 'danger',+ autoHideDelay: 5000,+ appendToast: true+ })+ }+ }+ });++ var vmorder = new Order().$mount('#ordersummarypagecart')++</script>\ No newline at end of filediff --git a/src/Web/Grand.Web/Views/Wishlist/Index.cshtml b/src/Web/Grand.Web/Views/Wishlist/Index.cshtmlindex 85aab4e9b..2e6516d9a 100644--- a/src/Web/Grand.Web/Views/Wishlist/Index.cshtml+++ b/src/Web/Grand.Web/Views/Wishlist/Index.cshtml@@ -1,5 +1,4 @@@model WishlistModel-@inject SeoSettings seoSettings@inject IWorkContext workContext@inject IPageHeadBuilder pagebuilder@{@@ -19,7 +18,7 @@//titlepagebuilder.AddTitleParts(Loc["Title.Wishlist"]);}-<div class="page wishlist-page mt-3">+<div class="page wishlist-page mt-3" id="wishlistPage"><h2 class="generalTitle text-center mt-3">@if (Model.IsEditable){@@ -30,185 +29,175 @@@String.Format(Loc["Wishlist.WishlistOf"], Model.CustomerFullname)}</h2>- @if (Model.Items.Any())- {+ <template v-if="vmwishlist.Model.Items.length > 0"><div class="wishlist-content mt-3">- @if (Model.Warnings.Any())- {+ <template v-if="vmwishlist.Model.Warnings.length > 0"><div class="message-error"><ul>- @foreach (var warning in Model.Warnings)- {- <li>@warning</li>- }+ <template v-for="warning in vmwishlist.Model.Warnings">+ <li>{{warning}}</li>+ </template></ul></div>- }- <form asp-controller="Wishlist" asp-action="Index" method="post">+ </template>+ <form asp-controller="Wishlist" asp-action="Index" method="post" id="wishlist-cart-form">@if (!Model.IsEditable && Model.Items.Any()){<input type="hidden" asp-for="@Model.CustomerGuid" />}<div class="shopping-cart-container"><div class="static-cart">- <div id="wishlist-cart"></div>- <script>- var WishlistCart = Vue.extend({- template: '<b-table :fields="fields" :items="items" id="cart-table" class="shopping-cart"> <template v-slot:cell(picture)="data"> <div v-html="data.value.picture"></div></template> <template v-slot:cell(product)="data"> <div v-html="data.value.name"></div><div v-html="data.value.sku"></div><div v-html="data.value.attributes"></div><div v-html="data.value.recurring"></div><div v-html="data.value.reservation"></div><div v-html="data.value.edit"></div><div v-html="data.value.warnings"></div></template> <template v-slot:cell(unit)="data"> <div v-html="data.value.unitprice"></div></template> <template v-slot:cell(qty)="data"> <div v-html="data.value.selector"></div></template> <template v-slot:cell(total)="data"> <div v-html="data.value.subtotal"></div></template> <template v-slot:cell(remove)="data"> <div v-html="data.value.href"></div></template> <template v-slot:cell(addtocart)="data"> <div v-html="data.value.href"></div></template> </b-table>',- data: function () {- return {- fields: [- @if (Model.ShowProductImages){- <text>- { key: 'picture', label: '@Loc["ShoppingCart.Image"]',class: 'text-center' },- </text>- }- { key: 'product', label: '@Loc["ShoppingCart.Product(s)"]', class: 'text-center' },- { key: 'unit', label: '@Loc["ShoppingCart.UnitPrice"]', sortable: true, class: 'text-center' },- { key: 'qty', label: '@Loc["ShoppingCart.Quantity"]', sortable: true, class: 'text-center' },- { key: 'total', label: '@Loc["ShoppingCart.ItemTotal"]', sortable: true, class: 'text-center' },- @if (Model.IsEditable || Model.DisplayAddToCart){- <text>- { key: 'remove', label: '@Loc["Remove"]' },- </text>- @if (Model.DisplayAddToCart)- {- <text>- { key: 'addtocart', label: '@Loc["addToCart"]' },- </text>- }- }- ],- items: [- @foreach (var item in Model.Items)- {- <text>- {- picture: {- picture: '<a href="@Url.RouteUrl("Product", new { SeName = item.ProductSeName })"><img alt="@item.Picture.AlternateText" src="@item.Picture.ImageUrl" title="@item.Picture.Title" /></a>'- },- product: {- name: '<a href="@Url.RouteUrl("Product", new { SeName = item.ProductSeName })" class="product-name">@item.ProductName</a>',- @if (Model.ShowSku && !String.IsNullOrEmpty(item.Sku))- {- <text>- sku: '<span class="sku-number">@item.Sku</span>',- </text>- }- @if (!String.IsNullOrEmpty(item.AttributeInfo))- {- <text>- attributes: '<div class="attributes small">@Html.Raw(item.AttributeInfo)</div>',- </text>- }- @if (!String.IsNullOrEmpty(item.RecurringInfo))- {- <text>- recuring: '<div class="recurring-info">@Html.Raw(item.RecurringInfo)</div>',- </text>- }- @if (Model.IsEditable && item.AllowItemEditing)- {- <text>- edit: '@{var editCartItemUrl = Url.RouteUrl("Product", new { SeName = item.ProductSeName }, Context.Request.Scheme);editCartItemUrl = Grand.Infrastructure.Extensions.CommonExtensions.ModifyQueryString(editCartItemUrl, "updatecartitemid", item.Id);<div class="edit-item mb-1 mt-1"><a class="btn btn-sm btn-secondary" href="@editCartItemUrl">@Loc["Common.Edit"]</a></div>}',- </text>- }- },- qty: {- @if (Model.IsEditable)- {- <text>- selector: '@if (item.AllowedQuantities.Count > 0){<select id="itemquantity@(item.Id)" name="itemquantity@(item.Id)" class="custom-select form-control qty-dropdown">@foreach (var qty in item.AllowedQuantities){<option id="itemqty@(item.Id)" selected="@qty.Selected" value="@qty.Value">@qty.Value</option>}</select>}else{<input id="itemquantity@(item.Id)" name="itemquantity@(item.Id)" type="number" value="@(item.Quantity)" min="1" class="qty-input form-control text-center" />}',- </text>- } else {- <text>- selector: '<input id="itemquantity@(item.Id)" name="itemquantity@(item.Id)" type="text" value="@(item.Quantity)" class="qty-input-ro form-control text-center" readonly />'- </text>- }- },- unit: {- unitprice: '<span class="product-unit-price price">@item.UnitPrice</span>'- },- total: {- @if (!String.IsNullOrEmpty(item.Discount)) {- <text>- subtotal: '<div class="d-flex flex-column"><p class="mb-0 prod-total">@item.SubTotal</p><div class="discount text-success text-center"><span>@Loc["ShoppingCart.ItemYouSave"]: </span><span>@item.Discount</span></div>',- </text>- } else {- <text>- subtotal: '<p class="mb-0 prod-total">@item.SubTotal</p>'- </text>- }- },- @if (Model.IsEditable || Model.DisplayAddToCart)- {- @if (Model.IsEditable) {- <text>- remove: {- href: '<label class="custom-control custom-switch mb-0 pl-0"><input type="checkbox" id="@Loc["Remove"]-@(item.Id)" name="removefromcart" class="custom-control-input" value="@(item.Id)"><span class="custom-control-label ml-5"></span></label>'- },- </text>- }- @if (Model.DisplayAddToCart)- {- <text>- addtocart: {- href: '<label class="custom-control custom-switch mb-0 pl-0"><input type="checkbox" id="account.shoppingcart-@(item.Id)" name="addtocart" class="custom-control-input" value="@(item.Id)"><span class="custom-control-label ml-5"></span></label>'- },- </text>- }- }- },- </text>- }- ]- }- }- })- new WishlistCart().$mount('#wishlist-cart')- </script>+ <div id="wishlist-cart">+ <table id="cart-table" class="table b-table shopping-cart">+ <thead role="rowgroup">+ <tr role="row">+ <template v-if="vmwishlist.Model.ShowProductImages">+ <th role="columnheader" scope="col" class="text-center">+ <div>@Loc["ShoppingCart.Image"]</div>+ </th>+ </template>+ <th role="columnheader" scope="col" class="text-center">+ <div>@Loc["ShoppingCart.Product(s)"]</div>+ </th>+ <th role="columnheader" scope="col" class="text-center">+ <div>@Loc["ShoppingCart.Quantity"]</div>+ </th>+ <th role="columnheader" scope="col" class="text-center">+ <div>@Loc["ShoppingCart.UnitPrice"]</div>+ </th>+ <th role="columnheader" scope="col" class="text-center">+ <div>@Loc["ShoppingCart.ItemTotal"]</div>+ </th>+ <template v-if="vmwishlist.Model.IsEditable || vmwishlist.Model.DisplayAddToCart">+ <template v-if="vmwishlist.Model.IsEditable">+ <th role="columnheader" scope="col" class="text-center">+ <div>@Loc["Remove"]</div>+ </th>+ </template>+ <template v-if="vmwishlist.Model.DisplayAddToCart">+ <th role="columnheader" scope="col" class="text-center">+ <div>@Loc["addToCart"]</div>+ </th>+ </template>+ </template>+ </tr>+ </thead>+ <tbody role="rowgroup">+ <template v-for="item in vmwishlist.Model.Items">+ <tr role="row">+ <template v-if="vmwishlist.Model.ShowProductImages">+ <td role="cell" class="text-center">+ <div>+ <a :href="item.ProductUrl">+ <img :alt="item.Picture.AlternateText" :src="item.Picture.ImageUrl" :title="item.Picture.Title" />+ </a>+ </div>+ </td>+ </template>+ <td role="cell" class="text-center">+ <div>+ <a :href="item.ProductUrl" class="product-name">{{item.ProductName}}</a>+ </div>+ <template v-if="vmwishlist.Model.ShowSku && item.Sku !== null">+ <span class="sku-number">{{item.Sku}}</span>+ </template>+ <template v-if="item.AttributeInfo !== null">+ <div class="attributes small" v-html="item.AttributeInfo"></div>+ </template>+ <template v-if="item.Warnings.length > 0">+ <div class="warnings message-error small alert alert-danger mt-2 mb-0">+ <ul class="mb-0 p-0">+ <template v-for="warning in item.Warnings">+ <li>{{warning}}</li>+ </template>+ </ul>+ </div>+ </template>+ <template v-if="item.RecurringInfo !== null">+ <div class="recurring-info" v-html="item.RecurringInfo"></div>+ </template>+ <template v-if="vmwishlist.Model.IsEditable && item.AllowItemEditing">+ <a class="btn btn-sm btn-secondary mt-2" @@click="vmwishlist.getItemCart(item.Id)">@Loc["Common.Edit"]</a>+ </template>+ </td>+ <template v-if="vmwishlist.Model.IsEditable">+ <td role="cell" class="text-center">+ <template v-if="item.AllowedQuantities[0]">+ <select :id="'itemquantity' + item.Id" :name="'itemquantity' + item.Id" class="custom-select form-control qty-dropdown" v-on:change="vmwishlist.updateQuantity('itemquantity', item.Id)">+ <template v-for="qty in item.AllowedQuantities">+ <option :id="'itemqty' + item.Id" :selected="qty.Selected" :value="qty.Value">{{qty.Value}}</option>+ </template>+ </select>+ </template>+ <template v-else>+ <input :id="'itemquantity' + item.Id" :name="'itemquantity' + item.Id" type="number" v-model="item.Quantity" min="1" v-on:change="vmwishlist.updateQuantity('itemquantity', item.Id)" class="qty-input form-control text-center" />+ </template>+ </td>+ </template>+ <template v-else>+ <td role="cell" class="text-center">+ <input :id="'itemquantity' + item.Id" :name="'itemquantity' + item.Id" type="text" :value="item.Quantity" class="qty-input-ro form-control text-center" readonly />+ </td>+ </template>+ <td role="cell" class="text-center">+ <span class="product-unit-price price">{{item.UnitPrice}}</span>+ </td>+ <template v-if="item.Discount !== null">+ <td role="cell" class="text-center">+ <div class="d-flex flex-column">+ <p class="mb-0 prod-total">{{item.SubTotal}}</p><div class="discount text-success text-center"><span>@Loc["ShoppingCart.ItemYouSave"]: </span><span>{{item.Discount}}</span></div>+ </div>+ </td>+ </template>+ <template v-else>+ <td role="cell" class="text-center">+ <p class="mb-0 prod-total">{{item.SubTotal}}</p>+ </td>+ </template>+ <template v-if="vmwishlist.Model.IsEditable || vmwishlist.Model.DisplayAddToCart">+ <template v-if="vmwishlist.Model.IsEditable">+ <td>+ <b-button variant="link" @@click="vmwishlist.deleteFromWishlist(item.Id)">+ <b-icon icon="trash" font-scale="1.5" class="text-danger"></b-icon>+ </b-button>+ </td>+ </template>+ <template v-if="vmwishlist.Model.DisplayAddToCart">+ <td>+ <b-button variant="link" @@click="vmwishlist.addToCartFromWishlist(item.Id)">+ <b-icon icon="cart" font-scale="1.5" class="text-info"></b-icon>+ </b-button>+ </td>+ </template>+ </template>+ </tr>+ </template>+ </tbody>+ </table>+ </div></div></div>- <div class="btn-group my-3">- @if (Model.IsEditable)- {- <button type="submit" asp-action="UpdateWishlist" name="update" variant="info" class="btn btn-info update-wishlist-button d-flex align-items-center">- <b-icon font-scale="2" icon="arrow-clockwise" class="pr-2"></b-icon>- <span>@Loc["Wishlist.UpdateCart"]</span>- </button>- }- @if (Model.DisplayAddToCart)- {- <button type="submit" asp-action="AddItemsToCartFromWishlist"- name="addtocartbutton" variant="info" class="btn btn-info wishlist-add-to-cart-button d-flex align-items-center ml-1">- <b-icon font-scale="2" icon="cart" class="pr-2"></b-icon>- <span>@Loc["ShoppingCart.AddToCart"]</span>- </button>- }- @if (Model.IsEditable && Model.EmailWishlistEnabled)- {- <button type="button" class="btn btn-secondary email-a-friend-wishlist-button d-flex align-items-center ml-1" onclick="location='@Url.RouteUrl("EmailWishlist")'">- <b-icon font-scale="2" icon="envelope" class="pr-2"></b-icon>- <span class="d-sm-block d-none">@Loc["Wishlist.EmailAFriend"]</span>- </button>- }- </div>+ <template v-if="vmwishlist.Model.IsEditable && vmwishlist.Model.EmailWishlistEnabled">+ <button type="button" class="btn btn-secondary email-a-friend-wishlist-button d-flex align-items-center my-3" onclick="location='@Url.RouteUrl("EmailWishlist")'">+ <b-icon font-scale="2" icon="envelope" class="pr-2"></b-icon>+ <span class="d-sm-block d-none">@Loc["Wishlist.EmailAFriend"]</span>+ </button>+ </template></form></div>- }- else- {+ </template>+ <template v-else><div class="no-data alert alert-info text-center">@Loc["Wishlist.CartIsEmpty"]</div>- }- @if (Model.IsEditable && Model.Items.Any())- {+ </template>+ <template v-if="vmwishlist.Model.IsEditable && vmwishlist.Model.Items.length > 0"><div class="row"><div class="col-12 share-info generalMarginSupporter text-center text-md-left"><span class="share-label">@Loc["Wishlist.YourWishlistURL"]:</span><a href="@Url.RouteUrl("Wishlist", new { customerGuid = Model.CustomerGuid })" class="small ml-2">@Url.RouteUrl("Wishlist", new { customerGuid = Model.CustomerGuid }, "http")</a></div></div>- }-</div>\ No newline at end of file+ </template>+</div>+<partial name="_ModelScript" model="Model" />\ No newline at end of filediff --git a/src/Web/Grand.Web/Views/Wishlist/_ModelScript.cshtml b/src/Web/Grand.Web/Views/Wishlist/_ModelScript.cshtmlnew file mode 100644index 000000000..52f93843f--- /dev/null+++ b/src/Web/Grand.Web/Views/Wishlist/_ModelScript.cshtml@@ -0,0 +1,117 @@+@model WishlistModel+<script asp-location="Header">+ var Wishlist = Vue.extend({+ props: {+ Model: null,+ PopupUpdateVueModal: null,+ },+ mounted() {+ this.Model = @Json.Serialize(Model);+ },+ methods: {+ deleteFromWishlist(id) {+ axios({+ url: '@Url.RouteUrl("DeleteItemFromWishlist")'+'/'+ id +'',+ method: 'post',+ headers: { 'Content-Type': 'application/json' }+ }).then(function (response) {+ if (response.data.success) {+ vmwishlist.getModel();+ } else {+ vmwishlist.displayWarning(response.data.message, 'danger');+ }+ });+ },+ addToCartFromWishlist(id) {+ axios({+ url: '@Url.RouteUrl("AddItemToCartFromWishlist")'+'/' + id,+ method: 'post',+ headers: { 'Content-Type': 'application/json' }+ }).then(function (response) {+ if (response.data.success) {+ vmwishlist.getModel();+ vm.updateFly();+ vmwishlist.displayWarning('@Loc["wishlist.addedtocart"]', 'info', '@Loc["common.success"]');+ } else {+ vmwishlist.displayWarning(response.data.message, 'danger');+ }+ });+ },+ getItemCart(id) {+ axios({+ url: '@Url.RouteUrl("GetItemCart")'+'/'+ id,+ method: 'get',+ headers: { 'Content-Type': 'application/json' }+ }).then(function (response) {+ if (response.data.success) {+ vm.PopupQuickViewVueModal = response.data.model;+ vm.UpdatedShoppingCartItemId = id;+ vm.$refs['ModalQuickView'].show();+ } else {+ vmwishlist.displayWarning(response.data.message, 'danger');+ }+ });+ },+ updateQuantity(element, id) {+ var elementById = document.getElementById(element + id);+ var data = new FormData();+ data.append('shoppingcartId', id);+ data.append('quantity', elementById.value);+ data.append('__RequestVerificationToken',+ document.querySelector('input[name=__RequestVerificationToken]').value);++ axios({+ method: 'post',+ data: data,+ url: '@Url.RouteUrl("UpdateQuantityWishlist")',+ }).then(function (response) {+ if (response.data.success) {+ vmwishlist.getModel();+ }+ else {+ vmwishlist.displayWarning(response.data.warnings, 'danger');+ }+ })+ },+ getModel() {+ var url = window.location.href;+ url = new URL(url);+ url.searchParams.set('timestamp', new Date().getTime());+ axios({+ baseURL: url,+ method: 'get',+ headers: {+ 'Accept': 'application/json',+ 'Content-Type': 'application/json',+ 'X-Response-View': 'Json',+ }+ }).then(function (response) {+ vmwishlist.Model = response.data;+ if (document.querySelector('.wishlist-qty')) {+ let total = 0;+ for (var i = 0; i < vmwishlist.Model.Items.length; i++) {+ total = total + vmwishlist.Model.Items[i].Quantity;+ }+ document.querySelector('.wishlist-qty').innerHTML = total;+ }+ }).then(function () {+ var stateurl = new URL(url);+ stateurl.searchParams.delete('timestamp');+ window.history.replaceState({ path: stateurl.href }, '', stateurl.href);+ });+ },+ displayWarning(message, variant, title) {+ if (typeof title == 'undefined') {+ title = '@Loc["common.warning"]';+ }+ this.$bvToast.toast(message, {+ title: title,+ variant: variant,+ autoHideDelay: 5000,+ appendToast: true+ })+ }+ }+ });+ var vmwishlist = new Wishlist().$mount('#wishlistPage')+</script>\ No newline at end of filediff --git a/src/Web/Grand.Web/wwwroot/theme/css/common/common.css b/src/Web/Grand.Web/wwwroot/theme/css/common/common.cssindex 44ec04dd9..cf680167f 100644--- a/src/Web/Grand.Web/wwwroot/theme/css/common/common.css+++ b/src/Web/Grand.Web/wwwroot/theme/css/common/common.css@@ -492,7 +492,7 @@ dl, ol, ul {/* quickview */-.qv-title {+.quick-view .qv-title {margin: 0;font-size: 28px;font-weight: 700;@@ -529,7 +529,7 @@ dl, ol, ul {.quick-view-overview .bid-input {height: 45px;}-.quick-view .add-to-cart-button {+.quick-view .quick-view-overview .main-button {font-size: 20px;font-weight: 500;height: 45px;@@ -1264,6 +1264,22 @@ footer .list-group-item span:last-child {}}@media (max-width: 575px) {+ .quick-view .qv-title {+ font-size: 18px;+ }+ .quick-view .attributes table tr {+ display: inline-flex;+ flex-wrap: wrap;+ width: 100%;+ }+ .quick-view .attributes table tr:not(:last-child) {+ border-bottom: 1px solid #dee2e6;+ }+ .quick-view .attributes table tr td {+ display: flex;+ width: 100%;+ border-top: 0;+ }.product-box .rating .b-rating-value,.product-box .rating output + span {display: none;diff --git a/src/Web/Grand.Web/wwwroot/theme/css/common/common.rtl.css b/src/Web/Grand.Web/wwwroot/theme/css/common/common.rtl.cssindex edc3e9ff7..ca8c23d12 100644--- a/src/Web/Grand.Web/wwwroot/theme/css/common/common.rtl.css+++ b/src/Web/Grand.Web/wwwroot/theme/css/common/common.rtl.css@@ -581,7 +581,7 @@ dl, ol, ul {.quick-view {text-align: right;}-.qv-title {+.quick-view .qv-title {margin: 0;font-size: 28px;font-weight: 700;@@ -647,7 +647,7 @@ dl, ol, ul {.quick-view-overview .bid-input {height: 45px;}-.quick-view .add-to-cart-button {+.quick-view .quick-view-overview .main-button {font-size: 20px;font-weight: 500;height: 45px;@@ -1360,6 +1360,22 @@ footer .list-group-item span:last-child {}}@media (max-width: 575px) {+ .quick-view .qv-title {+ font-size: 18px;+ }+ .quick-view .attributes table tr {+ display: inline-flex;+ flex-wrap: wrap;+ width: 100%;+ }+ .quick-view .attributes table tr:not(:last-child) {+ border-bottom: 1px solid #dee2e6;+ }+ .quick-view .attributes table tr td {+ display: flex;+ width: 100%;+ border-top: 0;+ }.product-box .rating .b-rating-value,.product-box .rating output + span {display: none;diff --git a/src/Web/Grand.Web/wwwroot/theme/script/app.js b/src/Web/Grand.Web/wwwroot/theme/script/app.jsindex 1cc91883a..e2387d605 100644--- a/src/Web/Grand.Web/wwwroot/theme/script/app.js+++ b/src/Web/Grand.Web/wwwroot/theme/script/app.js@@ -28,6 +28,7 @@flywish: null,wishlistitems: null,wishindicator: undefined,+ UpdatedShoppingCartItemId: null},mounted: function () {if (localStorage.fluid == "true") this.fluid = "fluid";diff --git a/src/Web/Grand.Web/wwwroot/theme/script/public.axios.js b/src/Web/Grand.Web/wwwroot/theme/script/public.axios.jsindex ed9727165..718864dff 100644--- a/src/Web/Grand.Web/wwwroot/theme/script/public.axios.js+++ b/src/Web/Grand.Web/wwwroot/theme/script/public.axios.js@@ -68,8 +68,44 @@ var AxiosCart = {}).catch(function (error) {error.axiosFailure;}).then(function () {+ if (typeof vmwishlist !== 'undefined') {+ vmwishlist.getModel();+ }+ if (typeof vmorder !== 'undefined') {+ vmorder.getModel();+ }this.AxiosCart.resetLoadWaiting();- });+ });+ },++ //update product on cart/wishlist+ updateitem: function (urlupdate) {+ var model;+ var form = document.querySelector('#ModalQuickView #product-details-form');+ var data = new FormData(form);++ if (typeof vmwishlist !== 'undefined') {+ model = vmwishlist;+ } else {+ model = vmorder;+ }++ axios({+ url: urlupdate,+ data: data,+ method: 'post',+ }).then(function (response) {+ if (response.data.success) {+ vm.$refs['ModalQuickView'].hide();+ } else {+ model.displayWarning(response.data.message, 'danger');+ }+ }).catch(function (error) {+ error.axiosFailure;+ }).then(function () {+ model.getModel();+ this.AxiosCart.resetLoadWaiting();+ });},//add bid