Beispiel #1
0
        public async Task <List <ShopProductModel> > GetAllShopProductsAsync()
        {
            var entity = await _shopProductRepository.AsQueryable()
                         .OrderByDescending(s => s.Id)
                         .ToListAsync();

            var result = new List <ShopProductModel>();

            foreach (var item in entity)
            {
                result.Add(
                    new ShopProductModel()
                {
                    Id = item.Id,
                    DescriptionProduct  = item.DescriptionProduct,
                    IsAvaliable         = item.IsAvaliable,
                    ManufacturerProduct = item.ManufacturerProduct,
                    PriceProduct        = item.Discounts == null ? item.PriceProduct : PriceHelper.GetPriceWithDiscount(item.PriceProduct, item.Discounts),
                    ProductName         = item.ProductName,
                    TypeProdycts        = EnumHelper.GetDescription(item.TypeProdyctsEnum),
                    Discount            = PriceHelper.IsDiscountExpired(item.Discounts)
                }
                    );
            }

            return(result);
        }
        protected string GetRemainingAmountInfo(GiftCard gc)
        {
            decimal remainingAmount = GiftCardHelper.GetGiftCardRemainingAmount(gc);
            string  result          = PriceHelper.FormatPrice(remainingAmount, true, false);

            return(result);
        }
        public async Task <IActionResult> Index(string currentFilter, string searchString, int?pageNumber)
        {
            if (searchString == null)
            {
                searchString = currentFilter;
            }
            else
            {
                pageNumber = 1;
            }

            ViewData["CurrentFilter"] = searchString;
            IQueryable <Product> products = _unitOfWork.Products.GetAll();

            if (!String.IsNullOrEmpty(searchString))
            {
                products = products.Where(p => p.Category.Name.Contains(searchString) || p.Name.Contains(searchString));
            }

            int pageSize = 5;

            IQueryable <ProductViewModel> productVMs = products.AsNoTracking().Select(p => new ProductViewModel
            {
                Id           = p.Id,
                CategoryName = p.Category.Name,
                Name         = p.Name,
                Description  = p.Description,
                Price        = PriceHelper.IntToDecimal(p.Price),
                Bidder       = p.Bidder
            });

            return(View(await PaginatedList <ProductViewModel> .CreateAsync(productVMs, pageNumber ?? 1, pageSize)));
        }
        public void GetRate_WhenInventoryBaseRateSameAsSelected_ReturnsBaseRate()
        {
            var rates = GetTestRates();
            var rate  = PriceHelper.GetRate(CurrencyNames.USD, CurrencyNames.USD, rates);

            Assert.True(rate == 1);
        }
Beispiel #5
0
        public static void ProcessUser(Config.Config config, uint userId, ProtocolType ftpFileType)
        {
            var userRoot  = Path.Combine(config.RootDir, userId.ToString());
            var pricesDir = Directory.CreateDirectory(Path.Combine(userRoot, "prices"));
            var marker    = pricesDir.EnumerateFiles("request.txt").FirstOrDefault();

            if (marker != null)
            {
                using (var session = Factory.OpenSession())
                    using (var trx = session.BeginTransaction()) {
                        PriceHelper.ExportPrices(session, userId, pricesDir, ftpFileType);
                        trx.Commit();
                    }
                marker.Delete();
            }

            var ordersDir = Directory.CreateDirectory(Path.Combine(userRoot, "orders"));

            OrderHelper.ImportOrders(ordersDir, userId, ftpFileType);

            var waybillsDir = Directory.CreateDirectory(Path.Combine(userRoot, "waybills"));

            using (var session = Factory.OpenSession())
                using (var trx = session.BeginTransaction()) {
                    WaybillsHelper.ExportWaybills(waybillsDir, session, userId, ftpFileType);
                    trx.Commit();
                }
        }
        public void GetVatPrice()
        {
            var notifier = new ProgressCancelNotifier();

            decimal vatRate                  = 20;
            decimal buyingPriceHt            = 100;
            decimal sellingPriceHt           = 200;
            decimal vatPriceOnRevenue        = 40;
            decimal sellingPriceTTCOnRevenue = 240;
            decimal vatPriceOnProfit         = 20;
            decimal sellingPriceTTCOnProfit  = sellingPriceHt + vatPriceOnProfit;

            if (PriceHelper.GetVATPriceOnProfit(buyingPriceHt, sellingPriceHt, vatRate) != vatPriceOnProfit)
            {
                throw new Exception();
            }
            if (PriceHelper.GetVATPriceOnRevenu(sellingPriceHt, vatRate) != vatPriceOnRevenue)
            {
                throw new Exception();
            }

            Assert.AreEqual(vatPriceOnRevenue, PriceHelper.GetVATPriceOnRevenuWithSellingPriceTTC(sellingPriceTTCOnRevenue, vatRate));

            if (PriceHelper.GetVATPriceOnProfitWithSellingPriceTTC(buyingPriceHt, sellingPriceTTCOnProfit, vatRate) != vatPriceOnProfit)
            {
                throw new Exception();
            }
        }
