示例#1
0
        public void TestBuy2GetOneFree()
        {
            //Product Amount = $100
            //Discount Applied is Buy 2 Get One Free
            //Total Quantity in Cart is 5
            //Expected Discount should be $200
            Cart cart = new Cart(new Member("Rohan"));

            // add items to the cart
            GenericProduct Trouser = new GenericProduct("Trouser", 100m);

            cart.AddLineItem(Trouser, 5);

            EventItem race = new EventItem("Ticket", 70m);

            cart.AddLineItem(race, 1);

            //Add Discount
            //This would generally be Dynamic from rule engine.
            Discount buyXGetY = new BuyXGetYFree("Buy 2 Trousers get 1 Trouser free", new List <Product> {
                Trouser
            }, 2, 1);

            buyXGetY.CanBeUsedInJuntionWithOtherDiscounts = false;
            buyXGetY.SupercedesOtherDiscounts             = true;
            cart.AddDiscount(buyXGetY);

            Order order = ProcessCartToOrder(cart);

            LineItem item = order.LineItems.FirstOrDefault(x => x.Product.Name == "Trouser");

            Assert.IsTrue(item.Subtotal == 300m);
            Assert.IsTrue(item.DiscountAmount == 200m);
        }
示例#2
0
        public BreadCrumbViewModel GenerateBreadCrumb(GenericProduct currentContent)
        {
            CatalogContentBase content = currentContent;
            var models = new List <CatalogContentModel>();

            while (!(content is CatalogContent))
            {
                var parentContent = _contentRepository.Get <CatalogContentBase>(content.ParentLink);
                var model         = new CatalogContentModel()
                {
                    DisplayName = parentContent is NodeContent ? ((NodeContent)parentContent).DisplayName : parentContent.Name,
                    Url         = UrlResolver.Current.GetUrl(parentContent)
                };
                models.Add(model);
                content = parentContent;
            }

            models.Reverse();
            models.RemoveAt(0);
            models.Add(new CatalogContentModel {
                DisplayName = currentContent.DisplayName
            });

            var startPage = _contentRepository.Get <HomePage>(ContentReference.StartPage);

            return(new BreadCrumbViewModel()
            {
                Models = models, HomepageUrl = startPage.LinkURL
            });
        }
 private IEnumerable <string> GetAvailableSizes(GenericProduct product, GenericVariant entry)
 {
     return(product != null && entry != null?
            _productService.GetVariants(product).OfType <GenericVariant>().Where(x => string.IsNullOrEmpty(x.Color) || string.IsNullOrEmpty(entry.Color) || x.Color.Equals(entry.Color))
            .Select(x => x.Size)
                : Enumerable.Empty <string>());
 }
 public ProductItemViewModel(GenericProduct genericProduct)
 {
     DisplayName = genericProduct.DisplayName;
     BrandName   = genericProduct.BrandName;
     Description = genericProduct.Description;
     Images      = genericProduct.GetImages();
 }
        public void Handle(CreateGenericProductCommand command)
        {
            var constraints    = ConstraintFactory.CreateFromDto(command.Constraints);
            var genericProduct = new GenericProduct(0, command.Name, constraints);

            //save generic product !
        }
示例#6
0
        // Updates the given product. Only product information should change, nothing from the item, like the name.
        // If the product is not part of the list, it is added.
        public async Task <bool> Add_Or_Update_Product_In_List(GenericProduct productNew, string thisUserId, string shoppingListId)
        {
            ShoppingList listEntity = GetShoppingListEntity(shoppingListId);

            if (listEntity == null)
            {
                throw new ShoppingListNotFoundException(shoppingListId);
            }
            CheckPermissionWithException(listEntity, thisUserId, ShoppingListPermissionType.Write);
            ShoppingList list = LoadShoppingList(shoppingListId);

            bool success = false;

            if (list != null)
            {
                int index = list.ProductList.FindIndex(prod => prod.Item.Name == productNew.Item.Name);
                if (index != -1)
                {
                    list.ProductList[index] = productNew;
                }
                else
                {
                    list.ProductList.Add(productNew);
                }
                success = UpdateShoppingList(list);
                if (success)
                {
                    await _hubService.SendProductAddedOrUpdated(_userService.GetById(thisUserId), productNew, list.SyncId, ShoppingListPermissionType.Read);
                }
            }
            return(success);
        }
 public ProductItemViewModel(GenericProduct product)
 {
     DisplayName      = product.DisplayName;
     BrandName        = product.BrandName;
     ShortDescription = GetShortDescription(product.Description);
     Link             = product.ContentLink.ContentUrl();
 }
