예제 #1
0
 public static void AddToDiscountList(Discount discount, List<Discount> discounts)
 {
     if (!discounts.Exists(x => x.DiscountCode.Equals(discount.DiscountCode)))
     {
         discounts.Add(discount);
     }
 }
예제 #2
0
        public void TestMethod1(int customerId)
        {
            var repository = new StubCustomerRepository();

            var discount = new Discount(repository);

            discount.CalculateCustomerDiscount(customerId);
        }
예제 #3
0
        public void TestMethod1(int customerId, Level level, int points)
        {
            var repository = new StubCustomerRepository(level, points);

            var discount = new Discount(repository);

            discount.CalculateCustomerDiscount(customerId);
        }
        public void TestMethod(int customerId)
        {
            var repository = new SICustomerRepository();

            repository.InstanceBehavior = PexChooseBehavedBehavior.Instance;

            var discount = new Discount(repository);

            discount.CalculateCustomerDiscount(customerId);
        }
        public static Discount ToWebModel(this VirtoCommerceOrderModuleWebModelDiscount serviceModel, IEnumerable<Currency> availCurrencies, Language language)
        {
            var webModel = new Discount();

            webModel.InjectFrom(serviceModel);
            var currency = availCurrencies.FirstOrDefault(x => x.Equals(serviceModel.Currency)) ?? new Currency(language, serviceModel.Currency);
            webModel.Amount = new Money(serviceModel.DiscountAmount ?? 0, currency);

            return webModel;
        }
예제 #6
0
        public static Discount ToWebModel(this VirtoCommerceCartModuleWebModelDiscount serviceModel)
        {
            var webModel = new Discount();

            webModel.InjectFrom(serviceModel);

            webModel.Amount = new Money(serviceModel.DiscountAmount ?? 0, serviceModel.Currency);

            return webModel;
        }
        public static bool Rule5Validation(SalesView sales)
        {
            Customer customer = new Customer("", sales.CustomerType, sales.AgeRange);
            Discount discount = new Discount(sales.DiscountMin,sales.DiscountMax, sales.VipDiscount);

            RulesManagerBase ruleMan = RulesValidationFactory.MakeRulesManager();

            IList<object> list = new List<object>();
            list.Add(customer);
            list.Add(discount);
            return ruleMan.Validate(ConfigurationManager.AppSettings["Rule5"], list);
        }
예제 #8
0
    protected override void Start()
    {
        base.Start();
        this.Pickup = PickUpType.GiftCard;
        pickupSound = Audiopocalypse.Sounds.Pickup_Card;

        switch(Random.Range(0, 3))
        {
            case 0: discount = Discount.DIS_25; break;
            case 1: discount = Discount.DIS_50; break;
            case 2: discount = Discount.DIS_75; break;
        }
    }
예제 #9
0
        public void Setup()
        {
            roadBike = new Bike("Speedster", "2000", 1000);
            mountainBike = new Bike("Cannondale", "F3", 1249);
            bmxBike = new Bike("Tricketer", "457", 599);

            twoHundredDollarDiscount = new Discount { Fixed = 200, Message = "Discount - $200", Condition = l => true };
            tenPercentDiscount = new Discount { Percentage = 0.10m, Message = "Discount - 10% Off", Condition = l => true };

            fiveItemDiscount = new Discount { Condition = s => s.Quantity >= 5, Message = "5 IItem Discount - 5% off", Percentage = 0.05m };
            tenItemDiscount = new Discount { Condition = s => s.Quantity >= 10, Message = "10 IItem Discount - 10% off", Percentage = 0.1m };
            twentyItemDiscount = new Discount { Condition = s => s.Quantity >= 20, Message = "20 IItem Discount - 20% off", Percentage = 0.2m };
        }
예제 #10
0
 public ActionResult EditDiscount(Discount disc, HttpPostedFileBase photo)
 {
     string fullpath = "";
     string map = "";
     if (photo != null)
     {
         string filename = System.IO.Path.GetFileName(photo.FileName);
         fullpath = "/Images/" + filename;
         map = Server.MapPath(fullpath);
         photo.SaveAs(map);
         disc.Photo = fullpath;
     }
     Repository.Save(disc);
     return RedirectToAction("Discounts");
 }
        public void Must_Be_Able_To_Print_Bill()
        {
            ObjectFactory.Initialize(x => x.Scan(scanner =>
            {
                scanner.AssembliesFromApplicationBaseDirectory();
                scanner.LookForRegistries();
            }));

            var subscriptionRegistration = ObjectFactory.GetInstance<ISubscriptionRegistration>();
            var customerRegistration = ObjectFactory.GetInstance<ICustomerRegistration>();

            var sub = SubscriptionHelper.CreateSubscriptionWithDefaultCustomer(subscriptionRegistration, customerRegistration, "55555555", "DK", CustomerStatus.Normal);
            var records = new List<Record>
                              {
                                  new Record("55555555", DateTime.Now, "Standard", "Call from 55555555 to 66666666", 12.5M)
                              };
            var discount = new Discount(CustomerStatus.VIP, 0.5M);

            var bill = new Bill(sub,records,discount);

            bill.ToString().Should().NotBeNullOrEmpty();
        }
        private void btn_add_Click(object sender, EventArgs e)
        {
            if (lv_avaiable.SelectedIndices.Count > 0)
            {
                selectedDiscount = (Discount)lv_avaiable.SelectedItems[0].Tag;

                this.avaiableDiscounts.Remove(selectedDiscount);
                ListViewItem tmp = null;
                foreach (ListViewItem item in lv_avaiable.Items)
                {
                    if ((Discount)item.Tag == selectedDiscount) { tmp = item; break; }
                }
                if (tmp != null) lv_avaiable.Items.Remove(tmp);

                this.discounts.Add(selectedDiscount);
                ListViewItem t = new ListViewItem(selectedDiscount.NiceID);
                t.SubItems.Add(selectedDiscount.Name);
                t.Tag = selectedDiscount;
                lv_on_job.Items.Add(t);

                this.changed = true;
                btn_save.Enabled = true;
            }
        }
예제 #13
0
        protected CheckoutShippingMethodModel PrepareShippingMethodModel(IList <OrganizedShoppingCartItem> cart)
        {
            var model = new CheckoutShippingMethodModel();

            var getShippingOptionResponse = _shippingService.GetShippingOptions(cart, _workContext.CurrentCustomer.ShippingAddress, "", _storeContext.CurrentStore.Id);

            if (getShippingOptionResponse.Success)
            {
                //performance optimization. cache returned shipping options.
                //we'll use them later (after a customer has selected an option).
                _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer,
                                                       SystemCustomerAttributeNames.OfferedShippingOptions, getShippingOptionResponse.ShippingOptions, _storeContext.CurrentStore.Id);

                var shippingMethods = _shippingService.GetAllShippingMethods();

                foreach (var shippingOption in getShippingOptionResponse.ShippingOptions)
                {
                    var soModel = new CheckoutShippingMethodModel.ShippingMethodModel()
                    {
                        ShippingMethodId = shippingOption.ShippingMethodId,
                        Name             = shippingOption.Name,
                        Description      = shippingOption.Description,
                        ShippingRateComputationMethodSystemName = shippingOption.ShippingRateComputationMethodSystemName,
                    };

                    var srcmProvider = _shippingService.LoadShippingRateComputationMethodBySystemName(shippingOption.ShippingRateComputationMethodSystemName);
                    if (srcmProvider != null)
                    {
                        soModel.BrandUrl = _pluginMediator.GetBrandImageUrl(srcmProvider.Metadata);
                    }

                    //adjust rate
                    Discount appliedDiscount = null;
                    var      shippingTotal   = _orderTotalCalculationService.AdjustShippingRate(
                        shippingOption.Rate, cart, shippingOption.Name, shippingMethods, out appliedDiscount);

                    decimal rateBase = _taxService.GetShippingPrice(shippingTotal, _workContext.CurrentCustomer);
                    decimal rate     = _currencyService.ConvertFromPrimaryStoreCurrency(rateBase, _workContext.WorkingCurrency);
                    soModel.FeeRaw = rate;
                    soModel.Fee    = _priceFormatter.FormatShippingPrice(rate, true);

                    model.ShippingMethods.Add(soModel);
                }

                //find a selected (previously) shipping method
                var selectedShippingOption = _workContext.CurrentCustomer.GetAttribute <ShippingOption>(SystemCustomerAttributeNames.SelectedShippingOption, _storeContext.CurrentStore.Id);
                if (selectedShippingOption != null)
                {
                    var shippingOptionToSelect = model.ShippingMethods.ToList()
                                                 .Find(so => !String.IsNullOrEmpty(so.Name) && so.Name.Equals(selectedShippingOption.Name, StringComparison.InvariantCultureIgnoreCase) &&
                                                       !String.IsNullOrEmpty(so.ShippingRateComputationMethodSystemName) &&
                                                       so.ShippingRateComputationMethodSystemName.Equals(selectedShippingOption.ShippingRateComputationMethodSystemName, StringComparison.InvariantCultureIgnoreCase));

                    if (shippingOptionToSelect != null)
                    {
                        shippingOptionToSelect.Selected = true;
                    }
                }
                //if no option has been selected, let's do it for the first one
                if (model.ShippingMethods.Where(so => so.Selected).FirstOrDefault() == null)
                {
                    var shippingOptionToSelect = model.ShippingMethods.FirstOrDefault();
                    if (shippingOptionToSelect != null)
                    {
                        shippingOptionToSelect.Selected = true;
                    }
                }
            }
            else
            {
                foreach (var error in getShippingOptionResponse.Errors)
                {
                    model.Warnings.Add(error);
                }
            }

            return(model);
        }