Beispiel #7
0
        public async Task <ProductResult> GetProductAsync(long id)
        {
            Product product = await _unitOfWork.Products.FindAsync(id);

            return(new ProductResult(product.Id, new CategoryResult(product.Category.Id, product.Category.Name, product.Category.ImageFileName),
                                     product.Name, product.Description, PriceHelper.IntToDecimal(product.Price), PriceHelper.IntToDecimal(product.SellerPrice), product.ImageFileName, product.Bidder));
        }
        /// <summary>
        /// Returns a list of products that belong to the given group.
        /// </summary>
        /// <param name="carModelProductId"></param>
        /// <param name="optionId"></param>
        /// <returns></returns>
        public IEnumerable <CarModelOptionProduct> GetCarModelsOptionProducts(int carModelProductId, int optionId)
        {
            var option = _productOptionRepository.GetById(optionId, carModelProductId);

            if (option == null)
            {
                return(null);
            }

            var products = _productRepository.GetOptionProducts(carModelProductId, optionId)
                           .Select(optionProduct =>
            {
                // Wenn es sich um ein Standard-Produkt handelt, ist der Preis im Preis des Fahrzeugs enthalten
                var grossPrice = option.DefaultProductIds.Contains(optionProduct.Id)
                        ? 0
                        : PriceHelper.GetGrossPrice(optionProduct.NetPrice, optionProduct.VATRate);

                return(new CarModelOptionProduct(optionProduct.EAN, optionProduct.Name,
                                                 optionProduct.Description, grossPrice,
                                                 option.DefaultProductIds != null && option.DefaultProductIds.Contains(optionProduct.Id)));
            })
                           .OrderBy(x => x.Price);

            return(products);
        }
        public string GetShoppingCartItemSubTotalString(ShoppingCartItem shoppingCartItem)
        {
            StringBuilder sb = new StringBuilder();
            decimal       shoppingCartItemSubTotalWithDiscountBase = TaxManager.GetPrice(shoppingCartItem.ProductVariant, PriceHelper.GetSubTotal(shoppingCartItem, customer, true), customer);
            decimal       shoppingCartItemSubTotalWithDiscount     = CurrencyManager.ConvertCurrency(shoppingCartItemSubTotalWithDiscountBase, CurrencyManager.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency);
            string        subTotalString = PriceHelper.FormatPrice(shoppingCartItemSubTotalWithDiscount);

            sb.Append(subTotalString);

            decimal shoppingCartItemDiscountBase = TaxManager.GetPrice(shoppingCartItem.ProductVariant, PriceHelper.GetDiscountAmount(shoppingCartItem, customer), customer);

            if (shoppingCartItemDiscountBase > decimal.Zero)
            {
                decimal shoppingCartItemDiscount = CurrencyManager.ConvertCurrency(shoppingCartItemDiscountBase, CurrencyManager.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency);
                string  discountString           = PriceHelper.FormatPrice(shoppingCartItemDiscount);

                sb.Append("<br />");
                //sb.Append(GetLocaleResourceString("ShoppingCart.ItemYouSave"));
                sb.Append("Saved:");
                sb.Append("&nbsp;&nbsp;");
                sb.Append(discountString);
                sb.Append("<br />");
                sb.Append("<em>NOTE: This discount is applied to the current user</em>");
            }
            return(sb.ToString());
        }
        /// <summary>
        /// Bid offer
        /// </summary>
        public async Task <decimal> Buy(long userId, long productId)
        {
            Product product = await _unitOfWork.Products.FindAsync(productId);

            product.Price       = product.SellerPrice;
            product.SellerPrice = (int)(product.Price * 1.1); // Increase by 10%
            product.Bidder      = userId;

            // DB Transaction of updating product
            using (var dbContextTransaction = _unitOfWork.BeginTransaction())
            {
                try
                {
                    _unitOfWork.Products.Update(product);
                    await _unitOfWork.SaveAsync();

                    dbContextTransaction.Commit();
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();  // Rollbacking
                    ExceptionDispatchInfo.Capture(ex).Throw();
                }
            }

            await _auctionHub.Clients.All.SendAsync(productId.ToString(), PriceHelper.IntToDecimal(product.SellerPrice));

            return(PriceHelper.IntToDecimal(product.Price));
        }
