Пример #1
0
 public PromoPackage(Book book1, Book book2, int discountAmount, DiscountType discountType)
 {
     this.book1 = book1;
     this.book2 = book2;
     this.discountAmount = discountAmount;
     this.discountType = discountType;
 }
Пример #2
0
 /// <summary>
 /// 取得折扣策略
 /// </summary>
 /// <param name="discountType">折扣類型</param>
 /// <returns></returns>
 private IDiscountStrategy GetStrategy(DiscountType discountType)
 {
     switch (discountType)
     {
         case DiscountType.Default:
             return null;
             break;
         case DiscountType.HarryPotter:
             return PotterDiscountStrategy.NewStrategy();
             break;
         default:
             return null;
             break;
     }
 }
Пример #3
0
		public OrderItem(Item item)
		{
			mItem = item;
			mQuantity = 1;
			mSubTotalPrice = 0;
			mDiscountType = DiscountType.None;
			mDiscountPrice = 0;
			mDiscountPercent = 0;
			mEnuriPrice = 0;
			mEnuriPercent = 0;
			mTotalPrice = 0;
			mTotalPercent = 0;

			recalculation();
		}
Пример #4
0
        public OrderLineItem CreateLineItem(Guid productId, decimal quantity, decimal value, string description, int lineItemSuquenceNo, decimal lineItemVatValue, OrderLineItemType lineItemType, decimal productDiscount, DiscountType discountType)
        {
            Product product = _productRepository.GetById(productId);
            var li = DocumentLineItemPrivateConstruct<OrderLineItem>(Guid.NewGuid());
            li.Product = product;
            li.Qty = quantity;
            li.Value = value;
            li.Description = description;
            li.LineItemSequenceNo = lineItemSuquenceNo;
            li.LineItemVatValue = lineItemVatValue;
            li.LineItemType = lineItemType;
            li.ProductDiscount = productDiscount;
            li.DiscountType = discountType;

            return li;
        }
        /// <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;
        }
Пример #6
0
		public void setDiscountPercent(uint discount = 10)
		{
			mDiscountType = DiscountType.Percent;

			if (discount > 100)
			{
				mDiscountPercent = 100;
			}
			else
			{
				mDiscountPercent = discount;
			}

			recalculation();
		}
Пример #7
0
 public Discount(DiscountType discount)
 {
     discountType = discount;
 }
 public ChangeDiscount(Guid orderItemId, DiscountType discountType, decimal discountValue) : base(orderItemId)
 {
     OrderItemId = orderItemId;
     DiscountType = discountType;
     DiscountValue = discountValue;
 }
        private List<OrderLineItem> AddLineItem(List<OrderLineItem> items, Guid productId, decimal qty, decimal vat, decimal unitprice, decimal productDiscout, OrderLineItemType type, DiscountType discointType)
        {
            items.Add(new OrderLineItem(Guid.NewGuid())
            {
                Product = _productRepository.GetById(productId),
                LineItemSequenceNo = 1,
                Qty = qty,// orderLineItemsViewModel.quantity,
                LineItemVatValue = vat,//vatClass != null ? vatClass.CurrentRate : 0,// orderLineItemsViewModel.LineItemVatTotal,
                Value = unitprice,//pricingTier!=null?item.Product.ProductPrice(pricingTier):0,// orderLineItemsViewModel.LineItemTotal,
                ProductDiscount = productDiscout,
                LineItemType = type,
                DiscountType = discointType,
            });
            return items;

        }
        public void SetDiscount(double price, DiscountType type)
        {
            // Enter discount amount
            UIUtil.DefaultProvider.TypeRADNumericById("ctl00_cphDialog_AmountTextBox", price);

            // Select group rule type
            UIUtil.DefaultProvider.SelectWithText("ctl00_cphDialog_ddlGroupRuleType", CustomStringAttribute.GetCustomString(type), LocateBy.Id);
        }
Пример #11
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;
        }
Пример #12
0
 public Campaign(Category category, double minimumQuantity, double discountAmount, DiscountType discountType)
     : base(discountAmount, discountType)
 {
     this.CheckRule(new ValueMustBeGreaterThanZeroRule(minimumQuantity, "Campaign Minimum Quantity"));
     Category        = category;
     MinimumQuantity = minimumQuantity;
 }
Пример #13
0
        public static decimal GetTotalPrice(decimal pricePerDay, int days, Season season, DiscountType discount = DiscountType.None)
        {
            decimal total = (pricePerDay * days) * (int)season;

            if (discount != 0)
            {
                total -= total * (int)discount / 100;
            }

            return(total);
        }
        public override CommandHandlerResponse Handle(IFiscalPrinterState fiscalPrinterState)
        {
            var state = fiscalPrinterState as FiscalPrinterState;

            if (state.TimeDiffrenceInMinutes == int.MinValue)
            {
                throw new FP_IllegalOperationException("RTC clock is not set up. Please do this before any actions.");
            }
            if (!state.IsInTransactionState)
            {
                throw new FP_IllegalOperationException("Fiscal Printer is not in transaction state.");
            }

            var slipLine = new SlipLine();


            DiscountType        discountType        = DiscountType.NO_DISCOUNT;
            DiscountDescription discountDescription = DiscountDescription.NONE;

            string discountDescriptionText = "";
            string productDescription      = "";
            double discountValueAmmount    = 0;



            if (!command.PnArguments.Any())
            {
                throw new FP_WrongNumberOfArgumentsException("This command required at least one argument");
            }

            if (command.PnArguments.Count() >= 1)
            {
                if (!int.TryParse(command.PnArguments.ElementAt(0), out int lineNumber))
                {
                    throw new FP_BadFormatOfArgumentException("first argument must be a number");
                }
            }
            if (command.PnArguments.Count() >= 2)
            {
                if (!Enum.TryParse <DiscountType>(command.PnArguments.ElementAt(1), out discountType))
                {
                    throw new FP_BadFormatOfArgumentException("Unknkown Pr command argument");
                }
            }

            if (command.PnArguments.Count() >= 3)
            {
                if (!Enum.TryParse <DiscountDescription>(command.PnArguments.ElementAt(2), out discountDescription))
                {
                    throw new FP_BadFormatOfArgumentException("Unknkown Po command argument");
                }
            }

            if (command.PnArguments.Count() == 4 && command.PnArguments.ElementAt(3) != "1")
            {
                throw new FP_BadFormatOfArgumentException("Bad command formatting. Check your arguments.");
            }
            if (command.PnArguments.Count() > 4)
            {
                throw new FP_BadFormatOfArgumentException("Bad number of arguments for this command.");
            }

            var commandParameters = command.Parameters.Split('/', (char)Constants.ASCICodeCR).Where(m => !string.IsNullOrEmpty(m)).ToArray();

            if (commandParameters.Length == 0)
            {
                throw new FP_WrongNumberOfArgumentsException("Cannot get any parameters from command.");
            }
            if (commandParameters.Length >= 1)
            {
                if (string.IsNullOrWhiteSpace(commandParameters[0]))
                {
                    throw new FP_BadFormatOfArgumentException("Product name cannot be null");
                }
                else if (commandParameters[0].Length > 40)
                {
                    throw new FP_BadFormatOfArgumentException("Product name cannot have more then 40 characters.");
                }
                else
                {
                    slipLine.ProductName = commandParameters[0];
                }
            }
            if (commandParameters.Length >= 2)
            {
                if (!double.TryParse(commandParameters[1], out double ammount))
                {
                    throw new FP_BadFormatOfArgumentException("Cannot parse ammount of product. Check formatting.");
                }
                else if (ammount == 0)
                {
                    throw new FP_BadFormatOfArgumentException("Ammoutn cannot be 0.");
                }
                else
                {
                    slipLine.Ammount = ammount;
                }
            }
            if (commandParameters.Length >= 3)
            {
                if (!Enum.TryParse <PTU>(commandParameters[2], out PTU ptu))
                {
                    throw new FP_BadFormatOfArgumentException("Cannot parse PTU type. Check if you pass right parameter.");
                }
                else
                {
                    slipLine.PTU = ptu;
                }
            }
            if (commandParameters.Length >= 4)
            {
                if (!double.TryParse(commandParameters[3], out double price))
                {
                    throw new FP_BadFormatOfArgumentException("Cannot parse product price. Check if you pass right parameter.");
                }
                else
                {
                    slipLine.ProductPrice = price;
                }
            }

            if (commandParameters.Length >= 5)
            {
                if (!double.TryParse(commandParameters[4], out double brutto))
                {
                    throw new FP_BadFormatOfArgumentException("Cannot parse product brutto price. Check if you pass right parameter.");
                }
                else
                {
                    slipLine.TotalPrice = brutto;
                }
            }

            if (commandParameters.Length >= 6)
            {
                if (!double.TryParse(commandParameters[5], out double discountAmmount))
                {
                    throw new FP_BadFormatOfArgumentException("Cannot parse product discount ammout. Check if you pass right parameter.");
                }
                else
                {
                    slipLine.DiscountValue = discountAmmount;
                }
            }

            if (commandParameters.Length >= 7)
            {
                if (discountDescription == DiscountDescription.CUSTOM && string.IsNullOrWhiteSpace(commandParameters[6]))
                {
                    throw new FP_BadFormatOfArgumentException("Description cannot be empty in custom type");
                }
                else if (discountDescription == DiscountDescription.CUSTOM && commandParameters[6].Length > 20)
                {
                    throw new FP_BadFormatOfArgumentException("Description cannot have more then 20 characters.");
                }
                else
                {
                    discountDescriptionText = commandParameters[6];
                }
            }

            if (commandParameters.Length == 8)
            {
                productDescription = commandParameters[7];
            }
            if (commandParameters.Length > 8)
            {
                throw new FP_WrongNumberOfArgumentsException("Too many parameters for this command.");
            }

            StringBuilder slipBuilder = new StringBuilder();


            if (!state.SlipLines.Any())
            {
                state.TransactionCounter += 1;

                var fiscalPrinterDate  = DateTime.Now.AddMinutes(state.TimeDiffrenceInMinutes).ToString("yyyy-MM-dd");
                var transactionCounter = state.TransactionCounter.ToString();

                slipBuilder.AppendLine(state.FiscalPrinterHeader);
                slipBuilder.AppendLine(fiscalPrinterDate.PadRight(Constants.ReciptWidth - transactionCounter.Length) + transactionCounter);
                slipBuilder.AppendLine("P A R A G O N  F I S K A L N Y".PadCenter(Constants.ReciptWidth));
                slipBuilder.AppendLine("".PadLeft(Constants.ReciptWidth, '-'));
            }


            if (slipLine.Ammount * slipLine.ProductPrice != slipLine.TotalPrice)
            {
                throw new FP_IllegalOperationException("Ammount x Price is not equal brutto value");
            }
            else
            {
                discountValueAmmount = slipLine.TotalPrice;
            }

            string financialSlipText = $"{slipLine.Ammount}x{slipLine.ProductPrice.ToString("0.00")}    {slipLine.TotalPrice.ToString("0.00")}{slipLine.PTU.ToString()}";

            if (Constants.ReciptWidth - financialSlipText.Length < slipLine.ProductName.Length)
            {
                slipBuilder.AppendLine(slipLine.ProductName.PadRight(Constants.ReciptWidth));
                slipBuilder.AppendLine(financialSlipText.PadLeft(Constants.ReciptWidth));
            }
            else
            {
                var paddingValue = Constants.ReciptWidth - financialSlipText.Length;
                slipBuilder.AppendLine(slipLine.ProductName.PadRight(paddingValue) + financialSlipText);
            }

            if (!string.IsNullOrWhiteSpace(productDescription))
            {
                slipBuilder.AppendLine("Opis: " + productDescription);
            }

            if (slipLine.DiscountValue != 0)
            {
                discountDescriptionText = discountDescription == DiscountDescription.CUSTOM
                                        ? discountDescriptionText
                                        : GetDiscountDescription(discountDescription);


                bool isPercentageDiscount = slipLine.DiscountValue < 1 && slipLine.DiscountValue > 0;


                var discountValueText = isPercentageDiscount
                                        ? (slipLine.DiscountValue * 100).ToString() + " %"
                                        : slipLine.DiscountValue.ToString("0.00");

                discountValueAmmount -= isPercentageDiscount ? slipLine.TotalPrice * slipLine.DiscountValue : slipLine.DiscountValue;


                var discountSlipLineLeftPart  = $"   {discountDescriptionText} {discountValueText} =";
                var discountSlipLineRightPart = $"-{(slipLine.TotalPrice - discountValueAmmount).ToString("0.00")} ";


                slipBuilder.AppendLine(discountSlipLineLeftPart.PadRight(
                                           Constants.ReciptWidth - discountSlipLineRightPart.Length)
                                       + discountSlipLineRightPart);

                slipBuilder.AppendLine($"{discountValueAmmount.ToString("0.00")}{slipLine.PTU.ToString()}".PadLeft(Constants.ReciptWidth));
            }

            state.SlipLines.Add(slipLine);
            return(new CommandHandlerResponse(slipBuilder.ToString()));
        }