예제 #14
0
 public Task <Discount> InsertDiscount(Discount discount)
 {
     return(Task.FromResult(Context.Discounts.Add(discount).Entity));
 }
 public override void DeleteDiscount(Discount discount)
 {
     if (!_promoSettings.Enabled)
         base.DeleteDiscount(discount);
     
     throw new NotSupportedException("DeleteDiscount");
 }
        public override bool IsDiscountValid(Discount discount, global::Nop.Core.Domain.Customers.Customer customer)
        {
            if (!_promoSettings.Enabled)
                return base.IsDiscountValid(discount, customer);

            if (discount.RequiresCouponCode)
            {
                return IsDiscountValid(discount, customer, discount.CouponCode);
            }
            else
            {
                throw new NotImplementedException("IsDiscountValid");
            }
        }
예제 #17
0
 partial void UpdateDiscount(Discount instance);
예제 #18
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create a unit group.
        /// Retrieve the default unit.
        /// Create few products.
        /// Create new discount list and discount.
        /// Create new price list and few price list items.
        /// Create an account record.
        /// Create a new opportunity and few opportunity products.
        /// </summary>
        public void CreateRequiredRecords()
        {
            // Create a unit group
            UoMSchedule newUnitGroup = new UoMSchedule
            {
                Name = "Example Unit Group",
                BaseUoMName = "Example Primary Unit"
            };

            _unitGroupId = _serviceProxy.Create(newUnitGroup);
            Console.WriteLine("Created {0}", newUnitGroup.Name);

            // Retrieve the default unit id that was automatically created
            // when we created the Unit Group
            QueryExpression unitQuery = new QueryExpression
            {
                EntityName = UoM.EntityLogicalName,
                ColumnSet = new ColumnSet("uomid", "name"),
                Criteria = new FilterExpression
                {
                    Conditions = 
                        {
                            new ConditionExpression 
                            {
                                AttributeName = "uomscheduleid",
                                Operator = ConditionOperator.Equal,
                                Values = { _unitGroupId }
                            }
                        }
                },
                PageInfo = new PagingInfo
                {
                    PageNumber = 1,
                    Count = 1
                }
            };          
            
            // Retrieve the unit.
            UoM unit = (UoM)_serviceProxy.RetrieveMultiple(unitQuery).Entities[0];

            _defaultUnitId = unit.UoMId.Value;

            Console.WriteLine("Retrieved {0}", unit.Name);
          
            // Create a few products
            Product newProduct1 = new Product
            {
                ProductNumber = "1",
                Name = "Example Product 1",
                ProductStructure = new OptionSetValue(1),
                QuantityDecimal = 2,
                DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, 
                    _unitGroupId),
                DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId)
            };

            _product1Id = _serviceProxy.Create(newProduct1);
            Console.WriteLine("Created {0}", newProduct1.Name);

            Product newProduct2 = new Product
            {
               ProductNumber = "2",
               Name = "Example Product 2",
               ProductStructure = new OptionSetValue(1),
               QuantityDecimal = 3,
               DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName, 
                   _unitGroupId),
               DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId)
            };

            _product2Id = _serviceProxy.Create(newProduct2);
            Console.WriteLine("Created {0}", newProduct2.Name);

            // Create a new discount list
            DiscountType newDiscountType = new DiscountType
            {
                Name = "Example Discount List",
                IsAmountType = false
            };

            _discountTypeId = _serviceProxy.Create(newDiscountType);
            Console.WriteLine("Created {0}", newDiscountType.Name);

            // Create a new discount
            Discount newDiscount = new Discount
            {
                DiscountTypeId = new EntityReference(DiscountType.EntityLogicalName, 
                    _discountTypeId),
                LowQuantity = 5,
                HighQuantity = 10,
                Percentage = 3
            };

            _discountId = _serviceProxy.Create(newDiscount);

            Console.WriteLine("Created new discount for the {0}.", newDiscountType.Name);

            // Create a price list
            PriceLevel newPriceList = new PriceLevel
            {
                Name = "Example Price List"
            };

            _priceListId = _serviceProxy.Create(newPriceList);
            Console.WriteLine("Created {0}", newPriceList.Name);

            // Create a price list item for the first product and apply volume discount
            ProductPriceLevel newPriceListItem1 = new ProductPriceLevel 
            {
                PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
                ProductId = new EntityReference(Product.EntityLogicalName, _product1Id),
                UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
                Amount = new Money(20),
                DiscountTypeId = new EntityReference(DiscountType.EntityLogicalName, 
                    _discountTypeId)
            };

            _priceListItem1Id = _serviceProxy.Create(newPriceListItem1);
            Console.WriteLine(@"Created price list item for the {0} and applied 
                volume discount.", newProduct1.Name);

            // Create a price list item for the second product
            ProductPriceLevel newPriceListItem2 = new ProductPriceLevel
            {
                PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
                ProductId = new EntityReference(Product.EntityLogicalName, _product2Id),
                UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
                Amount = new Money(20)
            };

            _priceListItem2Id = _serviceProxy.Create(newPriceListItem2);
            Console.WriteLine("Created price list item for the {0}.", newProduct1.Name);

            //Publish Product1
            SetStateRequest publishRequest1 = new SetStateRequest
            {
                EntityMoniker = new EntityReference(Product.EntityLogicalName, _product1Id),
                State = new OptionSetValue((int)ProductState.Active),
                Status = new OptionSetValue(1)
            };
            _serviceProxy.Execute(publishRequest1);

            //Publish Product2
            SetStateRequest publishRequest2 = new SetStateRequest
            {
                EntityMoniker = new EntityReference(Product.EntityLogicalName, _product2Id),
                State = new OptionSetValue((int)ProductState.Active),
                Status = new OptionSetValue(1)
            };
            _serviceProxy.Execute(publishRequest2);
            Console.WriteLine("Published both the products");

            // Create an account record for the opporutnity's potential customerid 
            Account newAccount = new Account
            {
                Name = "Example Account"
            };
            _accountId = _serviceProxy.Create(newAccount);

            Console.WriteLine("Created {0}", newAccount.Name);

            // Create a new opportunity
            Opportunity newOpportunity = new Opportunity
            {
                Name = "Example Opportunity",
                CustomerId = new EntityReference(Account.EntityLogicalName,
                    _accountId),
                PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName,
                    _priceListId)
            };

            _opportunityId = _serviceProxy.Create(newOpportunity);
            Console.WriteLine("Created {0}.", newOpportunity.Name);

            // Create some opportunity products
            OpportunityProduct newOpportunityProduct1 = new OpportunityProduct
            {
                OpportunityId = new EntityReference(Opportunity.EntityLogicalName,
                    _opportunityId),
                ProductId = new EntityReference(Product.EntityLogicalName,
                    _product1Id),
                UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
                Quantity = 8
            };

            _opportunityProduct1Id = _serviceProxy.Create(newOpportunityProduct1);

            OpportunityProduct newOpportunityProduct2 = new OpportunityProduct
            {
                OpportunityId = new EntityReference(Opportunity.EntityLogicalName,
                    _opportunityId),
                ProductId = new EntityReference(Product.EntityLogicalName,
                    _product2Id),
                UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
                Quantity = 1
            };

            _opportunityProduct2Id = _serviceProxy.Create(
                newOpportunityProduct2);

            Console.WriteLine("Created few opportunity products.");

            return;
        }
        public override decimal? GetShoppingCartShippingTotal(IList<global::Nop.Core.Domain.Orders.ShoppingCartItem> cart, bool includingTax,
            out decimal taxRate, out global::Nop.Core.Domain.Discounts.Discount appliedDiscount)
        {
            if (!_promoSettings.Enabled)
                return base.GetShoppingCartShippingTotal(cart, includingTax, out taxRate, out appliedDiscount);

            #region old code

            BasketResponse basketResponse = _promoUtilities.GetBasketResponse();
            decimal? shippingTotal = null;

            if (basketResponse == null)
            {
                return base.GetShoppingCartShippingTotal(cart, includingTax, out taxRate, out appliedDiscount);
            }

            taxRate = Decimal.Zero;
            appliedDiscount = null;

            var shippingOption = _workContext.CurrentCustomer.GetAttribute<ShippingOption>(SystemCustomerAttributeNames.SelectedShippingOption, _storeContext.CurrentStore.Id);

            if (shippingOption == null)
            {
                // Where there are items in the basket that are not for shipping, we need to ensure we return a zero.
                if (cart.Any(sci => sci.IsShipEnabled))
                    return null;
                else
                    return Decimal.Zero;
            }                

            shippingTotal = basketResponse.DeliveryPrice;

            if ((basketResponse.DeliveryPromotionDiscount > Decimal.Zero))
            {
                if (basketResponse.BasketLevelDiscountIncludesDeliveryAmount())
                {
                    shippingTotal = basketResponse.DeliveryOriginalPrice;
                }
                else
                {
                    appliedDiscount = new Discount();
                    appliedDiscount.DiscountAmount = basketResponse.DeliveryPromotionDiscount;
                    appliedDiscount.Name = basketResponse.DeliveryPromo().PromotionName;
                }
            }

            #endregion

            #region new code

            decimal? shippingTotalTaxed = shippingTotal;
            Customer customer = cart.GetCustomer();

            if (shippingTotal.HasValue)
            {
                if (shippingTotal.Value < decimal.Zero)
                    shippingTotal = decimal.Zero;

                //round
                if (_shoppingCartSettings.RoundPricesDuringCalculation)
                    shippingTotal = RoundingHelper.RoundPrice(shippingTotal.Value);

                shippingTotalTaxed = _taxService.GetShippingPrice(shippingTotal.Value,
                    includingTax,
                    customer,
                    out taxRate);

                //round
                if (_shoppingCartSettings.RoundPricesDuringCalculation)
                    shippingTotalTaxed = RoundingHelper.RoundPrice(shippingTotalTaxed.Value);
            }

            #endregion

            return shippingTotalTaxed;
        }