Beispiel #11
0
        public static void Config()
        {
            Mapper.Initialize(cfg => {
                cfg.CreateMap <Product, ProductDetailViewModel>()
                .ForMember(x => x.Brand, m => m.MapFrom(a => a.Brand.Name))
                .ForMember(x => x.Category, m => m.MapFrom(a => a.Category.CategoryName))
                .ForMember(x => x.Gender, m => m.MapFrom(a => a.Gender == 1 ? "Nam" : "Nữ"))
                .ForMember(x => x.Status, m => m.MapFrom(a => a.Status == true ? "Còn hàng" : "Hết hàng"))
                .ForMember(x => x.Price, m => m.MapFrom(a => PriceHelper.NormalizePrice(a.Price.ToString())))
                .ForMember(x => x.PromotionalPrice, m => m.MapFrom(a => PriceHelper.NormalizePrice(a.PromotionalPrice.ToString())))
                .ForMember(x => x.Save, m => m.MapFrom(a => PriceHelper.NormalizePrice((a.Price - a.PromotionalPrice).ToString())))
                .ForMember(x => x.Strap, m => m.MapFrom(a => StrapsToString(a.ProductStrap)))
                ;
                cfg.CreateMap <Product, ProductIndexViewModel>()
                .ForMember(x => x.Price, m => m.MapFrom(a => PriceHelper.NormalizePrice(a.Price.ToString())))
                .ForMember(x => x.PromotionalPrice, m => m.MapFrom(a => PriceHelper.NormalizePrice(a.PromotionalPrice.ToString())))
                ;
                cfg.CreateMap <ProductDetailViewModel, ProductShoppingCart>();
                cfg.CreateMap <PlaceOrderViewModel, OrderStatusViewModel>();
                cfg.CreateMap <PlaceOrderViewModel, Order>();

                cfg.CreateMap <ProductShoppingCart, Product>();
                cfg.CreateMap <Product, ProductShoppingCart>();
            });
        }
Beispiel #12
0
        protected void ddlVariantPrice_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                var productVariant  = e.Item.DataItem as ProductVariant;
                var lblPriceDisplay = e.Item.FindControl("lblPriceDisplay") as Label;
                var lblPrice        = e.Item.FindControl("lblPrice") as Label;
                var imgBuyNow       = e.Item.FindControl("imgBuyNow") as ImageButton;

                if (!SettingManager.GetSettingValueBoolean("Common.HidePricesForNonRegistered") ||
                    (NopContext.Current.User != null &&
                     !NopContext.Current.User.IsGuest))
                {
                    if (productVariant.CustomerEntersPrice)
                    {
                        int minimumCustomerEnteredPrice = Convert.ToInt32(Math.Ceiling(CurrencyManager.ConvertCurrency(productVariant.MinimumCustomerEnteredPrice, CurrencyManager.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency)));
                        lblPrice.Text        = minimumCustomerEnteredPrice.ToString();
                        lblPriceDisplay.Text = PriceHelper.FormatPrice(minimumCustomerEnteredPrice);
                    }
                    else
                    {
                        decimal fromPriceBase = TaxManager.GetPrice(productVariant, PriceHelper.GetFinalPrice(productVariant, false));
                        decimal fromPrice     = CurrencyManager.ConvertCurrency(fromPriceBase, CurrencyManager.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency);
                        lblPrice.Text        = fromPrice.ToString();
                        lblPriceDisplay.Text = PriceHelper.FormatPrice(fromPrice);
                    }
                }
                else
                {
                    lblPriceDisplay.Visible = false;
                    btnAddToCart.Visible    = false;
                }
            }
        }