Пример #15
0
        /// <summary>
        /// Initialises and places controls based on the type on input form
        /// </summary>
        void SetupForm()
        {
            if (currentFormState == FormType.MultiplicationAmount)
            {
                lblInstruction           = new Label();
                lblInstruction.Location  = new Point(0, 0);
                lblInstruction.Font      = new Font(sFontName, Properties.Settings.Default.fMainScreenFontSize);
                lblInstruction.ForeColor = cFormForeColour;
                lblInstruction.BackColor = cFormBackColour;
                lblInstruction.AutoSize  = true;
                lblInstruction.Text      = "Multiply Item Quantity By: ";
                this.Controls.Add(lblInstruction);

                tbInput           = new TextBox();
                tbInput.BackColor = cFormBackColour;
                tbInput.ForeColor = cFormForeColour;
                tbInput.Location  = lblInstruction.Location;
                tbInput.Left     += lblInstruction.Width;
                tbInput.Font      = lblInstruction.Font;
                tbInput.KeyDown  += new KeyEventHandler(tbInput_KeyDown);
                this.Controls.Add(tbInput);
            }
            else if (currentFormState == FormType.DiscountAmount)
            {
                lblInstruction           = new Label();
                lblInstruction.Location  = new Point(0, 0);
                lblInstruction.Font      = new Font(sFontName, Properties.Settings.Default.fMainScreenFontSize);
                lblInstruction.ForeColor = cFormForeColour;
                lblInstruction.BackColor = cFormBackColour;
                lblInstruction.AutoSize  = true;
                lblInstruction.Text      = "Discount Type: [P]ercentage, [A]mount, [S]et Price, [C]hange Line To Be Edited";
                dType = DiscountType.Amount;
                this.Controls.Add(lblInstruction);

                tbInput           = new TextBox();
                tbInput.BackColor = cFormBackColour;
                tbInput.ForeColor = cFormForeColour;
                tbInput.Location  = lblInstruction.Location;
                tbInput.Left     += lblInstruction.Width;
                tbInput.Font      = lblInstruction.Font;
                tbInput.Visible   = false;
                tbInput.KeyDown  += new KeyEventHandler(tbInput_KeyDown);
                this.Controls.Add(tbInput);

                this.KeyDown += new KeyEventHandler(frmInput_KeyDown);
            }
            else if (currentFormState == FormType.DeleteLineNum)
            {
                lblInstruction           = new Label();
                lblInstruction.Location  = new Point(0, 0);
                lblInstruction.Font      = new Font(sFontName, Properties.Settings.Default.fMainScreenFontSize);
                lblInstruction.ForeColor = cFormForeColour;
                lblInstruction.BackColor = cFormBackColour;
                lblInstruction.AutoSize  = true;
                lblInstruction.Text      = "Enter the line number to delete :";
                this.Controls.Add(lblInstruction);

                tbInput           = new TextBox();
                tbInput.BackColor = cFormBackColour;
                tbInput.ForeColor = cFormForeColour;
                tbInput.Location  = lblInstruction.Location;
                tbInput.Left     += lblInstruction.Width;
                tbInput.Font      = lblInstruction.Font;
                tbInput.Visible   = true;
                tbInput.KeyDown  += new KeyEventHandler(tbInput_KeyDown);
                this.Controls.Add(tbInput);

                tbInput.Focus();
            }
            else if (currentFormState == FormType.CashPaidOut)
            {
                lblInstruction           = new Label();
                lblInstruction.Location  = new Point(0, 0);
                lblInstruction.Font      = new Font(sFontName, Properties.Settings.Default.fMainScreenFontSize);
                lblInstruction.ForeColor = cFormForeColour;
                lblInstruction.BackColor = cFormBackColour;
                lblInstruction.AutoSize  = true;
                lblInstruction.Text      = "Enter amount of cash to pay out :";
                this.Controls.Add(lblInstruction);

                tbInput           = new TextBox();
                tbInput.BackColor = cFormBackColour;
                tbInput.ForeColor = cFormForeColour;
                tbInput.Location  = lblInstruction.Location;
                tbInput.Left     += lblInstruction.Width;
                tbInput.Font      = lblInstruction.Font;
                tbInput.Visible   = true;
                tbInput.KeyDown  += new KeyEventHandler(tbInput_KeyDown);
                this.Controls.Add(tbInput);
            }
            else if (currentFormState == FormType.PresetKeyEntry)
            {
                lblInstruction           = new Label();
                lblInstruction.Location  = new Point(0, 0);
                lblInstruction.Font      = new Font(sFontName, Properties.Settings.Default.fMainScreenFontSize);
                lblInstruction.ForeColor = cFormForeColour;
                lblInstruction.BackColor = cFormBackColour;
                lblInstruction.AutoSize  = true;
                lblInstruction.Text      = "Enter the new barcode for " + sOtherData[0] + ":   ";
                this.Controls.Add(lblInstruction);

                tbInput             = new TextBox();
                tbInput.BackColor   = cFormBackColour;
                tbInput.ForeColor   = cFormForeColour;
                tbInput.Location    = lblInstruction.Location;
                tbInput.Left       += lblInstruction.Width;
                tbInput.Width       = 150;
                tbInput.Font        = lblInstruction.Font;
                tbInput.BorderStyle = BorderStyle.None;
                tbInput.Visible     = true;
                tbInput.KeyDown    += new KeyEventHandler(tbInput_KeyDown);
                this.Controls.Add(tbInput);
            }
            else if (currentFormState == FormType.ReceivedOnAccount)
            {
                lblInstruction           = new Label();
                lblInstruction.Location  = new Point(0, 0);
                lblInstruction.Font      = new Font(sFontName, Properties.Settings.Default.fMainScreenFontSize);
                lblInstruction.ForeColor = cFormForeColour;
                lblInstruction.BackColor = cFormBackColour;
                lblInstruction.AutoSize  = true;
                lblInstruction.Text      = "Enter amount to receive from " + sOtherData[0] + ":   ";
                this.Controls.Add(lblInstruction);

                tbInput           = new TextBox();
                tbInput.BackColor = cFormBackColour;
                tbInput.ForeColor = cFormForeColour;
                tbInput.Location  = lblInstruction.Location;
                tbInput.Left     += lblInstruction.Width;
                tbInput.Font      = lblInstruction.Font;
                tbInput.Visible   = true;
                tbInput.KeyDown  += new KeyEventHandler(tbInput_KeyDown);
                this.Controls.Add(tbInput);
            }
            else if (currentFormState == FormType.GetUserID)
            {
                lblInstruction           = new Label();
                lblInstruction.Location  = new Point(0, 0);
                lblInstruction.Font      = new Font(sFontName, Properties.Settings.Default.fMainScreenFontSize);
                lblInstruction.ForeColor = cFormForeColour;
                lblInstruction.BackColor = cFormBackColour;
                lblInstruction.AutoSize  = true;
                lblInstruction.Text      = "Enter your Identification Number to start a transaction:";
                this.Controls.Add(lblInstruction);

                tbInput             = new TextBox();
                tbInput.BackColor   = cFormBackColour;
                tbInput.ForeColor   = cFormForeColour;
                tbInput.Location    = lblInstruction.Location;
                tbInput.Left       += lblInstruction.Width;
                tbInput.Width       = 150;
                tbInput.Font        = lblInstruction.Font;
                tbInput.BorderStyle = BorderStyle.None;
                tbInput.Visible     = true;
                tbInput.KeyDown    += new KeyEventHandler(tbInput_KeyDown);
                this.Controls.Add(tbInput);
            }
        }
Пример #16
0
 /// <summary>
 /// Discount per amount
 /// </summary>
 /// <param name="amount"></param>
 /// <param name="amountFree"></param>
 public Discount(int amount, int amountFree)
 {
     this.Disc       = DiscountType.ByQuantityFree;
     this.Amount     = amount;
     this.AmountFree = amountFree;
 }
