示例#1
0
        /// <summary>
        /// Gets a value indicating whether tax is free
        /// </summary>
        /// <param name="productVariant">Product variant</param>
        /// <param name="customer">Customer</param>
        /// <returns>A value indicating whether tax is free</returns>
        protected static bool IsFreeTax(ProductVariant productVariant, Customer customer)
        {
            if (customer != null)
            {
                if (customer.IsTaxExempt)
                    return true;

                CustomerRoleCollection customerRoles = customer.CustomerRoles;
                foreach (CustomerRole customerRole in customerRoles)
                    if (customerRole.TaxExempt)
                        return true;
            }
            
            if (productVariant == null)
            {
                return false;
            }

            if (productVariant.IsTaxExempt)
            {
                return true;
            }

            return false;
        }
        public string GetStockQuantity(ProductVariant productVariant)
        {
            string stock = string.Empty;

            if (productVariant.ManageInventory == (int)ManageInventoryMethodEnum.ManageStock)
                stock = productVariant.StockQuantity.ToString();

            return stock;
        }
        public string GetProductVariantName(ProductVariant productVariant)
        {
            string variantName = string.Empty;
            if (!String.IsNullOrEmpty(productVariant.Name))
                variantName = productVariant.Name;
            else
                variantName = GetLocaleResourceString("Admin.Product.ProductVariants.Unnamed");

            return variantName;
        }
示例#4
0
        /// <summary>
        /// Create request for tax calculation
        /// </summary>
        /// <param name="productVariant">Product variant</param>
        /// <param name="TaxClassID">Tax class identifier</param>
        /// <param name="customer">Customer</param>
        /// <returns>Package for tax calculation</returns>
        protected static CalculateTaxRequest CreateCalculateTaxRequest(ProductVariant productVariant, int TaxClassID, Customer customer)
        {
            CalculateTaxRequest calculateTaxRequest = new CalculateTaxRequest();
            calculateTaxRequest.Customer = customer;
            calculateTaxRequest.Item = productVariant;
            calculateTaxRequest.TaxClassID = TaxClassID;

            TaxBasedOnEnum basedOn = TaxManager.TaxBasedOn;

            if (basedOn == TaxBasedOnEnum.BillingAddress)
            {
                if (customer == null || customer.BillingAddress == null)
                {
                    basedOn = TaxBasedOnEnum.DefaultAddress;
                }
            }
            if (basedOn == TaxBasedOnEnum.ShippingAddress)
            {
                if (customer == null || customer.ShippingAddress == null)
                {
                    basedOn = TaxBasedOnEnum.DefaultAddress;
                }
            }

            Address address = null;

            switch (basedOn)
            {
                case TaxBasedOnEnum.BillingAddress:
                    {
                        address = customer.BillingAddress;
                    }
                    break;
                case TaxBasedOnEnum.ShippingAddress:
                    {
                        address = customer.ShippingAddress;
                    }
                    break;
                case TaxBasedOnEnum.DefaultAddress:
                    {
                        address = TaxManager.DefaultTaxAddress;
                    }
                    break;
                case TaxBasedOnEnum.ShippingOrigin:
                    {
                        address = ShippingManager.ShippingOrigin;
                    }
                    break;
            }

            calculateTaxRequest.Address = address;
            return calculateTaxRequest;
        }
        public Product SaveInfo()
        {
            DateTime nowDT = DateTime.UtcNow;

            string name = txtName.Text.Trim();
            string shortDescription = txtShortDescription.Text.Trim();
            string fullDescription = txtFullDescription.Value.Trim();
            string adminComment = txtAdminComment.Text.Trim();
            int templateId = int.Parse(this.ddlTemplate.SelectedItem.Value);
            bool showOnHomePage = cbShowOnHomePage.Checked;
            bool allowCustomerReviews = cbAllowCustomerReviews.Checked;
            bool allowCustomerRatings = cbAllowCustomerRatings.Checked;
            bool published = cbPublished.Checked;
            string sku = txtSKU.Text.Trim();
            string manufacturerPartNumber = txtManufacturerPartNumber.Text.Trim();
            bool isGiftCard = cbIsGiftCard.Checked;
            int giftCardType = int.Parse(this.ddlGiftCardType.SelectedItem.Value);
            bool isDownload = cbIsDownload.Checked;
            int productVariantDownloadId = 0;
            if (isDownload)
            {
                bool useDownloadURL = cbUseDownloadURL.Checked;
                string downloadURL = txtDownloadURL.Text.Trim();
                byte[] productVariantDownloadBinary = null;
                string downloadContentType = string.Empty;
                string downloadFilename = string.Empty;
                string downloadExtension = string.Empty;

                HttpPostedFile productVariantDownloadFile = fuProductVariantDownload.PostedFile;
                if ((productVariantDownloadFile != null) && (!String.IsNullOrEmpty(productVariantDownloadFile.FileName)))
                {
                    productVariantDownloadBinary = productVariantDownloadFile.GetDownloadBits();
                    downloadContentType = productVariantDownloadFile.ContentType;
                    downloadFilename = Path.GetFileNameWithoutExtension(productVariantDownloadFile.FileName);
                    downloadExtension = Path.GetExtension(productVariantDownloadFile.FileName);
                }

                var productVariantDownload = new Download()
                {
                    UseDownloadUrl = useDownloadURL,
                    DownloadUrl = downloadURL,
                    DownloadBinary = productVariantDownloadBinary,
                    ContentType = downloadContentType,
                    Filename = downloadFilename,
                    Extension = downloadExtension,
                    IsNew = true
                };
                this.DownloadService.InsertDownload(productVariantDownload);
                productVariantDownloadId = productVariantDownload.DownloadId;
            }

            bool unlimitedDownloads = cbUnlimitedDownloads.Checked;
            int maxNumberOfDownloads = txtMaxNumberOfDownloads.Value;
            int? downloadExpirationDays = null;
            if (!String.IsNullOrEmpty(txtDownloadExpirationDays.Text.Trim()))
                downloadExpirationDays = int.Parse(txtDownloadExpirationDays.Text.Trim());
            DownloadActivationTypeEnum downloadActivationType = (DownloadActivationTypeEnum)Enum.ToObject(typeof(DownloadActivationTypeEnum), int.Parse(this.ddlDownloadActivationType.SelectedItem.Value));
            bool hasUserAgreement = cbHasUserAgreement.Checked;
            string userAgreementText = txtUserAgreementText.Value;

            bool hasSampleDownload = cbHasSampleDownload.Checked;
            int productVariantSampleDownloadId = 0;
            if (hasSampleDownload)
            {
                bool useSampleDownloadURL = cbUseSampleDownloadURL.Checked;
                string sampleDownloadURL = txtSampleDownloadURL.Text.Trim();
                byte[] productVariantSampleDownloadBinary = null;
                string sampleDownloadContentType = string.Empty;
                string sampleDownloadFilename = string.Empty;
                string sampleDownloadExtension = string.Empty;

                HttpPostedFile productVariantSampleDownloadFile = fuProductVariantSampleDownload.PostedFile;
                if ((productVariantSampleDownloadFile != null) && (!String.IsNullOrEmpty(productVariantSampleDownloadFile.FileName)))
                {
                    productVariantSampleDownloadBinary = productVariantSampleDownloadFile.GetDownloadBits();
                    sampleDownloadContentType = productVariantSampleDownloadFile.ContentType;
                    sampleDownloadFilename = Path.GetFileNameWithoutExtension(productVariantSampleDownloadFile.FileName);
                    sampleDownloadExtension = Path.GetExtension(productVariantSampleDownloadFile.FileName);
                }

                var productVariantSampleDownload = new Download()
                {
                    UseDownloadUrl = useSampleDownloadURL,
                    DownloadUrl = sampleDownloadURL,
                    DownloadBinary = productVariantSampleDownloadBinary,
                    ContentType = sampleDownloadContentType,
                    Filename = sampleDownloadFilename,
                    Extension = sampleDownloadExtension,
                    IsNew = true
                };
                this.DownloadService.InsertDownload(productVariantSampleDownload);
                productVariantSampleDownloadId = productVariantSampleDownload.DownloadId;
            }

            bool isRecurring = cbIsRecurring.Checked;
            int cycleLength = txtCycleLength.Value;
            RecurringProductCyclePeriodEnum cyclePeriod = (RecurringProductCyclePeriodEnum)Enum.ToObject(typeof(RecurringProductCyclePeriodEnum), int.Parse(this.ddlCyclePeriod.SelectedItem.Value));
            int totalCycles = txtTotalCycles.Value;

            bool isShipEnabled = cbIsShipEnabled.Checked;
            bool isFreeShipping = cbIsFreeShipping.Checked;
            decimal additionalShippingCharge = txtAdditionalShippingCharge.Value;
            bool isTaxExempt = cbIsTaxExempt.Checked;
            int taxCategoryId = int.Parse(this.ddlTaxCategory.SelectedItem.Value);
            int manageStock = Convert.ToInt32(ddlManageStock.SelectedValue);
            int stockQuantity = txtStockQuantity.Value;
            bool displayStockAvailability = cbDisplayStockAvailability.Checked;
            bool displayStockQuantity = cbDisplayStockQuantity.Checked;
            int minStockQuantity = txtMinStockQuantity.Value;
            LowStockActivityEnum lowStockActivity = (LowStockActivityEnum)Enum.ToObject(typeof(LowStockActivityEnum), int.Parse(this.ddlLowStockActivity.SelectedItem.Value));
            int notifyForQuantityBelow = txtNotifyForQuantityBelow.Value;
            int backorders = int.Parse(this.ddlBackorders.SelectedItem.Value);
            int orderMinimumQuantity = txtOrderMinimumQuantity.Value;
            int orderMaximumQuantity = txtOrderMaximumQuantity.Value;
            int warehouseId = int.Parse(this.ddlWarehouse.SelectedItem.Value);
            bool disableBuyButton = cbDisableBuyButton.Checked;
            bool callForPrice = cbCallForPrice.Checked;
            decimal price = txtPrice.Value;
            decimal oldPrice = txtOldPrice.Value;
            decimal productCost = txtProductCost.Value;
            bool customerEntersPrice = cbCustomerEntersPrice.Checked;
            decimal minimumCustomerEnteredPrice = txtMinimumCustomerEnteredPrice.Value;
            decimal maximumCustomerEnteredPrice = txtMaximumCustomerEnteredPrice.Value;
            decimal weight = txtWeight.Value;
            decimal length = txtLength.Value;
            decimal width = txtWidth.Value;
            decimal height = txtHeight.Value;
            DateTime? availableStartDateTime = ctrlAvailableStartDateTimePicker.SelectedDate;
            DateTime? availableEndDateTime = ctrlAvailableEndDateTimePicker.SelectedDate;
            if (availableStartDateTime.HasValue)
            {
                availableStartDateTime = DateTime.SpecifyKind(availableStartDateTime.Value, DateTimeKind.Utc);
            }
            if (availableEndDateTime.HasValue)
            {
                availableEndDateTime = DateTime.SpecifyKind(availableEndDateTime.Value, DateTimeKind.Utc);
            }

            //product
            var product = new Product()
            {
                Name = name,
                ShortDescription = shortDescription,
                FullDescription = fullDescription,
                AdminComment = adminComment,
                TemplateId = templateId,
                ShowOnHomePage = showOnHomePage,
                AllowCustomerReviews = allowCustomerReviews,
                AllowCustomerRatings = allowCustomerRatings,
                Published = published,
                CreatedOn = nowDT,
                UpdatedOn = nowDT
            };

            this.ProductService.InsertProduct(product);

            //product variant
            var productVariant = new ProductVariant()
            {
                ProductId = product.ProductId,
                SKU = sku,
                ManufacturerPartNumber = manufacturerPartNumber,
                IsGiftCard = isGiftCard,
                GiftCardType = giftCardType,
                IsDownload = isDownload,
                DownloadId = productVariantDownloadId,
                UnlimitedDownloads = unlimitedDownloads,
                MaxNumberOfDownloads = maxNumberOfDownloads,
                DownloadExpirationDays = downloadExpirationDays,
                DownloadActivationType = (int)downloadActivationType,
                HasSampleDownload = hasSampleDownload,
                SampleDownloadId = productVariantSampleDownloadId,
                HasUserAgreement = hasUserAgreement,
                UserAgreementText = userAgreementText,
                IsRecurring = isRecurring,
                CycleLength = cycleLength,
                CyclePeriod = (int)cyclePeriod,
                TotalCycles = totalCycles,
                IsShipEnabled = isShipEnabled,
                IsFreeShipping = isFreeShipping,
                AdditionalShippingCharge = additionalShippingCharge,
                IsTaxExempt = isTaxExempt,
                TaxCategoryId = taxCategoryId,
                ManageInventory = manageStock,
                StockQuantity = stockQuantity,
                DisplayStockAvailability = displayStockAvailability,
                DisplayStockQuantity = displayStockQuantity,
                MinStockQuantity = minStockQuantity,
                LowStockActivityId = (int)lowStockActivity,
                NotifyAdminForQuantityBelow = notifyForQuantityBelow,
                Backorders = backorders,
                OrderMinimumQuantity = orderMinimumQuantity,
                OrderMaximumQuantity = orderMaximumQuantity,
                WarehouseId = warehouseId,
                DisableBuyButton = disableBuyButton,
                CallForPrice = callForPrice,
                Price = price,
                OldPrice = oldPrice,
                ProductCost = productCost,
                CustomerEntersPrice = customerEntersPrice,
                MinimumCustomerEnteredPrice = minimumCustomerEnteredPrice,
                MaximumCustomerEnteredPrice = maximumCustomerEnteredPrice,
                Weight = weight,
                Length = length,
                Width = width,
                Height = height,
                AvailableStartDateTime = availableStartDateTime,
                AvailableEndDateTime = availableEndDateTime,
                Published = published,
                Deleted = false,
                DisplayOrder = 1,
                CreatedOn = nowDT,
                UpdatedOn = nowDT
            };

            this.ProductService.InsertProductVariant(productVariant);

            SaveLocalizableContent(product);

            //product tags
            string[] newProductTags = ParseProductTags(txtProductTags.Text);
            foreach (string productTagName in newProductTags)
            {
                ProductTag productTag = null;
                var productTag2 = this.ProductService.GetProductTagByName(productTagName);
                if (productTag2 == null)
                {
                    //add new product tag
                    productTag = new ProductTag()
                    {
                        Name = productTagName,
                        ProductCount = 0
                    };
                    this.ProductService.InsertProductTag(productTag);
                }
                else
                {
                    productTag = productTag2;
                }
                this.ProductService.AddProductTagMapping(product.ProductId, productTag.ProductTagId);
            }

            return product;
        }
        protected void BindProductVariantInfo(ProductVariant productVariant)
        {
            //btnAddToWishlist.Visible = this.SettingManager.GetSettingValueBoolean("Common.EnableWishlist");

            //sku
            if (this.SettingManager.GetSettingValueBoolean("Display.Products.ShowSKU") &&
                !String.IsNullOrEmpty(productVariant.SKU))
            {
                phSKU.Visible = true;
                lSKU.Text = Server.HtmlEncode(productVariant.SKU);
            }
            else
            {
                phSKU.Visible = false;
            }

            //manufacturer part number
            if (this.SettingManager.GetSettingValueBoolean("Display.Products.ShowManufacturerPartNumber") &&
                !String.IsNullOrEmpty(productVariant.ManufacturerPartNumber))
            {
                phManufacturerPartNumber.Visible = true;
                lManufacturerPartNumber.Text = Server.HtmlEncode(productVariant.ManufacturerPartNumber);
            }
            else
            {
                phManufacturerPartNumber.Visible = false;
            }

            //ctrlTierPrices.ProductVariantId = productVariant.ProductVariantId;
            ctrlProductAttributes.ProductVariantId = productVariant.ProductVariantId;
            ctrlGiftCardAttributes.ProductVariantId = productVariant.ProductVariantId;
            ctrlProductPrice.ProductVariantId = productVariant.ProductVariantId;

            //stock
            string stockMessage = productVariant.FormatStockMessage();
            if (!String.IsNullOrEmpty(stockMessage))
            {
                lblStockAvailablity.Text = stockMessage;
            }
            else
            {
                pnlStockAvailablity.Visible = false;
            }

            //price entered by a customer
            if (productVariant.CustomerEntersPrice)
            {
                decimal minimumCustomerEnteredPrice = this.CurrencyService.ConvertCurrency(productVariant.MinimumCustomerEnteredPrice, this.CurrencyService.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency);
                decimal maximumCustomerEnteredPrice = this.CurrencyService.ConvertCurrency(productVariant.MaximumCustomerEnteredPrice, this.CurrencyService.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency);
                txtCustomerEnteredPrice.Visible = true;
                txtCustomerEnteredPrice.ValidationGroup = string.Format("ProductVariant{0}", productVariant.ProductVariantId);
                txtCustomerEnteredPrice.Value = minimumCustomerEnteredPrice;
                txtCustomerEnteredPrice.MinimumValue = minimumCustomerEnteredPrice.ToString();
                txtCustomerEnteredPrice.MaximumValue = maximumCustomerEnteredPrice.ToString();
                txtCustomerEnteredPrice.RangeErrorMessage = string.Format(GetLocaleResourceString("Products.CustomerEnteredPrice.Range"),
                    PriceHelper.FormatPrice(minimumCustomerEnteredPrice, false, false),
                        PriceHelper.FormatPrice(maximumCustomerEnteredPrice, false, false));
            }
            else
            {
                txtCustomerEnteredPrice.Visible = false;
            }

            //buttons
            if(!productVariant.DisableBuyButton)
            {
                txtQuantity.ValidationGroup = string.Format("ProductVariant{0}", productVariant.ProductVariantId);
                btnAddToCart.ValidationGroup = string.Format("ProductVariant{0}", productVariant.ProductVariantId);
                btnAddToWishlist.ValidationGroup = string.Format("ProductVariant{0}", productVariant.ProductVariantId);

                txtQuantity.Value = productVariant.OrderMinimumQuantity;
            }
            else
            {
                txtQuantity.Visible = false;
                btnAddToCart.Visible = false;
                btnAddToWishlist.Visible = false;
            }

            //sample downlaods
            if(pnlDownloadSample != null && hlDownloadSample != null)
            {
                if(productVariant.IsDownload && productVariant.HasSampleDownload)
                {
                    pnlDownloadSample.Visible = true;
                    hlDownloadSample.NavigateUrl = this.DownloadService.GetSampleDownloadUrl(productVariant);
                }
                else
                {
                    pnlDownloadSample.Visible = false;
                }
            }

            //final check - hide prices for non-registered customers
            if (!this.SettingManager.GetSettingValueBoolean("Common.HidePricesForNonRegistered") ||
                    (NopContext.Current.User != null &&
                    !NopContext.Current.User.IsGuest))
            {
                //
            }
            else
            {
                txtCustomerEnteredPrice.Visible = false;
                txtQuantity.Visible = false;
                btnAddToCart.Visible = false;
                btnAddToWishlist.Visible = false;
            }
        }