示例#8
0
        private static Cart LoadCart()
        {
            // create the cart
            Cart cart = new Cart(new Member("Rohan"));

            // add items to the cart
            GenericProduct Trouser = new GenericProduct("Trouser", 110m);

            cart.AddLineItem(Trouser, 5);

            EventItem race = new EventItem("Ticket", 90m);

            cart.AddLineItem(race, 1);

            //Add Discount
            //This would generally be Dynamic from rule engine.
            Discount buyXGetY = new BuyXGetYFree("Buy 2 Trousers get 1 Trouser free", new List <Product> {
                Trouser
            }, 2, 1);

            buyXGetY.CanBeUsedInJuntionWithOtherDiscounts = false;
            buyXGetY.SupercedesOtherDiscounts             = true;
            cart.AddDiscount(buyXGetY);

            return(cart);
        }
示例#9
0
        public async Task <IActionResult> Edit(Guid id, [Bind("Id,Name")] GenericProduct genericProduct)
        {
            if (id != genericProduct.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(genericProduct);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!GenericProductExists(genericProduct.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(genericProduct));
        }
示例#10
0
        public void Handle(CreateGenericProductCommand command)
        {
            var constraintValues = ConstraintFactory.CreateFromDto(command.ConstraintValues);
            var product          = new GenericProduct(0, command.Title, constraintValues);

            _repository.Add(product);
        }
 public static List <string> AvailableColors(this GenericProduct genericProduct)
 {
     return(genericProduct.ContentLink.GetAllVariants <GenericVariant>()
            .Select(x => x.Color)
            .Distinct()
            .ToList());
 }
示例#12
0
        public ProductItemViewModel BuildProductItem(GenericProduct product)
        {
            var viewModel = new ProductItemViewModel(product);

            PopulatePrices(product, viewModel);
            PopulateImage(product, viewModel);

            return(viewModel);
        }
示例#13
0
        public void Constructor_should_create_child_product()
        {
            var nectarName       = "Nectar";
            var orangeNectarName = "Orange Nectar";

            var nectar  = new GenericProduct(nectarName);
            var product = new DummyProduct(orangeNectarName, nectar);

            product.Name.Should().Be(orangeNectarName);
            product.ParentProductId.Should().Be(nectar.Id);     //TODO: it has no Id :|
        }
示例#14
0
        public void Edit(GenericProduct gp)
        {
            var choosenGp = _databaseNsContext.GenericProducts.Where(x => x.Id == gp.Id).First();

            choosenGp.Measurement = gp.Measurement;
            choosenGp.Name        = gp.Name;

            _databaseNsContext.GenericProducts.Update(choosenGp);

            _databaseNsContext.SaveChanges();
        }
示例#15
0
        public async Task <IActionResult> Create([Bind("Id,Name")] GenericProduct genericProduct)
        {
            if (ModelState.IsValid)
            {
                genericProduct.Id = Guid.NewGuid();
                _context.Add(genericProduct);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(genericProduct));
        }
示例#16
0
        public virtual GenericVariant SelectVariant(GenericProduct currentContent, string color, string size)
        {
            var variants = GetVariants <GenericVariant, GenericProduct>(currentContent);

            if (TryGetFashionVariantByColorAndSize(variants, color, size, out var variant) ||
                TryGetFashionVariantByColorAndSize(variants, color, string.Empty, out variant))   //if we cannot find variation with exactly both color and size then we will try to get variant by color only
            {
                return(variant);
            }

            return(null);
        }
示例#17
0
        public void Constructor_should_create_root_product()
        {
            var id          = 1;
            var name        = "Nectar";
            var constraints = GetSomeValidConstraints();

            var product = new GenericProduct(id, name, constraints);

            product.Name.Should().Be(name);
            product.Id.Should().Be(id);
            product.Constraints.Should().BeEquivalentTo(constraints);
        }
示例#18
0
        public List <InventoryRecord> GetInventory(GenericProduct product)
        {
            var variantRefs = product.GetVariants().ToList();
            var variants    = _contentLoader.GetItems(variantRefs, CultureInfo.CurrentUICulture)
                              .OfType <GenericVariant>()
                              .ToList();
            var variantCodes = variants.Select(x => x.Code);

            IList <InventoryRecord> inventoryRecords = _inventoryService.QueryByEntry(variantCodes);

            return(inventoryRecords.ToList());
        }
示例#19
0
        public void Should_be_constructed_properly()
        {
            var id               = 10;
            var title            = "Mobile Phone";
            var constraintValues = ConstraintValueTestFactory.SomeValidConstraintValues();

            var genericProduct = new GenericProduct(id, title, constraintValues);

            genericProduct.Id.Should().Be(id);
            genericProduct.Title.Should().Be(title);
            genericProduct.ConstraintValues.Should().BeEquivalentTo(constraintValues);
        }
 public void RemoveValidationRule(GenericProduct p, bool promotion, bool update = false, bool active = true)
 {
     client = new SQSAdminServiceClient();
     client.Endpoint.Address = new System.ServiceModel.EndpointAddress(CommonVariables.WcfEndpoint);
     client.SQSAdmin_StandardInclusion_RemoveValidationRule(p.validationruleID, update, active);
     client.Close();
     if (promotion && !update)
     {
         PromotionProducts.Remove(p);
     }
     else
     {
         UpgradeOptionProducts.Remove(p);
     }
 }
示例#21
0
        private void PopulatePrices(GenericProduct product, ProductItemViewModel viewModel)
        {
            var prices = _priceService.GetPrices(product)
                         .OrderBy(x => x.UnitPrice.Amount);

            if (!prices.Any())
            {
                return;
            }

            var minPrice = prices.First();
            var maxPrice = prices.Last();

            viewModel.MinPrice = minPrice.UnitPrice.Amount;
            viewModel.MaxPrice = maxPrice.UnitPrice.Amount;
        }
示例#22
0
        private Product CreateNewProductInstance(ISOProduct isoProduct)
        {
            // If there is a manufacturer defined attribute representing a crop name, use it
            string cropName = _manufacturer?.GetCropName(isoProduct);

            if (!string.IsNullOrWhiteSpace(cropName))
            {
                // New crop variety product
                var cropProduct = new CropVarietyProduct();
                cropProduct.ProductType = ProductTypeEnum.Variety;

                // Check if there is already Crop in ADAPT model
                Crop adaptCrop = TaskDataMapper.AdaptDataModel.Catalog.Crops.FirstOrDefault(x => x.Name.EqualsIgnoreCase(cropName));
                if (adaptCrop == null)
                {
                    // Create a new one
                    adaptCrop      = new Crop();
                    adaptCrop.Name = cropName;
                    TaskDataMapper.AdaptDataModel.Catalog.Crops.Add(adaptCrop);
                }
                cropProduct.CropId = adaptCrop.Id.ReferenceId;
                return(cropProduct);
            }

            Product product;

            //Type
            switch (isoProduct.ProductType)
            {
            case ISOProductType.Mixture:
            case ISOProductType.TemporaryMixture:
                product             = new MixProduct();
                product.ProductType = ProductTypeEnum.Mix;
                break;

            default:
                product             = new GenericProduct();
                product.ProductType = _manufacturer?.GetProductType(isoProduct) ?? ProductTypeEnum.Generic;
                break;
            }
            return(product);
        }
        public async Task <bool> SendProductAddedOrUpdated(
            User user,
            GenericProduct product,
            string listSyncId,
            ShoppingListPermissionType permission)
        {
            try
            {
                string        userJson    = JsonConvert.SerializeObject(user.WithoutPassword());
                string        productJson = JsonConvert.SerializeObject(product);
                List <string> users       = GetUsersWithPermissionsFiltered(user, listSyncId, permission);
                await _hubContext.Clients.Users(users).SendAsync("ProductAddedOrUpdated", userJson, listSyncId, productJson);

                return(true);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("SendProductAddedOrUpdatedn {0}", ex);
                return(false);
            }
        }
        public void GetUpgradeForStandardInclusion(string productid, string pbrandids)
        {
            DateTime dateValue = (DateTime)System.Data.SqlTypes.SqlDateTime.MinValue;

            client = new SQSAdminServiceClient();
            client.Endpoint.Address = new System.ServiceModel.EndpointAddress(CommonVariables.WcfEndpoint);
            DataSet ds = client.SQSAdmin_StandardInclusion_GetUpgradeOptionByStandardInclusion(productid, pbrandids);

            client.Close();
            UpgradeOptionProducts.Clear();
            PromotionProducts.Clear();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                GenericProduct p = new GenericProduct();
                p.BrandID            = int.Parse(dr["brandid"].ToString());
                p.BrandName          = dr["brandname"].ToString();
                p.ProductID          = dr["productid"].ToString();
                p.ProductName        = dr["productname"].ToString();
                p.ProductDescription = dr["productdescription"].ToString();
                p.validationruleID   = int.Parse(dr["idStudioM_Inclusionvalidationrule"].ToString());
                p.Promotion          = bool.Parse(dr["Promotion"].ToString());
                DateTime.TryParse(dr["EffectiveDate"].ToString(), out dateValue);
                if (dateValue != (DateTime)System.Data.SqlTypes.SqlDateTime.MinValue)
                {
                    p.EffectiveDate = dateValue.AddHours(3);
                }
                p.Active = bool.Parse(dr["active"].ToString());
                if (p.Promotion)
                {
                    PromotionProducts.Add(p);
                }
                else if (p.Active)
                {
                    // upgrade products show only the active items
                    UpgradeOptionProducts.Add(p);
                }
            }
        }
        public void GetStandardInclusion(string productid, string productname, int pstateid, string brandids)
        {
            client = new SQSAdminServiceClient();
            client.Endpoint.Address = new System.ServiceModel.EndpointAddress(CommonVariables.WcfEndpoint);
            DataSet ds = client.SQSAdmin_StandardInclusion_GetStandardInclusionProducts(productid, productname, pstateid, brandids);

            client.Close();
            StandarInclusionProducts.Clear();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                GenericProduct p = new GenericProduct();
                p.BrandID            = int.Parse(dr["BrandID"].ToString());
                p.BrandName          = dr["BrandName"].ToString();
                p.ProductID          = dr["productid"].ToString();
                p.ProductName        = dr["productname"].ToString();
                p.ProductDescription = dr["productdescription"].ToString();
                p.validationruleID   = 0;

                StandarInclusionProducts.Add(p);
            }
            UpgradeOptionProducts.Clear();
            PromotionProducts.Clear();
        }