Пример #17
0
        public SubOrderLineItem CreateFOCLineItem(Guid productId, decimal quantity, string description,DiscountType discountType)
        {
            Product product = _productRepository.GetById(productId);
            var li = DocumentLineItemPrivateConstruct<SubOrderLineItem>(Guid.NewGuid());
            li.Product = product;
            li.Qty = quantity;
            li.Value = 0;
            li.Description = description;
            li.LineItemSequenceNo = 0;
            li.ProductDiscount = 0;
            li.LineItemVatValue = 0;
            li.LineItemType = MainOrderLineItemType.Discount;
            li.DiscountType = discountType;
            li.LineItemStatus = MainOrderLineItemStatus.New;

            return li;
        }
        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public void CreateRequiredRecords()
        {

            #region Create or Retrieve the necessary system users

            // Retrieve the ldapPath
            String ldapPath = String.Empty;
            // Retrieve the sales team - 1 sales manager and 2 sales representatives.
            _salesManagerId = SystemUserProvider.RetrieveSalesManager(_serviceProxy, ref ldapPath);
            _salesRepresentativeIds = SystemUserProvider.RetrieveSalespersons(_serviceProxy, ref ldapPath);

            #endregion

            #region Create records to support Opportunity records
            // Create a unit group
            UoMSchedule newUnitGroup = new UoMSchedule
            {
                Name = "Example Unit Group",
                BaseUoMName = "Example Primary Unit"
            };
            _unitGroupId = _serviceProxy.Create(newUnitGroup);

            // 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;

            // 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);

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

            // Create a price list
            PriceLevel newPriceList = new PriceLevel
            {
                Name = "Example Price List"
            };
            _priceListId = _serviceProxy.Create(newPriceList);

            // 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);

            // 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);

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

            // Publish Product 2
            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 {0} and {1}", newProduct1.Name, newProduct2.Name);

            // Create an account record for the opportunity's potential customerid 
            Account newAccount = new Account
            {
                Name = "Litware, Inc.",
                Address1_PostalCode = "60661"
            };
            _accountIds.Add(_serviceProxy.Create(newAccount));

            newAccount = new Account
            {
                Name = "Margie's Travel",
                Address1_PostalCode = "99999"
            };
            _accountIds.Add(_serviceProxy.Create(newAccount));

            #endregion Create records to support Opportunity records

            #region Create Opportunity records
            // Create a new opportunity with user specified estimated revenue
            Opportunity newOpportunity = new Opportunity
            {
                Name = "Example Opportunity",
                CustomerId = new EntityReference(Account.EntityLogicalName,
                    _accountIds[0]),
                PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName,
                    _priceListId),
                IsRevenueSystemCalculated = false,
                EstimatedValue = new Money(400.00m),
                FreightAmount = new Money(10.00m),
                DiscountAmount = new Money(0.10m),
                DiscountPercentage = 0.20m,
                ActualValue = new Money(400.00m),
                OwnerId = new EntityReference
                {
                    Id = _salesRepresentativeIds[0],
                    LogicalName = SystemUser.EntityLogicalName
                }
            };
            _opportunityIds.Add(_serviceProxy.Create(newOpportunity));

            Opportunity secondOpportunity = new Opportunity
            {
                Name = "Example Opportunity 2",
                CustomerId = new EntityReference(Account.EntityLogicalName,
                    _accountIds[1]),
                PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName,
                    _priceListId),
                IsRevenueSystemCalculated = false,
                EstimatedValue = new Money(400.00m),
                FreightAmount = new Money(10.00m),
                DiscountAmount = new Money(0.10m),
                DiscountPercentage = 0.20m,
                ActualValue = new Money(400.00m),
                OwnerId = new EntityReference
                {
                    Id = _salesRepresentativeIds[1],
                    LogicalName = SystemUser.EntityLogicalName
                }
            };
            _opportunityIds.Add(_serviceProxy.Create(secondOpportunity));

            // Create a catalog product
            OpportunityProduct catalogProduct = new OpportunityProduct
            {
                OpportunityId = new EntityReference(Opportunity.EntityLogicalName,
                    _opportunityIds[0]),
                ProductId = new EntityReference(Product.EntityLogicalName,
                    _product1Id),
                UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
                Quantity = 8,
                Tax = new Money(12.42m),
            };
            _catalogProductId = _serviceProxy.Create(catalogProduct);
 
            // Create another catalog product and override the list price
            OpportunityProduct catalogProductPriceOverride = new OpportunityProduct
            {
                OpportunityId = new EntityReference(Opportunity.EntityLogicalName,
                    _opportunityIds[1]),
                ProductId = new EntityReference(Product.EntityLogicalName,
                    _product2Id),
                UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
                Quantity = 3,
                Tax = new Money(2.88m),
                IsPriceOverridden = true,
                PricePerUnit = new Money(12)
            };
            _catalogProductPriceOverrideId = _serviceProxy.Create(
                catalogProductPriceOverride);

            // create a new write-in opportunity product with a manual discount applied
            OpportunityProduct writeInProduct = new OpportunityProduct
            {
                OpportunityId = new EntityReference(Opportunity.EntityLogicalName,
                    _opportunityIds[1]),
                IsProductOverridden = true,
                ProductDescription = "Example Write-in Product",
                PricePerUnit = new Money(20.00m),
                Quantity = 5,
                ManualDiscountAmount = new Money(10.50m),
                Tax = new Money(7.16m)
            };
            _writeInProductId = _serviceProxy.Create(writeInProduct);

            // Close the opportunities as 'Won'
            WinOpportunityRequest winRequest = new WinOpportunityRequest()
            {
                OpportunityClose = new OpportunityClose()
                {
                    OpportunityId = new EntityReference
                    {
                        Id = _opportunityIds[0],
                        LogicalName = Opportunity.EntityLogicalName
                    },
                    ActualRevenue = new Money(400.00M),
                    ActualEnd = DateTime.Today
                },
                Status = new OptionSetValue(3)
            };
            _serviceProxy.Execute(winRequest);

            winRequest = new WinOpportunityRequest()
            {
                OpportunityClose = new OpportunityClose()
                {
                    OpportunityId = new EntityReference
                    {
                        Id = _opportunityIds[1],
                        LogicalName = Opportunity.EntityLogicalName
                    },
                    ActualRevenue = new Money(400.00M),
                    ActualEnd = DateTime.Today
                },
                Status = new OptionSetValue(3)
            };
            _serviceProxy.Execute(winRequest);

            #endregion Create Opportunity records
        }
Пример #19
0
 public ProductAsDiscount GetProductAsDiscount(DiscountType disType, Guid productId)
 {
     ProductAsDiscount pad = new ProductAsDiscount();
     if (discountLine.OfType<ProductAsDiscount>().Any(p => p.DiscountType == disType && p.ProductId == productId))
     {
         pad = discountLine.OfType<ProductAsDiscount>().FirstOrDefault(p => p.DiscountType == disType && p.ProductId == productId);
     }
     else
     {
         pad.ProductId = productId;
         pad.DiscountType = disType;
         discountLine.Add(pad);
     }
     return pad;
 }
Пример #20
0
 /// <summary>
 /// Create a new instance of the class to perform discount calculation using DiscountType.
 /// </summary>
 /// <param name="type">The enum containing the type of discount to calculate.</param>
 public DiscountEngine(DiscountType type)
 {
     discount = DiscountFactory.Create(type);
 }
Пример #21
0
 public void setDiscountType(DiscountType discountType)
 {
     DiscountType = discountType;
 }
Пример #22
0
 public Coupon(double minimumCartAmount, int discountValue, DiscountType discountType)
 {
     MinimumCartAmount = minimumCartAmount;
     DiscountValue     = discountValue;
     DiscountType      = discountType;
 }
Пример #23
0
        private void AddProduct(Guid productId, decimal quantity, string description, DiscountType discountType)
        {
           
               
                if(discountItem.Any(s=>s.ProductId==productId))
                {
                    var item = discountItem.First(s => s.ProductId == productId);
                    item.Quantity+=quantity;
                }else
                {
                    Product p = _productRepository.GetById(productId);
                    MainOrderLineItem item = new MainOrderLineItem();
                    item.ProductId = p.Id;
                    item.ProductName = p.Description;
                    item.ProductType = description;
                    item.DiscountType = discountType;
                    item.Quantity =quantity;
                    item.LineItemType =MainOrderLineItemType.Discount;
                    discountItem.Add(item);
                }

           
        }
Пример #24
0
 public Coupon(double discountAmount, DiscountType discountType, double minimumAmountToApply)
 {
     DiscountAmount       = discountAmount;
     DiscountType         = discountType;
     MinimumAmountToApply = minimumAmountToApply;
 }
Пример #25
0
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        bool status = false;

        if (ddlRuleTypes.SelectedValue == "0") // Promotions
        {
            if (!CheckAssemblyClass(typeof(ZNodePromotionOption)))
                return;

            DiscountType entity = new DiscountType();

            if(_ItemId > 0)
               entity = _RuleTypeAdmin.GetDiscountTypeById(_ItemId);

            entity.Name = txtRuleName.Text.Trim();
            entity.ClassName = txtRuleClassName.Text.Trim();
            entity.Description = txtRuleDesc.Text.Trim();
            entity.ActiveInd = chkEnable.Checked;

            if (_ItemId > 0)
                status = _RuleTypeAdmin.UpdateDicountType(entity);
            else
                status = _RuleTypeAdmin.AddDicountType(entity);
        }
        else if (ddlRuleTypes.SelectedValue == "1") // Shipping
        {
            if (!CheckAssemblyClass(typeof(ZNodeShippingOption)))
                return;

            ShippingType shipType = new ShippingType();

            if (_ItemId > 0)
                shipType = _RuleTypeAdmin.GetShippingTypeById(_ItemId);

            shipType.Name = txtRuleName.Text.Trim();
            shipType.Description = txtRuleDesc.Text.Trim();
            shipType.ClassName = txtRuleClassName.Text.Trim();
            shipType.IsActive = chkEnable.Checked;

            if (_ItemId > 0)
                status = _RuleTypeAdmin.UpdateShippingType(shipType);
            else
                status = _RuleTypeAdmin.AddShippingType(shipType);
        }
        else if (ddlRuleTypes.SelectedValue == "2") // Taxes
        {
            if (!CheckAssemblyClass(typeof(ZNodeTaxOption)))
                return;

            TaxRuleType taxRuleType = new TaxRuleType();

            if (_ItemId > 0)
                taxRuleType = _RuleTypeAdmin.GetTaxRuleTypeById(_ItemId);

            taxRuleType.Name = txtRuleName.Text.Trim();
            taxRuleType.Description = txtRuleDesc.Text.Trim();
            taxRuleType.ClassName = txtRuleClassName.Text.Trim();
            taxRuleType.ActiveInd = chkEnable.Checked;

            if (_ItemId > 0)
                status = _RuleTypeAdmin.UpdateTaxRuleType(taxRuleType);
            else
                status = _RuleTypeAdmin.AddTaxRuleType(taxRuleType);
        }
        else if (ddlRuleTypes.SelectedValue == "3") // supplier
        {
            if (!CheckAssemblyClass(typeof(ZNodeSupplierOption)))
                return;

            SupplierType supplierType = new SupplierType();

            if (_ItemId > 0)
                supplierType = _RuleTypeAdmin.GetSupplierTypeById(_ItemId);

            supplierType.Name = txtRuleName.Text.Trim();
            supplierType.Description = txtRuleDesc.Text.Trim();
            supplierType.ClassName = txtRuleClassName.Text.Trim();
            supplierType.ActiveInd = chkEnable.Checked;

            if (_ItemId > 0)
                status = _RuleTypeAdmin.UpdateSupplierType(supplierType);
            else
                status = _RuleTypeAdmin.AddSupplierType(supplierType);
        }

        if (status)
        {
            Response.Redirect(RedirectUrl);
        }
        else
        {
            lblErrorMsg.Text = "Unable to process your request. Please try again.";
        }
    }
 internal DiscountTypeNotUnknownRule(DiscountType type)
 {
     _type = type;
 }