Beispiel #13
0
        public async Task <ActionResult> Reservation(ReservationView reserv)
        {
            // var appId = db.Apartments.FirstOrDefault(t => t.ApTypeId == reserv.TypeId).ApartmentId;
            var appartment = db.Apartments.Include(r => r.Type).FirstOrDefault(r => r.ApTypeId == reserv.TypeId);
            //   var price = db.ApTypes.FirstOrDefault(w => w.TypeId == reserv.TypeId).Price;
            var reservation = new Reservation()
            {
                StartDate        = reserv.StartDate,
                GuestCount       = reserv.GuestCount,
                Name             = reserv.Name,
                EndDate          = reserv.EndDate,
                ApartmentId      = appartment.ApartmentId,
                ChildrenCount    = reserv.ChildrenCount,
                Note             = reserv.Note,
                PhoneNumber      = reserv.PhoneNumber,
                Status           = ReservationStatus.ReservedByUser,
                ReservationPriсe = PriceHelper.GetPrice(appartment.Type, reserv.GuestCount),
                Email            = reserv.Email
            };

            db.Reservations.Add(reservation);
            await db.SaveChangesAsync();

            reservation.Apartment =
                db.Apartments.Include(r => r.Type).FirstOrDefault(r => r.ApTypeId == reserv.TypeId);
            emailHelper.SendEmail(reservation, Server);


            return(RedirectToAction("Index"));
        }
        private async Task AddProductAsync(ProductViewModel productVM, string newFileName)
        {
            using (var dbContextTransaction = _unitOfWork.BeginTransaction())
            {
                try
                {
                    Product  product  = new Product();
                    Category category = await _unitOfWork.Categories.FindAsync(c => c.Name == productVM.CategoryName);

                    product.CategoryId    = category.Id;
                    product.Name          = productVM.Name;
                    product.Description   = productVM.Description;
                    product.Price         = PriceHelper.DecimalToInt(productVM.Price);
                    product.SellerPrice   = product.Price;
                    product.ImageFileName = FileHelper.FilterImageName(newFileName);
                    product.Bidder        = 0;
                    await _unitOfWork.Products.CreateAsync(product);

                    await _unitOfWork.SaveAsync();

                    dbContextTransaction.Commit();
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback(); // Rollbacking DB
                    ExceptionDispatchInfo.Capture(ex).Throw();
                }
            }
        }
Beispiel #15
0
        public void TestMethod19()
        {
            string     htmlString = File.ReadAllText("TestData\\Gewinnzahlen19.html");
            List <Day> days       = PriceScraper.ExtractPrices(htmlString);

            Assert.IsNotNull(days);


            Console.Write(PriceHelper.PrintDays(days, true));

            for (int i = 1; i <= 16; i++)
            {
                Day day = days.SingleOrDefault(x => x.Date == i);

                Assert.IsNotNull(day);



                Assert.IsTrue(0 < day.Prices.Count, $"Day {i} has no Prices.");

                foreach (Price p in day.Prices)
                {
                    Assert.AreEqual(p.Numbers.Count, p.IntNumbers.Count());

                    Assert.IsTrue(p.Numbers.Any(n => !string.IsNullOrEmpty(n)), $"Price '{p.Description}' of day {i} has no numbers.");
                }
            }
        }