示例#26
0
        private void PopulateImage(GenericProduct product, ProductItemViewModel viewModel)
        {
            var image = product.DefaultImage();

            if (image == null)
            {
                var variants = _contentLoader.GetItems(product.GetVariants().ToList(), CultureInfo.CurrentUICulture)
                               .OfType <GenericVariant>()
                               .ToList();

                image = variants
                        .Select(x => x.DefaultImage())
                        .Where(x => !x.IsNullOrEmpty())
                        .FirstOrDefault();
            }

            if (image == null)
            {
                image = ImagePlaceHolderUrl;
            }

            viewModel.Image = image;
        }
        public void GetAvailableUpgradeOptionProducts(string productid, string productname, string brandids, int pstateid, string stdinclusionproductid)
        {
            client = new SQSAdminServiceClient();
            client.Endpoint.Address = new System.ServiceModel.EndpointAddress(CommonVariables.WcfEndpoint);
            DataSet ds = client.SQSAdmin_StandardInclusion_GetAvailableUpgradeOptionProducts(productid, productname, brandids, pstateid, stdinclusionproductid);

            client.Close();
            AvailableOptionProducts.Clear();
            if (ds != null)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    GenericProduct p = new GenericProduct();
                    p.BrandID            = 0;
                    p.BrandName          = "";
                    p.ProductID          = dr["productid"].ToString();
                    p.ProductName        = dr["productname"].ToString();
                    p.ProductDescription = dr["productdescription"].ToString();
                    p.validationruleID   = 0;

                    AvailableOptionProducts.Add(p);
                }
            }
        }
        public void Copy_All_Fields_From_One_To_Another()
        {
            var from = new GenericProduct
            {
                GpInSt = "A",
                GpKode = 1,
                GpKtVr = 2,
                GpKTwg = 3,
                GpNmNr = 4,
                GpStNr = 5,
                GsKode = 6,
                MutKod = MutKod.RecordUpdated,
                SpKode = 7,
                ThEhHv = 8,
                ThKtVr = 9,
                ThKTwg = 10,
                XpEhHv = 11
            };
            var to = new GenericProduct();

            from.CopyTo(to);

            Assert.IsTrue(new GenericProductComparer().Equals(from, to));
        }