Пример #27
0
 public void AddTicketDiscount(DiscountType type, decimal amount, int userId)
 {
     var c = Discounts.SingleOrDefault(x => x.DiscountType == (int)type);
     if (c == null)
     {
         c = new Discount { DiscountType = (int)type, Amount = amount };
         Discounts.Add(c);
     }
     if (amount == 0) Discounts.Remove(c);
     c.UserId = userId;
     c.Amount = amount;
 }
Пример #28
0
 internal PercentDiscount(DiscountType discountType, decimal discountAmount)
     : base(discountType, discountAmount)
 {
 }
Пример #29
0
		public void setDiscountPrice(uint price)
		{
			mDiscountType = DiscountType.Price;
			mDiscountPrice = price;
			recalculation();
		}
Пример #30
0
 public Coupon(DiscountType discountType, int quantity, double discountAmount) : base(discountType, quantity, discountAmount)
 {
 }
Пример #31
0
 public Coupon(int minBasketTotal, double discount, DiscountType discountType)
 {
     MinimumBasketAmount = minBasketTotal;
     DiscountAmount      = discount;
     DiscountType        = discountType;
 }
        public void AddLineItem(Guid productId, string productDesc, decimal unitPrice, decimal vatValue,
                                decimal vatAmount, decimal qty, decimal totalPrice, bool isEditable, string liProdType,
                                Guid lineItemID, decimal productDiscount, OrderLineItemType orderLineItemType,
                                DiscountType discountType)
        {
            using (var container = NestedContainer)
            {
                IConfigService _configService = Using<IConfigService>(container);
                var _inventoryService = Using<IInventoryRepository>(container);
                IProductRepository _productService = Using<IProductRepository>(container);
                IOtherUtilities _otherUtilities = Using<IOtherUtilities>(container);

                ApproveSalesmanOrderItem li = null;
                Inventory availableInv = _inventoryService.GetByProductIdAndWarehouseId(productId, _configService.Load().CostCentreId);
                Product product = null;

                if (liProdType == "ReturnableProduct") //#$@$%#^!!
                {
                    if (availableInv != null)
                        if (availableInv.Balance < 0)
                            availableInv.Balance = 0;
                    product = _productService.GetById(productId);
                }


                int sequenceNo = 1;
                if (LineItems.Count > 0)
                {
                    sequenceNo = LineItems.Max(n => n.SequenceNo) + 1;
                }
                if (!LoadForProcessing)
                    isEditable = false;
                //Check the line item exists by productId and update it ..
                if (LineItems.Any(n => n.ProductId == productId && n.OrderLineItemType == orderLineItemType)) //
                {
                    li = LineItems.FirstOrDefault(n => n.ProductId == productId); //lineItem to update ..
                    if (_order.Status == DocumentStatus.Confirmed ||
                        (_order.Status == DocumentStatus.OrderPendingDispatch && ProcessingBackOrder))
                        // editing at confirm order and at process back order
                    {
                        if (!LoadForViewing)
                        {
                            li.Qty += qty;
                            li.TotalLineItemVatAmount += vatAmount;
                            li.LineItemVatValue = vatValue;
                            li.TotalPrice += totalPrice;
                            li.LineItemTotalProductDiscount += (productDiscount*qty);
                            li.ProcessedQty = (li.Qty - li.BackOrder);
                            li.ProcessedQty = li.ProcessedQty < 0 ? 0 : li.ProcessedQty;
                        }
                    }
                    else if (_order.Status == DocumentStatus.OrderPendingDispatch ||
                             _order.Status == DocumentStatus.OrderDispatchedToPhone ||
                             _order.Status == DocumentStatus.Closed ||
                             _order.Status == DocumentStatus.Cancelled ||
                             _order.Status == DocumentStatus.Rejected)
                        //load awaiting stock etc ...
                    {
                        if (!ProcessingBackOrder)
                        {
                            var item = _order.LineItems.FirstOrDefault(n => n.Id == lineItemID);
                            try
                            {
                                switch (item.LineItemType)
                                {
                                    case OrderLineItemType.BackOrder:
                                        li.BackOrder += qty;
                                        li.ProcessedQty = li.Qty - li.BackOrder;
                                        break;
                                    case OrderLineItemType.LostSale:
                                        li.LostSale = qty;
                                        break;
                                    case OrderLineItemType.ProcessedBackOrder:
                                        li.BackOrder -= qty;
                                        li.ProcessedQty = li.Qty - li.BackOrder;
                                        break;
                                }
                            }
                            catch
                            {
                            }
                        }
                    }
                }
                else
                {
                    #region New LineItem

                    li = new ApproveSalesmanOrderItem(_otherUtilities)
                             {
                                 SequenceNo = sequenceNo,
                                 ProductId = productId,
                                 Product = productDesc,
                                 UnitPrice = unitPrice,
                                 LineItemVatValue = vatValue,
                                 TotalLineItemVatAmount = vatAmount,
                                 Qty = qty,
                                 TotalPrice = totalPrice,
                                 IsEditable = isEditable,
                                 LineItemId = (Guid) lineItemID,
                                 AvailableProductInv = availableInv == null ? 0 : availableInv.Balance,
                                 LiProductType = liProdType,
                                 CanEdit = isEditable,
                                 CanRemove = isEditable,
                                 ProductType = liProdType,
                                 OrderLineItemType = orderLineItemType,
                                 ProductDiscount = productDiscount,
                                 LineItemTotalProductDiscount = productDiscount*qty,
                                 LineItemDiscountType = discountType,
                                 HlnkDeleteContent = GetLocalText("sl.approveOrder.lineItemsGrid.deleteLineItem"),
                             };

                    if (liProdType == "ReturnableProduct") li.CanEdit = false;
                    if (liProdType == "ReturnableProduct") li.CanRemove = false;

                    if (liProdType == "ReturnableProduct" && ((ReturnableProduct) product).Capacity > 1)
                        //cn: containers to be edited independently
                    {
                        li.CanEdit = true;
                        li.CanRemove = true;
                    }

                    //overriding editing determiners!!
                    if (li.OrderLineItemType == OrderLineItemType.Discount)
                    {
                        li.CanEdit = false;
                        li.CanRemove = false;
                    }

                    if (Status != "New" && Status != "Confirmed")
                    {
                        li.CanEdit = false;
                        li.CanRemove = false;
                    }

                    if (LoadForViewing)
                    {
                        li.CanEdit = false;
                        li.CanRemove = false;
                    }
                    LineItems.Add(li);

                    #endregion
                }
                CanProcessBackOrder = li.BackOrder > 0;
                CalcTotals();
            }
        }
Пример #33
0
        internal override void WriteXml(XmlTextWriter xmlWriter)
        {
            xmlWriter.WriteStartElement("coupon"); // Start: coupon

            xmlWriter.WriteElementString("coupon_code", CouponCode);
            xmlWriter.WriteElementString("name", Name);
            xmlWriter.WriteElementString("hosted_description", HostedDescription);
            xmlWriter.WriteElementString("invoice_description", InvoiceDescription);

            if (RedeemByDate.HasValue)
            {
                xmlWriter.WriteElementString("redeem_by_date", RedeemByDate.Value.ToString("s"));
            }

            if (SingleUse.HasValue)
            {
                xmlWriter.WriteElementString("single_use", SingleUse.Value.AsString());
            }

            if (AppliesForMonths.HasValue)
            {
                xmlWriter.WriteElementString("applies_for_months", AppliesForMonths.Value.AsString());
            }
            if (Duration != null)
            {
                xmlWriter.WriteElementString("duration", Duration.ToString().EnumNameToTransportCase());
            }
            if (TemporalUnit != null)
            {
                xmlWriter.WriteElementString("temporal_unit", TemporalUnit.ToString().EnumNameToTransportCase());
            }
            if (TemporalAmount.HasValue)
            {
                xmlWriter.WriteElementString("temporal_amount", TemporalAmount.Value.ToString());
            }

            if (AppliesToAllPlans.HasValue)
            {
                xmlWriter.WriteElementString("applies_to_all_plans", AppliesToAllPlans.Value.AsString());
            }

            if (AppliesToNonPlanCharges.HasValue)
            {
                xmlWriter.WriteElementString("applies_to_non_plan_charges", AppliesToNonPlanCharges.Value.AsString());
            }

            if (MaxRedemptions.HasValue)
            {
                xmlWriter.WriteElementString("max_redemptions", MaxRedemptions.Value.AsString());
            }

            if (MaxRedemptionsPerAccount.HasValue)
            {
                xmlWriter.WriteElementString("max_redemptions_per_account", MaxRedemptionsPerAccount.Value.AsString());
            }

            xmlWriter.WriteElementString("discount_type", DiscountType.ToString().EnumNameToTransportCase());

            xmlWriter.WriteElementString("redemption_resource", RedemptionResource.ToString().EnumNameToTransportCase());

            xmlWriter.WriteElementString("coupon_type", Type.ToString().EnumNameToTransportCase());

            if (Type == CouponType.Bulk)
            {
                xmlWriter.WriteElementString("unique_code_template", UniqueCodeTemplate);
            }

            if (CouponDiscountType.Percent == DiscountType && DiscountPercent.HasValue)
            {
                xmlWriter.WriteElementString("discount_percent", DiscountPercent.Value.AsString());
            }

            if (CouponDiscountType.Dollars == DiscountType)
            {
                xmlWriter.WriteIfCollectionHasAny("discount_in_cents", DiscountInCents, pair => pair.Key,
                                                  pair => pair.Value.AsString());
            }

            xmlWriter.WriteIfCollectionHasAny("plan_codes", Plans, s => "plan_code", s => s);

            if (FreeTrialAmount.HasValue)
            {
                xmlWriter.WriteElementString("free_trial_amount", FreeTrialAmount.Value.AsString());
            }

            if (FreeTrialUnit.HasValue)
            {
                xmlWriter.WriteElementString("free_trial_unit", FreeTrialUnit.Value.ToString().EnumNameToTransportCase());
            }

            xmlWriter.WriteEndElement(); // End: coupon
        }