예제 #20
0
        /// <summary>
        /// Validate discount
        /// </summary>
        /// <param name="discount">Discount</param>
        /// <param name="customer">Customer</param>
        /// <param name="couponCodesToValidate">Coupon codes to validate</param>
        /// <returns>Discount validation result</returns>
        public virtual DiscountValidationResult ValidateDiscount(Discount discount, Customer customer, string[] couponCodesToValidate)
        {
            if (discount == null)
            {
                throw new ArgumentNullException("discount");
            }

            if (customer == null)
            {
                throw new ArgumentNullException("customer");
            }

            //invalid by default

            string key = $"DiscountValidationResult_{customer.Id}_{discount.Id}_{string.Join("_", couponCodesToValidate)}";
            var    validationResult = _perRequestCache.Get(key, () =>
            {
                var result = new DiscountValidationResult();

                //check is enabled
                if (!discount.IsEnabled)
                {
                    return(result);
                }

                //check coupon code
                if (discount.RequiresCouponCode)
                {
                    if (couponCodesToValidate == null || !couponCodesToValidate.Any())
                    {
                        return(result);
                    }
                    var exists = false;
                    foreach (var item in couponCodesToValidate)
                    {
                        if (discount.Reused)
                        {
                            if (ExistsCodeInDiscount(item, discount.Id, null))
                            {
                                result.CouponCode = item;
                                exists            = true;
                            }
                        }
                        else
                        {
                            if (ExistsCodeInDiscount(item, discount.Id, false))
                            {
                                result.CouponCode = item;
                                exists            = true;
                            }
                        }
                    }
                    if (!exists)
                    {
                        return(result);
                    }
                }

                //Do not allow discounts applied to order subtotal or total when a customer has gift cards in the cart.
                //Otherwise, this customer can purchase gift cards with discount and get more than paid ("free money").
                if (discount.DiscountType == DiscountType.AssignedToOrderSubTotal ||
                    discount.DiscountType == DiscountType.AssignedToOrderTotal)
                {
                    var cart = customer.ShoppingCartItems
                               .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
                               .LimitPerStore(_storeContext.CurrentStore.Id)
                               .ToList();

                    var hasGiftCards = cart.Any(x => x.IsGiftCard);
                    if (hasGiftCards)
                    {
                        result.UserError = _localizationService.GetResource("ShoppingCart.Discount.CannotBeUsedWithGiftCards");
                        return(result);
                    }
                }

                //check date range
                DateTime now = DateTime.UtcNow;
                if (discount.StartDateUtc.HasValue)
                {
                    DateTime startDate = DateTime.SpecifyKind(discount.StartDateUtc.Value, DateTimeKind.Utc);
                    if (startDate.CompareTo(now) > 0)
                    {
                        result.UserError = _localizationService.GetResource("ShoppingCart.Discount.NotStartedYet");
                        return(result);
                    }
                }
                if (discount.EndDateUtc.HasValue)
                {
                    DateTime endDate = DateTime.SpecifyKind(discount.EndDateUtc.Value, DateTimeKind.Utc);
                    if (endDate.CompareTo(now) < 0)
                    {
                        result.UserError = _localizationService.GetResource("ShoppingCart.Discount.Expired");
                        return(result);
                    }
                }

                //discount limitation
                switch (discount.DiscountLimitation)
                {
                case DiscountLimitationType.NTimesOnly:
                    {
                        var usedTimes = GetAllDiscountUsageHistory(discount.Id, null, null, false, 0, 1).TotalCount;
                        if (usedTimes >= discount.LimitationTimes)
                        {
                            return(result);
                        }
                    }
                    break;

                case DiscountLimitationType.NTimesPerCustomer:
                    {
                        if (customer.IsRegistered())
                        {
                            var usedTimes = GetAllDiscountUsageHistory(discount.Id, customer.Id, null, false, 0, 1).TotalCount;
                            if (usedTimes >= discount.LimitationTimes)
                            {
                                result.UserError = _localizationService.GetResource("ShoppingCart.Discount.CannotBeUsedAnymore");
                                return(result);
                            }
                        }
                    }
                    break;

                case DiscountLimitationType.Unlimited:
                default:
                    break;
                }

                //discount requirements
                string keyReq    = string.Format(DiscountRequirementEventConsumer.DISCOUNT_REQUIREMENT_MODEL_KEY, discount.Id);
                var requirements = _cacheManager.Get(keyReq, () =>
                {
                    return(discount.DiscountRequirements.ToList());
                });
                foreach (var req in requirements)
                {
                    //load a plugin
                    var discountRequirementPlugin = LoadDiscountPluginBySystemName(req.DiscountRequirementRuleSystemName);

                    if (discountRequirementPlugin == null)
                    {
                        continue;
                    }

                    if (!_pluginFinder.AuthenticateStore(discountRequirementPlugin.PluginDescriptor, _storeContext.CurrentStore.Id))
                    {
                        continue;
                    }

                    var ruleRequest = new DiscountRequirementValidationRequest
                    {
                        DiscountRequirementId = req.Id,
                        DiscountId            = req.DiscountId,
                        Customer = customer,
                        Store    = _storeContext.CurrentStore
                    };

                    var singleRequirementRule = discountRequirementPlugin.GetRequirementRules().Single(x => x.SystemName == req.DiscountRequirementRuleSystemName);
                    var ruleResult            = singleRequirementRule.CheckRequirement(ruleRequest);
                    if (!ruleResult.IsValid)
                    {
                        result.UserError = ruleResult.UserError;
                        return(result);
                    }
                }

                result.IsValid = true;
                return(result);
            });

            return(validationResult);
        }