Beispiel #16
0
        private void PreparePrices(ParentItemDTO parentItemDto)
        {
            IList <RateByCountryDTO> allRates = new List <RateByCountryDTO>();

            using (var db = _dbFactory.GetRWDb())
            {
                allRates = db.RateByCountries.GetAllAsDto().ToList();
                foreach (var item in parentItemDto.Variations)
                {
                    double?weight       = item.Weight;
                    var    shippingSize = item.StyleId.HasValue ? db.StyleCaches.GetAll().FirstOrDefault(sc => sc.Id == item.StyleId.Value)?.ShippingSizeValue : null;
                    item.CurrentPriceCurrency = PriceHelper.GetCurrencyAbbr((MarketType)item.Market, item.MarketplaceId);
                    var newPrice = CalculatePrice(weight,
                                                  shippingSize,
                                                  item.CurrentPrice,
                                                  allRates,
                                                  (MarketType)item.Market,
                                                  item.MarketplaceId);
                    _log.Info("Price changed, SKU=" + item.SKU + ": " + item.CurrentPrice + "=>" + newPrice);
                    if (newPrice.HasValue)
                    {
                        item.CurrentPrice = newPrice.Value;
                    }
                    else
                    {
                        _log.Error("Convert price issue: " + item.SKU);
                    }
                }
            }
        }
        public void vatConverstion()
        {
            //input
            decimal buyingAmount = 100;
            decimal vatRate      = 20;

            decimal CATTC = 200m;
            decimal CAHT  = 166.67m;

            decimal BenefitTTC = 200m;
            decimal BenefitHT  = 183.33m;

            if (Math.Round(PriceHelper.GetPriceHTFromPriceTTCOnRevenu(CATTC, vatRate), 2) != CAHT)
            {
                throw new Exception();
            }

            if (Math.Round(PriceHelper.GetPriceTTCFromPriceHTOnRevenu(CAHT, vatRate), 2) != CATTC)
            {
                throw new Exception();
            }


            if (Math.Round(PriceHelper.GetPriceHTFromPriceTTCOnProfit(BenefitTTC, buyingAmount, vatRate), 2) != BenefitHT)
            {
                throw new Exception();
            }

            if (Math.Round(PriceHelper.GetPriceTTCFromPriceHTOnProfit(BenefitHT, buyingAmount, vatRate), 2) != BenefitTTC)
            {
                throw new Exception();
            }
        }
Beispiel #18
0
        private decimal?CalculatePrice(double?weight,
                                       string shippingSize,
                                       decimal usListingPrice,
                                       IList <RateByCountryDTO> allRates,
                                       MarketType forMarket,
                                       string forMarketplaceId)
        {
            var usShipping = RateService.GetMarketShippingAmount(MarketType.Amazon,
                                                                 MarketplaceKeeper.AmazonComMarketplaceId); // 4.49M;
            var currency   = PriceHelper.GetCurrencyAbbr(forMarket, forMarketplaceId);
            var caShipping = PriceHelper.ConvertToUSD(RateService.GetMarketShippingAmount(forMarket, forMarketplaceId), currency);

            var item = new OrderItemRateInfo()
            {
                Quantity     = 1,
                ShippingSize = shippingSize
            };

            IList <RateByCountryDTO> rates = null;

            if (weight.HasValue && weight > 0)
            {
                rates = allRates.Where(r => r.Weight == Math.Floor(weight.Value)).ToList();
            }

            var localPackageType = PackageTypeCode.Flat;

            if (!String.IsNullOrEmpty(shippingSize))
            {
                localPackageType = ShippingServiceUtils.IsSupportFlatEnvelope(new List <OrderItemRateInfo>()
                {
                    item
                })
                        ? PackageTypeCode.Flat
                        : PackageTypeCode.Regular;
            }

            decimal?caRateActualCostRegular = null;
            decimal?usRateActualCost        = null;

            if (rates != null && rates.Any())
            {
                var usPackageType = localPackageType.ToString();

                caRateActualCostRegular = rates.FirstOrDefault(r => r.Country == "CA" && r.PackageType == "Regular")?.Cost;
                usRateActualCost        = rates.FirstOrDefault(r => r.Country == "US" && r.PackageType == usPackageType)?.Cost;
            }
            if (!caRateActualCostRegular.HasValue ||
                !usRateActualCost.HasValue)
            {
                return(null);
            }

            var usIncome = usListingPrice + usShipping - usRateActualCost.Value;
            var newPrice = usIncome - (caShipping - caRateActualCostRegular.Value);

            newPrice = PriceHelper.ConvertFromUSD(newPrice, currency);

            return(newPrice);
        }
Beispiel #19
0
        public decimal?ApplyCharges(int shippingMethodId, decimal?rateAmount)
        {
            if (_isFulfillmentUser) //NOTE: Skip, only for Client Role
            {
                return(rateAmount);
            }

            if (!rateAmount.HasValue)
            {
                return(rateAmount);
            }

            if (_shippingCharges == null)
            {
                using (var db = _dbFactory.GetRWDb())
                {
                    _shippingCharges = db.ShippingCharges.GetAllAsDto().ToList();
                }
            }

            var shippingCharge = _shippingCharges.FirstOrDefault(ch => ch.ShippingMethodId == shippingMethodId);

            if (shippingCharge != null)
            {
                return(PriceHelper.RoundToTwoPrecision(rateAmount * (1 + shippingCharge.ChargePercent / 100M)));
            }

            return(rateAmount);
        }