Пример #34
0
 internal QualifiedDiscounts(DiscountType type, decimal discountAmount)
     : base(type, discountAmount)
 {
 }
Пример #35
0
 public Coupon(double _amount, double _value, DiscountType _type)
 {
     MinimumAmount = _amount;
     DiscountValue = _value;
     DiscountType  = _type;
 }
Пример #36
0
        /// <summary>
        /// Mapped ebInterface4p1 InvoiceType auf InvoiceType Model
        /// </summary>
        /// <param name="source">ebInterface4p1 InvoiceType</param>
        /// <returns>InvoiceType Model</returns>
        internal static IInvoiceModel MapV4P1ToVm(SRC.InvoiceType source)
        {
            IInvoiceModel invoice = InvoiceFactory.CreateInvoice();

            #region Rechnungskopf
            invoice.InvoiceNumber    = source.InvoiceNumber;
            invoice.InvoiceDate      = source.InvoiceDate;
            invoice.GeneratingSystem = source.GeneratingSystem;
            invoice.DocumentTitle    = source.DocumentTitle;
            invoice.DocumentType     = source.DocumentType.ConvertEnum <DocumentTypeType>();
            invoice.InvoiceCurrency  = source.InvoiceCurrency.ConvertEnum <CurrencyType>(); // source.InvoiceCurrency.ConvertEnum<CurrencyType>();
            invoice.Language         = source.Language.ConvertEnum <LanguageType>();
            invoice.Comment          = source.Comment;
            if (source.CancelledOriginalDocument == null)
            {
                invoice.CancelledOriginalDocument = null;
            }
            else
            {
                invoice.CancelledOriginalDocument = new CancelledOriginalDocumentType()
                {
                    Comment               = source.CancelledOriginalDocument.Comment,
                    DocumentType          = source.CancelledOriginalDocument.DocumentType.ConvertEnum <DocumentTypeType>(),
                    DocumentTypeSpecified = source.CancelledOriginalDocument.DocumentTypeSpecified,
                    InvoiceDate           = source.CancelledOriginalDocument.InvoiceDate,
                    InvoiceNumber         = source.CancelledOriginalDocument.InvoiceNumber
                };
            }
            #endregion
            #region Releated Document
            if (source.RelatedDocument != null && source.RelatedDocument.Any())
            {
                invoice.RelatedDocument = new List <RelatedDocumentType>();
                foreach (SRC.RelatedDocumentType relDoc in source.RelatedDocument)
                {
                    var newRel = new RelatedDocumentType()
                    {
                        Comment = relDoc.Comment,
                        DocumentTypeSpecified = relDoc.DocumentTypeSpecified,
                        InvoiceDateSpecified  = relDoc.InvoiceDateSpecified,
                        InvoiceNumber         = relDoc.InvoiceNumber
                    };
                    if (relDoc.InvoiceDateSpecified)
                    {
                        newRel.InvoiceDate = relDoc.InvoiceDate;
                    }
                    if (relDoc.DocumentTypeSpecified)
                    {
                        newRel.DocumentType = relDoc.DocumentType.ConvertEnum <DocumentTypeType>();
                    }
                    invoice.RelatedDocument.Add(newRel);
                }
            }

            #endregion

            #region Delivery
            if (source.Delivery != null)
            {
                if (source.Delivery.Item is SRC.PeriodType)
                {
                    var deliveryType = new PeriodType
                    {
                        FromDate = ((SRC.PeriodType)source.Delivery.Item).FromDate,
                        ToDate   = ((SRC.PeriodType)source.Delivery.Item).ToDate
                    };
                    invoice.Delivery.Item = deliveryType;
                }
                else
                {
                    var period = new PeriodType();
                    if (source.Delivery.Item != null)
                    {
                        period.FromDate = (DateTime)source.Delivery.Item;
                    }
                    invoice.Delivery.Item = period;    // für das Model immer eine Lieferperiode, damit von/bis leichter abgebildet werden kann
                }
            }
            #endregion

            #region Biller
            invoice.Biller.VATIdentificationNumber   = source.Biller.VATIdentificationNumber;
            invoice.Biller.InvoiceRecipientsBillerID = source.Biller.InvoiceRecipientsBillerID;
            invoice.Biller.Address = GetAddress(source.Biller.Address);
            invoice.Biller.Contact = GetContact(source.Biller.Address);
            invoice.Biller.FurtherIdentification = GetFurtherIdentification(source.Biller.FurtherIdentification);

            #endregion

            #region InvoiceRecipient
            invoice.InvoiceRecipient.BillersInvoiceRecipientID = source.InvoiceRecipient.BillersInvoiceRecipientID;
            invoice.InvoiceRecipient.VATIdentificationNumber   = source.InvoiceRecipient.VATIdentificationNumber;
            invoice.InvoiceRecipient.Address = GetAddress(source.InvoiceRecipient.Address);
            invoice.InvoiceRecipient.Contact = GetContact(source.InvoiceRecipient.Address);
            if (source.InvoiceRecipient.OrderReference != null)
            {
                invoice.InvoiceRecipient.OrderReference.OrderID = source.InvoiceRecipient.OrderReference.OrderID;
                invoice.InvoiceRecipient.OrderReference.ReferenceDateSpecified = source.InvoiceRecipient.OrderReference.ReferenceDateSpecified;
                invoice.InvoiceRecipient.OrderReference.ReferenceDate          = source.InvoiceRecipient.OrderReference.ReferenceDate;
            }
            invoice.InvoiceRecipient.FurtherIdentification = GetFurtherIdentification(source.InvoiceRecipient.FurtherIdentification);
            invoice.InvoiceRecipient.SubOrganizationID     = source.InvoiceRecipient.SubOrganizationID;
            invoice.InvoiceRecipient.AccountingArea        = source.InvoiceRecipient.AccountingArea;
            #endregion

            #region Details
            invoice.Details.HeaderDescription = source.Details.HeaderDescription;
            invoice.Details.FooterDescription = source.Details.FooterDescription;

            invoice.Details.ItemList = new List <ItemListType>();

            if (source.Details.ItemList != null)
            {
                foreach (SRC.ItemListType srcItemList in source.Details.ItemList)
                {
                    ItemListType item = new ItemListType
                    {
                        ListLineItem = new List <ListLineItemType>()
                    };
                    foreach (SRC.ListLineItemType srcLineItem in srcItemList.ListLineItem)
                    {
                        ListLineItemType lineItem = new ListLineItemType
                        {
                            AdditionalInformation = null,
                            PositionNumber        = srcLineItem.PositionNumber,
                            Description           = new List <string>()
                        };
                        if (srcLineItem.Description != null)
                        {
                            lineItem.Description = srcLineItem.Description.ToList();
                        }

                        lineItem.ArticleNumber = GetArtikelList(srcLineItem.ArticleNumber);

                        // Menge
                        lineItem.Quantity = new UnitType
                        {
                            Unit  = srcLineItem.Quantity.Unit,
                            Value = srcLineItem.Quantity.Value
                        };

                        // Einzelpreis
                        lineItem.UnitPrice = new UnitPriceType()
                        {
                            Value = srcLineItem.UnitPrice.Value
                        };

                        // Auftragsreferenz
                        lineItem.InvoiceRecipientsOrderReference.OrderID =
                            srcLineItem.InvoiceRecipientsOrderReference.OrderID;
                        lineItem.InvoiceRecipientsOrderReference.OrderPositionNumber =
                            srcLineItem.InvoiceRecipientsOrderReference?.OrderPositionNumber;


                        // Rabatte / Zuschläge
                        if (srcLineItem.ReductionAndSurchargeListLineItemDetails != null)
                        {
                            lineItem.ReductionAndSurchargeListLineItemDetails = GetReductionDetails(srcLineItem.ReductionAndSurchargeListLineItemDetails);
                        }
                        lineItem.Description = new List <string>();
                        if (srcLineItem.Description != null)
                        {
                            lineItem.Description = srcLineItem.Description.ToList();
                        }

                        // lineItem.LineItemAmount = srcLineItem.LineItemAmount;
                        lineItem.ReCalcLineItemAmount();
                        // Steuer
                        lineItem.TaxItem = MapVatItemType2Vm(srcLineItem.Item, lineItem.LineItemAmount);
                        item.ListLineItem.Add(lineItem);
                    }
                    invoice.Details.ItemList.Add(item);
                }
            }

            if (source.Details.BelowTheLineItem != null)
            {
                //if (source.Details.BelowTheLineItem.Length > 0)
                //{
                //    List<BelowTheLineItemType> belowItems = new List<BelowTheLineItemType>();
                //    foreach (SRC.BelowTheLineItemType item in source.Details.BelowTheLineItem)
                //    {
                //        belowItems.Add(new BelowTheLineItemType()
                //        {
                //            Description = item.Description,
                //            LineItemAmount = item.LineItemAmount
                //        });
                //    }
                //    invoice.Details.BelowTheLineItem.AddRange(belowItems);
                //}
                Mapping.MapInvoice.MappingErrors.Add(new MappingError(source.Details.BelowTheLineItem.GetType(), "BelowTheLineItem nicht konvertiert."));
            }
            #endregion

            #region Tax
            invoice.CalculateTotals();
            #endregion

            #region Amount
            invoice.TotalGrossAmount = source.TotalGrossAmount;
            invoice.PayableAmount    = source.PayableAmount;
            #endregion

            #region PaymentMethod
            invoice.PaymentMethod.Comment = source.PaymentMethod.Comment;

            if (source.PaymentMethod.Item != null && source.PaymentMethod.Item.GetType() == typeof(SRC.UniversalBankTransactionType))
            {
                SRC.UniversalBankTransactionType txType = source.PaymentMethod.Item as SRC.UniversalBankTransactionType;
                invoice.PaymentMethod = new PaymentMethodType
                {
                    Item = new UniversalBankTransactionType()
                };
                ((UniversalBankTransactionType)invoice.PaymentMethod.Item).BeneficiaryAccount = new List <AccountType>()
                {
                    new AccountType()
                    {
                        BIC              = txType.BeneficiaryAccount[0].BIC,
                        BankName         = txType.BeneficiaryAccount[0].BankName,
                        IBAN             = txType.BeneficiaryAccount[0].IBAN,
                        BankAccountOwner = txType.BeneficiaryAccount[0].BankAccountOwner
                    },
                };
            }

            #endregion

            #region PaymentConditions
            invoice.PaymentConditions.DueDate = source.PaymentConditions.DueDate;
            if (source.PaymentConditions.Discount != null)
            {
                invoice.PaymentConditions.Discount.Clear();
                foreach (SRC.DiscountType srcDiscount in source.PaymentConditions.Discount)
                {
                    DiscountType discount = new DiscountType()
                    {
                        Amount              = srcDiscount.Amount,
                        AmountSpecified     = srcDiscount.AmountSpecified,
                        BaseAmount          = srcDiscount.BaseAmount,
                        BaseAmountSpecified = srcDiscount.BaseAmountSpecified,
                        PaymentDate         = srcDiscount.PaymentDate,
                        Percentage          = srcDiscount.Percentage,
                        PercentageSpecified = srcDiscount.PercentageSpecified
                    };
                    invoice.PaymentConditions.Discount.Add(discount);
                }
            }

            #endregion
            return(invoice);
        }