예제 #21
0
        /// <summary>
        /// Delete discount
        /// </summary>
        /// <param name="discount">Discount</param>
        public virtual void DeleteDiscount(Discount discount)
        {
            if (discount == null)
            {
                throw new ArgumentNullException("discount");
            }

            var usagehistory = GetAllDiscountUsageHistory(discount.Id);

            if (usagehistory.Count > 0)
            {
                throw new ArgumentNullException("discount has a history");
            }

            var builder = Builders <BsonDocument> .Filter;

            if (discount.DiscountType == DiscountType.AssignedToSkus)
            {
                var builderproduct = Builders <Product> .Update;
                var updatefilter   = builderproduct.Pull(x => x.AppliedDiscounts, discount.Id);
                var result         = _productRepository.Collection.UpdateManyAsync(new BsonDocument(), updatefilter).Result;
                _cacheManager.RemoveByPattern(PRODUCTS_PATTERN_KEY);
            }

            if (discount.DiscountType == DiscountType.AssignedToCategories)
            {
                var buildercategory = Builders <Category> .Update;
                var updatefilter    = buildercategory.Pull(x => x.AppliedDiscounts, discount.Id);
                var result          = _categoryRepository.Collection.UpdateManyAsync(new BsonDocument(), updatefilter).Result;
                _cacheManager.RemoveByPattern(CATEGORIES_PATTERN_KEY);
            }

            if (discount.DiscountType == DiscountType.AssignedToManufacturers)
            {
                var buildermanufacturer = Builders <Manufacturer> .Update;
                var updatefilter        = buildermanufacturer.Pull(x => x.AppliedDiscounts, discount.Id);
                var result = _manufacturerRepository.Collection.UpdateManyAsync(new BsonDocument(), updatefilter).Result;
                _cacheManager.RemoveByPattern(MANUFACTURERS_PATTERN_KEY);
            }
            if (discount.DiscountType == DiscountType.AssignedToVendors)
            {
                var buildervendor = Builders <Vendor> .Update;
                var updatefilter  = buildervendor.Pull(x => x.AppliedDiscounts, discount.Id);
                var result        = _vendorRepository.Collection.UpdateManyAsync(new BsonDocument(), updatefilter).Result;
                _cacheManager.RemoveByPattern(VENDORS_PATTERN_KEY);
            }

            if (discount.DiscountType == DiscountType.AssignedToStores)
            {
                var builderstore = Builders <Store> .Update;
                var updatefilter = builderstore.Pull(x => x.AppliedDiscounts, discount.Id);
                var result       = _storeRepository.Collection.UpdateManyAsync(new BsonDocument(), updatefilter).Result;
                _cacheManager.RemoveByPattern(STORES_PATTERN_KEY);
            }


            //remove coupon codes
            var filtersCoupon = Builders <DiscountCoupon> .Filter;
            var filterCrp     = filtersCoupon.Eq(x => x.DiscountId, discount.Id);

            _discountCouponRepository.Collection.DeleteMany(filterCrp);

            _discountRepository.Delete(discount);



            _cacheManager.RemoveByPattern(DISCOUNTS_PATTERN_KEY);

            //event notification
            _eventPublisher.EntityDeleted(discount);
        }
예제 #22
0
        private string CreateRequest(string accessKey, string username, string password,
                                     GetShippingOptionRequest getShippingOptionRequest, UPSCustomerClassification customerClassification,
                                     UPSPickupType pickupType, UPSPackagingType packagingType)
        {
            var usedMeasureWeight = _measureService.GetMeasureWeightBySystemKeyword(MEASUREWEIGHTSYSTEMKEYWORD);

            if (usedMeasureWeight == null)
            {
                throw new NopException(string.Format("UPS shipping service. Could not load \"{0}\" measure weight", MEASUREWEIGHTSYSTEMKEYWORD));
            }

            var usedMeasureDimension = _measureService.GetMeasureDimensionBySystemKeyword(MEASUREDIMENSIONSYSTEMKEYWORD);

            if (usedMeasureDimension == null)
            {
                throw new NopException(string.Format("UPS shipping service. Could not load \"{0}\" measure dimension", MEASUREDIMENSIONSYSTEMKEYWORD));
            }

            int length = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureDimension(getShippingOptionRequest.GetTotalLength(), usedMeasureDimension)));
            int height = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureDimension(getShippingOptionRequest.GetTotalHeight(), usedMeasureDimension)));
            int width  = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureDimension(getShippingOptionRequest.GetTotalWidth(), usedMeasureDimension)));
            int weight = Convert.ToInt32(Math.Ceiling(_measureService.ConvertFromPrimaryMeasureWeight(_shippingService.GetShoppingCartTotalWeight(getShippingOptionRequest.Items), usedMeasureWeight)));

            if (length < 1)
            {
                length = 1;
            }
            if (height < 1)
            {
                height = 1;
            }
            if (width < 1)
            {
                width = 1;
            }
            if (weight < 1)
            {
                weight = 1;
            }

            string zipPostalCodeFrom = getShippingOptionRequest.ZipPostalCodeFrom;
            string zipPostalCodeTo   = getShippingOptionRequest.ShippingAddress.ZipPostalCode;
            string countryCodeFrom   = getShippingOptionRequest.CountryFrom.TwoLetterIsoCode;
            string countryCodeTo     = getShippingOptionRequest.ShippingAddress.Country.TwoLetterIsoCode;


            decimal  orderSubTotalDiscountAmount  = decimal.Zero;
            Discount orderSubTotalAppliedDiscount = null;
            decimal  subTotalWithoutDiscountBase  = decimal.Zero;
            decimal  subTotalWithDiscountBase     = decimal.Zero;

            _orderTotalCalculationService.GetShoppingCartSubTotal(getShippingOptionRequest.Items,
                                                                  out orderSubTotalDiscountAmount, out orderSubTotalAppliedDiscount,
                                                                  out subTotalWithoutDiscountBase, out subTotalWithDiscountBase);

            var sb = new StringBuilder();

            sb.Append("<?xml version='1.0'?>");
            sb.Append("<AccessRequest xml:lang='en-US'>");
            sb.AppendFormat("<AccessLicenseNumber>{0}</AccessLicenseNumber>", accessKey);
            sb.AppendFormat("<UserId>{0}</UserId>", username);
            sb.AppendFormat("<Password>{0}</Password>", password);
            sb.Append("</AccessRequest>");
            sb.Append("<?xml version='1.0'?>");
            sb.Append("<RatingServiceSelectionRequest xml:lang='en-US'>");
            sb.Append("<Request>");
            sb.Append("<TransactionReference>");
            sb.Append("<CustomerContext>Bare Bones Rate Request</CustomerContext>");
            sb.Append("<XpciVersion>1.0001</XpciVersion>");
            sb.Append("</TransactionReference>");
            sb.Append("<RequestAction>Rate</RequestAction>");
            sb.Append("<RequestOption>Shop</RequestOption>");
            sb.Append("</Request>");
            if (String.Equals(countryCodeFrom, "US", StringComparison.InvariantCultureIgnoreCase) == true)
            {
                sb.Append("<PickupType>");
                sb.AppendFormat("<Code>{0}</Code>", GetPickupTypeCode(pickupType));
                sb.Append("</PickupType>");
                sb.Append("<CustomerClassification>");
                sb.AppendFormat("<Code>{0}</Code>", GetCustomerClassificationCode(customerClassification));
                sb.Append("</CustomerClassification>");
            }
            sb.Append("<Shipment>");
            sb.Append("<Shipper>");
            sb.Append("<Address>");
            sb.AppendFormat("<PostalCode>{0}</PostalCode>", zipPostalCodeFrom);
            sb.AppendFormat("<CountryCode>{0}</CountryCode>", countryCodeFrom);
            sb.Append("</Address>");
            sb.Append("</Shipper>");
            sb.Append("<ShipTo>");
            sb.Append("<Address>");
            sb.Append("<ResidentialAddressIndicator/>");
            sb.AppendFormat("<PostalCode>{0}</PostalCode>", zipPostalCodeTo);
            sb.AppendFormat("<CountryCode>{0}</CountryCode>", countryCodeTo);
            sb.Append("</Address>");
            sb.Append("</ShipTo>");
            sb.Append("<ShipFrom>");
            sb.Append("<Address>");
            sb.AppendFormat("<PostalCode>{0}</PostalCode>", zipPostalCodeFrom);
            sb.AppendFormat("<CountryCode>{0}</CountryCode>", countryCodeFrom);
            sb.Append("</Address>");
            sb.Append("</ShipFrom>");
            sb.Append("<Service>");
            sb.Append("<Code>03</Code>");
            sb.Append("</Service>");


            if ((!IsPackageTooHeavy(weight)) && (!IsPackageTooLarge(length, height, width)))
            {
                sb.Append("<Package>");
                sb.Append("<PackagingType>");
                sb.AppendFormat("<Code>{0}</Code>", GetPackagingTypeCode(packagingType));
                sb.Append("</PackagingType>");
                sb.Append("<Dimensions>");
                sb.AppendFormat("<Length>{0}</Length>", length);
                sb.AppendFormat("<Width>{0}</Width>", width);
                sb.AppendFormat("<Height>{0}</Height>", height);
                sb.Append("</Dimensions>");
                sb.Append("<PackageWeight>");
                sb.AppendFormat("<Weight>{0}</Weight>", weight);
                sb.Append("</PackageWeight>");

                if (_upsSettings.InsurePackage)
                {
                    //The maximum declared amount per package: 50000 USD.
                    int packageInsurancePrice = Convert.ToInt32(subTotalWithDiscountBase);
                    sb.Append("<PackageServiceOptions>");
                    sb.Append("<InsuredValue>");
                    sb.AppendFormat("<CurrencyCode>{0}</CurrencyCode>", _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode);
                    sb.AppendFormat("<MonetaryValue>{0}</MonetaryValue>", packageInsurancePrice);
                    sb.Append("</InsuredValue>");
                    sb.Append("</PackageServiceOptions>");
                }
                sb.Append("</Package>");
            }
            else
            {
                int totalPackages        = 1;
                int totalPackagesDims    = 1;
                int totalPackagesWeights = 1;
                if (IsPackageTooHeavy(weight))
                {
                    totalPackagesWeights = Convert.ToInt32(Math.Ceiling((decimal)weight / (decimal)MAXPACKAGEWEIGHT));
                }
                if (IsPackageTooLarge(length, height, width))
                {
                    totalPackagesDims = Convert.ToInt32(Math.Ceiling((decimal)TotalPackageSize(length, height, width) / (decimal)108));
                }
                totalPackages = totalPackagesDims > totalPackagesWeights ? totalPackagesDims : totalPackagesWeights;
                if (totalPackages == 0)
                {
                    totalPackages = 1;
                }

                int weight2 = weight / totalPackages;
                int height2 = height / totalPackages;
                int width2  = width / totalPackages;
                int length2 = length / totalPackages;
                if (weight2 < 1)
                {
                    weight2 = 1;
                }
                if (height2 < 1)
                {
                    height2 = 1;
                }
                if (width2 < 1)
                {
                    width2 = 1;
                }
                if (length2 < 1)
                {
                    length2 = 1;
                }

                //The maximum declared amount per package: 50000 USD.
                int packageInsurancePrice = Convert.ToInt32(subTotalWithDiscountBase / totalPackages);

                for (int i = 0; i < totalPackages; i++)
                {
                    sb.Append("<Package>");
                    sb.Append("<PackagingType>");
                    sb.AppendFormat("<Code>{0}</Code>", GetPackagingTypeCode(packagingType));
                    sb.Append("</PackagingType>");
                    sb.Append("<Dimensions>");
                    sb.AppendFormat("<Length>{0}</Length>", length2);
                    sb.AppendFormat("<Width>{0}</Width>", width2);
                    sb.AppendFormat("<Height>{0}</Height>", height2);
                    sb.Append("</Dimensions>");
                    sb.Append("<PackageWeight>");
                    sb.AppendFormat("<Weight>{0}</Weight>", weight2);
                    sb.Append("</PackageWeight>");

                    if (_upsSettings.InsurePackage)
                    {
                        sb.Append("<PackageServiceOptions>");
                        sb.Append("<InsuredValue>");
                        sb.AppendFormat("<CurrencyCode>{0}</CurrencyCode>", _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode);
                        sb.AppendFormat("<MonetaryValue>{0}</MonetaryValue>", packageInsurancePrice);
                        sb.Append("</InsuredValue>");
                        sb.Append("</PackageServiceOptions>");
                    }

                    sb.Append("</Package>");
                }
            }


            sb.Append("</Shipment>");
            sb.Append("</RatingServiceSelectionRequest>");
            string requestString = sb.ToString();

            return(requestString);
        }