Beispiel #20
0
        public void SubmitTestPriceFeed(WalmartCAApi api)
        {
            var item1 = new ItemDTO()
            {
                StyleId      = 1158,
                SKU          = "21TE062ERDZA-1-3T", // "21TE062ERDZA-1-3T",
                CurrentPrice = 19.89M
            };

            using (var db = _dbFactory.GetRWDb())
            {
                if (item1.StyleId.HasValue)
                {
                    var itemStyle = db.StyleFeatureValues.GetFeatureValueByStyleIdByFeatureId(
                        item1.StyleId.Value,
                        StyleFeatureHelper.ITEMSTYLE);

                    if (!item1.ListPrice.HasValue && itemStyle != null)
                    {
                        item1.ListPrice = PriceHelper.GetDefaultMSRP(itemStyle.Value);
                    }
                }
            }

            //var result = api.GetFeed("20F17E0B509143B89023AD9B8036D158@AQYBAQA");
            //_log.Info(result.ToString());

            //var result = api.SendPrice(item1);
            //_log.Info(result.ToString());

            api.SubmitPriceFeed("1", new List <ItemDTO>()
            {
                item1
            }, AppSettings.WalmartFeedBaseDirectory);
        }
Beispiel #21
0
        private double strikeFromPrice(double price, Option.Type optionType, double referenceStrike)
        {
            double a, b, min, max, k;

            if (optionType == Option.Type.Call)
            {
                a   = swapRateValue_;
                min = referenceStrike;
                b   = max = k = Math.Min(smileSection_.maxStrike(), shiftedUpperBound_);
            }
            else
            {
                a   = min = k = Math.Max(smileSection_.minStrike(), shiftedLowerBound_);
                b   = swapRateValue_;
                max = referenceStrike;
            }

            PriceHelper h      = new PriceHelper(smileSection_, optionType, price);
            Brent       solver = new Brent();

            try
            {
                k = solver.solve(h, 1.0E-5, swapRateValue_, a, b);
            }
            catch (Exception)
            {
                // use default value set above
            }

            return(Math.Min(Math.Max(k, min), max));
        }
        public override async Task DoWorkAsync(CancellationToken cancellationToken)
        {
            var inventoryItems = await _inventoryService.GetInventoryAsync();

            var cardsToSell = inventoryItems
                              .FilterByMarketable()
                              .FilterByCommodity()
                              .FilterByType(ItemType.TradingCard);

            _logger.LogDebug($"Filtered cards to sell: '{cardsToSell.Count}'");

            foreach (var card in cardsToSell)
            {
                _delayedExecutionPool.EnqueueTaskToPool(async() =>
                {
                    var price = await _marketService.GetItemPriceAsync(card);

                    if (price.LowestPrice == null && price.MedianPrice == null)
                    {
                        return;
                    }

                    var calculatedPrice = price.LowestPrice > PriceHelper.ExpensivePrice && price.LowestPrice < price.MedianPrice
                        ? PriceHelper.CalculateSellerPrice(price.LowestPrice, true)
                        : PriceHelper.CalculateSellerPrice(price.MedianPrice, true);

                    if (card.IsCardFoil())
                    {
                        _logger.LogInformation($"Sending foil '{card.MarketHashName}'. Cost '{calculatedPrice}', lowest price '{price.LowestPrice}', median price '{price.MedianPrice}'");
                    }

                    await _marketService.SellItemAsync(card, calculatedPrice);
                });
            }
        }
        /// <summary>
        /// Bid offer
        /// </summary>
        public async Task <decimal> Buy(long userId, long productId)
        {
            Product product = await _unitOfWork.Products.GetAsync(productId);

            product.Price       = product.SellerPrice;
            product.SellerPrice = (int)(product.Price * priceIncreaseCoeff);
            product.Bidder      = userId;

            // DB Transaction of updating product
            using (var dbContextTransaction = _unitOfWork.BeginTransaction())
            {
                try
                {
                    _unitOfWork.Products.Update(product);
                    await _unitOfWork.SaveAsync();

                    dbContextTransaction.Commit();
                }
                catch (Exception e)
                {
                    dbContextTransaction.Rollback(); // Rollbacking
                    throw new Exception("DB Transaction Failed. Rollback Changes. " + e.Message);
                }
            }

            await _auctionHub.Clients.All.SendAsync(productId.ToString(), PriceHelper.IntToDecimal(product.SellerPrice));

            return(PriceHelper.IntToDecimal(product.Price));
        }
        private async Task AddProductAsync(ProductViewModel productVM, string newFileName)
        {
            using (var dbContextTransaction = _unitOfWork.BeginTransaction())
            {
                try
                {
                    Product  product  = new Product();
                    Category category = await _unitOfWork.Categories.GetAll().AsNoTracking().SingleOrDefaultAsync(c => c.Name == productVM.CategoryName);

                    product.CategoryId    = category.Id;
                    product.Name          = productVM.Name;
                    product.Description   = productVM.Description;
                    product.Price         = PriceHelper.DecimalToInt(productVM.Price);
                    product.SellerPrice   = product.Price;
                    product.ImageFileName = FileHelper.FilterImageName(newFileName);
                    product.Bidder        = 0;
                    await _unitOfWork.Products.CreateAsync(product);

                    await _unitOfWork.SaveAsync();

                    dbContextTransaction.Commit();
                }
                catch (Exception e)
                {
                    dbContextTransaction.Rollback(); // Rollbacking DB
                    throw new Exception("DB Transaction Failed. " + e.Message);
                }
            }
        }
        protected string GetInitialValueInfo(GiftCard gc)
        {
            decimal initialValue = GiftCardHelper.GetGiftCardInitialValue(gc);
            string  result       = PriceHelper.FormatPrice(initialValue, true, false);

            return(result);
        }
        public string GetShoppingCartItemSubTotalString(ShoppingCartItem shoppingCartItem)
        {
            StringBuilder sb      = new StringBuilder();
            decimal       taxRate = decimal.Zero;
            decimal       shoppingCartItemSubTotalWithDiscountBase = this.TaxService.GetPrice(shoppingCartItem.ProductVariant, PriceHelper.GetSubTotal(shoppingCartItem, customer, true), customer, out taxRate);
            decimal       shoppingCartItemSubTotalWithDiscount     = this.CurrencyService.ConvertCurrency(shoppingCartItemSubTotalWithDiscountBase, this.CurrencyService.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency);
            string        subTotalString = PriceHelper.FormatPrice(shoppingCartItemSubTotalWithDiscount);

            sb.Append(subTotalString);

            decimal shoppingCartItemDiscountBase = this.TaxService.GetPrice(shoppingCartItem.ProductVariant, PriceHelper.GetDiscountAmount(shoppingCartItem, customer), customer, out taxRate);

            if (shoppingCartItemDiscountBase > decimal.Zero)
            {
                decimal shoppingCartItemDiscount = this.CurrencyService.ConvertCurrency(shoppingCartItemDiscountBase, this.CurrencyService.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency);
                string  discountString           = PriceHelper.FormatPrice(shoppingCartItemDiscount);

                sb.Append("<br />");
                //sb.Append(GetLocaleResourceString("ShoppingCart.ItemYouSave"));
                sb.Append("Saved:");
                sb.Append("&nbsp;&nbsp;");
                sb.Append(discountString);
            }
            return(sb.ToString());
        }
        /// <summary>
        /// Gets shopping cart subtotal
        /// </summary>
        /// <param name="Cart">Cart</param>
        /// <param name="customer">Customer</param>
        /// <param name="SubTotalDiscount">Subtotal discount</param>
        /// <param name="includingTax">A value indicating whether calculated price should include tax</param>
        /// <param name="Error">Error</param>
        /// <returns>Shopping cart subtotal</returns>
        public static decimal GetShoppingCartSubTotal(ShoppingCart Cart, Customer customer,
                                                      out decimal SubTotalDiscount, bool includingTax, ref string Error)
        {
            SubTotalDiscount = decimal.Zero;

            decimal subTotalWithoutDiscount = decimal.Zero;
            decimal subTotalWithDiscount    = decimal.Zero;

            foreach (ShoppingCartItem shoppingCartItem in Cart)
            {
                string  Error2     = string.Empty;
                decimal scSubTotal = PriceHelper.GetSubTotal(shoppingCartItem, customer, true);
                subTotalWithoutDiscount += TaxManager.GetPrice(shoppingCartItem.ProductVariant, scSubTotal, includingTax, customer, ref Error2);
                if (!String.IsNullOrEmpty(Error2))
                {
                    Error = Error2;
                }
            }


            SubTotalDiscount = GetOrderDiscount(customer, subTotalWithoutDiscount);

            subTotalWithDiscount = subTotalWithoutDiscount - SubTotalDiscount;
            if (subTotalWithDiscount < decimal.Zero)
            {
                subTotalWithDiscount = decimal.Zero;
            }

            subTotalWithDiscount = Math.Round(subTotalWithDiscount, 2);

            return(subTotalWithDiscount);
        }