示例#29
0
        private Product GetProduct(Model.ShippedItemInstance shippedItemInstance)
        {
            // Look for product with a description that matches the shipped item instance
            Product product = Catalog.Products.FirstOrDefault(p => p.Description == shippedItemInstance.Description?.Content);

            if (product == null && shippedItemInstance.Description?.Content != null)
            {
                if (shippedItemInstance.TypeCode == null || shippedItemInstance.TypeCode.ToLower() == "seed")
                {
                    product = new CropVarietyProduct();
                }
                else
                {
                    product = new GenericProduct();
                }

                product.Description = shippedItemInstance.Description?.Content;
                product.ContextItems.AddRange(CreateProductContextItems(shippedItemInstance));

                Catalog.Products.Add(product);
            }

            return(product);
        }
示例#30
0
        public Product ImportProduct(ISOProduct isoProduct)
        {
            //First check if we've already created a matching seed product from the crop type
            Product product = DataModel.Catalog.Products.FirstOrDefault(p => p.ProductType == ProductTypeEnum.Variety && p.Description == isoProduct.ProductDesignator);

            //If not, create a new product
            if (product == null)
            {
                //Type
                switch (isoProduct.ProductType)
                {
                case ISOProductType.Mixture:
                case ISOProductType.TemporaryMixture:
                    product             = new MixProduct();
                    product.ProductType = ProductTypeEnum.Mix;
                    break;

                default:
                    product             = new GenericProduct();
                    product.ProductType = ProductTypeEnum.Generic;
                    break;
                }
            }

            //ID
            if (!ImportIDs(product.Id, isoProduct.ProductId))
            {
                //Replace the CVT id with the PDT id in the mapping
                TaskDataMapper.InstanceIDMap.ReplaceISOID(product.Id.ReferenceId, isoProduct.ProductId);
            }

            //Description
            product.Description = isoProduct.ProductDesignator;

            //Mixes
            if (isoProduct.ProductRelations.Any())
            {
                if (product.ProductComponents == null)
                {
                    product.ProductComponents = new List <ProductComponent>();
                }

                foreach (ISOProductRelation prn in isoProduct.ProductRelations)
                {
                    //Find the product referenced by the relation
                    ISOProduct isoComponent = ISOTaskData.ChildElements.OfType <ISOProduct>().FirstOrDefault(p => p.ProductId == prn.ProductIdRef);

                    //Find or create the active ingredient to match the component
                    Ingredient ingredient = DataModel.Catalog.Ingredients.FirstOrDefault(i => i.Id.FindIsoId() == isoComponent.ProductId);
                    if (ingredient == null)
                    {
                        ingredient             = new ActiveIngredient();
                        ingredient.Description = isoComponent.ProductDesignator;
                        DataModel.Catalog.Ingredients.Add(ingredient);
                    }

                    //Create a component for this ingredient
                    ProductComponent component = new ProductComponent()
                    {
                        IngredientId = ingredient.Id.ReferenceId
                    };
                    if (!string.IsNullOrEmpty(isoComponent.QuantityDDI))
                    {
                        component.Quantity = prn.QuantityValue.AsNumericRepresentationValue(isoComponent.QuantityDDI, RepresentationMapper);
                    }
                    product.ProductComponents.Add(component);
                }

                //Total Mix quantity
                if (isoProduct.MixtureRecipeQuantity.HasValue)
                {
                    MixProduct mixProduct = product as MixProduct;
                    mixProduct.TotalQuantity = isoProduct.MixtureRecipeQuantity.Value.AsNumericRepresentationValue(isoProduct.QuantityDDI, RepresentationMapper);
                }
            }

            //Density
            if (isoProduct.DensityMassPerCount.HasValue)
            {
                product.Density = isoProduct.DensityMassPerCount.Value.AsNumericRepresentationValue("007A", RepresentationMapper);
            }
            else if (isoProduct.DensityMassPerVolume.HasValue)
            {
                product.Density = isoProduct.DensityMassPerVolume.Value.AsNumericRepresentationValue("0079", RepresentationMapper);
            }
            else if (isoProduct.DensityVolumePerCount.HasValue)
            {
                product.Density = isoProduct.DensityVolumePerCount.Value.AsNumericRepresentationValue("007B", RepresentationMapper);
            }

            return(product);
        }
        bool SetProduct(string[] items, Trade trade)
        {
            var temp = items[secCol];
            var tokens = temp.Split('-');
            var prod = Env.Current.Trade.GetProductByCode(Product.DefaultTicker, items[bbgKeyCol]) ??
                    Env.Current.Trade.GetProductByCode(Product.RtDefaultTicker, tokens[0]) ??
                    Env.Current.Trade.GetProductByCode(Product.CusipProductCode, items[cusipCol]) ??
                    Env.Current.Trade.GetProductByCode(Product.IsinProductCode, items[isinCol]) ??
                    Env.Current.Trade.GetProductByCode(Product.SedolProductCode, items[sedolCol]);

            if (prod == null)
            {
                Logger.Error("Cannot find product with Rt ticker sec_symbol=" + temp);
                var prodType = items[secTypeCol];
                var gproduct = new GenericProduct
                {
                    ProductProcessingType = prodType,
                    ProductPricingType = prodType,
                    ProductDescription = temp + " " + items[descCol],
                    ProductCategory = prodType,
                };
                trade.Product = gproduct;
                return false;
            }
            else
                trade.Product = prod;
            var fut = prod as Future;
            if (fut != null)
            {
                if (Utilities.IsPercentageQuotation(fut.Quotation) || fut.Quotation == QuotationType.Cents)
                    trade.Price /= 100;
                else if (fut.Quotation == QuotationType.Yield) trade.Price /= 10000;
            }
            return true;
        }