예제 #23
0
        //分页获取数据列表
        //public DataSet GetList(int PageSize,int PageIndex,string strWhere)
        //{
        //return dal.GetList(PageSize,PageIndex,strWhere);
        //}

        #endregion  BasicMethod

        #region  ExtensionMethod

        /// <summary>
        /// 用事务新增客户和折扣
        /// </summary>
        public bool AddClientAndDiscount(Client client, Discount discount)
        {
            return(dal.AddClientAndDiscount(client, discount));
        }
예제 #24
0
 public ItemQuantityDiscount(Discount nextDiscount, int minQuantity, double percentage) : base(nextDiscount)
 {
     this.minQuantity = minQuantity;
     this.percentage  = percentage;
 }
예제 #25
0
 public AgeBasedPromotion(int age, Discount discount)
 {
     this.age = age;
     Discount = discount;
 }
예제 #26
0
 public void Put(Discount value)
 {
     service.Create(value);
 }
        public override decimal AdjustShippingRate(decimal shippingRate, IList<ShoppingCartItem> cart, out Discount appliedDiscount)
        {
            if (!_promoSettings.Enabled)
                return base.AdjustShippingRate(shippingRate, cart, out appliedDiscount);

            appliedDiscount = null;

            decimal additionalShippingCharge = GetShoppingCartAdditionalShippingCharge(cart);

            return shippingRate + additionalShippingCharge;
        }
예제 #28
0
        public void Can_get_product_discount()
        {
            var product = new Product
            {
                Id    = 1,
                Name  = "Product name 1",
                Price = 12.34M,
                CustomerEntersPrice = false,
                Published           = true,
            };

            //customer
            Customer customer = null;

            //discounts
            var discount1 = new Discount()
            {
                Id                 = 1,
                Name               = "Discount 1",
                DiscountType       = DiscountType.AssignedToSkus,
                DiscountAmount     = 3,
                DiscountLimitation = DiscountLimitationType.Unlimited
            };

            discount1.AppliedToProducts.Add(product);
            product.AppliedDiscounts.Add(discount1);
            //set HasDiscountsApplied property
            product.HasDiscountsApplied = true;
            _discountService.Expect(ds => ds.IsDiscountValid(discount1, customer)).Return(true);
            _discountService.Expect(ds => ds.GetAllDiscounts(DiscountType.AssignedToCategories)).Return(new List <Discount>());
            _discountService.Expect(ds => ds.GetAllDiscounts(DiscountType.AssignedToManufacturers)).Return(new List <Discount>());

            var discount2 = new Discount()
            {
                Id                 = 2,
                Name               = "Discount 2",
                DiscountType       = DiscountType.AssignedToSkus,
                DiscountAmount     = 4,
                DiscountLimitation = DiscountLimitationType.Unlimited
            };

            discount2.AppliedToProducts.Add(product);
            product.AppliedDiscounts.Add(discount2);
            _discountService.Expect(ds => ds.IsDiscountValid(discount2, customer)).Return(true);

            var discount3 = new Discount()
            {
                Id                 = 3,
                Name               = "Discount 3",
                DiscountType       = DiscountType.AssignedToOrderSubTotal,
                DiscountAmount     = 5,
                DiscountLimitation = DiscountLimitationType.Unlimited,
                RequiresCouponCode = true,
                CouponCode         = "SECRET CODE"
            };

            discount3.AppliedToProducts.Add(product);
            product.AppliedDiscounts.Add(discount3);
            //discount is not valid
            _discountService.Expect(ds => ds.IsDiscountValid(discount3, customer)).Return(false);


            Discount appliedDiscount;

            _priceCalcService.GetDiscountAmount(product, customer, 0, 1, out appliedDiscount).ShouldEqual(4);
            appliedDiscount.ShouldNotBeNull();
            appliedDiscount.ShouldEqual(discount2);
        }
        protected override decimal GetOrderTotalDiscount(Customer customer, decimal orderTotal, out Discount appliedDiscount)
        {
            if (!_rewardPointsSettings.Enabled)
                return base.GetOrderTotalDiscount(customer, orderTotal, out appliedDiscount);

            BasketResponse basketResponse = _promoUtilities.GetBasketResponse();

            appliedDiscount = null;
            decimal discountAmount = decimal.Zero;

            if (basketResponse == null)
                return discountAmount;

            if (basketResponse.BasketLevelDiscountIncludesDeliveryAmount())
            {
                discountAmount = basketResponse.BasketLevelPromotion().DiscountAmount;
                appliedDiscount = new Discount()
                {
                    Name = basketResponse.BasketLevelPromotion().PromotionName,
                    DiscountAmount = discountAmount
                };
            }

            if (discountAmount < decimal.Zero)
                discountAmount = decimal.Zero;

            return discountAmount;
        }
