コード例 #1
0
        public void AddItemToCheckout(int sku, decimal quantity, MeasurmentUnits buyUnit, DiscountRule discountRule)
        {
            // First get the product with the corresponding SKU from repository
            var product = _productsRepo.GetProduct(sku);

            if (product == null)
            {
                throw new ArgumentException($"Cannot find product with SKU : {sku}");
            }

            if (product.UnitPrice <= 0)
            {
                throw new ArgumentOutOfRangeException("Cannot add a product with invalid price");
            }

            if (quantity <= 0)
            {
                throw new ArgumentOutOfRangeException("Cannot add a product with negative or zero quantity");
            }

            if (product.MeasurmentUnit == MeasurmentUnits.PIECE && quantity != Math.Round(quantity))
            {
                throw new ArgumentException("Cannot add product sold by number with a floating decimal quantity");
            }

            if (product.MeasurmentUnit != buyUnit)
            {
                try
                {
                    // get the quantity corresponding to the sell unit, rounded to 3 decimals
                    quantity = Math.Round(GetQuantityFromUnit(quantity, product.MeasurmentUnit, buyUnit), 3);
                }
                catch (Exception e)
                {
                    throw new ArgumentException(e.Message + $": Sell Unit {product.MeasurmentUnit}, Buy Unit {buyUnit}");
                }
            }

            if (discountRule != null)
            {
                discountRule = ConfigureDiscountRuleParams(discountRule.Id, product.UnitPrice);
            }

            // Finally add a "quantity" of this product to the list of
            // checkout items if all the checking conditions are met
            _checkoutRepo.AddItem(product, quantity, buyUnit, discountRule);
        }