public static class UmbracoCommerceUmbracoBuilderExtensions
{
public static IUmbracoCommerceBuilder AddEventHandlers(IUmbracoCommerceBuilder builder)
{
// Register event handlers
builder.WithValidationEvent<ValidateOrderProductAdd>()
.RegisterHandler<ProductAddValidationHandler>();
builder.WithValidationEvent<ValidateOrderLineQuantityChange>()
.RegisterHandler<OrderLineQuantityValidationHandler>();
return builder;
}
}public class ProductAddValidationHandler : ValidationEventHandlerBase<ValidateOrderProductAdd>
{
private readonly IProductService _productService;
public ProductAddValidationHandler(IProductService productService)
{
_productService = productService;
}
public override void Validate(ValidateOrderProductAdd evt)
{
var order = evt.Order;
var productReference = evt.ProductReference;
var stock = _productService.GetProductStock(evt.Order.StoreId, productReference);
if (stock.HasValue && evt.Quantity > stock.Value)
evt.Fail($"Only {stock} quantities can be purchased for {productReference}.");
}
}
public class OrderLineQuantityValidationHandler : ValidationEventHandlerBase<ValidateOrderLineQuantityChange>
{
private readonly IProductService _productService;
public OrderLineQuantityValidationHandler(IProductService productService)
{
_productService = productService;
}
public override void Validate(ValidateOrderLineQuantityChange evt)
{
var orderLine = evt.OrderLine;
var productReference = orderLine.ProductReference;
var stock = _productService.GetProductStock(evt.Order.StoreId, productReference);
if (stock.HasValue && evt.Quantity.To > stock.Value)
evt.Fail($"Only {stock} quantities can be purchased for {productReference}.");
}
}