예제 #30
0
        public ActionResult Create(Discount discount, FormCollection form)
        {
            //if (ModelState.IsValid)
            //{
            Discount dcnt = new Discount();

            dcnt.DiscountCode    = discount.DiscountCode;
            dcnt.StoreID         = Session["StoreID"].ToString();
            dcnt.DiscountTitle   = discount.DiscountTitle;
            dcnt.DiscountDetails = discount.DiscountDetails;
            foreach (string file in Request.Files)
            {
                var fileContent = Request.Files[file];
                if (fileContent != null && fileContent.ContentLength > 0)
                {
                    string pic  = System.IO.Path.GetFileName(fileContent.FileName);
                    string path = System.IO.Path.Combine(Server.MapPath("~/images/"), pic);
                    fileContent.SaveAs(path);
                    dcnt.DiscountImage = "http://livingstud.com/images/" + fileContent.FileName;
                }
            }
            dcnt.DiscountedProductCategoryID = discount.DiscountedProductCategoryID;
            dcnt.DiscountProductID           = discount.DiscountProductID;
            dcnt.DiscountVendorID            = Convert.ToInt32(Session["CustId"]);
            dcnt.DiscountStartDate           = discount.DiscountStartDate;
            dcnt.DiscountEndDate             = discount.DiscountEndDate;
            dcnt.DiscountAmount     = discount.DiscountAmount;
            dcnt.DiscountAmountType = discount.DiscountAmountType;
            dcnt.IsOnCategories     = discount.IsOnCategories;
            dcnt.IsOnProducts       = discount.IsOnProducts;
            dcnt.IsOnStore          = discount.IsOnStore;
            dcnt.IsAllProducts      = discount.IsAllProducts;
            dcnt.InsertDate         = DateTime.Now.ToString();
            dcnt.UpdateDate         = DateTime.Now.ToString();
            dcnt.IsActive           = true;
            dcnt.IsDelete           = false;
            dcnt.IsUpdate           = true;
            db.Discounts.Add(dcnt);
            db.SaveChanges();
            ProductDetails pd = new ProductDetails();

            if (discount.IsOnProducts == true)
            {
                int lastProductId = discount.DiscountProductID;
                pd = db.ProductDetails.Where(x => x.ProductID == lastProductId).FirstOrDefault();

                //pd.IsDiscounted = true;
                //if (discount.DiscountAmountType == "1")
                //{
                //    pd.DiscountAmount = Math.Round(pd.ProductPrice, 0) * Convert.ToDecimal(discount.DiscountAmount) / 100;
                //}
                //else
                //{
                //    pd.DiscountAmount = Math.Round(pd.ProductPrice, 0) - Convert.ToDecimal(discount.DiscountAmount);

                //}

                db.Entry(pd).State = EntityState.Modified;
                db.SaveChanges();
            }
            if (discount.IsOnCategories == true)
            {
                List <ProductDetails> lstProd = new List <ProductDetails>();
                int catid = discount.DiscountedProductCategoryID;
                lstProd = db.ProductDetails.Where(x => x.ProductCategory == catid).ToList();
                if (lstProd.Count > 0)
                {
                    for (int i = 0; i < lstProd.Count; i++)
                    {
                        int lastProductId = lstProd[i].ProductID;
                        pd = db.ProductDetails.Where(x => x.ProductID == lastProductId).FirstOrDefault();

                        //pd.IsDiscounted = true;
                        //if (discount.DiscountAmountType == "1")
                        //{
                        //    pd.DiscountAmount = Math.Round(pd.ProductPrice, 0) * Convert.ToDecimal(discount.DiscountAmount) / 100;
                        //}
                        //else
                        //{
                        //    pd.DiscountAmount = Math.Round(pd.ProductPrice, 0) - Convert.ToDecimal(discount.DiscountAmount);
                        //}

                        db.Entry(pd).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                }
            }
            if (discount.IsAllProducts == true)
            {
                List <ProductDetails> lstProd = new List <ProductDetails>();
                lstProd = db.ProductDetails.ToList();
                if (lstProd.Count > 0)
                {
                    for (int i = 0; i < lstProd.Count; i++)
                    {
                        int lastProductId = lstProd[i].ProductID;
                        pd = db.ProductDetails.Where(x => x.ProductID == lastProductId).FirstOrDefault();

                        //pd.IsDiscounted = true;
                        //if (discount.DiscountAmountType == "1")
                        //{
                        //    pd.DiscountAmount = Math.Round(pd.ProductPrice, 0) * Convert.ToDecimal(discount.DiscountAmount) / 100;
                        //}
                        //else
                        //{
                        //    pd.DiscountAmount = Math.Round(pd.ProductPrice, 0) - Convert.ToDecimal(discount.DiscountAmount);
                        //}

                        db.Entry(pd).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                }
            }
            return(RedirectToAction("Index"));

            return(View(discount));
        }
예제 #31
0
	private void detach_Discounts(Discount entity)
	{
		this.SendPropertyChanging();
		entity.Business = null;
	}
예제 #32
0
 public Discount Create(Discount discount)
 {
     _context.Discounts.Add(discount);
     _context.SaveChanges();
     return(discount);
 }
예제 #33
0
 public static bool IsAvailable(this Discount discount, DateTime currentDateTime)
 {
     return(discount.IsActive && discount.ValidFrom == null && discount.ValidUntil == null ||
            discount.ValidFrom < currentDateTime &&
            discount.ValidUntil > currentDateTime);
 }
예제 #34
0
 public void Delete(Discount discount)
 {
     _context.Discounts.Remove(discount);
     _context.SaveChanges();
 }
        public override void UpdateDiscount(Discount discount)
        {
            if (!_promoSettings.Enabled)
            {
                base.UpdateDiscount(discount);
                return;
            }

            throw new NotSupportedException("UpdateDiscount");
        }
예제 #36
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Discount obj)
 {
     return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr);
 }
예제 #37
0
        public Discount ToDiscountModel(decimal originAmount, Currency currency)
        {
            decimal absoluteAmount = GetAbsoluteDiscountAmount(originAmount);

            var discount = new Discount();
            discount.Amount = new Money(absoluteAmount, currency.Code);
            discount.Description = Promotion.Description;
            discount.PromotionId = Promotion.Id;

            return discount;
        }
예제 #38
0
 public void Update(Discount discount)
 {
     throw new NotImplementedException();
 }
예제 #39
0
 public Discount Create(Discount discount)
 {
     _discounts.InsertOne(discount);
     return discount;
 }
예제 #40
0
        public ActionResult SubmitButton()
        {
            try
            {
                //user validation
                if ((Services.WorkContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed))
                {
                    return(RedirectToRoute("Login"));
                }

                var store    = Services.StoreContext.CurrentStore;
                var customer = Services.WorkContext.CurrentCustomer;
                var settings = Services.Settings.LoadSetting <PayPalExpressPaymentSettings>(store.Id);
                var cart     = Services.WorkContext.CurrentCustomer.GetCartItems(ShoppingCartType.ShoppingCart, store.Id);

                if (cart.Count == 0)
                {
                    return(RedirectToRoute("ShoppingCart"));
                }

                if (String.IsNullOrEmpty(settings.ApiAccountName))
                {
                    throw new ApplicationException("PayPal API Account Name is not set");
                }
                if (String.IsNullOrEmpty(settings.ApiAccountPassword))
                {
                    throw new ApplicationException("PayPal API Password is not set");
                }
                if (String.IsNullOrEmpty(settings.Signature))
                {
                    throw new ApplicationException("PayPal API Signature is not set");
                }

                var provider  = PaymentService.LoadPaymentMethodBySystemName(PayPalExpressProvider.SystemName, true);
                var processor = provider != null ? provider.Value as PayPalExpressProvider : null;
                if (processor == null)
                {
                    throw new SmartException("PayPal Express Checkout module cannot be loaded");
                }

                var processPaymentRequest = new PayPalProcessPaymentRequest();

                processPaymentRequest.StoreId = store.Id;

                //Get sub-total and discounts that apply to sub-total
                decimal  orderSubTotalDiscountAmountBase = decimal.Zero;
                Discount orderSubTotalAppliedDiscount    = null;
                decimal  subTotalWithoutDiscountBase     = decimal.Zero;
                decimal  subTotalWithDiscountBase        = decimal.Zero;

                _orderTotalCalculationService.GetShoppingCartSubTotal(cart,
                                                                      out orderSubTotalDiscountAmountBase, out orderSubTotalAppliedDiscount, out subTotalWithoutDiscountBase, out subTotalWithDiscountBase);

                //order total
                decimal resultTemp = decimal.Zero;
                resultTemp += subTotalWithDiscountBase;

                //Get discounts that apply to Total
                Discount appliedDiscount = null;
                var      discountAmount  = _orderTotalCalculationService.GetOrderTotalDiscount(customer, resultTemp, out appliedDiscount);

                //if the current total is less than the discount amount, we only make the discount equal to the current total
                if (resultTemp < discountAmount)
                {
                    discountAmount = resultTemp;
                }

                //reduce subtotal
                resultTemp -= discountAmount;

                if (resultTemp < decimal.Zero)
                {
                    resultTemp = decimal.Zero;
                }

                decimal tempDiscount = discountAmount + orderSubTotalDiscountAmountBase;

                resultTemp = _currencyService.ConvertFromPrimaryStoreCurrency(resultTemp, Services.WorkContext.WorkingCurrency);
                if (tempDiscount > decimal.Zero)
                {
                    tempDiscount = _currencyService.ConvertFromPrimaryStoreCurrency(tempDiscount, Services.WorkContext.WorkingCurrency);
                }

                processPaymentRequest.PaymentMethodSystemName = PayPalExpressProvider.SystemName;
                processPaymentRequest.OrderTotal         = resultTemp;
                processPaymentRequest.Discount           = tempDiscount;
                processPaymentRequest.IsRecurringPayment = false;

                //var selectedPaymentMethodSystemName = _workContext.CurrentCustomer.GetAttribute<string>(SystemCustomerAttributeNames.SelectedPaymentMethod, _storeContext.CurrentStore.Id);

                processPaymentRequest.CustomerId = Services.WorkContext.CurrentCustomer.Id;
                this.Session["OrderPaymentInfo"] = processPaymentRequest;

                var resp = processor.SetExpressCheckout(processPaymentRequest, cart);

                if (resp.Ack == AckCodeType.Success)
                {
                    processPaymentRequest.PaypalToken         = resp.Token;
                    processPaymentRequest.OrderGuid           = new Guid();
                    processPaymentRequest.IsShippingMethodSet = ControllerContext.RouteData.IsRouteEqual("ShoppingCart", "Cart");
                    this.Session["OrderPaymentInfo"]          = processPaymentRequest;

                    _genericAttributeService.SaveAttribute <string>(customer, SystemCustomerAttributeNames.SelectedPaymentMethod, PayPalExpressProvider.SystemName, store.Id);

                    var result = new RedirectResult(String.Format(settings.GetPayPalUrl() + "?cmd=_express-checkout&useraction=commit&token={0}", resp.Token));

                    return(result);
                }
                else
                {
                    var error = new StringBuilder("We apologize, but an error has occured.<br />");
                    foreach (var errormsg in resp.Errors)
                    {
                        error.AppendLine(String.Format("{0} | {1} | {2}", errormsg.ErrorCode, errormsg.ShortMessage, errormsg.LongMessage));
                    }

                    Logger.InsertLog(LogLevel.Error, resp.Errors[0].ShortMessage, resp.Errors[0].LongMessage, customer);

                    NotifyError(error.ToString(), false);

                    return(RedirectToAction("Cart", "ShoppingCart", new { area = "" }));
                }
            }
            catch (Exception ex)
            {
                Logger.InsertLog(LogLevel.Error, ex.Message, ex.StackTrace, Services.WorkContext.CurrentCustomer);

                NotifyError(ex.Message, false);

                return(RedirectToAction("Cart", "ShoppingCart", new { area = "" }));
            }
        }