Пример #37
0
        public bool CheckDiscoutAndSavetempDiscountType(IConnectionHandler connectionHandler, IConnectionHandler filemanagerconnection, DiscountType discountType, Guid tempId)
        {
            var fileTransactionalFacade = FileManagerComponent.Instance.FileTransactionalFacade(filemanagerconnection);
            var discountType1           = new DiscountTypeBO().Get(connectionHandler, discountType.Id);
            var added    = false;
            var discount = base.FirstOrDefault(connectionHandler,
                                               c => c.TempId == tempId && c.DiscountTypeId == discountType.Id, true);

            if (discount == null)
            {
                discount = new TempDiscount()
                {
                    TempId         = tempId,
                    DiscountTypeId = discountType1.Id,
                };
            }
            else
            {
                added = true;
            }
            if (discountType1.ForceAttach)
            {
                if (discount.AttachId.HasValue)
                {
                    fileTransactionalFacade.Update(discountType.UserAttachedFile, (Guid)discount.AttachId);
                }
                else
                {
                    if (discountType.UserAttachedFile == null)
                    {
                        throw new Exception(Resources.Payment.PleaseEnterDiscountAttachFile);
                    }
                    discount.AttachId = fileTransactionalFacade.Insert(discountType.UserAttachedFile);
                }
            }
            if (discountType1.ForceCode)
            {
                if (string.IsNullOrEmpty(discountType.UserCode))
                {
                    throw new Exception(Resources.Payment.PleaseEnterDiscountCode);
                }
                if (discountType1.IsAutoCode)
                {
                    var firstOrDefault = new DiscountTypeAutoCodeBO().FirstOrDefault(connectionHandler, x =>
                                                                                     x.DiscountTypeId == discountType1.Id && x.Code == discountType.UserCode);
                    if (firstOrDefault == null)
                    {
                        throw new Exception(Resources.Payment.Discountcodeenteredisnotcorrect);
                    }
                    if (!added)
                    {
                        if (firstOrDefault.Used)
                        {
                            throw new Exception(Resources.Payment.Enterdiscountcodehasalreadybeenused);
                        }
                        firstOrDefault.Used = true;
                        if (!new DiscountTypeAutoCodeBO().Update(connectionHandler, firstOrDefault))
                        {
                            throw new Exception(Resources.Payment.ErrorInSaveDiscountCode);
                        }
                    }
                }
                else
                {
                    if (discountType1.Code != discountType.UserCode)
                    {
                        throw new Exception(Resources.Payment.Discountcodeenteredisnotcorrect);
                    }
                    if (!added)
                    {
                        if (discountType1.RemainCapacity == 0)
                        {
                            throw new Exception(Resources.Payment.Usingthecapacityfilledrebates);
                        }
                        discountType1.RemainCapacity--;
                        if (!new DiscountTypeBO().Update(connectionHandler, discountType1))
                        {
                            throw new Exception(Resources.Payment.ErrorInSaveDiscountCode);
                        }
                    }
                }
            }
            if (added)
            {
                if (!this.Update(connectionHandler, discount))
                {
                    throw new Exception(Resources.Payment.ErrorInSaveTransactionDiscount);
                }
            }
            else
            {
                if (!this.Insert(connectionHandler, discount))
                {
                    throw new Exception(Resources.Payment.ErrorInSaveTransactionDiscount);
                }
            }
            return(true);
        }
        private async Task TryAddDiscounts(ICollection <Discount> source, HashSet <Discount> target, DiscountType type, PriceCalculationOptions options)
        {
            foreach (var discount in source)
            {
                // TODO: (mg) (core) Pass through context data from CalculationOptions (Store etc.)
                if (discount.DiscountType == type && !target.Contains(discount) && await _discountService.IsDiscountValidAsync(discount, options.Customer))
                {
                    bool isValid;
                    if (options.CheckDiscountValidity)
                    {
                        isValid = await _discountService.IsDiscountValidAsync(discount, options.Customer);
                    }
                    else
                    {
                        // If validity check is disabled: exclude discounts which require coupon codes or have any usage restriction.
                        isValid = !discount.RequiresCouponCode && discount.DiscountLimitation == DiscountLimitationType.Unlimited;
                    }

                    if (isValid)
                    {
                        target.Add(discount);
                    }
                }
            }
        }
Пример #39
0
 public AmountDiscount GetAmountDiscount(DiscountType disType)
 {
     AmountDiscount ad;
     if (discountLine.OfType<AmountDiscount>().Any(p => p.DiscountType == disType))
     {
         ad = discountLine.OfType<AmountDiscount>().FirstOrDefault(p => p.DiscountType == disType);
     }
     else
     {
         ad = new AmountDiscount();
         ad.DiscountType = disType;
         discountLine.Add(ad);
     }
     return ad;
 }
Пример #40
0
 protected Discount(int minimumAmount, decimal discountAmount, DiscountType discountType)
 {
     DiscountAmount = discountAmount;
     DiscountType   = discountType;
     MinimumAmount  = minimumAmount;
 }
Пример #41
0
 public Coupon(double minimumPurchaseAmount, double discountRate, DiscountType discountType)
 {
     MinimumPurchaseAmount = minimumPurchaseAmount;
     DiscountRate          = discountRate;
     DiscountType          = discountType;
 }