示例#32
0
        public void Delete(GenericProduct gp)
        {
            _databaseNsContext.GenericProducts.Remove(gp);

            _databaseNsContext.SaveChanges();
        }
        public void Return_False_On_IsIdentical_When_Identity_Is_Different()
        {
            var x = new GenericProduct
            {
                GpKode = 1
            };
            var y = new GenericProduct
            {
                GpKode = 2
            };

            Assert.IsFalse(x.IsIdentical(y));
        }
 Product GetProduct(string[] items)
 {
     var prodType = items[secTypeCol];
     var unknown = false;
     Product prod = null;
     if (prodType.EndsWith("F") || prodType.EndsWith("O"))
         prod = Env.Current.Trade.GetProductByCode(Product.RtDefaultTicker, items[rSymbolCol]) ??
             Env.Current.Trade.GetProductByCode(TradeImportHelper.ImagineMaturity, items[rSymbolCol]) ??
             FindFuture(items);
     else if (prodType.Equals("S"))
         prod = Env.Current.Trade.GetProductByCode(Product.CusipProductCode, items[cusipCol]) ??
             Env.Current.Trade.GetProductByCode(Product.IsinProductCode, items[isinCol]) ??
             Env.Current.Trade.GetProductByCode(Product.SedolProductCode, items[sedolCol]);
     else if (prodType.Equals("CUR"))
     {
         var fx = new FX();
         var sec = items[rSymbolCol];
         if (sec.Length == 6)
         {
             fx.Primary = sec.Substring(0, 3);
             fx.Quoting = sec.Substring(3);
             fx.PrimaryAmount = double.Parse(items[quantityCol]);
             fx.QuotingAmount = double.Parse(items[notionalCol]);
             fx.SpotRate = double.Parse(items[costCol]);
             prod = fx;
         }
     }
     else
         unknown = true;
     if (prod == null)
     {
         var gproduct = new GenericProduct
         {
             ProductProcessingType = prodType,
             ProductPricingType = prodType,
             ProductDescription = unknown ? TypeUnknown : items[descCol],
             ProductCategory = prodType,
         };
         prod = gproduct;                
     }
     return prod;
 }
        public Product GetProduct(IDictionary<string, Contract> contracts, Log logger)
        {
            Product prod = null;
            var prodCurrency = Env.Current.StaticData.GetCurrency(Currency1);
            if (SecurityType.Equals(TradeInfo.Bonds))
            {
                prod = Env.Current.Trade.GetProductByCode(Product.IsinProductCode, Identifier2) ??
                    Env.Current.Trade.GetProductByCode(Product.CusipProductCode, Identifier2);
            }
            else if (IsFuture)
            {
                var tickerSymbol = Identifier1.Length == 1 ? Identifier1 + " " : Identifier1;
                string ticker = tickerSymbol;
                if (SecurityType.Equals(TradeInfo.EquityFutures))
                {
                    ticker += " Index";
                }
                else if (SecurityType.Equals(TradeInfo.OtherFutures))
                {
                    ticker += " Curncy";
                }
                else
                {
                    ticker += " Comdty";
                }
                Contract c = null;
                contracts.TryGetValue(ticker, out c);
                if (c == null)
                    contracts.TryGetValue(tickerSymbol, out c);
                if (c != null)
                {
                    var maturity = Maturity;
                    if (c.UnderlierType == ContractUnderlierType.Bond)
                    {
                        var expirations = c.NextExpiries(ReportDate, c.TotalListed, true, true);
                        if (expirations != null && expirations.Count > 0)
                        {
                            foreach (var ex in expirations)
                            {
                                if (maturity == c.LastDeliveryDate(ex))
                                {
                                    maturity = ex;
                                    break;
                                }
                            }
                        }
                    }
                    var bbgTicker = c.GetFutureCode(maturity) + " " + c.TickerSuffix;
                    prod = Env.Current.Trade.GetProductByCode(Product.DefaultTicker, bbgTicker) ??
                        ImportHelper.FindFuture(false, null, contracts.Values.ToList(), bbgTicker, null, null,
                    c.ContractMonth(maturity), maturity, 0, 0, Currency1, new List<Exception>(), null);
                    if (prod == null)
                        prod = Env.Current.Trade.GetProductByCode(TradeImportHelper.MurexMaturity, c.TickerSymbol + " " + maturity);
                }
            }
            else if (IsListedOption)
            {
                Contract c = null;
                var tickerSymbol = Identifier1.Length == 1 ? Identifier1 + " " : Identifier1;
                var ticker = tickerSymbol;
                if (SecurityType.Equals(TradeInfo.IrfOption))
                {
                    ticker += " Comdty";
                }
                else if (SecurityType.Equals(TradeInfo.EqOption))
                {
                    ticker += " Equity";
                }
                else
                {
                    ticker += " Comdty";
                }
                contracts.TryGetValue(ticker, out c);
                if (c == null)
                    contracts.TryGetValue(tickerSymbol, out c);
                if (c != null)
                {
                    var contractMonth = c.ContractMonth(Maturity);
                    var bbgTicker = tickerSymbol + DateHelper.ToImm(contractMonth) + contractMonth.Year % 10
                        + CallPut + " " + Strike + " " + c.TickerSuffix;
                    prod = Env.Current.Trade.GetProductByCode(Product.DefaultTicker, bbgTicker) ??
                        ImportHelper.FindFuture(true, null, contracts.Values.ToList(), bbgTicker, null, null, contractMonth, Maturity,
                        Strike, CallPut.Equals("P") ? OptionType.Put : OptionType.Call, Currency1, new List<Exception>(), null);
                    if (prod == null)
                        prod = Env.Current.Trade.GetProductByCode(TradeImportHelper.MurexMaturity, c.TickerSymbol + " " + Maturity
                            + " " + CallPut + Strike);
                }
            }
            else if (SecurityType.Equals(SwapInfo.IRSwap) || SecurityType.Equals(Fras) || SecurityType.Equals(SwapInfo.CcySwap)
                || SecurityType.Equals(SwaptionInfo.Swaption))
            {
                var murex = new MurexProduct();
                prod = murex;
                string prodtype;
                if (SecurityType.Equals(SwapInfo.IRSwap))
                {
                    prodtype = prodCurrency.IsNonDeliverable ? "NDS" : "Swap";
                }
                else if (SecurityType.Equals(SwapInfo.CcySwap))
                {
                    prodtype = Instrument.Contains("MTM") ? "MTMCurrencySwap" : "CurrencySwap";
                }
                else if (SecurityType.Equals(MurexInfo.Fras))
                {
                    prodtype = "FRA";
                }
                else
                {
                    prodtype = "Swaption";
                }
                murex.ProductProcessingType = prodtype;
                murex.ProductAccountingType = prodtype;
                murex.ProductPricingType = prodtype;
                murex.Generator = Instrument;
                if (prodtype == "Swaption")
                {
                    murex.Nominal1 = Math.Abs(Nominal1);
                    murex.Nominal2 = Math.Abs(Nominal2);
                    murex.Notional = murex.Nominal1;
                    murex.Currency1 = Currency1;
                    murex.Currency2 = Currency2;
                    if (OptionExerciseMethod != null)
                    {
                        murex.ExerciseSettlement = OptionExerciseMethod.Equals("0")
                            ? ExerciseSettlement.Physical : ExerciseSettlement.Cash;
                    }
                    murex.EffectiveDate = SettleDate;
                    murex.EndDate = SwaptionMaturity;
                    murex.SwapStartDate = StartDate1;
                    murex.SwapEndDate = EndDate;
                    murex.UpFrontAmount = UpFrontAmount;
                    murex.UpFrontCcy = UpFrontCcy;
                    murex.UpFrontDate = UpFrontDate;
                    murex.FixedRate = Strike / 100;
                    if (CallPut != null)
                        murex.CallPut = CallPut.Equals("C") ? OptionType.Call : OptionType.Put;
                    if (OptionStyle != null)
                        murex.ExerciseType = OptionStyle.Equals("E") ? OptionExerciseType.European : OptionExerciseType.American;
                }
                else
                {
                    // swap, fra..
                    murex.Nominal1 = Math.Abs(Nominal1);
                    murex.Nominal2 = Math.Abs(Nominal2);
                    murex.Notional = murex.Nominal1;
                    murex.Currency1 = Currency1;
                    murex.Currency2 = Currency2;
                    murex.EffectiveDate = StartDate1;
                    murex.EndDate = EndDate;
                    murex.FirstFixingRate1 = FirstFixingRate1 / 100;
                    murex.FirstFixingRate2 = FirstFixingRate2 / 100;
                    murex.Spread1 = Spread1 / 100;
                    murex.Spread2 = Spread2 / 100;
                    murex.FixedRate = Price / 100;
                    murex.UpFrontAmount = UpFrontAmount;
                    murex.UpFrontCcy = UpFrontCcy;
                    murex.UpFrontDate = UpFrontDate;
                }
            }
            else if (SecurityType.Equals(FxInfo.SpotForward) || SecurityType.Equals(FxoInfo.SimpleFXO))
            {
                CurrencyPair cp;
                string c1, c2;
                c1 = PrimaryCcy ?? Currency1;
                c2 = QuotingCcy ?? Currency2;
                cp = Env.Current.Trade.GetCurrencyPair(c1, c2);
                if (cp != null)
                {
                    var ccy1 = Env.Current.StaticData.GetCurrency(cp.Primary);
                    var ccy2 = Env.Current.StaticData.GetCurrency(cp.Quoting);
                    var isNdf = false;
                    if (!FixingDate.IsNull)
                        isNdf = true;
                    if (SecurityType.Equals(FxInfo.SpotForward))
                    {
                        var fx = isNdf ? new NDF() : new FX();
                        prod = fx;
                        fx.IsForward = false;
                        fx.Primary = cp.Primary;
                        fx.Quoting = cp.Quoting;
                        fx.PrimarySettleDate = NDFSettleDate;
                        fx.QuotingSettleDate = NDFSettleDate;
                        if (fx.Primary == PrimaryCcy)
                        {
                            fx.PrimaryAmount = Math.Abs(PrimaryAmount);
                            fx.QuotingAmount = Math.Abs(QuotingAmount);
                        }
                        else
                        {
                            fx.PrimaryAmount = Math.Abs(QuotingAmount);
                            fx.QuotingAmount = Math.Abs(PrimaryAmount);
                        }
                        fx.SpotRate = Math.Abs(Price);
                        if (isNdf)
                        {
                            var ndCcy = ccy1.IsNonDeliverable ? cp.Primary : cp.Quoting;
                            var ndfixing = cp.Quoting + "/" + cp.Primary;
                            var ndf = fx as NDF;
                            ndf.NonDeliverableCurrency = ndCcy;
                            var fix = Env.Current.StaticData.GetFxFixing(ndfixing);
                            if (fix != null)
                            {
                                ndf.FXFixingName = fix.Name;
                                ndf.FXFixingOffset = fix.FixingLag;
                                ndf.FXFixingDate = FixingDate;
                                ndf.FixingValue = FixingRate;
                            }
                        }
                    }
                    else
                    {
                        var fxo = new FXOption();
                        prod = fxo;
                        fxo.ExpiryDate = Maturity;
                        fxo.Primary = cp.Primary;
                        fxo.Quoting = cp.Quoting;
                        fxo.IsBuy = BuySell.Equals("B") ? true : false;
                        if (fxo.Primary.Equals(Currency1))
                        {
                            fxo.PrimaryAmount = Math.Abs(Nominal1);
                            fxo.QuotingAmount = Math.Abs(Nominal2);

                        }
                        else
                        {
                            fxo.PrimaryAmount = Math.Abs(Nominal2);
                            fxo.QuotingAmount = Math.Abs(Nominal1);
                        }
                        fxo.OptionStrike = Math.Abs(Strike);
                        if (OptionExerciseMethod != null)
                            fxo.ExerciseSettlement = OptionExerciseMethod.Equals("0") ? ExerciseSettlement.Cash : ExerciseSettlement.Physical;
                        fxo.InitialPremiumAmount = Math.Abs(UpFrontAmount);
                        fxo.InitialPremiumDate = UpFrontDate;
                        fxo.InitialPremiumCurrency = UpFrontCcy;
                        fxo.InitialPremiumPayReceive = UpFrontAmount > 0 ? PayReceive.Receive : PayReceive.Pay;
                        fxo.OptionType = CallPut == "P" ? OptionType.Put : OptionType.Call;
                        if (fxo.ExerciseSettlement == ExerciseSettlement.Cash)
                            fxo.SettleCurrency = Currency1;
                        fxo.SettlementMarketPlaces = cp.DefaultMarketPlaces;
                        fxo.SettlementLag = cp.SpotLag;
                        fxo.ExerciseType = OptionExerciseType.European;
                    }
                }
                else
                    logger.Error("Cannot find CurrencyPair: " + Symbol);
            }
            if (prod == null)
                prod = new GenericProduct
                {
                    ProductProcessingType = SecurityType,
                    ProductDescription = Symbol
                };
            return prod;
        }
        public void Return_True_On_IsIdentical_When_Identity_Is_Equal()
        {
            var x = new GenericProduct
            {
                GpKode = 1
            };
            var y = new GenericProduct
            {
                GpKode = 1
            };

            Assert.IsTrue(x.IsIdentical(y));
        }