예제 #41
0
 public static List <SelectListItem> GetApplicationOptions(this Discount discount)
 {
     return(TypeHelper.GetAllConcreteMappedClassesAssignableFrom <DiscountApplication>()
            .BuildSelectItemList(type => type.Name.BreakUpString(), type => type.FullName,
                                 emptyItemText: null));
 }
예제 #42
0
 public static DiscountModel ToModel(this Discount entity)
 {
     return(entity.MapTo <Discount, DiscountModel>());
 }
예제 #43
0
        protected virtual string GetRequirementUrlInternal(IDiscountRequirementRule discountRequirementRule, Discount discount, int?discountRequirementId)
        {
            if (discountRequirementRule == null)
            {
                throw new ArgumentNullException("discountRequirementRule");
            }

            if (discount == null)
            {
                throw new ArgumentNullException("discount");
            }

            string url = string.Format("{0}{1}", _webHelper.GetStoreLocation(), discountRequirementRule.GetConfigurationUrl(discount.Id, discountRequirementId));

            return(url);
        }
예제 #44
0
 public static Discount ToEntity(this DiscountModel model, Discount destination)
 {
     return(model.MapTo(destination));
 }
        protected override decimal GetShippingDiscount(Customer customer, decimal shippingTotal, out Discount appliedDiscount)
        {
            if (!_promoSettings.Enabled)
                return base.GetShippingDiscount(customer, shippingTotal, out appliedDiscount);

            appliedDiscount = null;

            BasketResponse basketResponse = _promoUtilities.GetBasketResponse();
            var discountAmount = basketResponse.DeliveryPromoDiscount();
            if (discountAmount != decimal.Zero)
            {
                appliedDiscount = new Discount()
                {
                    Name = basketResponse.DeliveryPromoName(),
                    DiscountAmount = discountAmount
                };
            }

            return discountAmount;
        }
예제 #46
0
 public frmModDiscount(Discount Discount)
 {
     InitializeComponent();
     discount = Discount;
     Load_Discount(discount);
 }
        public override decimal? GetShoppingCartTotal(IList<global::Nop.Core.Domain.Orders.ShoppingCartItem> cart, out decimal discountAmount, out global::Nop.Core.Domain.Discounts.Discount appliedDiscount, out List<AppliedGiftCard> appliedGiftCards, out int redeemedRewardPoints, out decimal redeemedRewardPointsAmount, bool ignoreRewardPonts = false, bool usePaymentMethodAdditionalFee = true)
        {
            if (!_promoSettings.Enabled)
                return base.GetShoppingCartTotal(cart, out discountAmount, out appliedDiscount, out appliedGiftCards, out redeemedRewardPoints, out redeemedRewardPointsAmount, ignoreRewardPonts, usePaymentMethodAdditionalFee);

            BasketResponse basketResponse = _promoUtilities.GetBasketResponse();

            if (basketResponse == null || basketResponse.Items == null || basketResponse.Summary == null)
            {
                return base.GetShoppingCartTotal(cart, out discountAmount, out appliedDiscount, out appliedGiftCards, out redeemedRewardPoints, out redeemedRewardPointsAmount, ignoreRewardPonts, usePaymentMethodAdditionalFee);
            }

            if (!basketResponse.Summary.ProcessingResult)
            {
                return base.GetShoppingCartTotal(cart, out discountAmount, out appliedDiscount, out appliedGiftCards, out redeemedRewardPoints, out redeemedRewardPointsAmount, ignoreRewardPonts, usePaymentMethodAdditionalFee);
            }

            Customer customer = cart.GetCustomer();

            discountAmount = decimal.Zero;
            appliedDiscount = null;
            decimal resultTemp = basketResponse.BasketTotal;

            #region Applied gift cards

            appliedGiftCards = new List<AppliedGiftCard>();
            if (!cart.IsRecurring())
            {
                //we don't apply gift cards for recurring products
                var giftCards = _giftCardService.GetActiveGiftCardsAppliedByCustomer(customer);
                if (giftCards != null)
                    foreach (var gc in giftCards)
                        if (resultTemp > decimal.Zero)
                        {
                            decimal remainingAmount = gc.GetGiftCardRemainingAmount();
                            decimal amountCanBeUsed = decimal.Zero;
                            if (resultTemp > remainingAmount)
                                amountCanBeUsed = remainingAmount;
                            else
                                amountCanBeUsed = resultTemp;

                            //reduce subtotal
                            resultTemp -= amountCanBeUsed;

                            var appliedGiftCard = new AppliedGiftCard();
                            appliedGiftCard.GiftCard = gc;
                            appliedGiftCard.AmountCanBeUsed = amountCanBeUsed;
                            appliedGiftCards.Add(appliedGiftCard);
                        }
            }

            if (resultTemp < decimal.Zero)
                resultTemp = decimal.Zero;
            if (_shoppingCartSettings.RoundPricesDuringCalculation)
                resultTemp = RoundingHelper.RoundPrice(resultTemp);

            #endregion

            redeemedRewardPoints = 0;
            redeemedRewardPointsAmount = Decimal.Zero;

            decimal orderTotal = basketResponse.BasketTotal - appliedGiftCards.Sum(agc => agc.AmountCanBeUsed);

            #region Reward points

            if (_rewardPointsSettings.Enabled &&
                !ignoreRewardPonts &&
                customer.GetAttribute<bool>(SystemCustomerAttributeNames.UseRewardPointsDuringCheckout,
                    _genericAttributeService, _storeContext.CurrentStore.Id))
            {
                int rewardPointsBalance = customer.GetRewardPointsBalance();
                if (CheckMinimumRewardPointsToUseRequirement(rewardPointsBalance))
                {
                    decimal rewardPointsBalanceAmount = ConvertRewardPointsToAmount(rewardPointsBalance);
                    if (orderTotal > decimal.Zero)
                    {
                        if (orderTotal > rewardPointsBalanceAmount)
                        {
                            redeemedRewardPoints = rewardPointsBalance;
                            redeemedRewardPointsAmount = rewardPointsBalanceAmount;
                        }
                        else
                        {
                            redeemedRewardPointsAmount = orderTotal;
                            redeemedRewardPoints = ConvertAmountToRewardPoints(redeemedRewardPointsAmount);
                        }
                    }
                }
            }

            #endregion

            var shippingOption = _workContext.CurrentCustomer.GetAttribute<ShippingOption>(SystemCustomerAttributeNames.SelectedShippingOption, _storeContext.CurrentStore.Id);
            if (shippingOption == null)
            {
                // Where there are items in the basket that are not for shipping, ensure we carry on, otherwise placing orders gets stuck.
                if(cart.Any(sci => sci.IsShipEnabled))
                    return null;                
            }

            discountAmount = basketResponse.OrderDiscountTotal();
            if (discountAmount > 0)
            {
                appliedDiscount = new Discount()
                {
                    Name = basketResponse.BasketLevelPromotion().PromotionName,
                    DiscountAmount = discountAmount
                };
            }

            decimal tax = GetTaxTotal(cart);

            return basketResponse.BasketTotal + tax - appliedGiftCards.Sum(agc => agc.AmountCanBeUsed) - redeemedRewardPointsAmount;
        }
