Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,11 @@ public AuctionService(IRepository<Bid> bidRepository,

public virtual async Task<Bid?> GetLatestBid(string productId)
{
var bid = _bidRepository.Table
var query = _bidRepository.Table
.Where(x => x.ProductId == productId)
.OrderByDescending(x => x.Date)
.ToList();
.OrderByDescending(x => x.Date);

return await Task.FromResult(bid.FirstOrDefault());
return await _bidRepository.FirstOrDefaultAsync(query);
}

public virtual async Task<IPagedList<Bid>> GetBidsByProductId(string productId, int pageIndex = 0,
Expand Down Expand Up @@ -94,7 +93,9 @@ public virtual async Task UpdateHighestBid(Product product, double bid, string?
{
product.HighestBid = bid;
product.HighestBidder = highestBidder;
await _productRepository.UpdateAsync(product);
//only these fields: the product may be a cached copy, and writing all of it would undo changes made since
await _productRepository.UpdateOneAsync(x => x.Id == product.Id,
UpdateBuilder<Product>.Create().Set(x => x.HighestBid, bid).Set(x => x.HighestBidder, highestBidder));

await _mediator.Publish(new ProductChangedEvent(product.Id));

Expand All @@ -111,10 +112,14 @@ public virtual async Task<IList<Product>> GetAuctionsToEnd()
public virtual async Task UpdateAuctionEnded(Product product, bool ended, bool endDate = false)
{
product.AuctionEnded = ended;
var update = UpdateBuilder<Product>.Create().Set(x => x.AuctionEnded, ended);
if (endDate)
{
product.AvailableEndDateTimeUtc = DateTime.UtcNow;
update.Set(x => x.AvailableEndDateTimeUtc, product.AvailableEndDateTimeUtc);
}

await _productRepository.UpdateAsync(product);
await _productRepository.UpdateOneAsync(x => x.Id == product.Id, update);

await _mediator.Publish(new ProductChangedEvent(product.Id));

Expand Down Expand Up @@ -150,8 +155,18 @@ await _mediator.Send(new SendOutBidCustomerCommand {
Bid = latest,
Language = language
});
product.HighestBid = amount;
await UpdateHighestBid(product, amount, customer.Id);
//only forward: a lower bid checked against the same state as a concurrent higher one never lowers the highest bid
await _productRepository.UpdateOneAsync(x => x.Id == product.Id && x.HighestBid < amount,
UpdateBuilder<Product>.Create().Set(x => x.HighestBid, amount).Set(x => x.HighestBidder, customer.Id));

//the caller shows the product after the bid, so it gets the highest bid that was stored
var stored = await _productRepository.GetByIdAsync(product.Id);
product.HighestBid = stored?.HighestBid ?? amount;
product.HighestBidder = stored?.HighestBidder ?? customer.Id;

await _mediator.Publish(new ProductChangedEvent(product.Id));

await _mediator.EntityUpdated(product);
}

/// <summary>
Expand All @@ -160,16 +175,24 @@ await _mediator.Send(new SendOutBidCustomerCommand {
/// <param name="orderId">OrderId</param>
public virtual async Task CancelBidByOrder(string orderId)
{
var bid = await _bidRepository.GetOneAsync(x => x.OrderId == orderId);
if (bid != null)
//one order can hold several auction items, each with its own bid
var query = _bidRepository.Table.Where(x => x.OrderId == orderId);
var bids = await _bidRepository.ToListAsync(query);
foreach (var bid in bids)
{
await _bidRepository.DeleteAsync(bid);
await _mediator.EntityDeleted(bid);

var product = await _productRepository.GetByIdAsync(bid.ProductId);
if (product != null)
{
await UpdateHighestBid(product, 0, "");
await UpdateAuctionEnded(product, false);
}
if (product == null) continue;

//the auction stays ended - the store owner decides whether to list it again;
//no bidder is set, so none of the remaining bids reads as the winner,
//and the earlier bids of the customer who cancelled do not count
var highestBid = (await GetBidsByProductId(bid.ProductId))
.Where(x => x.CustomerId != bid.CustomerId)
.MaxBy(x => x.Amount);
await UpdateHighestBid(product, highestBid?.Amount ?? 0, "");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -929,8 +929,8 @@ protected virtual async Task UpdateBids(Order order, PlaceOrderContainer details
{
foreach (var sc in details.Cart.Where(x => x.ShoppingCartTypeId == ShoppingCartType.Auctions))
{
var bid = (await _auctionService.GetBidsByProductId(sc.Id)).FirstOrDefault(x =>
x.CustomerId == details.Customer.Id);
var bid = (await _auctionService.GetBidsByProductId(sc.ProductId)).FirstOrDefault(x =>
x.Win && x.CustomerId == details.Customer.Id && string.IsNullOrEmpty(x.OrderId));
if (bid == null) continue;
bid.OrderId = order.Id;
await _auctionService.UpdateBid(bid);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ public ShoppingCartStandardValidator(ITranslationService translationService, IAc
case ShoppingCartType.ShoppingCart when value.Product.DisableBuyButton:
context.AddFailure(translationService.GetResource("ShoppingCart.BuyingDisabled", value.Language.Id));
break;
//buy it now no longer applies once the bidding has reached its price
case ShoppingCartType.ShoppingCart when value.Product.IsBuyNowOutbid():
context.AddFailure(translationService.GetResource("ShoppingCart.BuyingDisabled", value.Language.Id));
break;
//disabled "add to wishlist" button
case ShoppingCartType.Wishlist when value.Product.DisableWishlistButton:
context.AddFailure(translationService.GetResource("ShoppingCart.WishlistDisabled", value.Language.Id));
Expand Down
13 changes: 13 additions & 0 deletions src/Core/Grand.Domain/Catalog/ProductExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -448,4 +448,17 @@ public static bool IsAvailable(this Product product, DateTime dateTime)

return true;
}

/// <summary>
/// Get a value indicating whether the bidding of an auction has reached its buy-it-now price
/// </summary>
/// <param name="product">Product</param>
/// <returns>Result</returns>
public static bool IsBuyNowOutbid(this Product product)
{
ArgumentNullException.ThrowIfNull(product);

return product.ProductTypeId == ProductType.Auction && product.HighestBid > 0 &&
product.HighestBid >= product.Price;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Grand.Business.Core.Interfaces.Messages;
using Grand.Business.Core.Interfaces.System.ScheduleTasks;
using Grand.Business.Core.Utilities.Checkout;
using Grand.Domain.Catalog;
using Grand.Domain.Localization;
using Grand.Domain.Orders;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -74,8 +75,10 @@ await _catalogMessageProviderService.SendAuctionEndedStoreOwnerMessage(auctionTo
var bidder = await _customerService.GetCustomerById(bid.CustomerId);
if (bidder == null)
{
_logger.LogWarning("EndAuctionTask - Product {Name} - the customer of the highest bid does not exist",
_logger.LogWarning(
"EndAuctionTask - Product {Name} - the customer of the highest bid does not exist, the auction ends without a winner",
auctionToEnd.Name);
await EndWithoutWinner(auctionToEnd);
continue;
}

Expand All @@ -97,9 +100,23 @@ await _catalogMessageProviderService.SendAuctionEndedStoreOwnerMessage(auctionTo
}
else
{
_logger.LogInformation("EndAuctionTask - Product {Name} - warnings {Join}", auctionToEnd.Name,
string.Join(",", warnings.ToArray()));
_logger.LogWarning(
"EndAuctionTask - Product {Name} - the highest bid cannot be added to the cart, the auction ends without a winner - warnings {Join}",
auctionToEnd.Name, string.Join(",", warnings.ToArray()));
await EndWithoutWinner(auctionToEnd);
}
}
}

/// <summary>
/// Ends an auction whose highest bid cannot win, so it is not picked up again on every run
/// </summary>
private async Task EndWithoutWinner(Product product)
{
//no bidder is named, so the highest bid does not read as a win
await _auctionService.UpdateHighestBid(product, product.HighestBid, "");
await _auctionService.UpdateAuctionEnded(product, true);
await _catalogMessageProviderService.SendAuctionEndedStoreOwnerMessage(product,
_languageSettings.DefaultAdminLanguageId, null);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Grand.Domain.Localization;
using Grand.Domain.Stores;
using Grand.Infrastructure;
using Grand.Infrastructure.Events;
using Grand.Mediator;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
Expand Down Expand Up @@ -268,4 +269,136 @@ public async Task CancelBidByOrderTest()
//Assert
Assert.AreEqual(0, _repository.Table.Count());
}
}

[TestMethod]
public async Task NewBid_LowerBidValidatedAgainstTheSameState_DoesNotLowerTheHighestBid()
{
//Arrange - both bids were checked against the same product, as two concurrent requests are
var product = new Product { ProductTypeId = ProductType.Auction, StartPrice = 100 };
_productrepository.Insert(product);
var seenByFirst = _productrepository.Table.First(x => x.Id == product.Id);
var seenBySecond = _productrepository.Table.First(x => x.Id == product.Id);

//Act
await _auctionService.NewBid(new Customer { Id = "high" }, seenByFirst, new Store(), new Language(), "", 120);
await _auctionService.NewBid(new Customer { Id = "low" }, seenBySecond, new Store(), new Language(), "", 110);

//Assert
var result = _productrepository.Table.First(x => x.Id == product.Id);
Assert.AreEqual(120, result.HighestBid);
Assert.AreEqual("high", result.HighestBidder);
Assert.AreEqual(2, _repository.Table.Count(x => x.ProductId == product.Id));
}

[TestMethod]
public async Task UpdateHighestBid_KeepsFieldsChangedSinceTheProductWasRead()
{
//Arrange
var product = new Product { ProductTypeId = ProductType.Auction, Name = "read" };
_productrepository.Insert(product);
var stale = _productrepository.Table.First(x => x.Id == product.Id);
await _productrepository.UpdateField(product.Id, x => x.Name, "edited meanwhile");

//Act
await _auctionService.UpdateHighestBid(stale, 15, "bidder");

//Assert
var result = _productrepository.Table.First(x => x.Id == product.Id);
Assert.AreEqual("edited meanwhile", result.Name);
Assert.AreEqual(15, result.HighestBid);
Assert.AreEqual("bidder", result.HighestBidder);
}

[TestMethod]
public async Task UpdateAuctionEnded_KeepsFieldsChangedSinceTheProductWasRead()
{
//Arrange
var product = new Product {
ProductTypeId = ProductType.Auction, AvailableEndDateTimeUtc = DateTime.UtcNow.AddDays(1)
};
_productrepository.Insert(product);
var stale = _productrepository.Table.First(x => x.Id == product.Id);
await _productrepository.UpdateField(product.Id, x => x.HighestBid, 50d);

//Act
await _auctionService.UpdateAuctionEnded(stale, true, true);

//Assert
var result = _productrepository.Table.First(x => x.Id == product.Id);
Assert.AreEqual(50, result.HighestBid);
Assert.IsTrue(result.AuctionEnded);
Assert.IsTrue(result.AvailableEndDateTimeUtc <= DateTime.UtcNow);
}

[TestMethod]
public async Task CancelBidByOrder_AuctionStaysEnded_HighestBidFromRemainingBids()
{
//Arrange
var product = new Product {
ProductTypeId = ProductType.Auction,
AuctionEnded = true,
AvailableEndDateTimeUtc = DateTime.UtcNow.AddDays(-1),
HighestBid = 20,
HighestBidder = "winner"
};
_productrepository.Insert(product);
await _auctionService.InsertBid(new Bid {
Amount = 20, ProductId = product.Id, CustomerId = "winner", OrderId = "order1", Win = true
});
await _auctionService.InsertBid(new Bid { Amount = 15, ProductId = product.Id, CustomerId = "second" });

//Act
await _auctionService.CancelBidByOrder("order1");

//Assert
var result = _productrepository.Table.First(x => x.Id == product.Id);
Assert.IsTrue(result.AuctionEnded);
Assert.AreEqual(15, result.HighestBid);
Assert.AreEqual("", result.HighestBidder);
Assert.AreEqual(1, _repository.Table.Count());
}

[TestMethod]
public async Task CancelBidByOrder_EveryBidOfTheOrderIsDeleted()
{
//Arrange
var product1 = new Product { ProductTypeId = ProductType.Auction, AuctionEnded = true, HighestBid = 20 };
var product2 = new Product { ProductTypeId = ProductType.Auction, AuctionEnded = true, HighestBid = 30 };
_productrepository.Insert(product1);
_productrepository.Insert(product2);
await _auctionService.InsertBid(new Bid {
Amount = 20, ProductId = product1.Id, CustomerId = "winner", OrderId = "order1", Win = true
});
await _auctionService.InsertBid(new Bid {
Amount = 30, ProductId = product2.Id, CustomerId = "winner", OrderId = "order1", Win = true
});

//Act
await _auctionService.CancelBidByOrder("order1");

//Assert
Assert.AreEqual(0, _repository.Table.Count());
Assert.AreEqual(0, _productrepository.Table.First(x => x.Id == product2.Id).HighestBid);
_mediatorMock.Verify(x => x.Publish(It.IsAny<EntityDeleted<Bid>>(), It.IsAny<CancellationToken>()),
Times.Exactly(2));
}

[TestMethod]
public async Task CancelBidByOrder_EarlierBidsOfTheCancellingCustomerDoNotCount()
{
//Arrange
var product = new Product { ProductTypeId = ProductType.Auction, AuctionEnded = true, HighestBid = 20 };
_productrepository.Insert(product);
await _auctionService.InsertBid(new Bid {
Amount = 20, ProductId = product.Id, CustomerId = "winner", OrderId = "order1", Win = true
});
await _auctionService.InsertBid(new Bid { Amount = 18, ProductId = product.Id, CustomerId = "winner" });
await _auctionService.InsertBid(new Bid { Amount = 15, ProductId = product.Id, CustomerId = "second" });

//Act
await _auctionService.CancelBidByOrder("order1");

//Assert
Assert.AreEqual(15, _productrepository.Table.First(x => x.Id == product.Id).HighestBid);
}
}
Loading
Loading