Example #1
0
 public PromoPackage(Book book1, Book book2, int discountAmount, DiscountType discountType)
 {
     this.book1 = book1;
     this.book2 = book2;
     this.discountAmount = discountAmount;
     this.discountType = discountType;
 }
Example #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;
     }
 }
Example #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();
		}
Example #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;
        }
Example #5
0
 public DiscountRate(DiscountType discType, double rate)
 {
     this.DiscountType = discType;
     this.Rate = rate;
 }
        /// <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;
            });
        }
Example #7
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create a unit group.
        /// Retrieve the default unit.
        /// Create few products.
        /// Create new discount list and discount.
        /// Create new price list and few price list items.
        /// Create an account record.
        /// Create a new opportunity and few opportunity products.
        /// </summary>
        public void CreateRequiredRecords()
        {
            // Create a unit group
            UoMSchedule newUnitGroup = new UoMSchedule
            {
                Name = "Example Unit Group",
                BaseUoMName = "Example Primary Unit"
            };

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

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

            _defaultUnitId = unit.UoMId.Value;

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

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

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

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

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

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

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

            _discountId = _serviceProxy.Create(newDiscount);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            _opportunityProduct1Id = _serviceProxy.Create(newOpportunityProduct1);

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

            _opportunityProduct2Id = _serviceProxy.Create(
                newOpportunityProduct2);

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

            return;
        }
        public 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();
        }
Example #9
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);
                }

           
        }
Example #10
0
 public Discount(DiscountType discount)
 {
     discountType = discount;
 }
        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);
        }
 public ChangeDiscount(Guid orderItemId, DiscountType discountType, decimal discountValue) : base(orderItemId)
 {
     OrderItemId = orderItemId;
     DiscountType = discountType;
     DiscountValue = discountValue;
 }
Example #13
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;
 }
Example #14
0
		public void setDiscountPrice(uint price)
		{
			mDiscountType = DiscountType.Price;
			mDiscountPrice = price;
			recalculation();
		}
Example #15
0
		public void setDiscountPercent(uint discount = 10)
		{
			mDiscountType = DiscountType.Percent;

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

			recalculation();
		}
        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();
            }
        }
Example #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
        }
Example #19
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.";
        }
    }
        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;

        }
 /// <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;
 }
        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") //#[email protected]$%#^!!
                {
                    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();
            }
        }
 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;
 }
 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;
 }
        /// <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;
        }
 public void SetDiscountType(String type)
 {
     discountType = (DiscountType)Enum.Parse(typeof(DiscountType), type);
 }