예제 #48
0
        public ActionResult <Discount> Create(Discount discount)
        {
            _discountService.Create(discount);

            return(CreatedAtRoute("GetDiscount", new { id = discount.Id.ToString() }, discount));
        }
예제 #49
0
 public DiscountItem(Discount discount)
 {
     Code   = discount.DiscountCode;
     Amount = discount.DiscountValue;
 }
예제 #50
0
파일: Discount.cs 프로젝트: minikie/test
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Discount obj) {
   return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
 }
예제 #51
0
 /// <summary>
 /// Add discount item to lvDiscount.
 /// </summary>
 /// <param name="discount"> The discount.</param>
 private void AddToDiscountList(Discount discount)
 {
     if (!_discounts.Exists(x => x.DiscountCode.Equals(discount.DiscountCode)))
     {
         _discounts.Add(discount);
     }
 }
예제 #52
0
 public void Remove(Discount discountIn) =>
     _discounts.DeleteOne(discount => discount.Id == discountIn.Id);
예제 #53
0
 partial void InsertDiscount(Discount instance);
        //public override void InsertDiscountUsageHistory(DiscountUsageHistory discountUsageHistory)
        //{
        //    if (discountUsageHistory == null)
        //        throw new ArgumentNullException("discountUsageHistory");

        //    _discountUsageHistoryRepository.Insert(discountUsageHistory);

        //    _cacheManager.RemoveByPattern(DISCOUNTS_PATTERN_KEY);

        //    //event notification
        //    _eventPublisher.EntityInserted(discountUsageHistory);
        //}

        public override bool IsDiscountValid(Discount discount, global::Nop.Core.Domain.Customers.Customer customer, string couponCodeToValidate)
        {
            if (!_promoSettings.Enabled)
                return base.IsDiscountValid(discount, customer, couponCodeToValidate);

            BasketResponse basketResponse = _promoUtilities.GetBasketResponse();

            if (basketResponse == null || basketResponse.Items == null || basketResponse.Summary == null)
                return false;

            if (!basketResponse.Summary.ProcessingResult)
                return false;

            if (basketResponse.Coupons == null)
                    return false;

            if (basketResponse.Coupons == null)
                return false;

            if (basketResponse.Coupons.Count == 0)
                return false;

            var coupon = (from c in basketResponse.Coupons where c.CouponCode.Equals(couponCodeToValidate, StringComparison.InvariantCultureIgnoreCase) select c).FirstOrDefault();

            if (coupon == null)
                return false;

            return coupon.Utilized;
        }
예제 #55
0
 partial void DeleteDiscount(Discount instance);
예제 #56
0
 public Task RemoveDiscount(Discount discount)
 {
     Context.Discounts.Remove(discount);
     return(Task.CompletedTask);
 }
예제 #57
0
 public void Save(Discount discount)
 {
     context.Discount.Add(discount);
     context.SaveChanges();
 }
        public static decimal CalculatePrice(decimal pricePerDay, int numberOfDays, Season season, Discount discount)
        {
            int     multiplier          = (int)season;
            decimal discountMultiplier  = (decimal)discount / 100;
            decimal priceBeforeDiscount = numberOfDays * pricePerDay * multiplier;
            decimal discountedAmount    =
                priceBeforeDiscount * discountMultiplier;
            decimal finalPrice = priceBeforeDiscount - discountedAmount;

            return(finalPrice);
        }
예제 #59
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create a unit group.
        /// Retrieve the default unit.
        /// Create few products.
        /// Create new discount list and discount.
        /// Create new price list and few price list items.
        /// Create an account record.
        /// </summary>
        public void CreateRequiredRecords()
        {
            // Create a unit group
            UoMSchedule newUnitGroup = new UoMSchedule
            {
                Name        = "Example Unit Group",
                BaseUoMName = "Example Primary Unit"
            };

            _unitGroupId = _serviceProxy.Create(newUnitGroup);
            Console.WriteLine("Created {0}", newUnitGroup.Name);

            // Retrieve the default unit id that was automatically created
            // when we created the Unit Group
            QueryExpression unitQuery = new QueryExpression
            {
                EntityName = UoM.EntityLogicalName,
                ColumnSet  = new ColumnSet("uomid", "name"),
                Criteria   = new FilterExpression
                {
                    Conditions =
                    {
                        new ConditionExpression
                        {
                            AttributeName = "uomscheduleid",
                            Operator      = ConditionOperator.Equal,
                            Values        = { _unitGroupId }
                        }
                    }
                },
                PageInfo = new PagingInfo
                {
                    PageNumber = 1,
                    Count      = 1
                }
            };

            // Retrieve the unit.
            UoM unit = (UoM)_serviceProxy.RetrieveMultiple(unitQuery).Entities[0];

            _defaultUnitId = unit.UoMId.Value;

            Console.WriteLine("Retrieved {0}", unit.Name);

            // Create a few products
            Product newProduct1 = new Product
            {
                ProductNumber        = "1",
                Name                 = "Example Product 1",
                ProductStructure     = new OptionSetValue(1),
                QuantityDecimal      = 2,
                DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName,
                                                           _unitGroupId),
                DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId)
            };

            _product1Id = _serviceProxy.Create(newProduct1);
            Console.WriteLine("Created {0}", newProduct1.Name);

            Product newProduct2 = new Product
            {
                ProductNumber        = "2",
                Name                 = "Example Product 2",
                ProductStructure     = new OptionSetValue(1),
                QuantityDecimal      = 3,
                DefaultUoMScheduleId = new EntityReference(UoMSchedule.EntityLogicalName,
                                                           _unitGroupId),
                DefaultUoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId)
            };

            _product2Id = _serviceProxy.Create(newProduct2);
            Console.WriteLine("Created {0}", newProduct2.Name);

            // Create a new discount list
            DiscountType newDiscountType = new DiscountType
            {
                Name         = "Example Discount List",
                IsAmountType = false
            };

            _discountTypeId = _serviceProxy.Create(newDiscountType);
            Console.WriteLine("Created {0}", newDiscountType.Name);

            // Create a new discount
            Discount newDiscount = new Discount
            {
                DiscountTypeId = new EntityReference(DiscountType.EntityLogicalName,
                                                     _discountTypeId),
                LowQuantity  = 5,
                HighQuantity = 10,
                Percentage   = 3
            };

            _discountId = _serviceProxy.Create(newDiscount);

            Console.WriteLine("Created new discount for the {0}.", newDiscountType.Name);

            // Create a price list
            PriceLevel newPriceList = new PriceLevel
            {
                Name = "Example Price List"
            };

            _priceListId = _serviceProxy.Create(newPriceList);
            Console.WriteLine("Created {0}", newPriceList.Name);

            // Create a price list item for the first product and apply volume discount
            ProductPriceLevel newPriceListItem1 = new ProductPriceLevel
            {
                PriceLevelId   = new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
                ProductId      = new EntityReference(Product.EntityLogicalName, _product1Id),
                UoMId          = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
                Amount         = new Money(20),
                DiscountTypeId = new EntityReference(DiscountType.EntityLogicalName,
                                                     _discountTypeId)
            };

            _priceListItem1Id = _serviceProxy.Create(newPriceListItem1);
            Console.WriteLine(@"Created price list item for the {0} and applied 
                volume discount.", newProduct1.Name);

            // Create a price list item for the second product
            ProductPriceLevel newPriceListItem2 = new ProductPriceLevel
            {
                PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId),
                ProductId    = new EntityReference(Product.EntityLogicalName, _product2Id),
                UoMId        = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
                Amount       = new Money(15)
            };

            _priceListItem2Id = _serviceProxy.Create(newPriceListItem2);
            Console.WriteLine("Created price list item for the {0}.", newProduct1.Name);

            //Publish Product1
            SetStateRequest publishRequest1 = new SetStateRequest
            {
                EntityMoniker = new EntityReference(Product.EntityLogicalName, _product1Id),
                State         = new OptionSetValue((int)ProductState.Active),
                Status        = new OptionSetValue(1)
            };

            _serviceProxy.Execute(publishRequest1);

            //Publish Product2
            SetStateRequest publishRequest2 = new SetStateRequest
            {
                EntityMoniker = new EntityReference(Product.EntityLogicalName, _product2Id),
                State         = new OptionSetValue((int)ProductState.Active),
                Status        = new OptionSetValue(1)
            };

            _serviceProxy.Execute(publishRequest2);
            Console.WriteLine("Published both the products");

            // Create an account record for the opporutnity's potential customerid
            Account newAccount = new Account
            {
                Name = "Example Account"
            };

            _accountId = _serviceProxy.Create(newAccount);

            Console.WriteLine("Created {0}", newAccount.Name);

            return;
        }
예제 #60
0
 public void Update(string id, Discount discountIn) =>
    _discounts.ReplaceOne(discount => discount.Id == id, discountIn);