Beispiel #28
0
        public string GetShoppingCartItemSubTotalString(ShoppingCartItem shoppingCartItem)
        {
            var     sb = new StringBuilder();
            decimal shoppingCartItemSubTotalWithDiscountBase = TaxManager.GetPrice(shoppingCartItem.ProductVariant, PriceHelper.GetSubTotal(shoppingCartItem, true));
            decimal shoppingCartItemSubTotalWithDiscount     = CurrencyManager.ConvertCurrency(shoppingCartItemSubTotalWithDiscountBase, CurrencyManager.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency);
            string  subTotalString = PriceHelper.FormatPrice(shoppingCartItemSubTotalWithDiscount);

            sb.Append("<span class=\"productPrice\">");
            sb.Append(subTotalString);
            sb.Append("</span>");

            decimal shoppingCartItemDiscountBase = TaxManager.GetPrice(shoppingCartItem.ProductVariant, PriceHelper.GetDiscountAmount(shoppingCartItem));

            if (shoppingCartItemDiscountBase > decimal.Zero)
            {
                decimal shoppingCartItemDiscount = CurrencyManager.ConvertCurrency(shoppingCartItemDiscountBase, CurrencyManager.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency);
                string  discountString           = PriceHelper.FormatPrice(shoppingCartItemDiscount);

                sb.Append("<br />");
                sb.Append(GetLocaleResourceString("Wishlist.ItemYouSave"));
                sb.Append("&nbsp;&nbsp;");
                sb.Append(discountString);
            }
            return(sb.ToString());
        }