示例#7
0
        /// <summary>
        /// Gets allowed discounts
        /// </summary>
        /// <param name="productVariant">Product variant</param>
        /// <param name="customer">Customer</param>
        /// <returns>Discounts</returns>
        protected static DiscountCollection GetAllowedDiscounts(ProductVariant productVariant, Customer customer)
        {
            int customerID = 0;
            if (customer != null)
                customerID = customer.CustomerID;

            DiscountCollection allowedDiscounts = new DiscountCollection();

            //CustomerRoleCollection customerRoles = CustomerManager.GetCustomerRolesByCustomerID(customerID);
            //foreach (CustomerRole _customerRole in customerRoles)
            //    foreach (Discount _discount in _customerRole.Discounts)
            //        if (_discount.IsActive && _discount.DiscountType == DiscountTypeEnum.AssignedToSKUs && !allowedDiscounts.ContainsDiscount(_discount.Name))
            //            allowedDiscounts.Add(_discount);

            string customerCouponCode = string.Empty;
            if (customer != null)
                customerCouponCode = customer.LastAppliedCouponCode;

            foreach (Discount _discount in productVariant.AllDiscounts)
            {
                if (_discount.IsActive(customerCouponCode) &&
                    _discount.DiscountType == DiscountTypeEnum.AssignedToSKUs &&
                    !allowedDiscounts.ContainsDiscount(_discount.Name))
                {
                    switch (_discount.DiscountRequirement)
                    {
                        case DiscountRequirementEnum.None:
                            {
                                allowedDiscounts.Add(_discount);
                            }
                            break;
                        case DiscountRequirementEnum.MustBeAssignedToCustomerRole:
                            {
                                if (_discount.CheckCustomerRoleRequirement(customerID))
                                    allowedDiscounts.Add(_discount);
                            }
                            break;
                        default:
                            break;
                    }
                }
            }

            ProductCategoryCollection productCategories = CategoryManager.GetProductCategoriesByProductID(productVariant.ProductID);
            foreach (ProductCategory _productCategory in productCategories)
            {
                Category category = _productCategory.Category;
                if (category != null)
                {
                    foreach (Discount _discount in category.Discounts)
                    {
                        if (_discount.IsActive(customerCouponCode) &&
                            _discount.DiscountType == DiscountTypeEnum.AssignedToSKUs &&
                            !allowedDiscounts.ContainsDiscount(_discount.Name))
                        {
                            switch (_discount.DiscountRequirement)
                            {
                                case DiscountRequirementEnum.None:
                                    {
                                        allowedDiscounts.Add(_discount);
                                    }
                                    break;
                                case DiscountRequirementEnum.MustBeAssignedToCustomerRole:
                                    {
                                        allowedDiscounts.Add(_discount);
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                }
            }
            return allowedDiscounts;
        }
示例#8
0
 /// <summary>
 /// Gets discount amount
 /// </summary>
 /// <param name="productVariant">Product variant</param>
 /// <param name="customer">The customer</param>
 /// <returns>Discount amount</returns>
 public static decimal GetDiscountAmount(ProductVariant productVariant, Customer customer)
 {
     return GetDiscountAmount(productVariant, customer, decimal.Zero);
 }
示例#9
0
        /// <summary>
        /// Gets the final price
        /// </summary>
        /// <param name="productVariant">Product variant</param>
        /// <param name="customer">The customer</param>
        /// <param name="AdditionalCharge">Additional charge</param>
        /// <param name="includeDiscounts">A value indicating whether include discounts or not for final price computation</param>
        /// <returns>Final price</returns>
        public static decimal GetFinalPrice(ProductVariant productVariant, Customer customer, decimal AdditionalCharge, bool includeDiscounts)
        {
            decimal result = decimal.Zero;
            if (includeDiscounts)
            {
                decimal discountAmount = GetDiscountAmount(productVariant, customer, AdditionalCharge);
                result = productVariant.Price + AdditionalCharge - discountAmount;
            }
            else
            {
                result = productVariant.Price + AdditionalCharge;
            }
            if (result < decimal.Zero)
                result = decimal.Zero;

            if (HttpContext.Current.Request.Cookies["Currency"] != null && HttpContext.Current.Request.Cookies["Currency"].Value == "USD")
            {
                result = Math.Round(PriceConverter.ToUsd(result));
            }

            return result;
        }
示例#10
0
        /// <summary>
        /// Updates the product variant
        /// </summary>
        /// <param name="productVariant">The product variant</param>
        public void UpdateProductVariant(ProductVariant productVariant)
        {
            if (productVariant == null)
                throw new ArgumentNullException("productVariant");

            productVariant.Name = CommonHelper.EnsureNotNull(productVariant.Name);
            productVariant.Name = CommonHelper.EnsureMaximumLength(productVariant.Name, 400);
            productVariant.SKU = CommonHelper.EnsureNotNull(productVariant.SKU);
            productVariant.SKU = productVariant.SKU.Trim();
            productVariant.SKU = CommonHelper.EnsureMaximumLength(productVariant.SKU, 100);
            productVariant.Description = CommonHelper.EnsureNotNull(productVariant.Description);
            productVariant.Description = CommonHelper.EnsureMaximumLength(productVariant.Description, 4000);
            productVariant.AdminComment = CommonHelper.EnsureNotNull(productVariant.AdminComment);
            productVariant.AdminComment = CommonHelper.EnsureMaximumLength(productVariant.AdminComment, 4000);
            productVariant.ManufacturerPartNumber = CommonHelper.EnsureNotNull(productVariant.ManufacturerPartNumber);
            productVariant.ManufacturerPartNumber = CommonHelper.EnsureMaximumLength(productVariant.ManufacturerPartNumber, 100);
            productVariant.UserAgreementText = CommonHelper.EnsureNotNull(productVariant.UserAgreementText);

            if (!_context.IsAttached(productVariant))
                _context.ProductVariants.Attach(productVariant);

            _context.SaveChanges();

            if (this.CacheEnabled)
            {
                _cacheManager.RemoveByPattern(PRODUCTS_PATTERN_KEY);
                _cacheManager.RemoveByPattern(PRODUCTVARIANTS_PATTERN_KEY);
                _cacheManager.RemoveByPattern(TIERPRICES_PATTERN_KEY);
                _cacheManager.RemoveByPattern(CUSTOMERROLEPRICES_PATTERN_KEY);
            }

            //raise event
            EventContext.Current.OnProductVariantUpdated(null,
                new ProductVariantEventArgs() { ProductVariant = productVariant });
        }
示例#11
0
 /// <summary>
 /// Gets discount amount
 /// </summary>
 /// <param name="productVariant">Product variant</param>
 /// <param name="customer">The customer</param>
 /// <returns>Discount amount</returns>
 public static decimal GetDiscountAmount(ProductVariant productVariant, Customer customer)
 {
     return(GetDiscountAmount(productVariant, customer, decimal.Zero));
 }
示例#12
0
        /// <summary>
        /// Gets discount amount
        /// </summary>
        /// <param name="productVariant">Product variant</param>
        /// <returns>Discount amount</returns>
        public static decimal GetDiscountAmount(ProductVariant productVariant)
        {
            Customer customer = NopContext.Current.User;

            return(GetDiscountAmount(productVariant, customer, decimal.Zero));
        }
示例#13
0
 /// <summary>
 /// Gets the final price
 /// </summary>
 /// <param name="productVariant">Product variant</param>
 /// <param name="customer">The customer</param>
 /// <param name="includeDiscounts">A value indicating whether include discounts or not for final price computation</param>
 /// <returns>Final price</returns>
 public static decimal GetFinalPrice(ProductVariant productVariant, Customer customer, bool includeDiscounts)
 {
     return(GetFinalPrice(productVariant, customer, decimal.Zero, includeDiscounts));
 }
示例#14
0
        /// <summary>
        /// Gets the final price
        /// </summary>
        /// <param name="productVariant">Product variant</param>
        /// <param name="includeDiscounts">A value indicating whether include discounts or not for final price computation</param>
        /// <returns>Final price</returns>
        public static decimal GetFinalPrice(ProductVariant productVariant, bool includeDiscounts)
        {
            Customer customer = NopContext.Current.User;

            return(GetFinalPrice(productVariant, customer, includeDiscounts));
        }
示例#15
0
 /// <summary>
 /// Gets a preferred discount
 /// </summary>
 /// <param name="productVariant">Product variant</param>
 /// <param name="customer">Customer</param>
 /// <returns>Preferred discount</returns>
 protected static Discount GetPreferredDiscount(ProductVariant productVariant, Customer customer)
 {
     return(GetPreferredDiscount(productVariant, customer, decimal.Zero));
 }
示例#16
0
        /// <summary>
        /// Sends a "quantity below" notification to a store owner
        /// </summary>
        /// <param name="productVariant">Product variant</param>
        /// <param name="languageId">Message language identifier</param>
        /// <returns>Queued email identifier</returns>
        public int SendQuantityBelowStoreOwnerNotification(ProductVariant productVariant, int languageId)
        {
            if (productVariant == null)
                throw new ArgumentNullException("productVariant");

            string templateName = "QuantityBelow.StoreOwnerNotification";
            LocalizedMessageTemplate localizedMessageTemplate = this.GetLocalizedMessageTemplate(templateName, languageId);
            if(localizedMessageTemplate == null || !localizedMessageTemplate.IsActive)
                return 0;

            var emailAccount = localizedMessageTemplate.EmailAccount;

            string subject = ReplaceMessageTemplateTokens(productVariant, localizedMessageTemplate.Subject, languageId);
            string body = ReplaceMessageTemplateTokens(productVariant, localizedMessageTemplate.Body, languageId);
            string bcc = localizedMessageTemplate.BccEmailAddresses;
            var from = new MailAddress(emailAccount.Email, emailAccount.DisplayName);
            var to = new MailAddress(emailAccount.Email, emailAccount.DisplayName);
            var queuedEmail = InsertQueuedEmail(5, from, to, string.Empty, bcc, subject, body,
                DateTime.UtcNow, 0, null, emailAccount.EmailAccountId);
            return queuedEmail.QueuedEmailId;
        }
        protected void SaveLocalizableContent(ProductVariant productVariant)
        {
            if (productVariant == null)
                return;

            if (!this.HasLocalizableContent)
                return;

            foreach (RepeaterItem item in rptrLanguageDivs.Items)
            {
                if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
                {
                    var txtLocalizedName = (TextBox)item.FindControl("txtLocalizedName");
                    var txtLocalizedDescription = (FCKeditor)item.FindControl("txtLocalizedDescription");
                    var lblLanguageId = (Label)item.FindControl("lblLanguageId");

                    int languageId = int.Parse(lblLanguageId.Text);
                    string name = txtLocalizedName.Text;
                    string description = txtLocalizedDescription.Value;

                    bool allFieldsAreEmpty = (string.IsNullOrEmpty(name) && string.IsNullOrEmpty(description));

                    var content = this.ProductService.GetProductVariantLocalizedByProductVariantIdAndLanguageId(productVariant.ProductVariantId, languageId);
                    if (content == null)
                    {
                        if (!allFieldsAreEmpty && languageId > 0)
                        {
                            //only insert if one of the fields are filled out (avoid too many empty records in db...)
                            content = new ProductVariantLocalized()
                            {
                                ProductVariantId = productVariant.ProductVariantId,
                                LanguageId = languageId,
                                Name = name,
                                Description = description
                            };
                            this.ProductService.InsertProductVariantLocalized(content);
                        }
                    }
                    else
                    {
                        if (languageId > 0)
                        {
                            content.LanguageId = languageId;
                            content.Name = name;
                            content.Description = description;
                            this.ProductService.UpdateProductVariantLocalized(content);
                        }
                    }
                }
            }
        }
示例#18
0
        /// <summary>
        /// Gets allowed discounts
        /// </summary>
        /// <param name="productVariant">Product variant</param>
        /// <param name="customer">Customer</param>
        /// <returns>Discounts</returns>
        protected static DiscountCollection GetAllowedDiscounts(ProductVariant productVariant, Customer customer)
        {
            int customerID = 0;

            if (customer != null)
            {
                customerID = customer.CustomerID;
            }

            DiscountCollection allowedDiscounts = new DiscountCollection();

            //CustomerRoleCollection customerRoles = CustomerManager.GetCustomerRolesByCustomerID(customerID);
            //foreach (CustomerRole _customerRole in customerRoles)
            //    foreach (Discount _discount in _customerRole.Discounts)
            //        if (_discount.IsActive && _discount.DiscountType == DiscountTypeEnum.AssignedToSKUs && !allowedDiscounts.ContainsDiscount(_discount.Name))
            //            allowedDiscounts.Add(_discount);

            string customerCouponCode = string.Empty;

            if (customer != null)
            {
                customerCouponCode = customer.LastAppliedCouponCode;
            }

            foreach (Discount _discount in productVariant.AllDiscounts)
            {
                if (_discount.IsActive(customerCouponCode) &&
                    _discount.DiscountType == DiscountTypeEnum.AssignedToSKUs &&
                    !allowedDiscounts.ContainsDiscount(_discount.Name))
                {
                    switch (_discount.DiscountRequirement)
                    {
                    case DiscountRequirementEnum.None:
                    {
                        allowedDiscounts.Add(_discount);
                    }
                    break;

                    case DiscountRequirementEnum.MustBeAssignedToCustomerRole:
                    {
                        if (_discount.CheckCustomerRoleRequirement(customerID))
                        {
                            allowedDiscounts.Add(_discount);
                        }
                    }
                    break;

                    default:
                        break;
                    }
                }
            }

            ProductCategoryCollection productCategories = CategoryManager.GetProductCategoriesByProductID(productVariant.ProductID);

            foreach (ProductCategory _productCategory in productCategories)
            {
                Category category = _productCategory.Category;
                if (category != null)
                {
                    foreach (Discount _discount in category.Discounts)
                    {
                        if (_discount.IsActive(customerCouponCode) &&
                            _discount.DiscountType == DiscountTypeEnum.AssignedToSKUs &&
                            !allowedDiscounts.ContainsDiscount(_discount.Name))
                        {
                            switch (_discount.DiscountRequirement)
                            {
                            case DiscountRequirementEnum.None:
                            {
                                allowedDiscounts.Add(_discount);
                            }
                            break;

                            case DiscountRequirementEnum.MustBeAssignedToCustomerRole:
                            {
                                allowedDiscounts.Add(_discount);
                            }
                            break;

                            default:
                                break;
                            }
                        }
                    }
                }
            }
            return(allowedDiscounts);
        }
示例#19
0
        /// <summary>
        /// Formats the stock availability/quantity message
        /// </summary>
        /// <param name="productVariant">Product variant</param>
        /// <returns>The stock message</returns>
        public static string FormatStockMessage(ProductVariant productVariant)
        {
            if (productVariant == null)
            {
                throw new ArgumentNullException("productVariant");
            }

            string stockMessage = string.Empty;

            if (productVariant.ManageInventory == (int)ManageInventoryMethodEnum.ManageStock &&
                productVariant.DisplayStockAvailability)
            {
                switch (productVariant.Backorders)
                {
                case (int)BackordersModeEnum.NoBackorders:
                {
                    if (productVariant.StockQuantity > 0)
                    {
                        if (productVariant.DisplayStockQuantity)
                        {
                            //display "in stock" with stock quantity
                            stockMessage = string.Format(LocalizationManager.GetLocaleResourceString("Products.Availability"), string.Format(LocalizationManager.GetLocaleResourceString("Products.InStockWithQuantity"), productVariant.StockQuantity));
                        }
                        else
                        {
                            //display "in stock" without stock quantity
                            stockMessage = string.Format(LocalizationManager.GetLocaleResourceString("Products.Availability"), LocalizationManager.GetLocaleResourceString("Products.InStock"));
                        }
                    }
                    else
                    {
                        //display "out of stock"
                        stockMessage = string.Format(LocalizationManager.GetLocaleResourceString("Products.Availability"), LocalizationManager.GetLocaleResourceString("Products.OutOfStock"));
                    }
                }
                break;

                case (int)BackordersModeEnum.AllowQtyBelow0:
                {
                    if (productVariant.StockQuantity > 0)
                    {
                        if (productVariant.DisplayStockQuantity)
                        {
                            //display "in stock" with stock quantity
                            stockMessage = string.Format(LocalizationManager.GetLocaleResourceString("Products.Availability"), string.Format(LocalizationManager.GetLocaleResourceString("Products.InStockWithQuantity"), productVariant.StockQuantity));
                        }
                        else
                        {
                            //display "in stock" without stock quantity
                            stockMessage = string.Format(LocalizationManager.GetLocaleResourceString("Products.Availability"), LocalizationManager.GetLocaleResourceString("Products.InStock"));
                        }
                    }
                    else
                    {
                        //display "in stock" without stock quantity
                        stockMessage = string.Format(LocalizationManager.GetLocaleResourceString("Products.Availability"), LocalizationManager.GetLocaleResourceString("Products.InStock"));
                    }
                }
                break;

                case (int)BackordersModeEnum.AllowQtyBelow0AndNotifyCustomer:
                {
                    if (productVariant.StockQuantity > 0)
                    {
                        if (productVariant.DisplayStockQuantity)
                        {
                            //display "in stock" with stock quantity
                            stockMessage = string.Format(LocalizationManager.GetLocaleResourceString("Products.Availability"), string.Format(LocalizationManager.GetLocaleResourceString("Products.InStockWithQuantity"), productVariant.StockQuantity));
                        }
                        else
                        {
                            //display "in stock" without stock quantity
                            stockMessage = string.Format(LocalizationManager.GetLocaleResourceString("Products.Availability"), LocalizationManager.GetLocaleResourceString("Products.InStock"));
                        }
                    }
                    else
                    {
                        //display "backorder" without stock quantity
                        stockMessage = string.Format(LocalizationManager.GetLocaleResourceString("Products.Availability"), LocalizationManager.GetLocaleResourceString("Products.Backordering"));
                    }
                }
                break;

                default:
                    break;
                }
            }

            return(stockMessage);
        }
示例#20
0
 /// <summary>
 /// Gets price
 /// </summary>
 /// <param name="productVariant">Product variant</param>
 /// <param name="taxClassId">Tax class identifier</param>
 /// <param name="price">Price</param>
 /// <param name="includingTax">A value indicating whether calculated price should include tax</param>
 /// <param name="customer">Customer</param>
 /// <param name="priceIncludesTax">A value indicating whether price already includes tax</param>
 /// <param name="taxRate">Tax rate</param>
 /// <returns>Price</returns>
 public static decimal GetPrice(ProductVariant productVariant, int taxClassId,
     decimal price, bool includingTax, Customer customer, out decimal taxRate, 
     bool priceIncludesTax)
 {
     string error = string.Empty;
     return GetPrice(productVariant, taxClassId, price, includingTax,
         customer, priceIncludesTax, out taxRate, ref error);
 }
示例#21
0
 /// <summary>
 /// Gets discount amount
 /// </summary>
 /// <param name="productVariant">Product variant</param>
 /// <returns>Discount amount</returns>
 public static decimal GetDiscountAmount(ProductVariant productVariant)
 {
     Customer customer = NopContext.Current.User;
     return GetDiscountAmount(productVariant, customer, decimal.Zero);
 }
示例#22
0
        /// <summary>
        /// Gets price
        /// </summary>
        /// <param name="productVariant">Product variant</param>
        /// <param name="taxClassId">Tax class identifier</param>
        /// <param name="price">Price</param>
        /// <param name="includingTax">A value indicating whether calculated price should include tax</param>
        /// <param name="customer">Customer</param>
        /// <param name="priceIncludesTax">A value indicating whether price already includes tax</param>
        /// <param name="taxRate">Tax rate</param>
        /// <param name="error">Error</param>
        /// <returns>Price</returns>
        public static decimal GetPrice(ProductVariant productVariant, int taxClassId,
            decimal price, bool includingTax, Customer customer,
            bool priceIncludesTax, out decimal taxRate, ref string error)
        {
            taxRate = GetTaxRate(productVariant, taxClassId, customer, ref error);

            if (priceIncludesTax)
            {
                if (!includingTax)
                {
                    price = CalculatePrice(price, taxRate, false);
                }
            }
            else
            {
                if (includingTax)
                {
                    price = CalculatePrice(price, taxRate, true);
                }
            }

            if (price < decimal.Zero)
                price = decimal.Zero;
            price = Math.Round(price, 2);

            return price;
        }
示例#23
0
 /// <summary>
 /// Gets discount amount
 /// </summary>
 /// <param name="productVariant">Product variant</param>
 /// <param name="customer">The customer</param>
 /// <param name="AdditionalCharge">Additional charge</param>
 /// <returns>Discount amount</returns>
 public static decimal GetDiscountAmount(ProductVariant productVariant, Customer customer, decimal AdditionalCharge)
 {
     decimal preferredDiscountAmount = decimal.Zero;
     Discount preferredDiscount = GetPreferredDiscount(productVariant, customer, AdditionalCharge);
     if (preferredDiscount != null)
     {
         decimal finalPriceWithoutDiscount = GetFinalPrice(productVariant, customer, AdditionalCharge, false);
         preferredDiscountAmount = preferredDiscount.GetDiscountAmount(finalPriceWithoutDiscount);
     }
     return preferredDiscountAmount;
 }
示例#24
0
 /// <summary>
 /// Gets tax rate
 /// </summary>
 /// <param name="productVariant">Product variant</param>
 /// <param name="customer">Customer</param>
 /// <param name="error">Error</param>
 /// <returns>Tax rate</returns>
 public static decimal GetTaxRate(ProductVariant productVariant, 
     Customer customer, ref string error)
 {
     return GetTaxRate(productVariant, 0, customer, ref error);
 }
示例#25
0
        /// <summary>
        /// Gets a sample download url for a product variant
        /// </summary>
        /// <param name="productVariant">Product variant instance</param>
        /// <returns>Download url</returns>
        public static string GetSampleDownloadUrl(ProductVariant productVariant)
        {
            if (productVariant == null)
                throw new ArgumentNullException("productVariant");

            string url = string.Empty;
            if (productVariant.IsDownload && productVariant.HasSampleDownload)
            {
                url = CommonHelper.GetStoreLocation() + "GetDownload.ashx?SampleDownloadProductVariantID=" + productVariant.ProductVariantID.ToString();
            }
            return url;
        }
示例#26
0
        /// <summary>
        /// Gets tax rate
        /// </summary>
        /// <param name="productVariant">Product variant</param>
        /// <param name="taxClassId">Tax class identifier</param>
        /// <param name="customer">Customer</param>
        /// <param name="error">Error</param>
        /// <returns>Tax rate</returns>
        public static decimal GetTaxRate(ProductVariant productVariant, 
            int taxClassId, Customer customer, ref string error)
        {
            //tax exempt
            if (IsTaxExempt(productVariant, customer))
            {
                return decimal.Zero;
            }

            //tax request
            var calculateTaxRequest = CreateCalculateTaxRequest(productVariant, taxClassId, customer);

            //make EU VAT exempt validation (the European Union Value Added Tax)
            if (TaxManager.EUVatEnabled)
            {
                if (IsVatExempt(calculateTaxRequest.Address, calculateTaxRequest.Customer))
                {
                    //return zero if VAT is not chargeable
                    return decimal.Zero;
                }
            }

            //instantiate tax provider
            var activeTaxProvider = TaxManager.ActiveTaxProvider;
            if (activeTaxProvider == null)
                throw new NopException("Tax provider could not be loaded");
            var iTaxProvider = Activator.CreateInstance(Type.GetType(activeTaxProvider.ClassName)) as ITaxProvider;

            //get tax rate
            decimal taxRate = iTaxProvider.GetTaxRate(calculateTaxRequest, ref error);
            return taxRate;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Product product = this.ProductService.GetProductById(this.ProductId);

                if (product != null)
                {
                    lblTitle.Text = Server.HtmlEncode(product.Name);
                    if (product.ProductVariants[0].Vendor.CustomerId !=
                            NopCommerce.BusinessLogic.NopContext.Current.User.Vendor.CustomerId)
                    {
                        //this user is not allowed to edit other items.  Redirect to their
                        //products page.
                        Response.Redirect("Products.aspx");
                    }
                }
                else
                {
                    DateTime nowDT = DateTime.UtcNow;

                    //create new product without activated set.
                    product = new Product()
                    {
                        Name = "New " + NopCommerce.BusinessLogic.NopContext.Current.User.Vendor.CompanyName + " Product ",
                        ShortDescription = String.Empty,
                        FullDescription = String.Empty,
                        AdminComment = "Created",
                        TemplateId = 5, //default for sewbie.
                        ShowOnHomePage = false,
                        AllowCustomerReviews = true,
                        AllowCustomerRatings = true,
                        Published = false,
                        Activated = false,
                        CreatedOn = DateTime.UtcNow,
                        UpdatedOn = DateTime.UtcNow
                    };

                    this.ProductService.InsertProduct(product);

                    ProductVariant prv = new ProductVariant()
                    {
                        ProductId = product.ProductId,
                        Name = product.Name,
                        SKU = String.Empty,
                        Description = String.Empty,
                        AdminComment = "Created",
                        ManufacturerPartNumber = String.Empty,
                        IsGiftCard = false,
                        GiftCardType = 0,
                        IsDownload = false,
                        DownloadId = 0,
                        UnlimitedDownloads = false,
                        MaxNumberOfDownloads = 0,
                        DownloadExpirationDays = 0,
                        DownloadActivationType = 0,
                        HasSampleDownload = false,
                        SampleDownloadId = 0,
                        HasUserAgreement = false,
                        UserAgreementText = String.Empty,
                        IsRecurring = false,
                        CycleLength = 0,
                        CyclePeriod = 0,
                        TotalCycles = 0,
                        IsShipEnabled = false,
                        IsFreeShipping = false,
                        AdditionalShippingCharge = 0,
                        IsTaxExempt = false,
                        TaxCategoryId = 0,
                        ManageInventory = 0,
                        StockQuantity = 1,
                        DisplayStockAvailability = false,
                        DisplayStockQuantity = true,
                        MinStockQuantity = 1,
                        LowStockActivityId = 0,
                        NotifyAdminForQuantityBelow = 1,
                        Backorders = 0,
                        OrderMinimumQuantity = 1,
                        OrderMaximumQuantity = 10000,
                        WarehouseId = 0,
                        DisableBuyButton = false,
                        CallForPrice = false,
                        Price = 0.01M,
                        OldPrice = 0,
                        ProductCost = 0,
                        CustomerEntersPrice = false,
                        MinimumCustomerEnteredPrice = 0,
                        MaximumCustomerEnteredPrice = 0,
                        Weight = 0,
                        Length = 0,
                        Width = 0,
                        Height = 0,
                        PictureId = 0,
                        AvailableStartDateTime = null,
                        AvailableEndDateTime = null,
                        Published = false,
                        Deleted = false,
                        DisplayOrder = 1,
                        VendorId = NopCommerce.BusinessLogic.NopContext.Current.User.CustomerId,
                        CreatedOn = nowDT,
                        UpdatedOn = nowDT
                    };

                    this.ProductService.InsertProductVariant(prv);

                    //we're going to do a redirect here so that the product id makes it into the
                    //query strnig and this page should load as if it's an edit.
                    Response.Redirect("ProductDetails.aspx?productid=" + product.ProductId);
                }
            }
        }
示例#28
0
        /// <summary>
        /// Replaces a message template tokens
        /// </summary>
        /// <param name="productVariant">Product variant instance</param>
        /// <param name="template">Template</param>
        /// <param name="localFormat">Localization Provider Short name (en-US, de-DE, etc.)</param>
        /// <param name="additionalKeys">Additional keys</param>
        /// <param name="affiliateId">Affiliate identifier</param>
        /// <param name="price">Price</param>
        /// <returns>New template</returns>
        protected string ReplaceMessageTemplateTokens(ProductVariant productVariant, 
            string template, string localFormat, NameValueCollection additionalKeys,
            int affiliateId, decimal price)
        {
            NameValueCollection tokens = new NameValueCollection();

            IFormatProvider locProvider = new System.Globalization.CultureInfo(localFormat);

            string strHelper = template;

            while (strHelper.Contains("%"))
            {
                strHelper = strHelper.Substring(strHelper.IndexOf("%") + 1);
                string strToken = strHelper.Substring(0, strHelper.IndexOf("%"));
                string strFormat = "";
                strHelper = strHelper.Substring(strHelper.IndexOf("%") + 1);

                if (strToken.Contains(":"))
                {
                    strFormat = strToken.Substring(strToken.IndexOf(":"));
                    strToken = strToken.Substring(0, strToken.IndexOf(":"));
                }

                if (tokens.Get(strToken + strFormat) == null)
                {
                    switch (strToken.ToLower())
                    {
                        case "store.name":
                            {
                                tokens.Add(strToken + strFormat, String.Format(locProvider, "{0" + strFormat + "}", IoC.Resolve<ISettingManager>().StoreName));
                            }
                            break;
                        case "product.pictureurl":
                            {
                                var pictures = productVariant.Product.ProductPictures;
                                if (pictures.Count > 0)
                                {
                                    tokens.Add(strToken + strFormat, String.Format(locProvider, "{0" + strFormat + "}", IoC.Resolve<IPictureService>().GetPictureUrl(pictures[0].PictureId)));
                                }
                                else
                                {
                                    tokens.Add(strToken + strFormat, String.Format(locProvider, "{0" + strFormat + "}", string.Empty));
                                }
                            }
                            break;
                        case "pv.producturl":
                            {
                                tokens.Add(strToken + strFormat, String.Format(locProvider, "{0" + strFormat + "}", GetProductUrlWithPricelistProvider(productVariant.ProductId, AffiliateId)));
                            }
                            break;
                        case "pv.price":
                            {
                            tokens.Add(strToken + strFormat, String.Format(locProvider, "{0" + strFormat + "}", price));
                            }
                            break;
                        case "pv.name":
                            {
                                tokens.Add(strToken + strFormat, String.Format(locProvider, "{0" + strFormat + "}", productVariant.FullProductName));
                            }
                            break;
                        case "pv.description":
                            {
                                tokens.Add(strToken + strFormat, String.Format(locProvider, "{0" + strFormat + "}", productVariant.Description));
                            }
                            break;
                        case "product.description":
                            {
                                tokens.Add(strToken + strFormat, String.Format(locProvider, "{0" + strFormat + "}", productVariant.Product.FullDescription));
                            }
                            break;
                        case "product.shortdescription":
                            {
                                tokens.Add(strToken + strFormat, String.Format(locProvider, "{0" + strFormat + "}", productVariant.Product.ShortDescription));
                            }
                            break;
                        case "pv.partnumber":
                            {
                                tokens.Add(strToken + strFormat, String.Format(locProvider, "{0" + strFormat + "}", productVariant.ManufacturerPartNumber));
                            }
                            break;
                        case "product.manufacturer":
                            {
                                string mans = string.Empty;
                                var productManufacturers = productVariant.Product.ProductManufacturers;
                                foreach (ProductManufacturer pm in productManufacturers)
                                {
                                    mans += ", " + pm.Manufacturer.Name;
                                }
                                if (mans.Length != 0)
                                    mans = mans.Substring(2);

                                if (productManufacturers.Count > 0)
                                    tokens.Add(strToken + strFormat, String.Format(locProvider, "{0" + strFormat + "}", mans));
                            }
                            break;
                        case "product.category":
                            {
                                string cats = string.Empty;
                                var productCategories = productVariant.Product.ProductCategories;
                                foreach (ProductCategory pc in productCategories)
                                {
                                    cats += ", " + pc.Category.Name;
                                }
                                if (cats.Length != 0)
                                    cats = cats.Substring(2);

                                if (productCategories.Count > 0)
                                    tokens.Add(strToken + strFormat, String.Format(locProvider, "{0" + strFormat + "}", cats));
                            }
                            break;
                        case "product.shippingcosts":
                            {
                            }
                            break;
                        default:
                            {
                            tokens.Add(strToken + strFormat, strToken + strFormat);
                            }
                            break;
                    }
                }

            }

            foreach (string token in tokens.Keys)
                template = template.Replace(string.Format(@"%{0}%", token), tokens[token]);

            foreach (string token in additionalKeys.Keys)
                template = template.Replace(string.Format(@"%{0}%", token), additionalKeys[token]);

            return template;
        }
示例#29
0
        private static ProductVariant DBMapping(DBProductVariant dbItem)
        {
            if (dbItem == null)
                return null;

            ProductVariant item = new ProductVariant();
            item.ProductVariantID = dbItem.ProductVariantID;
            item.ProductID = dbItem.ProductID;
            item.Name = dbItem.Name;
            item.SKU = dbItem.SKU;
            item.Description = dbItem.Description;
            item.AdminComment = dbItem.AdminComment;
            item.ManufacturerPartNumber = dbItem.ManufacturerPartNumber;
            item.IsDownload = dbItem.IsDownload;
            item.DownloadID = dbItem.DownloadID;
            item.UnlimitedDownloads = dbItem.UnlimitedDownloads;
            item.MaxNumberOfDownloads = dbItem.MaxNumberOfDownloads;
            item.HasSampleDownload = dbItem.HasSampleDownload;
            item.SampleDownloadID = dbItem.SampleDownloadID;
            item.IsShipEnabled = dbItem.IsShipEnabled;
            item.IsFreeShipping = dbItem.IsFreeShipping;
            item.AdditionalShippingCharge = dbItem.AdditionalShippingCharge;
            item.IsTaxExempt = dbItem.IsTaxExempt;
            item.TaxCategoryID = dbItem.TaxCategoryID;
            item.ManageInventory = dbItem.ManageInventory;
            item.StockQuantity = dbItem.StockQuantity;
            item.MinStockQuantity = dbItem.MinStockQuantity;
            item.LowStockActivityID = dbItem.LowStockActivityID;
            item.NotifyAdminForQuantityBelow = dbItem.NotifyAdminForQuantityBelow;
            item.OrderMinimumQuantity = dbItem.OrderMinimumQuantity;
            item.OrderMaximumQuantity = dbItem.OrderMaximumQuantity;
            item.WarehouseId = dbItem.WarehouseId;
            item.DisableBuyButton = dbItem.DisableBuyButton;
            item.Price = dbItem.Price;
            item.OldPrice = dbItem.OldPrice;
            item.Weight = dbItem.Weight;
            item.Length = dbItem.Length;
            item.Width = dbItem.Width;
            item.Height = dbItem.Height;
            item.PictureID = dbItem.PictureID;
            item.AvailableStartDateTime = dbItem.AvailableStartDateTime;
            item.AvailableEndDateTime = dbItem.AvailableEndDateTime;
            item.Published = dbItem.Published;
            item.Deleted = dbItem.Deleted;
            item.DisplayOrder = dbItem.DisplayOrder;
            item.CreatedOn = dbItem.CreatedOn;
            item.UpdatedOn = dbItem.UpdatedOn;
            return item;
        }
示例#30
0
 /// <summary>
 /// Gets a preferred discount
 /// </summary>
 /// <param name="productVariant">Product variant</param>
 /// <param name="customer">Customer</param>
 /// <returns>Preferred discount</returns>
 protected static Discount GetPreferredDiscount(ProductVariant productVariant, Customer customer)
 {
     return GetPreferredDiscount(productVariant, customer, decimal.Zero);
 }
示例#31
0
 /// <summary>
 /// Gets a preferred discount
 /// </summary>
 /// <param name="productVariant">Product variant</param>
 /// <param name="customer">Customer</param>
 /// <param name="AdditionalCharge">Additional charge</param>
 /// <returns>Preferred discount</returns>
 protected static Discount GetPreferredDiscount(ProductVariant productVariant, Customer customer, decimal AdditionalCharge)
 {
     DiscountCollection allowedDiscounts = GetAllowedDiscounts(productVariant, customer);
     decimal finalPriceWithoutDiscount = GetFinalPrice(productVariant, customer, AdditionalCharge, false);
     Discount preferredDiscount = DiscountManager.GetPreferredDiscount(allowedDiscounts, finalPriceWithoutDiscount);
     return preferredDiscount;
 }
示例#32
0
        /// <summary>
        /// Gets a tier price
        /// </summary>
        /// <param name="productVariant">Product variant</param>
        /// <param name="Quantity">Quantity</param>
        /// <returns>Price</returns>
        protected static decimal GetTierPrice(ProductVariant productVariant, int Quantity)
        {
            TierPriceCollection tierPrices = productVariant.TierPrices;

            int previousQty = 1;
            decimal previousPrice = productVariant.Price;
            foreach (TierPrice tierPrice in tierPrices)
            {
                if (Quantity < tierPrice.Quantity)
                    continue;

                if (tierPrice.Quantity < previousQty)
                    continue;

                previousPrice = tierPrice.Price;
                previousQty = tierPrice.Quantity;
            }

            return previousPrice;
        }
示例#33
0
        /// <summary>
        /// Replaces a message template tokens
        /// </summary>
        /// <param name="productVariant">Product variant</param>
        /// <param name="template">Template</param>
        /// <param name="languageId">Language identifier</param>
        /// <returns>New template</returns>
        private string ReplaceMessageTemplateTokens(ProductVariant productVariant,
            string template, int languageId)
        {
            var tokens = new NameValueCollection();
            tokens.Add("Store.Name", IoC.Resolve<ISettingManager>().StoreName);
            tokens.Add("Store.URL", IoC.Resolve<ISettingManager>().StoreUrl);
            tokens.Add("Store.Email", this.DefaultEmailAccount.Email);

            tokens.Add("ProductVariant.ID", productVariant.ProductVariantId.ToString());
            tokens.Add("ProductVariant.FullProductName", HttpUtility.HtmlEncode(productVariant.FullProductName));
            tokens.Add("ProductVariant.StockQuantity", productVariant.StockQuantity.ToString());

            foreach (string token in tokens.Keys)
            {
                template = Replace(template, String.Format(@"%{0}%", token), tokens[token]);
            }

            return template;
        }
示例#34
0
 /// <summary>
 /// Gets the final price
 /// </summary>
 /// <param name="productVariant">Product variant</param>
 /// <param name="includeDiscounts">A value indicating whether include discounts or not for final price computation</param>
 /// <returns>Final price</returns>
 public static decimal GetFinalPrice(ProductVariant productVariant, bool includeDiscounts)
 {
     Customer customer = NopContext.Current.User;
     return GetFinalPrice(productVariant, customer, includeDiscounts);
 }
        public ProductVariant SaveInfo()
        {
            DateTime nowDT = DateTime.UtcNow;

            string name = txtName.Text.Trim();
            string sku = txtSKU.Text.Trim();
            string description = txtDescription.Value;
            string adminComment = txtAdminComment.Text.Trim();
            string manufacturerPartNumber = txtManufacturerPartNumber.Text.Trim();
            bool isGiftCard = cbIsGiftCard.Checked;
            int giftCardType = int.Parse(this.ddlGiftCardType.SelectedItem.Value);
            bool isDownload = cbIsDownload.Checked;
            bool unlimitedDownloads = cbUnlimitedDownloads.Checked;
            int maxNumberOfDownloads = txtMaxNumberOfDownloads.Value;
            int? downloadExpirationDays = null;
            if (!String.IsNullOrEmpty(txtDownloadExpirationDays.Text.Trim()))
                downloadExpirationDays = int.Parse(txtDownloadExpirationDays.Text.Trim());
            DownloadActivationTypeEnum downloadActivationType = (DownloadActivationTypeEnum)Enum.ToObject(typeof(DownloadActivationTypeEnum), int.Parse(this.ddlDownloadActivationType.SelectedItem.Value));
            bool hasUserAgreement = cbHasUserAgreement.Checked;
            string userAgreementText = txtUserAgreementText.Value;
            bool hasSampleDownload = cbHasSampleDownload.Checked;

            bool isRecurring = cbIsRecurring.Checked;
            int cycleLength = txtCycleLength.Value;
            RecurringProductCyclePeriodEnum cyclePeriod = (RecurringProductCyclePeriodEnum)Enum.ToObject(typeof(RecurringProductCyclePeriodEnum), int.Parse(this.ddlCyclePeriod.SelectedItem.Value));
            int totalCycles = txtTotalCycles.Value;

            bool isShipEnabled = cbIsShipEnabled.Checked;
            bool isFreeShipping = cbIsFreeShipping.Checked;
            decimal additionalShippingCharge = txtAdditionalShippingCharge.Value;
            bool isTaxExempt = cbIsTaxExempt.Checked;
            int taxCategoryId = int.Parse(this.ddlTaxCategory.SelectedItem.Value);
            int manageStock = Convert.ToInt32(ddlManageStock.SelectedValue);
            int stockQuantity = txtStockQuantity.Value;
            bool displayStockAvailability = cbDisplayStockAvailability.Checked;
            bool displayStockQuantity = cbDisplayStockQuantity.Checked;
            int minStockQuantity = txtMinStockQuantity.Value;
            LowStockActivityEnum lowStockActivity = (LowStockActivityEnum)Enum.ToObject(typeof(LowStockActivityEnum), int.Parse(this.ddlLowStockActivity.SelectedItem.Value));
            int notifyForQuantityBelow = txtNotifyForQuantityBelow.Value;
            int backorders = int.Parse(this.ddlBackorders.SelectedItem.Value);
            int orderMinimumQuantity = txtOrderMinimumQuantity.Value;
            int orderMaximumQuantity = txtOrderMaximumQuantity.Value;
            int warehouseId = int.Parse(this.ddlWarehouse.SelectedItem.Value);
            bool disableBuyButton = cbDisableBuyButton.Checked;
            bool callForPrice = cbCallForPrice.Checked;
            decimal price = txtPrice.Value;
            decimal oldPrice = txtOldPrice.Value;
            decimal productCost = txtProductCost.Value;
            bool customerEntersPrice = cbCustomerEntersPrice.Checked;
            decimal minimumCustomerEnteredPrice = txtMinimumCustomerEnteredPrice.Value;
            decimal maximumCustomerEnteredPrice = txtMaximumCustomerEnteredPrice.Value;
            decimal weight = txtWeight.Value;
            decimal length = txtLength.Value;
            decimal width = txtWidth.Value;
            decimal height = txtHeight.Value;
            DateTime? availableStartDateTime = ctrlAvailableStartDateTimePicker.SelectedDate;
            DateTime? availableEndDateTime = ctrlAvailableEndDateTimePicker.SelectedDate;
            if (availableStartDateTime.HasValue)
            {
                availableStartDateTime = DateTime.SpecifyKind(availableStartDateTime.Value, DateTimeKind.Utc);
            }
            if (availableEndDateTime.HasValue)
            {
                availableEndDateTime = DateTime.SpecifyKind(availableEndDateTime.Value, DateTimeKind.Utc);
            }
            bool published = cbPublished.Checked;
            int displayOrder = txtDisplayOrder.Value;

            ProductVariant productVariant = this.ProductService.GetProductVariantById(ProductVariantId);
            if (productVariant != null)
            {
                #region Update
                Picture productVariantPicture = productVariant.Picture;
                HttpPostedFile productVariantPictureFile = fuProductVariantPicture.PostedFile;
                if ((productVariantPictureFile != null) && (!String.IsNullOrEmpty(productVariantPictureFile.FileName)))
                {
                    byte[] productVariantPictureBinary = productVariantPictureFile.GetPictureBits();
                    if (productVariantPicture != null)
                        productVariantPicture = this.PictureService.UpdatePicture(productVariantPicture.PictureId, productVariantPictureBinary, productVariantPictureFile.ContentType, true);
                    else
                        productVariantPicture = this.PictureService.InsertPicture(productVariantPictureBinary, productVariantPictureFile.ContentType, true);
                }
                int productVariantPictureId = 0;
                if (productVariantPicture != null)
                    productVariantPictureId = productVariantPicture.PictureId;

                int productVariantDownloadId = 0;
                if (isDownload)
                {
                    Download productVariantDownload = productVariant.Download;
                    bool useDownloadURL = cbUseDownloadURL.Checked;
                    string downloadURL = txtDownloadURL.Text.Trim();
                    byte[] productVariantDownloadBinary = null;
                    string downloadContentType = string.Empty;
                    string downloadFilename = string.Empty;
                    string downloadExtension = string.Empty;
                    if (productVariantDownload != null)
                    {
                        productVariantDownloadBinary = productVariantDownload.DownloadBinary;
                        downloadContentType = productVariantDownload.ContentType;
                        downloadFilename = productVariantDownload.Filename;
                        downloadExtension = productVariantDownload.Extension;
                    }

                    HttpPostedFile productVariantDownloadFile = fuProductVariantDownload.PostedFile;
                    if ((productVariantDownloadFile != null) && (!String.IsNullOrEmpty(productVariantDownloadFile.FileName)))
                    {
                        productVariantDownloadBinary = productVariantDownloadFile.GetDownloadBits();
                        downloadContentType = productVariantDownloadFile.ContentType;
                        downloadFilename = Path.GetFileNameWithoutExtension(productVariantDownloadFile.FileName);
                        downloadExtension = Path.GetExtension(productVariantDownloadFile.FileName);
                    }

                    if (productVariantDownload != null)
                    {
                        productVariantDownload.UseDownloadUrl = useDownloadURL;
                        productVariantDownload.DownloadUrl = downloadURL;
                        productVariantDownload.DownloadBinary = productVariantDownloadBinary;
                        productVariantDownload.ContentType = downloadContentType;
                        productVariantDownload.Filename = downloadFilename;
                        productVariantDownload.Extension = downloadExtension;
                        productVariantDownload.IsNew = true;
                        this.DownloadService.UpdateDownload(productVariantDownload);
                    }
                    else
                    {
                        productVariantDownload = new Download()
                        {
                            UseDownloadUrl = useDownloadURL,
                            DownloadUrl = downloadURL,
                            DownloadBinary = productVariantDownloadBinary,
                            ContentType = downloadContentType,
                            Filename = downloadFilename,
                            Extension = downloadExtension,
                            IsNew = true
                        };
                        this.DownloadService.InsertDownload(productVariantDownload);
                    }

                    productVariantDownloadId = productVariantDownload.DownloadId;
                }

                int productVariantSampleDownloadId = 0;
                if (hasSampleDownload)
                {
                    Download productVariantSampleDownload = productVariant.SampleDownload;
                    bool useSampleDownloadURL = cbUseSampleDownloadURL.Checked;
                    string sampleDownloadURL = txtSampleDownloadURL.Text.Trim();
                    byte[] productVariantSampleDownloadBinary = null;
                    string sampleDownloadContentType = string.Empty;
                    string sampleDownloadFilename = string.Empty;
                    string sampleDownloadExtension = string.Empty;
                    if (productVariantSampleDownload != null)
                    {
                        productVariantSampleDownloadBinary = productVariantSampleDownload.DownloadBinary;
                        sampleDownloadContentType = productVariantSampleDownload.ContentType;
                        sampleDownloadFilename = productVariantSampleDownload.Filename;
                        sampleDownloadExtension = productVariantSampleDownload.Extension;
                    }

                    HttpPostedFile productVariantSampleDownloadFile = fuProductVariantSampleDownload.PostedFile;
                    if ((productVariantSampleDownloadFile != null) && (!String.IsNullOrEmpty(productVariantSampleDownloadFile.FileName)))
                    {
                        productVariantSampleDownloadBinary = productVariantSampleDownloadFile.GetDownloadBits();
                        sampleDownloadContentType = productVariantSampleDownloadFile.ContentType;
                        sampleDownloadFilename = Path.GetFileNameWithoutExtension(productVariantSampleDownloadFile.FileName);
                        sampleDownloadExtension = Path.GetExtension(productVariantSampleDownloadFile.FileName);
                    }

                    if (productVariantSampleDownload != null)
                    {
                        productVariantSampleDownload.UseDownloadUrl = useSampleDownloadURL;
                        productVariantSampleDownload.DownloadUrl = sampleDownloadURL;
                        productVariantSampleDownload.DownloadBinary = productVariantSampleDownloadBinary;
                        productVariantSampleDownload.ContentType = sampleDownloadContentType;
                        productVariantSampleDownload.Filename = sampleDownloadFilename;
                        productVariantSampleDownload.Extension = sampleDownloadExtension;
                        productVariantSampleDownload.IsNew = true;
                        this.DownloadService.UpdateDownload(productVariantSampleDownload);
                    }
                    else
                    {
                        productVariantSampleDownload = new Download()
                        {
                            UseDownloadUrl = useSampleDownloadURL,
                            DownloadUrl = sampleDownloadURL,
                            DownloadBinary = productVariantSampleDownloadBinary,
                            ContentType = sampleDownloadContentType,
                            Filename = sampleDownloadFilename,
                            Extension = sampleDownloadExtension,
                            IsNew = true
                        };
                        this.DownloadService.InsertDownload(productVariantSampleDownload);
                    }

                    productVariantSampleDownloadId = productVariantSampleDownload.DownloadId;
                }

                productVariant.Name = name;
                productVariant.SKU = sku;
                productVariant.Description = description;
                productVariant.AdminComment = adminComment;
                productVariant.ManufacturerPartNumber = manufacturerPartNumber;
                productVariant.IsGiftCard = isGiftCard;
                productVariant.GiftCardType = giftCardType;
                productVariant.IsDownload = isDownload;
                productVariant.DownloadId = productVariantDownloadId;
                productVariant.UnlimitedDownloads = unlimitedDownloads;
                productVariant.MaxNumberOfDownloads = maxNumberOfDownloads;
                productVariant.DownloadExpirationDays = downloadExpirationDays;
                productVariant.DownloadActivationType = (int)downloadActivationType;
                productVariant.HasSampleDownload = hasSampleDownload;
                productVariant.SampleDownloadId = productVariantSampleDownloadId;
                productVariant.HasUserAgreement = hasUserAgreement;
                productVariant.UserAgreementText = userAgreementText;
                productVariant.IsRecurring = isRecurring;
                productVariant.CycleLength = cycleLength;
                productVariant.CyclePeriod = (int)cyclePeriod;
                productVariant.TotalCycles = totalCycles;
                productVariant.IsShipEnabled = isShipEnabled;
                productVariant.IsFreeShipping = isFreeShipping;
                productVariant.AdditionalShippingCharge = additionalShippingCharge;
                productVariant.IsTaxExempt = isTaxExempt;
                productVariant.TaxCategoryId = taxCategoryId;
                productVariant.ManageInventory = manageStock;
                productVariant.StockQuantity = stockQuantity;
                productVariant.DisplayStockAvailability = displayStockAvailability;
                productVariant.DisplayStockQuantity = displayStockQuantity;
                productVariant.MinStockQuantity = minStockQuantity;
                productVariant.LowStockActivityId = (int)lowStockActivity;
                productVariant.NotifyAdminForQuantityBelow = notifyForQuantityBelow;
                productVariant.Backorders = backorders;
                productVariant.OrderMinimumQuantity = orderMinimumQuantity;
                productVariant.OrderMaximumQuantity = orderMaximumQuantity;
                productVariant.WarehouseId = warehouseId;
                productVariant.DisableBuyButton = disableBuyButton;
                productVariant.CallForPrice = callForPrice;
                productVariant.Price = price;
                productVariant.OldPrice = oldPrice;
                productVariant.ProductCost = productCost;
                productVariant.CustomerEntersPrice = customerEntersPrice;
                productVariant.MinimumCustomerEnteredPrice = minimumCustomerEnteredPrice;
                productVariant.MaximumCustomerEnteredPrice = maximumCustomerEnteredPrice;
                productVariant.Weight = weight;
                productVariant.Length = length;
                productVariant.Width = width;
                productVariant.Height = height;
                productVariant.PictureId = productVariantPictureId;
                productVariant.AvailableStartDateTime = availableStartDateTime;
                productVariant.AvailableEndDateTime = availableEndDateTime;
                productVariant.Published = published;
                productVariant.DisplayOrder = displayOrder;
                productVariant.UpdatedOn = nowDT;

                this.ProductService.UpdateProductVariant(productVariant);

                #endregion
            }
            else
            {
                #region Insert
                Product product = this.ProductService.GetProductById(this.ProductId);
                if (product != null)
                {
                    Picture productVariantPicture = null;
                    HttpPostedFile productVariantPictureFile = fuProductVariantPicture.PostedFile;
                    if ((productVariantPictureFile != null) && (!String.IsNullOrEmpty(productVariantPictureFile.FileName)))
                    {
                        byte[] productVariantPictureBinary = productVariantPictureFile.GetPictureBits();
                        productVariantPicture = this.PictureService.InsertPicture(productVariantPictureBinary, productVariantPictureFile.ContentType, true);
                    }
                    int productVariantPictureId = 0;
                    if (productVariantPicture != null)
                        productVariantPictureId = productVariantPicture.PictureId;

                    int productVariantDownloadId = 0;
                    if (isDownload)
                    {
                        bool useDownloadURL = cbUseDownloadURL.Checked;
                        string downloadURL = txtDownloadURL.Text.Trim();
                        byte[] productVariantDownloadBinary = null;
                        string downloadContentType = string.Empty;
                        string downloadFilename = string.Empty;
                        string downloadExtension = string.Empty;

                        HttpPostedFile productVariantDownloadFile = fuProductVariantDownload.PostedFile;
                        if ((productVariantDownloadFile != null) && (!String.IsNullOrEmpty(productVariantDownloadFile.FileName)))
                        {
                            productVariantDownloadBinary = productVariantDownloadFile.GetDownloadBits();
                            downloadContentType = productVariantDownloadFile.ContentType;
                            downloadFilename = Path.GetFileNameWithoutExtension(productVariantDownloadFile.FileName);
                            downloadExtension = Path.GetExtension(productVariantDownloadFile.FileName);
                        }

                        var productVariantDownload = new Download()
                        {
                            UseDownloadUrl = useDownloadURL,
                            DownloadUrl = downloadURL,
                            DownloadBinary = productVariantDownloadBinary,
                            ContentType = downloadContentType,
                            Filename = downloadFilename,
                            Extension = downloadExtension,
                            IsNew = true
                        };
                        this.DownloadService.InsertDownload(productVariantDownload);
                        productVariantDownloadId = productVariantDownload.DownloadId;
                    }

                    int productVariantSampleDownloadId = 0;
                    if (hasSampleDownload)
                    {
                        bool useSampleDownloadURL = cbUseSampleDownloadURL.Checked;
                        string sampleDownloadURL = txtSampleDownloadURL.Text.Trim();
                        byte[] productVariantSampleDownloadBinary = null;
                        string sampleDownloadContentType = string.Empty;
                        string sampleDownloadFilename = string.Empty;
                        string sampleDownloadExtension = string.Empty;

                        HttpPostedFile productVariantSampleDownloadFile = fuProductVariantSampleDownload.PostedFile;
                        if ((productVariantSampleDownloadFile != null) && (!String.IsNullOrEmpty(productVariantSampleDownloadFile.FileName)))
                        {
                            productVariantSampleDownloadBinary = productVariantSampleDownloadFile.GetDownloadBits();
                            sampleDownloadContentType = productVariantSampleDownloadFile.ContentType;
                            sampleDownloadFilename = Path.GetFileNameWithoutExtension(productVariantSampleDownloadFile.FileName);
                            sampleDownloadExtension = Path.GetExtension(productVariantSampleDownloadFile.FileName);
                        }

                        var productVariantSampleDownload = new Download()
                        {
                            UseDownloadUrl = useSampleDownloadURL,
                            DownloadUrl = sampleDownloadURL,
                            DownloadBinary = productVariantSampleDownloadBinary,
                            ContentType = sampleDownloadContentType,
                            Filename = sampleDownloadFilename,
                            Extension = sampleDownloadExtension,
                            IsNew = true
                        };
                        this.DownloadService.InsertDownload(productVariantSampleDownload);
                        productVariantSampleDownloadId = productVariantSampleDownload.DownloadId;
                    }

                    productVariant = new ProductVariant()
                    {
                        ProductId = product.ProductId,
                        Name = name,
                        SKU = sku,
                        Description = description,
                        AdminComment = adminComment,
                        ManufacturerPartNumber = manufacturerPartNumber,
                        IsGiftCard = isGiftCard,
                        GiftCardType = giftCardType,
                        IsDownload = isDownload,
                        DownloadId = productVariantDownloadId,
                        UnlimitedDownloads = unlimitedDownloads,
                        MaxNumberOfDownloads = maxNumberOfDownloads,
                        DownloadExpirationDays = downloadExpirationDays,
                        DownloadActivationType = (int)downloadActivationType,
                        HasSampleDownload = hasSampleDownload,
                        SampleDownloadId = productVariantSampleDownloadId,
                        HasUserAgreement = hasUserAgreement,
                        UserAgreementText = userAgreementText,
                        IsRecurring = isRecurring,
                        CycleLength = cycleLength,
                        CyclePeriod = (int)cyclePeriod,
                        TotalCycles = totalCycles,
                        IsShipEnabled = isShipEnabled,
                        IsFreeShipping = isFreeShipping,
                        AdditionalShippingCharge = additionalShippingCharge,
                        IsTaxExempt = isTaxExempt,
                        TaxCategoryId = taxCategoryId,
                        ManageInventory = manageStock,
                        StockQuantity = stockQuantity,
                        DisplayStockAvailability = displayStockAvailability,
                        DisplayStockQuantity = displayStockQuantity,
                        MinStockQuantity = minStockQuantity,
                        LowStockActivityId = (int)lowStockActivity,
                        NotifyAdminForQuantityBelow = notifyForQuantityBelow,
                        Backorders = backorders,
                        OrderMinimumQuantity = orderMinimumQuantity,
                        OrderMaximumQuantity = orderMaximumQuantity,
                        WarehouseId = warehouseId,
                        DisableBuyButton = disableBuyButton,
                        CallForPrice = callForPrice,
                        Price = price,
                        OldPrice = oldPrice,
                        ProductCost = productCost,
                        CustomerEntersPrice = customerEntersPrice,
                        MinimumCustomerEnteredPrice = minimumCustomerEnteredPrice,
                        MaximumCustomerEnteredPrice = maximumCustomerEnteredPrice,
                        Weight = weight,
                        Length = length,
                        Width = width,
                        Height = height,
                        PictureId = productVariantPictureId,
                        AvailableStartDateTime = availableStartDateTime,
                        AvailableEndDateTime = availableEndDateTime,
                        Published = published,
                        Deleted = false,
                        DisplayOrder = displayOrder,
                        CreatedOn = nowDT,
                        UpdatedOn = nowDT
                    };

                    this.ProductService.InsertProductVariant(productVariant);
                }
                else
                {
                    Response.Redirect("Products.aspx");
                }
                #endregion
            }

            SaveLocalizableContent(productVariant);

            return productVariant;
        }
示例#36
0
 /// <summary>
 /// Gets the final price
 /// </summary>
 /// <param name="productVariant">Product variant</param>
 /// <param name="customer">The customer</param>
 /// <param name="includeDiscounts">A value indicating whether include discounts or not for final price computation</param>
 /// <returns>Final price</returns>
 public static decimal GetFinalPrice(ProductVariant productVariant, Customer customer, bool includeDiscounts)
 {
     return GetFinalPrice(productVariant, customer, decimal.Zero, includeDiscounts);
 }
示例#37
0
        /// <summary>
        /// Creates a copy of product with all depended data
        /// </summary>
        /// <param name="productId">The product identifier</param>
        /// <param name="name">The name of product duplicate</param>
        /// <param name="isPublished">A value indicating whether the product duplicate should be published</param>
        /// <param name="copyImages">A value indicating whether the product images should be copied</param>
        /// <returns>Product entity</returns>
        public Product DuplicateProduct(int productId, string name,
            bool isPublished, bool copyImages)
        {
            var product = GetProductById(productId);
            if (product == null)
                return null;

            Product productCopy = null;
            //uncomment this line to support transactions
            //using (var scope = new System.Transactions.TransactionScope())
            {
                // product
                productCopy = new Product()
                {
                    Name = name,
                    ShortDescription = product.ShortDescription,
                    FullDescription = product.FullDescription,
                    AdminComment = product.AdminComment,
                    TemplateId = product.TemplateId,
                    ShowOnHomePage = product.ShowOnHomePage,
                    MetaKeywords = product.MetaKeywords,
                    MetaDescription = product.MetaDescription,
                    MetaTitle = product.MetaTitle,
                    SEName = product.SEName,
                    AllowCustomerReviews = product.AllowCustomerReviews,
                    AllowCustomerRatings = product.AllowCustomerRatings,
                    Published = isPublished,
                    Deleted = product.Deleted,
                    CreatedOn = DateTime.UtcNow,
                    UpdatedOn = DateTime.UtcNow
                };
                InsertProduct(productCopy);

                if (productCopy == null)
                    return null;

                var languages = IoC.Resolve<ILanguageService>().GetAllLanguages(true);

                //localization
                foreach (var lang in languages)
                {
                    var productLocalized = GetProductLocalizedByProductIdAndLanguageId(product.ProductId, lang.LanguageId);
                    if (productLocalized != null)
                    {
                        var productLocalizedCopy = new ProductLocalized()
                        {
                            ProductId = productCopy.ProductId,
                            LanguageId = productLocalized.LanguageId,
                            Name = productLocalized.Name,
                            ShortDescription = productLocalized.ShortDescription,
                            FullDescription = productLocalized.FullDescription,
                            MetaKeywords = productLocalized.MetaKeywords,
                            MetaDescription = productLocalized.MetaDescription,
                            MetaTitle = productLocalized.MetaTitle,
                            SEName = productLocalized.SEName
                        };
                        InsertProductLocalized(productLocalizedCopy);
                    }
                }

                // product pictures
                if (copyImages)
                {
                    foreach (var productPicture in product.ProductPictures)
                    {
                        var picture = productPicture.Picture;

                        var pictureCopy = IoC.Resolve<IPictureService>().InsertPicture(picture.PictureBinary,
                            picture.MimeType,
                            picture.IsNew);

                        InsertProductPicture(new ProductPicture()
                        {
                            ProductId = productCopy.ProductId,
                            PictureId = pictureCopy.PictureId,
                            DisplayOrder = productPicture.DisplayOrder
                        });
                    }
                }

                // product <-> categories mappings
                foreach (var productCategory in product.ProductCategories)
                {
                    var productCategoryCopy = new ProductCategory()
                    {
                        ProductId = productCopy.ProductId,
                        CategoryId = productCategory.CategoryId,
                        IsFeaturedProduct = productCategory.IsFeaturedProduct,
                        DisplayOrder = productCategory.DisplayOrder
                    };

                    IoC.Resolve<ICategoryService>().InsertProductCategory(productCategoryCopy);
                }

                // product <-> manufacturers mappings
                foreach (var productManufacturers in product.ProductManufacturers)
                {
                    var productManufacturerCopy = new ProductManufacturer()
                    {
                        ProductId = productCopy.ProductId,
                        ManufacturerId = productManufacturers.ManufacturerId,
                        IsFeaturedProduct = productManufacturers.IsFeaturedProduct,
                        DisplayOrder = productManufacturers.DisplayOrder
                    };

                    IoC.Resolve<IManufacturerService>().InsertProductManufacturer(productManufacturerCopy);
                }

                // product <-> releated products mappings
                foreach (var relatedProduct in product.RelatedProducts)
                {
                    InsertRelatedProduct(
                        new RelatedProduct()
                        {
                            ProductId1 = productCopy.ProductId,
                            ProductId2 = relatedProduct.ProductId2,
                            DisplayOrder = relatedProduct.DisplayOrder
                        });
                }

                // product specifications
                foreach (var productSpecificationAttribute in IoC.Resolve<ISpecificationAttributeService>().GetProductSpecificationAttributesByProductId(product.ProductId))
                {
                    var psaCopy = new ProductSpecificationAttribute()
                    {
                        ProductId = productCopy.ProductId,
                        SpecificationAttributeOptionId = productSpecificationAttribute.SpecificationAttributeOptionId,
                        AllowFiltering = productSpecificationAttribute.AllowFiltering,
                        ShowOnProductPage = productSpecificationAttribute.ShowOnProductPage,
                        DisplayOrder = productSpecificationAttribute.DisplayOrder
                    };
                    IoC.Resolve<ISpecificationAttributeService>().InsertProductSpecificationAttribute(psaCopy);
                }

                // product variants
                var productVariants = GetProductVariantsByProductId(product.ProductId, true);
                foreach (var productVariant in productVariants)
                {
                    // product variant picture
                    int pictureId = 0;
                    if (copyImages)
                    {
                        var picture = productVariant.Picture;
                        if (picture != null)
                        {
                            var pictureCopy = IoC.Resolve<IPictureService>().InsertPicture(picture.PictureBinary, picture.MimeType, picture.IsNew);
                            pictureId = pictureCopy.PictureId;
                        }
                    }

                    // product variant download & sample download
                    int downloadId = productVariant.DownloadId;
                    int sampleDownloadId = productVariant.SampleDownloadId;
                    if (productVariant.IsDownload)
                    {
                        var download = productVariant.Download;
                        if (download != null)
                        {
                            var downloadCopy = new Download()
                                {
                                    UseDownloadUrl = download.UseDownloadUrl,
                                    DownloadUrl = download.DownloadUrl,
                                    DownloadBinary = download.DownloadBinary,
                                    ContentType = download.ContentType,
                                    Filename = download.Filename,
                                    Extension = download.Extension,
                                    IsNew = download.IsNew
                                };
                            IoC.Resolve<IDownloadService>().InsertDownload(downloadCopy);
                            downloadId = downloadCopy.DownloadId;
                        }

                        if (productVariant.HasSampleDownload)
                        {
                            var sampleDownload = productVariant.SampleDownload;
                            if (sampleDownload != null)
                            {
                                var sampleDownloadCopy = new Download()
                                {
                                    UseDownloadUrl = sampleDownload.UseDownloadUrl,
                                    DownloadUrl = sampleDownload.DownloadUrl,
                                    DownloadBinary = sampleDownload.DownloadBinary,
                                    ContentType = sampleDownload.ContentType,
                                    Filename = sampleDownload.Filename,
                                    Extension = sampleDownload.Extension,
                                    IsNew = sampleDownload.IsNew
                                };
                                IoC.Resolve<IDownloadService>().InsertDownload(sampleDownloadCopy);
                                sampleDownloadId = sampleDownloadCopy.DownloadId;
                            }
                        }
                    }

                    // product variant
                    var productVariantCopy = new ProductVariant()
                    {
                        ProductId = productCopy.ProductId,
                        Name = productVariant.Name,
                        SKU = productVariant.SKU,
                        Description = productVariant.Description,
                        AdminComment = productVariant.AdminComment,
                        ManufacturerPartNumber = productVariant.ManufacturerPartNumber,
                        IsGiftCard = productVariant.IsGiftCard,
                        GiftCardType = productVariant.GiftCardType,
                        IsDownload = productVariant.IsDownload,
                        DownloadId = downloadId,
                        UnlimitedDownloads = productVariant.UnlimitedDownloads,
                        MaxNumberOfDownloads = productVariant.MaxNumberOfDownloads,
                        DownloadExpirationDays = productVariant.DownloadExpirationDays,
                        DownloadActivationType = productVariant.DownloadActivationType,
                        HasSampleDownload = productVariant.HasSampleDownload,
                        SampleDownloadId = sampleDownloadId,
                        HasUserAgreement = productVariant.HasUserAgreement,
                        UserAgreementText = productVariant.UserAgreementText,
                        IsRecurring = productVariant.IsRecurring,
                        CycleLength = productVariant.CycleLength,
                        CyclePeriod = productVariant.CyclePeriod,
                        TotalCycles = productVariant.TotalCycles,
                        IsShipEnabled = productVariant.IsShipEnabled,
                        IsFreeShipping = productVariant.IsFreeShipping,
                        AdditionalShippingCharge = productVariant.AdditionalShippingCharge,
                        IsTaxExempt = productVariant.IsTaxExempt,
                        TaxCategoryId = productVariant.TaxCategoryId,
                        ManageInventory = productVariant.ManageInventory,
                        StockQuantity = productVariant.StockQuantity,
                        DisplayStockAvailability = productVariant.DisplayStockAvailability,
                        DisplayStockQuantity = productVariant.DisplayStockQuantity,
                        MinStockQuantity = productVariant.MinStockQuantity,
                        LowStockActivityId = productVariant.LowStockActivityId,
                        NotifyAdminForQuantityBelow = productVariant.NotifyAdminForQuantityBelow,
                        Backorders = productVariant.Backorders,
                        OrderMinimumQuantity = productVariant.OrderMinimumQuantity,
                        OrderMaximumQuantity = productVariant.OrderMaximumQuantity,
                        WarehouseId = productVariant.WarehouseId,
                        DisableBuyButton = productVariant.DisableBuyButton,
                        CallForPrice = productVariant.CallForPrice,
                        Price = productVariant.Price,
                        OldPrice = productVariant.OldPrice,
                        ProductCost = productVariant.ProductCost,
                        CustomerEntersPrice = productVariant.CustomerEntersPrice,
                        MinimumCustomerEnteredPrice = productVariant.MinimumCustomerEnteredPrice,
                        MaximumCustomerEnteredPrice = productVariant.MaximumCustomerEnteredPrice,
                        Weight = productVariant.Weight,
                        Length = productVariant.Length,
                        Width = productVariant.Width,
                        Height = productVariant.Height,
                        PictureId = pictureId,
                        AvailableStartDateTime = productVariant.AvailableStartDateTime,
                        AvailableEndDateTime = productVariant.AvailableEndDateTime,
                        Published = productVariant.Published,
                        Deleted = productVariant.Deleted,
                        DisplayOrder = productVariant.DisplayOrder,
                        CreatedOn = DateTime.UtcNow,
                        UpdatedOn = DateTime.UtcNow
                    };

                    InsertProductVariant(productVariantCopy);

                    //localization
                    foreach (var lang in languages)
                    {
                        var productVariantLocalized = GetProductVariantLocalizedByProductVariantIdAndLanguageId(productVariant.ProductVariantId, lang.LanguageId);
                        if (productVariantLocalized != null)
                        {
                            var productVariantLocalizedCopy = new ProductVariantLocalized()
                            {
                                ProductVariantId = productVariantCopy.ProductVariantId,
                                LanguageId = productVariantLocalized.LanguageId,
                                Name = productVariantLocalized.Name,
                                Description = productVariantLocalized.Description
                            };
                            InsertProductVariantLocalized(productVariantLocalizedCopy);
                        }
                    }

                    // product variant <-> attributes mappings
                    foreach (var productVariantAttribute in IoC.Resolve<IProductAttributeService>().GetProductVariantAttributesByProductVariantId(productVariant.ProductVariantId))
                    {
                        var productVariantAttributeCopy = new ProductVariantAttribute()
                        {
                            ProductVariantId = productVariantCopy.ProductVariantId,
                            ProductAttributeId = productVariantAttribute.ProductAttributeId,
                            TextPrompt = productVariantAttribute.TextPrompt,
                            IsRequired = productVariantAttribute.IsRequired,
                            AttributeControlTypeId = productVariantAttribute.AttributeControlTypeId,
                            DisplayOrder = productVariantAttribute.DisplayOrder
                        };
                        IoC.Resolve<IProductAttributeService>().InsertProductVariantAttribute(productVariantAttributeCopy);

                        // product variant attribute values
                        var productVariantAttributeValues = IoC.Resolve<IProductAttributeService>().GetProductVariantAttributeValues(productVariantAttribute.ProductVariantAttributeId);
                        foreach (var productVariantAttributeValue in productVariantAttributeValues)
                        {
                            var pvavCopy = new ProductVariantAttributeValue()
                            {
                                ProductVariantAttributeId = productVariantAttributeCopy.ProductVariantAttributeId,
                                Name = productVariantAttributeValue.Name,
                                PriceAdjustment = productVariantAttributeValue.PriceAdjustment,
                                WeightAdjustment = productVariantAttributeValue.WeightAdjustment,
                                IsPreSelected = productVariantAttributeValue.IsPreSelected,
                                DisplayOrder = productVariantAttributeValue.DisplayOrder
                            };
                            IoC.Resolve<IProductAttributeService>().InsertProductVariantAttributeValue(pvavCopy);

                            //localization
                            foreach (var lang in languages)
                            {
                                var pvavLocalized = IoC.Resolve<IProductAttributeService>().GetProductVariantAttributeValueLocalizedByProductVariantAttributeValueIdAndLanguageId(productVariantAttributeValue.ProductVariantAttributeValueId, lang.LanguageId);
                                if (pvavLocalized != null)
                                {
                                    var pvavLocalizedCopy = new ProductVariantAttributeValueLocalized()
                                    {
                                        ProductVariantAttributeValueId = pvavCopy.ProductVariantAttributeValueId,
                                        LanguageId = pvavLocalized.LanguageId,
                                        Name = pvavLocalized.Name
                                    };
                                    IoC.Resolve<IProductAttributeService>().InsertProductVariantAttributeValueLocalized(pvavLocalizedCopy);
                                }
                            }
                        }
                    }
                    foreach (var combination in IoC.Resolve<IProductAttributeService>().GetAllProductVariantAttributeCombinations(productVariant.ProductVariantId))
                    {
                        var combinationCopy = new ProductVariantAttributeCombination()
                        {
                            ProductVariantId = productVariantCopy.ProductVariantId,
                            AttributesXml = combination.AttributesXml,
                            StockQuantity = combination.StockQuantity,
                            AllowOutOfStockOrders = combination.AllowOutOfStockOrders
                        };
                        IoC.Resolve<IProductAttributeService>().InsertProductVariantAttributeCombination(combinationCopy);
                    }

                    // product variant tier prices
                    foreach (var tierPrice in productVariant.TierPrices)
                    {
                        InsertTierPrice(
                            new TierPrice()
                            {
                                ProductVariantId = productVariantCopy.ProductVariantId,
                                Quantity = tierPrice.Quantity,
                                Price = tierPrice.Price
                            });
                    }

                    // product variant <-> discounts mapping
                    foreach (var discount in productVariant.AllDiscounts)
                    {
                        IoC.Resolve<IDiscountService>().AddDiscountToProductVariant(productVariantCopy.ProductVariantId, discount.DiscountId);
                    }

                    // prices by customer role
                    foreach (var crpp in productVariant.CustomerRoleProductPrices)
                    {
                        this.InsertCustomerRoleProductPrice(
                            new CustomerRoleProductPrice()
                            {
                                CustomerRoleId = crpp.CustomerRoleId,
                                ProductVariantId = productVariantCopy.ProductVariantId,
                                Price = crpp.Price
                            }
                            );
                    }
                }

                //uncomment this line to support transactions
                //scope.Complete();
            }

            return productCopy;
        }
示例#38
0
 /// <summary>
 /// Gets the final price
 /// </summary>
 /// <param name="productVariant">Product variant</param>
 /// <param name="customer">The customer</param>
 /// <param name="additionalCharge">Additional charge</param>
 /// <param name="includeDiscounts">A value indicating whether include discounts or not for final price computation</param>
 /// <returns>Final price</returns>
 public static decimal GetFinalPrice(ProductVariant productVariant, Customer customer,
                                     decimal additionalCharge, bool includeDiscounts)
 {
     return(GetFinalPrice(productVariant, customer, additionalCharge,
                          includeDiscounts, 1));
 }