Пример #42
0
        /// <summary>
        /// Mapped InvoiceType Model auf ebInterface4p1
        /// </summary>
        /// <param name="source">Invoice Model</param>
        /// <returns>ebInterface 4p1 InvoiceType</returns>
        internal static TARGET.InvoiceType MapModelToV4p1(Model.IInvoiceModel source)
        {
            TARGET.InvoiceType invoice = new TARGET.InvoiceType(); // new V4P1.InvoiceType();

            #region Rechnungskopf
            invoice.InvoiceSubtype   = source.InvoiceSubtype;
            invoice.InvoiceNumber    = source.InvoiceNumber;
            invoice.InvoiceDate      = source.InvoiceDate;
            invoice.GeneratingSystem = source.GeneratingSystem;
            invoice.DocumentType     = source.DocumentType.ConvertEnum <DocumentTypeType>();
            invoice.DocumentTitle    = source.DocumentTitle;
            invoice.InvoiceCurrency  = source.InvoiceCurrency.ConvertEnum <CurrencyType>();

            invoice.Language = source.Language.ConvertEnum <LanguageType>();
            invoice.Comment  = source.Comment;
            invoice.CancelledOriginalDocument = null;
            if (source.CancelledOriginalDocument != null)
            {
                invoice.CancelledOriginalDocument = new TARGET.CancelledOriginalDocumentType()
                {
                    Comment               = source.CancelledOriginalDocument.Comment,
                    DocumentType          = source.CancelledOriginalDocument.DocumentType.ConvertEnum <TARGET.DocumentTypeType>(),
                    DocumentTypeSpecified = source.CancelledOriginalDocument.DocumentTypeSpecified,
                    InvoiceDate           = source.CancelledOriginalDocument.InvoiceDate,
                    InvoiceNumber         = source.CancelledOriginalDocument.InvoiceNumber
                };
            }
            #endregion

            #region Related Document
            if (source.RelatedDocument.Any())
            {
                invoice.RelatedDocument = new TARGET.RelatedDocumentType[]
                {
                    new TARGET.RelatedDocumentType()
                    {
                        Comment               = source.RelatedDocument[0].Comment,
                        DocumentType          = source.RelatedDocument[0].DocumentType.ConvertEnum <TARGET.DocumentTypeType>(),
                        DocumentTypeSpecified = source.RelatedDocument[0].DocumentTypeSpecified,
                        InvoiceDate           = source.RelatedDocument[0].InvoiceDate,
                        InvoiceDateSpecified  = source.RelatedDocument[0].InvoiceDateSpecified,
                        InvoiceNumber         = source.RelatedDocument[0].InvoiceNumber
                    },
                };
            }
            #endregion

            #region Delivery
            if (source.Delivery.Item is Model.PeriodType delType)
            {
                if ((delType.ToDate != null) && (delType.ToDate != DateTime.MinValue))
                {
                    var deliveryType = new TARGET.PeriodType
                    {
                        FromDate = delType.FromDate,
                        ToDate   = delType.ToDate
                    };
                    invoice.Delivery.Item = deliveryType;
                }
                else
                {
                    invoice.Delivery.Item = delType.FromDate;
                }
            }
            else
            {
                invoice.Delivery.Item = source.Delivery.Item;
            }
            #endregion

            #region Biller
            if (source.Biller != null)
            {
                invoice.Biller = new TARGET.BillerType
                {
                    VATIdentificationNumber   = source.Biller.VATIdentificationNumber,
                    InvoiceRecipientsBillerID = source.Biller.InvoiceRecipientsBillerID,
                    Address = GetAddress(source.Biller.Address, source.Biller.Contact),
                    FurtherIdentification = GetFurtherIdentification(source.Biller.FurtherIdentification)
                };
            }
            #endregion

            #region InvoiceReceipient
            if (source.InvoiceRecipient != null)
            {
                invoice.InvoiceRecipient = new TARGET.InvoiceRecipientType
                {
                    BillersInvoiceRecipientID = source.InvoiceRecipient.BillersInvoiceRecipientID,
                    VATIdentificationNumber   = source.InvoiceRecipient.VATIdentificationNumber,
                    Address        = GetAddress(source.InvoiceRecipient.Address, source.InvoiceRecipient.Contact),
                    OrderReference = new OrderReferenceType()
                };
                invoice.InvoiceRecipient.OrderReference.OrderID = source.InvoiceRecipient.OrderReference.OrderID;
                if (source.InvoiceRecipient.OrderReference.ReferenceDateSpecified)
                {
                    invoice.InvoiceRecipient.OrderReference.ReferenceDate          = source.InvoiceRecipient.OrderReference.ReferenceDate;
                    invoice.InvoiceRecipient.OrderReference.ReferenceDateSpecified = source.InvoiceRecipient.OrderReference.ReferenceDateSpecified;
                }
                invoice.InvoiceRecipient.AccountingArea        = source.InvoiceRecipient.AccountingArea;
                invoice.InvoiceRecipient.SubOrganizationID     = source.InvoiceRecipient.SubOrganizationID;
                invoice.InvoiceRecipient.FurtherIdentification = GetFurtherIdentification(source.InvoiceRecipient.FurtherIdentification);
            }
            #endregion

            #region Details
            invoice.Details = new DetailsType
            {
                HeaderDescription = source.Details.HeaderDescription,
                FooterDescription = source.Details.FooterDescription
            };

            // inv4P1.Details.ItemList = new List<InvV4p1.ItemListType>();
            var detailsItemList = new List <ItemListType>();
            // inv4P1.Details.ItemList.Clear();

            // InvV4p1.ItemListType item = new InvV4p1.ItemListType();

            foreach (Model.ItemListType srcItemList in source.Details.ItemList)
            {
                ItemListType itemList = new ItemListType();

                var itemListLineItem = new List <ListLineItemType>();
                foreach (Model.ListLineItemType srcLineItem in srcItemList.ListLineItem)
                {
                    ListLineItemType lineItem = new ListLineItemType
                    {
                        PositionNumber        = srcLineItem.PositionNumber,
                        Description           = srcLineItem.Description.ToArray(),
                        AdditionalInformation = null,

                        ArticleNumber = GetArtikelList(srcLineItem.ArticleNumber),

                        // Menge
                        Quantity = new UnitType()
                    };
                    lineItem.Quantity.Unit  = srcLineItem.Quantity.Unit;
                    lineItem.Quantity.Value = srcLineItem.Quantity.Value;

                    // Einzelpreis
                    lineItem.UnitPrice = new UnitPriceType()
                    {
                        Value = srcLineItem.UnitPrice.Value
                    };

                    // Auftragsreferenz
                    if (!string.IsNullOrEmpty(srcLineItem.InvoiceRecipientsOrderReference.OrderPositionNumber) ||
                        source.InvoiceRecipient.BestellPositionErforderlich)   // Orderposition angegeben oder erforderlich
                    {
                        lineItem.InvoiceRecipientsOrderReference.OrderID             = source.InvoiceRecipient.OrderReference.OrderID;
                        lineItem.InvoiceRecipientsOrderReference.OrderPositionNumber =
                            srcLineItem.InvoiceRecipientsOrderReference.OrderPositionNumber;
                    }

                    // Rabatte / Zuschläge
                    lineItem.DiscountFlagSpecified = true;
                    lineItem.DiscountFlag          = false;
                    lineItem.ReductionAndSurchargeListLineItemDetails = null;
                    if (srcLineItem.ReductionAndSurchargeListLineItemDetails != null)
                    {
                        lineItem.ReductionAndSurchargeListLineItemDetails = GetReductionDetails(srcLineItem.ReductionAndSurchargeListLineItemDetails, out bool discountFlag);

                        if (lineItem.ReductionAndSurchargeListLineItemDetails != null)
                        {
                            lineItem.DiscountFlag          = discountFlag;
                            lineItem.DiscountFlagSpecified = true;
                        }
                    }
                    lineItem.Description = srcLineItem.Description.ToArray();
                    lineItem.ReCalcLineItemAmount();
                    // Steuer
                    lineItem.Item = MapVatItemType(srcLineItem.TaxItem);

                    itemListLineItem.Add(lineItem);
                }
                itemList.ListLineItem = itemListLineItem.ToArray();
                detailsItemList.Add(itemList);
            }
            invoice.Details.ItemList = detailsItemList.ToArray();
            //if (source.Details.BelowTheLineItem != null)
            //{
            //    if (source.Details.BelowTheLineItem.Count > 0)
            //    {
            //        List<BelowTheLineItemType> belowItems = new List<BelowTheLineItemType>();
            //        foreach (VM.BelowTheLineItemType item in source.Details.BelowTheLineItem)
            //        {

            //            if (!string.IsNullOrEmpty(item.Description))
            //            {
            //                belowItems.Add(new BelowTheLineItemType()
            //                {
            //                    Description = item.Description,
            //                    LineItemAmount = item.LineItemAmount
            //                });

            //            }
            //        }
            //        if (belowItems.Any())
            //        {
            //            invoice.Details.BelowTheLineItem = belowItems.ToArray();
            //        }
            //    }
            //}
            #endregion

            #region Global ReductionANdSurcharge
            invoice.ReductionAndSurchargeDetails = new ReductionAndSurchargeDetailsType
            {
                Items            = null,
                ItemsElementName = new ItemsChoiceType1[]
                {
                    ItemsChoiceType1.Reduction
                }
            };

            #endregion

            #region Tax
            var taxVATList = new List <VATItemType>();
            foreach (var vatItem in source.Tax.TaxItem)
            {
                VATItemType vatItemNeu = new VATItemType()
                {
                    Amount      = vatItem.TaxAmount,
                    TaxedAmount = vatItem.TaxableAmount,
                };

                vatItemNeu.Item = MapVatItemType(vatItem);
                taxVATList.Add(vatItemNeu);
            }
            invoice.Tax.VAT = taxVATList.ToArray();
            #endregion


            #region Amount
            invoice.TotalGrossAmount      = source.TotalGrossAmount;
            invoice.PaymentMethod.Comment = source.PaymentMethod.Comment;
            invoice.PayableAmount         = source.PayableAmount;
            #endregion

            #region PaymentMethod
            invoice.PaymentMethod.Comment = source.PaymentMethod.Comment;
            if (source.PaymentMethod.Item.GetType() == typeof(Model.UniversalBankTransactionType))
            {
                Model.UniversalBankTransactionType txType = source.PaymentMethod.Item as Model.UniversalBankTransactionType;

                invoice.PaymentMethod = new PaymentMethodType
                {
                    Item = new UniversalBankTransactionType()
                };
                ((UniversalBankTransactionType)invoice.PaymentMethod.Item).BeneficiaryAccount = new AccountType[]
                {
                    new AccountType()
                    {
                        BIC              = txType.BeneficiaryAccount.First().BIC,
                        BankName         = txType.BeneficiaryAccount.First().BankName,
                        IBAN             = txType.BeneficiaryAccount.First().IBAN,
                        BankAccountOwner = txType.BeneficiaryAccount.First().BankAccountOwner
                    }
                };
            }
            #endregion

            #region PaymentCoditions
            if (source.PaymentConditions.DueDate > DateTime.MinValue)
            {
                invoice.PaymentConditions.DueDate = source.PaymentConditions.DueDate;
            }
            if (source.PaymentConditions.Discount != null)
            {
                // inv4P1.PaymentConditions.Discount.Clear();
                var discountList = new List <DiscountType>();
                foreach (Model.DiscountType srcDiscount in source.PaymentConditions.Discount)
                {
                    DiscountType discount = new DiscountType()
                    {
                        Amount              = srcDiscount.Amount,
                        AmountSpecified     = srcDiscount.AmountSpecified,
                        BaseAmount          = srcDiscount.BaseAmount,
                        BaseAmountSpecified = srcDiscount.BaseAmountSpecified,
                        PaymentDate         = srcDiscount.PaymentDate,
                        Percentage          = srcDiscount.Percentage,
                        PercentageSpecified = srcDiscount.PercentageSpecified
                    };
                    discountList.Add(discount);
                }
                invoice.PaymentConditions.Discount = discountList.ToArray();
            }
            #endregion

            // Fixe Einträge
            #region PresentationDetails
            invoice.PresentationDetails = new PresentationDetailsType()
            {
                URL                   = "http://www.austriapro.at",
                SuppressZero          = true,
                SuppressZeroSpecified = true
            };
            #endregion
            return(invoice);
        }
Пример #43
0
 public DiscountTypeNotAllowedException(DiscountType type) :
     base(String.Format("Discount type {0} is not allowed", type.ToString()))
 {
 }
        public void AddLineItem(Guid productId, string productDesc, decimal unitPrice, decimal vatValue,
                                decimal vatAmount, decimal qty,
                                decimal totalPrice, bool sellInBulk, bool isEditable, Guid lineItemId,
                                Guid parentProductId, OrderLineItemType orderLineItemType, DiscountType discounType,
                                decimal productDiscount, string productType = "")
        {
            using(StructureMap.IContainer cont = NestedContainer)
            {
                if (loadingFromDb)
                {
                    ReceiveReturnable = unitPrice < 0;
                }
                //are we receiving returnables ...
                if (!loadingFromDb)
                {
                    if (ReceiveReturnable)
                    {
                        vatAmount = -vatAmount;
                        totalPrice = -totalPrice;
                        vatValue = -vatValue;
                    }
                }

                int sequenceNo = 1;
                if (LineItems.Count > 0)
                {
                    sequenceNo = LineItems.Max(n => n.SequenceNo) + 1;
                }

                bool isReturnableProduct = false;
                if (!LoadForViewing)
                {
                    isReturnableProduct = Using<IProductRepository>(cont).GetById(productId).GetType() ==
                                          typeof (ReturnableProduct);
                }

                //Check the line item exists by product
                EditPOSSaleLineItem li = null;
                if (ReceiveReturnable)
                {
                    if (LineItems.Any(n => n.ProductId == productId && n.IsReceivedReturnable == true))
                    {
                        li = LineItems.FirstOrDefault(n => n.ProductId == productId && n.IsReceivedReturnable == true);
                    }
                }
                else
                {
                    if (
                        LineItems.Any(
                            n =>
                            n.ProductId == productId && !n.IsReceivedReturnable &&
                            n.OrderLineItemType == orderLineItemType))
                    {
                        li =
                            LineItems.FirstOrDefault(
                                n =>
                                n.ProductId == productId && !n.IsReceivedReturnable &&
                                n.OrderLineItemType == orderLineItemType);
                    }
                }

                //if found update it
                if (li != null)
                {
                    li.Qty += qty;
                    li.VatAmount += vatAmount;
                    li.LineItemVatValue += vatValue;
                    li.TotalPrice += totalPrice;
                    li.ProductDiscount = productDiscount;
                    li.LineItemTotalProductDiscount += (productDiscount*qty);
                }
                else
                {
                    li = new EditPOSSaleLineItem(Using<IOtherUtilities>(cont))
                             {
                                 SequenceNo = sequenceNo,
                                 ProductId = productId,
                                 Product = productDesc,
                                 UnitPrice = unitPrice < 0 ? -unitPrice : unitPrice,
                                 //display +ve value for received returnables
                                 LineItemVatValue = vatValue,
                                 VatAmount = vatAmount,
                                 Qty = qty,
                                 TotalPrice = totalPrice,
                                 LineItemId = (Guid) lineItemId,
                                 IsReceivedReturnable = ReceiveReturnable,
                                 CanEditLineItem = true,
                                 CanRemoveLineItem = true,
                                 ProductType = productType,
                                 OrderLineItemType = orderLineItemType,
                                 LineItemDiscountType = discounType,
                                 ProductDiscount = productDiscount,
                                 LineItemTotalProductDiscount = (productDiscount*qty),
                             };
                    if (li.OrderLineItemType == OrderLineItemType.Discount)
                    {
                        li.CanEditLineItem = false;
                        li.CanRemoveLineItem = false;
                    }

                    if (!ReceiveReturnable)
                    {
                        if (isReturnableProduct && li.TotalPrice >= 0) li.CanEditLineItem = false;
                        if (isReturnableProduct && li.TotalPrice >= 0) li.CanRemoveLineItem = false;

                        if (li.LineItemDiscountType == DiscountType.FreeOfChargeDiscount)
                        {
                            li.CanEditLineItem = true;
                            li.CanRemoveLineItem = true;
                        }
                    }

                    if (Status != "New")
                    {
                        li.CanEditLineItem = false;
                        li.CanRemoveLineItem = false;
                    }
                    LineItems.Add(li);
                }
                CalcTotals();
            }
        }
        public void SetGroupDiscountRule(
            int size, 
            GroupSizeOption sizeOrMore, 
            double discountPrice, 
            DiscountType type, 
            AdditionalRegOption additionalOrAll, 
            int? additionalNumber)
        {
            // Enable group discount rule
            this.SetEnableRule(true);

            // Set group size
            this.SetRuleGroupSize(size, sizeOrMore);

            // Set group discount
            this.SetDiscount(discountPrice, type);

            if (sizeOrMore == GroupSizeOption.JustSize)
            {
                this.SetAdditionalRegOption(additionalOrAll, additionalNumber);
            }

            this.SaveAndClose();
        }