Beispiel #29
0
        private void BindData()
        {
            GiftCard gc = OrderManager.GetGiftCardById(this.GiftCardId);

            if (gc != null)
            {
                this.lblOrder.Text    = string.Format("<a href=\"OrderDetails.aspx?OrderID={0}\">{1}</a>", gc.PurchasedOrderProductVariant.OrderId, GetLocaleResourceString("Admin.GiftCardInfo.Order.View"));
                this.lblCustomer.Text = string.Format("<a href=\"CustomerDetails.aspx?CustomerID={0}\">{1}</a>", gc.PurchasedOrderProductVariant.Order.CustomerId, GetLocaleResourceString("Admin.GiftCardInfo.Customer.View"));

                this.txtInitialValue.Value = GiftCardHelper.GetGiftCardInitialValue(gc);
                decimal remainingAmount = GiftCardHelper.GetGiftCardRemainingAmount(gc);
                this.lblRemainingAmount.Text       = PriceHelper.FormatPrice(remainingAmount, true, false);
                this.cbIsGiftCardActivated.Checked = gc.IsGiftCardActivated;
                this.txtCouponCode.Text            = gc.GiftCardCouponCode;
                this.txtRecipientName.Text         = gc.RecipientName;
                this.txtRecipientEmail.Text        = gc.RecipientEmail;
                this.txtSenderName.Text            = gc.SenderName;
                this.txtSenderEmail.Text           = gc.SenderEmail;
                this.txtMessage.Text = gc.Message;
                if (gc.IsRecipientNotified)
                {
                    lblIsRecipientNotified.Text = GetLocaleResourceString("Admin.Common.Yes");
                }
                else
                {
                    lblIsRecipientNotified.Text = GetLocaleResourceString("Admin.Common.No");
                }
                this.lblPurchasedOn.Text = DateTimeHelper.ConvertToUserTime(gc.CreatedOn).ToString();
            }
            else
            {
                Response.Redirect("PurchasedGiftCards.aspx");
            }
        }
Beispiel #30
0
        protected string FormatShippingOption(ShippingOption shippingOption)
        {
            decimal rateBase = TaxManager.GetShippingPrice(shippingOption.Rate, NopContext.Current.User);
            decimal rate     = CurrencyManager.ConvertCurrency(rateBase, CurrencyManager.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency);
            string  rateStr  = PriceHelper.FormatShippingPrice(rate, true);

            return(string.Format("({0})", rateStr));
        }