Пример #46
0
 public static Coupon GenerateCoupon(decimal minAmount, decimal discountQuantity, DiscountType discountType)
 {
     if (discountType == DiscountType.Amount)
     {
         AmountDiscountStrategy amountDiscountStrategy = new AmountDiscountStrategy();
         return(new Coupon(minAmount, discountQuantity, amountDiscountStrategy));
     }
     else if (discountType == DiscountType.Rate)
     {
         RateDiscountStrategy rateDiscountStrategy = new RateDiscountStrategy();
         return(new Coupon(minAmount, discountQuantity, rateDiscountStrategy));
     }
     else
     {
         throw new NotImplementedException();
     }
 }
Пример #47
0
        /// <summary>
        /// Gets all discounts
        /// </summary>
        /// <param name="discountType">Discount type; null to load all discount</param>
        /// <param name="showHidden">A value indicating whether to show hidden records</param>
        /// <returns>Discount collection</returns>
        public virtual IList<Discount> GetAllDiscounts(DiscountType? discountType, bool showHidden = false)
        {
            int? discountTypeId = null;
            if (discountType.HasValue)
                discountTypeId = (int)discountType.Value;

            string key = string.Format(DISCOUNTS_ALL_KEY, showHidden, discountTypeId.HasValue ? discountTypeId.Value : 0);
            return _cacheManager.Get(key, () =>
            {
                var query = _discountRepository.Table;
                if (!showHidden)
                {
                    //The function 'CurrentUtcDateTime' is not supported by SQL Server Compact.
                    //That's why we pass the date value
                    var nowUtc = DateTime.UtcNow;
                    query = query.Where(d =>
                        (!d.StartDateUtc.HasValue || d.StartDateUtc <= nowUtc)
                        && (!d.EndDateUtc.HasValue || d.EndDateUtc >= nowUtc)
                        );
                }
                if (discountTypeId.HasValue && discountTypeId.Value > 0)
                {
                    query = query.Where(d => d.DiscountTypeId == discountTypeId);
                }
                query = query.OrderByDescending(d => d.Id);

                var discounts = query.ToList();
                return discounts;
            });
        }
Пример #48
0
 public Cart(DiscountType discountType, double discount)
 {
     cartItemList = new List <CartItem>();
     invoice      = new Invoice(this.cartItemList, DiscountType.CategoryDiscount);
 }
Пример #49
0
 public DiscountRate(DiscountType discType, double rate)
 {
     this.DiscountType = discType;
     this.Rate = rate;
 }
Пример #50
0
 public void CreateCampaign(string categoryTitle, double amount, int minItemCount, DiscountType type)
 {
     EnsureCampaignIsValid(categoryTitle, amount, minItemCount, type);
     campaignRepo.CreateCampaign(new Campaign(categoryTitle, amount, minItemCount, type));
 }
Пример #51
0
 /// <summary>
 /// Gets all discounts
 /// </summary>
 /// <param name="discountType">Discount type; null to load all discount</param>
 /// <param name="couponCode">Coupon code to find (exact match)</param>
 /// <param name="discountName">Discount name</param>
 /// <param name="showHidden">A value indicating whether to show hidden records</param>
 /// <returns>Discounts</returns>
 public virtual IList<Discount> GetAllDiscounts(DiscountType? discountType,
     string couponCode = "", string discountName = "", bool showHidden = false)
 {
     //we load all discounts, and filter them by passed "discountType" parameter later
     //we do it because we know that this method is invoked several times per HTTP request with distinct "discountType" parameter
     //that's why let's access the database only once
     string key = string.Format(DISCOUNTS_ALL_KEY, showHidden, couponCode, discountName);
     var result = _cacheManager.Get(key, () =>
     {
         var query = _discountRepository.Table;
         if (!showHidden)
         {
             //The function 'CurrentUtcDateTime' is not supported by SQL Server Compact. 
             //That's why we pass the date value
             var nowUtc = DateTime.UtcNow;
             query = query.Where(d =>
                 (!d.StartDateUtc.HasValue || d.StartDateUtc <= nowUtc)
                 && (!d.EndDateUtc.HasValue || d.EndDateUtc >= nowUtc)
                 );
         }
         if (!String.IsNullOrEmpty(couponCode))
         {
             query = query.Where(d => d.CouponCode == couponCode);
         }
         if (!String.IsNullOrEmpty(discountName))
         {
             query = query.Where(d => d.Name.Contains(discountName));
         }
         query = query.OrderBy(d => d.Name);
         
         var discounts = query.ToList();
         return discounts;
     });
     //we know that this method is usually inkoved multiple times
     //that's why we filter discounts by type on the application layer
     if (discountType.HasValue)
     {
         result = result.Where(d => d.DiscountType == discountType.Value).ToList();
     }
     return result;
 }
Пример #52
0
        private void EnsureCampaignIsValid(string categoryTitle, double amount, int minItemCount, DiscountType type)
        {
            if (!categoryService.CategoryExists(categoryTitle))
            {
                throw new Exception($"Category with title: {categoryTitle} does not exists");
            }

            if (amount <= 0)
            {
                throw new Exception($"Discount amount can not be negative regardless of type");
            }
            if (type == DiscountType.Rate && (amount >= 100))
            {
                throw new Exception($"Discount amount should be between 0 and 100 for rate typed discounts");
            }
            if (minItemCount < 0)
            {
                throw new Exception($"Min item count should be zero or a positive number");
            }
            if (type == DiscountType.Amount)
            {
                var products = productService.GetProductsByCategoryTitle(categoryTitle);
                if (products.Any(p => p.Price < amount))
                {
                    throw new Exception($"Category {categoryTitle} contains a product which has a lower price than the discount amount: {amount}");
                }
            }
        }
        public void ApplyCouponTest_ShouldApplyCoupon(decimal minAmount, decimal discount, DiscountType discountType)
        {
            ShoppingCart cart = new ShoppingCart();

            Coupon coupon = new Coupon(minAmount, discount, discountType);

            cart.applyCoupon(coupon);

            Assert.True(cart.coupon.minAmount == minAmount);
            Assert.True(cart.coupon.discount == discount);
            Assert.True(cart.coupon.discountType == discountType);
        }
        public void GetCouponDiscountTest_ShouldApplyCoupon_WhenCartMeetsCouponRequirements(decimal minAmount, decimal discount, DiscountType discountType, decimal expectedDiscount)
        {
            Category category = new Category("food");

            Product apple  = new Product("Apple", 100, category);
            Product almond = new Product("Almonds", 150, category);

            ShoppingCart cart = new ShoppingCart();

            cart.addItem(apple, 3);
            cart.addItem(almond, 1); //cart amount 450

            Coupon coupon = new Coupon(minAmount, discount, discountType);

            cart.applyCoupon(coupon);

            var calculatedCouponDiscount = cart.getCouponDiscount();

            Assert.True(calculatedCouponDiscount == expectedDiscount);
        }
Пример #55
0
        /// <summary>
        /// Gets all discounts
        /// </summary>
        /// <param name="discountType">Discount type; null to load all discount</param>
        /// <param name="couponCode">Coupon code to find (exactl match)</param>
        /// <param name="showHidden">A value indicating whether to show hidden records</param>
        /// <returns>Discount collection</returns>
        public virtual IList<Discount> GetAllDiscounts(DiscountType? discountType, string couponCode = "", bool showHidden = false)
        { 
            int? discountTypeId = null;
            if (discountType.HasValue)
                discountTypeId = (int)discountType.Value;

            //we load all discounts, and filter them by passed "discountType" parameter later
            //we do it because we know that this method is invoked several times per HTTP request with distinct "discountType" parameter
            //that's why let's access the database only once
            string key = string.Format(DISCOUNTS_ALL_KEY, showHidden, couponCode);
            var result = _cacheManager.Get(key, () =>
            {
                var query = _discountRepository.Table;
                if (!showHidden)
                {
                    //The function 'CurrentUtcDateTime' is not supported by SQL Server Compact. 
                    //That's why we pass the date value
                    var nowUtc = DateTime.UtcNow;
                    query = query.Where(d =>
                        (!d.StartDateUtc.HasValue || d.StartDateUtc <= nowUtc)
                        && (!d.EndDateUtc.HasValue || d.EndDateUtc >= nowUtc)
                        );
                }
                if (!String.IsNullOrWhiteSpace(couponCode))
                {
                    couponCode = couponCode.Trim();

                    query = query.Where(d => d.CouponCode == couponCode);
                }
                query = query.OrderByDescending(d => d.Id);
                
                var discounts = query.ToList();
                return discounts;
            });
            if (discountTypeId.HasValue && discountTypeId.Value > 0)
            {
                result = result.Where(d => d.DiscountTypeId == discountTypeId).ToList();
            }
            return result;
        }
Пример #56
0
 public void SetDiscountType(String type)
 {
     discountType = (DiscountType)Enum.Parse(typeof(DiscountType), type);
 }