private object DummyEcommerceMethod2() { SKUInfo sku = null; IOrderRepository orderRepository = null; int orderId = 0; //DocSection:DisplayCatalogDiscounts // Initializes the needed services ShoppingService shoppingService = new ShoppingService(); PricingService pricingService = new PricingService(); // Gets the current shopping cart ShoppingCart shoppingCart = shoppingService.GetCurrentShoppingCart(); // Calculates prices for the specified product ProductPrice price = pricingService.CalculatePrice(sku, shoppingCart); // Gets the catalog discount decimal catalogDiscount = price.Discount; //EndDocSection:DisplayCatalogDiscounts //DocSection:DisplayOrderList // Gets the current customer Customer currentCustomer = shoppingService.GetCurrentCustomer(); // If the customer does not exist, returns error 404 if (currentCustomer == null) { return(HttpNotFound()); } // Creates a view model representing a collection of the customer's orders OrdersViewModel model = new OrdersViewModel() { Orders = orderRepository.GetByCustomerId(currentCustomer.ID) }; //EndDocSection:DisplayOrderList //DocSection:ReorderExistingOrder // Gets the order based on its ID Order order = orderRepository.GetById(orderId); // Gets the current visitor's shopping cart ShoppingCart cart = shoppingService.GetCurrentShoppingCart(); // Loops through the items in the order and adds them to the shopping cart foreach (OrderItem item in order.OrderItems) { cart.AddItem(item.SKUID, item.Units); } // Evaluates the shopping cart cart.Evaluate(); // Saves the shopping cart cart.Save(); //EndDocSection:ReorderExistingOrder return(null); }
public JsonResult Variant(int variantID) { // Gets SKU information based on the variant's ID SKUInfo variant = SKUInfoProvider.GetSKUInfo(variantID); // If the variant is null, returns null if (variant == null) { return(null); } // Calculates the price of the variant ProductPrice variantPrice = pricingService.CalculatePrice(variant, shoppingService.GetCurrentShoppingCart()); // Finds out whether the variant is in stock bool isInStock = variant.SKUTrackInventory == TrackInventoryTypeEnum.Disabled || variant.SKUAvailableItems > 0; // Creates a JSON response for the JavaScript that switches the variants var response = new { totalPrice = variantPrice.Currency.FormatPrice(variantPrice.Price), inStock = isInStock, stockMessage = isInStock ? "Yes" : "No" }; // Returns the response return(Json(response)); }
public InvoiceController(LiteDatabase db) { _db = db; InvoiceDatabase = _db.GetCollection <Invoice>("invoices"); var invoice = new Invoice(); var deliveryChargePrice = new ProductPrice { CalculatedPrice = 100 }; var deliveryCharge = new Product { Name = "Delivery Charge", Nickname = "DelCharge", UpdatedAt = DateTimeOffset.Now, Price = deliveryChargePrice }; var pipePrice = new ProductPrice { CalculatedPrice = 200 }; var pipe = new Product { Name = "Delivery Charge", Nickname = "DelCharge", UpdatedAt = DateTimeOffset.Now, Price = pipePrice }; invoice.Products.Add(new ProductsListItem(deliveryCharge, 1)); invoice.Products.Add(new ProductsListItem(pipe, 20)); InvoiceDatabase.Insert(invoice); }
private void ApplyProductPricesInternal(IEnumerable<Product> products, IEnumerable<VirtoCommercePricingModuleWebModelPrice> prices) { var workContext = _workContextFactory(); var alreadyDefinedProductsPriceGroups = prices.Select(x => x.ToWebModel(workContext.AllCurrencies, workContext.CurrentLanguage)).GroupBy(x => x.ProductId); foreach (var product in products) { var productPricesGroup = alreadyDefinedProductsPriceGroups.FirstOrDefault(x => x.Key == product.Id); if (productPricesGroup != null) { //Get first price for each currency product.Prices = productPricesGroup.GroupBy(x => x.Currency).Select(x => x.FirstOrDefault()).Where(x => x != null).ToList(); } //Need add product price for all store currencies (even if not returned from api need make it by currency exchange convertation) foreach (var storeCurrency in workContext.CurrentStore.Currencies) { var price = product.Prices.FirstOrDefault(x => x.Currency == storeCurrency); if (price == null) { price = new ProductPrice(storeCurrency); if (product.Prices.Any()) { price = product.Prices.First().ConvertTo(storeCurrency); } product.Prices.Add(price); } } product.Currency = workContext.CurrentCurrency; product.Price = product.Prices.FirstOrDefault(x => x.Currency.Equals(workContext.CurrentCurrency)); } }
public async Task <ActionResult <ProductPrice> > PostProductPrice(ProductPrice productPrice) { _context.ProductPrice.Add(productPrice); await _context.SaveChangesAsync(); return(CreatedAtAction("GetProductPrice", new { id = productPrice.ProductPriceId }, productPrice)); }
private static ProductPrice GetItemPrice(RequestContext requestContext, string itemId, string inventDimId, string unitOfMeasure, string customerAcctNumber) { SalesTransaction salesTransaction = new SalesTransaction { Id = Guid.NewGuid().ToString(), CustomerId = customerAcctNumber, }; SalesLine salesLine = new SalesLine() { LineId = Guid.NewGuid().ToString("N"), ItemId = itemId, InventoryDimensionId = inventDimId, SalesOrderUnitOfMeasure = unitOfMeasure, Quantity = 1m, }; salesTransaction.SalesLines.Add(salesLine); GetIndependentPriceDiscountServiceRequest priceRequest = new GetIndependentPriceDiscountServiceRequest(salesTransaction); GetPriceServiceResponse pricingServiceResponse = requestContext.Execute <GetPriceServiceResponse>(priceRequest); SalesLine resultLine = pricingServiceResponse.Transaction.SalesLines[0]; ProductPrice productPrice = GetProductPrice( resultLine.ItemId, resultLine.InventoryDimensionId, resultLine.BasePrice, resultLine.AgreementPrice, resultLine.AdjustedPrice, requestContext.GetChannelConfiguration().Currency); return(productPrice); }
public ActionResult AddStockPrice(ProductStockPriceModel model) { if (ModelState.IsValid) { using (_dbContext = new karrykartEntities()) { var productSizeMapping = new ProductSizeMapping() { ProductID = model.ProductID, SizeID = model.SizeID, UnitID = model.UnitID, Stock = model.Stock }; _dbContext.ProductSizeMappings.Add(productSizeMapping); var productprice = new ProductPrice() { UnitID = model.UnitID, CurrencyID = model.CurrencyID, ProductID = model.ProductID, SizeID = model.SizeID, Price = Convert.ToDecimal(model.Price) }; _dbContext.ProductPrices.Add(productprice); var productShipping = new ProductShipping() { UnitID = model.UnitID, ProductID = model.ProductID, SizeID = model.SizeID, Cost = Convert.ToDecimal(model.ShippingCost) }; _dbContext.ProductShippings.Add(productShipping); _dbContext.SaveChanges(); _logger.WriteLog(CommonHelper.MessageType.Success, "Product Stock and price added successfully with ID=" + model.Name, "AddStockPrice", "ProductController", User.Identity.Name); return(RedirectToAction("Index", "Product")); } } CreateViewBagForStockPrice(); return(View()); }
private JsonResult GetVariantResponse(ProductPrice priceDetail, bool inStock, string stockMessageResourceString, int variantSKUID) { string priceSavings = string.Empty; var currency = priceDetail.Currency; var beforeDiscount = priceDetail.Price + priceDetail.Discount; if (priceDetail.Discount > 0) { var discountPercentage = Math.Round(priceDetail.Discount * 100 / beforeDiscount); var discount = currency.FormatPrice(priceDetail.Discount); priceSavings = $"{discount} ({discountPercentage}%)"; } var response = new { totalPrice = currency.FormatPrice(priceDetail.Price), beforeDiscount = priceDetail.Discount > 0 ? currency.FormatPrice(beforeDiscount) : string.Empty, savings = priceSavings, stockMessage = ResHelper.GetString(stockMessageResourceString), inStock, variantSKUID }; return(Json(response)); }
public ActionResult <List <ProductPrice> > Create(ProductPrice ProductPrice) { //_context.ProductPrices.Add(new ProductPrice { ID=id }); _context.ProductPrices.Add(ProductPrice); _context.SaveChanges(); return(_context.ProductPrices.ToList()); }
protected decimal GetRetailPrice(object productID) { Product product = DataAccessContext.ProductRepository.GetOne(StoreContext.Culture, (string)productID, StoreContext.CurrentStore.StoreID); ProductPrice productPrice = product.GetProductPrice(StoreContext.CurrentStore.StoreID); return(productPrice.RetailPrice); }
public async Task <IActionResult> Create([Bind("ID, Ten, ProducerID, CategoryID, Gia")] ProductWithCurrentPrice model) { if (ModelState.IsValid) { var product = new Product { ID = model.ID, Ten = model.Ten, SoLuong = 0, ProducerID = model.ProducerID, CategoryID = model.CategoryID }; _context.Products.Add(product); await _context.SaveChangesAsync(); var productPrice = new ProductPrice { Gia = model.Gia, TGBD = DateTime.Now, TGKT = DateTime.Parse("9999-1-1"), ProductID = product.ID }; _context.ProductPrices.Add(productPrice); await _context.SaveChangesAsync(); TempData["messageSuccess"] = $"Sản phẩm \"{model.Ten}\" đã được thêm"; return(RedirectToAction("Details", "Products", new { id = product.ID })); } ViewBag.CategoryID = new SelectList(_context.Categories, "ID", "Ten", model.CategoryID); ViewBag.ProducerID = new SelectList(_context.Producers, "ID", "Ten", model.ProducerID); return(View(model)); }
public void GetProductPrices_Returns_Correct_Prices() { // Arrange Product product1 = GetProductWithName("Name1"); Product product2 = GetProductWithName("Name2"); product2.Id = 2; ProductContext ctx = new ProductContext(new DbContextOptions <ProductContext>()); ctx.Products = GetProductDbSet(product1, product2); ProductPrice price1a = GetPrice(product1); ProductPrice price1b = GetPrice(product1); ProductPrice price2a = GetPrice(product2); ProductPrice price2b = GetPrice(product2); ctx.Prices = GetPricesDbSet(price1a, price1b, price2a, price2b); SqlProductRepository target = new SqlProductRepository(ctx); // Act var result = target.GetProductPrices(2); // Assert Assert.Contains(price2a, result); Assert.Contains(price2b, result); }
private void populatePageData() { populateGrid(); grid.Sort(col_grid_productStoreName, ListSortDirection.Ascending); if (_inventory != null) { Guid?productPriceID = ProductPrice.getByCombination(null, null, null, null, _inventory.id, null); if (productPriceID != null) { _productPrice = new ProductPrice((Guid)productPriceID); setChkUseInventoryID(true); } else { productPriceID = ProductPrice.getByCombination(_inventory.product_store_name_id, _inventory.grade_id, _inventory.product_width_id, _inventory.length_unit_id, null, (Guid?)cbColors.SelectedValue); if (productPriceID != null) { _productPrice = new ProductPrice((Guid)productPriceID); } } } setMode(); }
private void chkUseInventoryID_CheckedChanged(object sender, EventArgs e) { if (_inventory != null) { Guid?productPriceID = null; if (chkUseInventoryID.Checked) { productPriceID = ProductPrice.getByCombination(null, null, null, null, _inventory.id, null); } else { productPriceID = ProductPrice.getByCombination(_inventory.product_store_name_id, _inventory.grade_id, _inventory.product_width_id, _inventory.length_unit_id, null, (Guid?)cbColors.SelectedValue); } if (productPriceID != null) { _productPrice = new ProductPrice((Guid)productPriceID); } else { _productPrice = null; } setMode(); } }
public async Task <IActionResult> PutProductPrice(int id, ProductPrice productPrice) { if (id != productPrice.ProductPriceId) { return(BadRequest()); } _context.Entry(productPrice).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ProductPriceExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
private string BuildOptionName(ProductPrice priceOption, string currencyCode, string option) { string optionName = string.Empty; if (priceOption.OfferRuleId != 0) { optionName = string.Format(DT_OPTION_NAME_FORMAT_OFFER_CURRENCY, currencyCode, priceOption.OfferPriceInclTax, option, currencyCode, priceOption.PriceInclTax, priceOption.Stock); } else { optionName = string.Format(DT_OPTION_NAME_FORMAT_CURRENCY, currencyCode, priceOption.PriceInclTax, option, priceOption.Stock); } return(optionName); }
public int InsertProductPrice(ProductPrice entity) { entity.CreatedBy = Convert.ToInt32(HttpContext.Current.Session["UserId"]); entity.UpdatedDate = DateTime.Now; entity.Status = true; return(_productPriceRepo.Insert(entity)); }
public void Update(ProductPriceDto item, bool save = true) { try { // Get existing Category object from database ProductPrice oldItem = GetFromModel().FirstOrDefault(x => x.Id.Equals(item.Id)); // Set the new values for the fetched Category object if (oldItem != null) { oldItem.Date = PersianDateTime.Now.ToString(); oldItem.PriceWithDiscount = item.PriceWithDiscount; oldItem.PriceWithoutDiscount = item.PriceWithoutDiscount; oldItem.ProductId = item.ProductId; if (save) { this.Context.SaveChanges(); } } } catch (Exception ex) { throw ex; } }
public IActionResult Create(ProductPriceViewModel productPriceViewModel) { productPriceViewModel.ProductId = productPriceViewModel.ProductId == 0 ? null : productPriceViewModel.ProductId; productPriceViewModel.PriceId = productPriceViewModel.PriceId == 0 ? null : productPriceViewModel.PriceId; if (ModelState.IsValid) { var productPrice = new ProductPrice { ProductId = productPriceViewModel.ProductId, PriceValue = productPriceViewModel.PriceValue, PriceId = productPriceViewModel.PriceId }; _work.ProductPrice.Add(productPrice); bool isSaved = _work.Save() > 0; if (isSaved) { return(Json(true)); } return(Json(false)); } return(Json(false)); }
private void SaveProductPrice() { try { var productPrice = new ProductPrice { Product = new Product { ProductCode = this.productCode }, StartDate = dtpStartDate.Value, EndDate = dtpStartDate.Value.AddDays(Convert.ToInt16(txtDay.Text)), Day = Convert.ToInt16(txtDay.Text), UnitPrice = Convert.ToDecimal(txtUnitPrice.Text), CreateBy = "system", ModifiedBy = "system" }; if (btnLovProduct.Enabled == true && txtProductName.Enabled == true) { ProductPriceController.Insert(productPrice); } else { ProductPriceController.Update(productPrice); } } catch (Exception) { throw; } }
/// <summary> /// Apply prices to product /// </summary> /// <param name="prices"></param> /// <param name="currentCurrency"></param> /// <param name="allCurrencies"></param> public virtual void ApplyPrices(IEnumerable <PricingModule.Core.Model.Price> prices, Currency currency) { AllPrices.Clear(); Price = null; AllPrices = prices.Where(x => x.ProductId == Id) .Select(x => { var productPrice = new ProductPrice(currency) { PricelistId = x.PricelistId, ListPrice = new Money(x.List, currency), MinQuantity = x.MinQuantity }; productPrice.SalePrice = x.Sale == null ? productPrice.ListPrice : new Money(x.Sale.GetValueOrDefault(), currency); return(productPrice); }).ToList(); //group prices by currency var groupByCurrencyPrices = AllPrices.GroupBy(x => x.Currency).Where(x => x.Any()); foreach (var currencyGroup in groupByCurrencyPrices) { //For each currency need get nominal price (with min qty) var orderedPrices = currencyGroup.OrderBy(x => x.MinQuantity ?? 0).ThenBy(x => x.ListPrice); var nominalPrice = orderedPrices.FirstOrDefault(); //and add to nominal price other prices as tier prices nominalPrice.TierPrices.AddRange(orderedPrices.Select(x => new TierPrice(x.SalePrice, x.MinQuantity ?? 1))); //Add nominal price to product prices list AllPrices.Add(nominalPrice); } //Set current product price for current currency Price = AllPrices.FirstOrDefault(x => x.Currency.Equals(currency)); }
private void textBoxSearch_TextChanged(object sender, EventArgs e) { DAL.ProductPrice productPrice = new ProductPrice(); productPrice.Search = textBoxSearch.Text; proGrid1.AutoGenerateColumns = false; proGrid1.DataSource = productPrice.Select().Tables[0]; }
private void buttonDelete_Click(object sender, EventArgs e) { if (proGrid1.SelectedRows.Count <= 0) { return; } DialogResult deleteConfrm = MessageBox.Show("Are you sure?", "Confirmation", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (deleteConfrm != DialogResult.Yes) { return; } DAL.ProductPrice productPrice = new ProductPrice(); string ids = ""; for (int i = 0; i < proGrid1.SelectedRows.Count; i++) { ids += proGrid1.SelectedRows[i].Cells["ColId"].Value.ToString() + ", "; } ids = ids.Substring(0, ids.Length - 2); if (productPrice.Delete(ids)) { MessageBox.Show("Product price is deleted"); buttonSearch.PerformClick(); } else { MessageBox.Show(productPrice.Error); } }
private List <Product> GetProductList() { Product product = new Product() { Id = 1, Description = "Description", Image = new byte[1], Name = "Name" }; ProductPrice price = new ProductPrice() { Id = 2, LastUpdate = DateTime.MinValue, Price = 1M, Product = product, ProductId = product.Id }; product.Price = new List <ProductPrice>() { price }; return(new List <Product>() { product }); }
private void btn_ok_Click(object sender, RoutedEventArgs e) { using (TransactionScope ts = new TransactionScope()) { try { /////////////////////////////////////////////ثبت قیمت جدید ProductPrice PP = new ProductPrice(); PP.ProductPricePurch = Convert.ToInt64(txt_purch.Text.Trim()); PP.ProductPriceSell = Convert.ToInt64(txt_sale.Text.Trim()); PP.ProductPriceDate = lbl_date.Content.ToString(); PP.ProductPriceDesc = txt_desc.Text.Trim(); PP.ProductId = this.productid; PP.UserId = PublicVariable.gUserId; database.ProductPrices.Add(PP); database.SaveChanges(); ///////////////////////////////////////////// بروز رسانی قیمت database.Sp_UpdateFee_Product(this.productid, Convert.ToInt64(txt_sale.Text.Trim()), Convert.ToInt64(txt_purch.Text.Trim())); database.SaveChanges(); ////////////////////////// ts.Complete(); MessageBox.Show("اطلاعات با موفقیت ذخیره شد"); } catch { MessageBox.Show("در ثبت اطلاعات مشکلی بوجود آمد"); } finally { this.Close(); } } }
public GeneralResponse DeleteProductPrice(DeleteRequest request) { GeneralResponse response = new GeneralResponse(); ProductPrice productPrice = new ProductPrice(); productPrice = _productPriceRepository.FindBy(request.ID); if (productPrice != null) { try { _productPriceRepository.Remove(productPrice); _uow.Commit(); ////response.success = true; } catch (Exception ex) { response.ErrorMessages.Add(ex.Message); } } return(response); }
public static ProductPrice PopulateProductPriceFromIDataReader(IDataReader dr) { ProductPrice productPrice = new ProductPrice(); productPrice.PriceID = DataRecordHelper.GetInt32(dr, "PriceID"); productPrice.ProductID = DataRecordHelper.GetInt32(dr, "ProductID"); productPrice.ModelID = DataRecordHelper.GetInt32(dr, "ModelID"); productPrice.DeliverySpan = DataRecordHelper.GetString(dr, "DeliverySpan"); productPrice.WarrantySpan = DataRecordHelper.GetString(dr, "WarrantySpan"); productPrice.IncludeFreight = (PriceIncludeType)DataRecordHelper.GetInt32(dr, "IncludeFreight"); productPrice.IncludeTax = (PriceIncludeType)DataRecordHelper.GetInt32(dr, "IncludeTax"); productPrice.ApplyTaxRate = DataRecordHelper.GetDecimal(dr, "ApplyTaxRate"); productPrice.QuoteMOQ = DataRecordHelper.GetInt32(dr, "QuoteMOQ"); productPrice.PriceMarket = DataRecordHelper.GetNullableDecimal(dr, "PriceMarket"); productPrice.PricePromotion = DataRecordHelper.GetNullableDecimal(dr, "PricePromotion"); productPrice.PriceFloor = DataRecordHelper.GetNullableDecimal(dr, "PriceFloor"); productPrice.PricePurchase = DataRecordHelper.GetNullableDecimal(dr, "PricePurchase"); productPrice.PriceGradeA = DataRecordHelper.GetNullableDecimal(dr, "PriceGradeA"); productPrice.PriceGradeB = DataRecordHelper.GetNullableDecimal(dr, "PriceGradeB"); productPrice.PriceGradeC = DataRecordHelper.GetNullableDecimal(dr, "PriceGradeC"); productPrice.PriceGradeD = DataRecordHelper.GetNullableDecimal(dr, "PriceGradeD"); productPrice.PriceGradeE = DataRecordHelper.GetNullableDecimal(dr, "PriceGradeE"); productPrice.SupplyRegion = DataRecordHelper.GetInt32(dr, "SupplyRegion"); productPrice.QuoteFrom = DataRecordHelper.GetDateTime(dr, "QuoteFrom"); productPrice.QuoteEnd = DataRecordHelper.GetDateTime(dr, "QuoteEnd"); productPrice.QuoteRenewal = DataRecordHelper.GetInt32(dr, "QuoteRenewal"); productPrice.SupplyStatus = (ComponentStatus)DataRecordHelper.GetInt32(dr, "SupplyStatus"); productPrice.CreateTime = DataRecordHelper.GetDateTime(dr, "CreateTime"); productPrice.CreateUser = DataRecordHelper.GetInt32(dr, "CreateUser"); productPrice.UpdateTime = DataRecordHelper.GetDateTime(dr, "UpdateTime"); productPrice.UpdateUser = DataRecordHelper.GetInt32(dr, "UpdateUser"); productPrice.SetSerializerData(CommonDataProvider.PopulateSerializerDataIDataRecord(dr)); return(productPrice); }
private void ApplyProductPricesInternal(IEnumerable <Product> products, IEnumerable <VirtoCommercePricingModuleWebModelPrice> prices) { var workContext = _workContextFactory(); var alreadyDefinedProductsPriceGroups = prices.Select(x => x.ToWebModel(workContext.AllCurrencies, workContext.CurrentLanguage)).GroupBy(x => x.ProductId); foreach (var product in products) { var productPricesGroup = alreadyDefinedProductsPriceGroups.FirstOrDefault(x => x.Key == product.Id); if (productPricesGroup != null) { //Get first price for each currency product.Prices = productPricesGroup.GroupBy(x => x.Currency).Select(x => x.FirstOrDefault()).Where(x => x != null).ToList(); } //Need add product price for all store currencies (even if not returned from api need make it by currency exchange convertation) foreach (var storeCurrency in workContext.CurrentStore.Currencies) { var price = product.Prices.FirstOrDefault(x => x.Currency == storeCurrency); if (price == null) { price = new ProductPrice(storeCurrency); if (product.Prices.Any()) { price = product.Prices.First().ConvertTo(storeCurrency); } product.Prices.Add(price); } } product.Currency = workContext.CurrentCurrency; product.Price = product.Prices.FirstOrDefault(x => x.Currency.Equals(workContext.CurrentCurrency)); } }
private void grid_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (Util.isColumnMatch(sender, e, col_grid_Checked)) { ProductPrice.update_Checked((Guid)Util.getSelectedRowValue(grid, col_grid_id), !Util.getCheckboxValue(sender, e)); populateGrid(); } else if (Tools.isCorrectColumn(sender, e, typeof(DataGridViewLinkColumn), col_grid_productStoreName.Name)) { clearForm(); _productPrice = new ProductPrice(Util.getClickedRowValue <Guid>(sender, e, col_grid_id)); if (_productPrice.InventoryID != null) { _inventory = new Inventory((Guid)_productPrice.InventoryID); } else { _inventory = null; } setMode(); } else if (Util.isColumnMatch(sender, e, col_grid_IsSelected)) { gbNonSelectionPanel.Visible = false; gbSelectionPanel.Visible = true; Util.clickDataGridViewCheckbox(sender, e); } }
private void btnSubmit_Click(object sender, EventArgs e) { ProductPrice obj; if (isInputFieldsValid(btnSubmit.Text == BTN_TEXT_UPDATE)) { if (chkUseInventoryID.Checked) { obj = new ProductPrice(null, null, null, null, Tools.zeroNonNumericString(txtTagPrice.Text), txtNotes.Text, _inventory.id, null, in_BuyPrice.Value); } else { obj = new ProductPrice((Guid)cbProductStoreNames.SelectedValue, (Guid)cbGrades.SelectedValue, (Guid)cbProductWidths.SelectedValue, (Guid)cbLengthUnits.SelectedValue, Tools.zeroNonNumericString(txtTagPrice.Text), txtNotes.Text, null, (Guid?)cbColors.SelectedValue, in_BuyPrice.Value); } if (btnSubmit.Text == BTN_TEXT_ADDNEW) { if (obj.submitNew() != null) { clearForm(); setInputAvailability(true); populateGrid(); } } else { obj.ID = _productPrice.ID; ProductPrice.update(obj.ID, obj.ProductStoreNameID, obj.GradeID, obj.ProductWidthID, obj.LengthUnitID, obj.TagPrice, obj.Notes, obj.InventoryID, obj.ColorID, obj.BuyPrice); populateGrid(); } } }
//EndDocSection:DisplayProduct //DocSection:DisplayVariant /// <summary> /// Displays product detail page of a product or a product variant specified by ID of the product's or variant's page. /// </summary> /// <param name="id">Node ID of the product's (variant's) page.</param> /// <param name="productAlias">Node alias of the product's (variant's) page.</param> public ActionResult Detail(int id, string productAlias) { // Gets the product from Kentico SKUTreeNode product = GetProduct(id); // If the product is not found or if it is not allowed for sale, redirects to error 404 if ((product == null) || !product.SKU.SKUEnabled) { return(HttpNotFound()); } // Redirects if the specified page alias does not match if (!string.IsNullOrEmpty(productAlias) && !product.NodeAlias.Equals(productAlias, StringComparison.InvariantCultureIgnoreCase)) { return(RedirectToActionPermanent("Detail", new { id = product.NodeID, productAlias = product.NodeAlias })); } // Gets all product variants of the product List <Variant> variants = variantRepository.GetByProductId(product.NodeSKUID).OrderBy(v => v.VariantPrice).ToList(); // Selects the first product variant Variant selectedVariant = variants.FirstOrDefault(); // Calculates the price of the product or the variant ShoppingCart cart = shoppingService.GetCurrentShoppingCart(); ProductPrice priceDetail = selectedVariant != null?pricingService.CalculatePrice(selectedVariant, cart) : pricingService.CalculatePrice(product.SKU, cart); // Initializes the view model of the product or product variant ProductViewModel viewModel = new ProductViewModel(product, priceDetail, variants, selectedVariant?.VariantSKUID ?? 0); // Displays the product detail page return(View(viewModel)); }
public ActionResult AddItem(int order, int product) { var entity = SalesQuote.TryFind (order); var p = Product.TryFind (product); int pl = entity.Customer.PriceList.Id; var cost = (from x in ProductPrice.Queryable where x.Product.Id == product && x.List.Id == 0 select x).SingleOrDefault (); var price = (from x in ProductPrice.Queryable where x.Product.Id == product && x.List.Id == pl select x).SingleOrDefault (); var discount = (from x in CustomerDiscount.Queryable where x.Product.Id == product && x.Customer.Id == entity.Customer.Id select x.Discount).SingleOrDefault (); if (entity.IsCompleted || entity.IsCancelled) { Response.StatusCode = 400; return Content (Resources.ItemAlreadyCompletedOrCancelled); } if (cost == null) { cost = new ProductPrice { Value = decimal.Zero }; } if (price == null) { price = new ProductPrice { Value = decimal.MaxValue }; } var item = new SalesQuoteDetail { SalesQuote = entity, Product = p, ProductCode = p.Code, ProductName = p.Name, TaxRate = p.TaxRate, IsTaxIncluded = p.IsTaxIncluded, Quantity = p.MinimumOrderQuantity, Price = price.Value, Discount = discount, Currency = entity.Currency, ExchangeRate = entity.ExchangeRate }; if (p.Currency != entity.Currency) { item.Price = price.Value * CashHelpers.GetTodayExchangeRate (p.Currency, entity.Currency); } using (var scope = new TransactionScope ()) { item.CreateAndFlush (); } return Json (new { id = item.Id }); }
public static ProductPrice ToWebModel(this VirtoCommercePricingModuleWebModelPrice price, IEnumerable<Currency> availCurrencies, Language language) { var currency = availCurrencies.FirstOrDefault(x => x.Equals(price.Currency)) ?? new Currency(language, price.Currency); var retVal = new ProductPrice(currency); retVal.InjectFrom(price); retVal.Currency = currency; retVal.ListPrice = new Money(price.List ?? 0d, currency); retVal.SalePrice = price.Sale == null ? retVal.ListPrice : new Money(price.Sale ?? 0d, currency); retVal.ActiveDiscount = new Discount { Amount = new Money(currency) }; return retVal; }
public static ProductPrice ToWebModel(this VirtoCommercePricingModuleWebModelPrice price) { var currency = new Currency(EnumUtility.SafeParse<CurrencyCodes>(price.Currency, CurrencyCodes.USD)); var retVal = new ProductPrice(currency); retVal.InjectFrom(price); retVal.Currency = currency; retVal.ListPrice = new Money((decimal)(price.List ?? 0), price.Currency); retVal.SalePrice = price.Sale == null ? retVal.ListPrice : new Money((decimal)price.Sale, price.Currency); retVal.AbsoluteBenefit = retVal.ListPrice - retVal.SalePrice; retVal.ActiveDiscount = new Discount { Amount = new Money(0, price.Currency) }; retVal.ActualPrice = retVal.SalePrice - retVal.ActiveDiscount.Amount; return retVal; }
public async Task EvaluateProductPricesAsync(IEnumerable<Product> products) { var workContext = _workContextFactory(); //Evaluate products prices var evalContext = new VirtoCommerceDomainPricingModelPriceEvaluationContext { ProductIds = products.Select(p => p.Id).ToList(), PricelistIds = workContext.CurrentPricelists.Select(p => p.Id).ToList(), CatalogId = workContext.CurrentStore.Catalog, CustomerId = workContext.CurrentCustomer.Id, Language = workContext.CurrentLanguage.CultureName, CertainDate = workContext.StorefrontUtcNow, StoreId = workContext.CurrentStore.Id }; var pricesResponse = await _pricingApi.PricingModuleEvaluatePricesAsync(evalContext); var alreadyDefinedProductsPriceGroups = pricesResponse.Select(x => x.ToWebModel(workContext.AllCurrencies, workContext.CurrentLanguage)).GroupBy(x => x.ProductId); foreach (var product in products) { var productPricesGroup = alreadyDefinedProductsPriceGroups.FirstOrDefault(x => x.Key == product.Id); if (productPricesGroup != null) { //Get first price for each currency product.Prices = productPricesGroup.GroupBy(x => x.Currency).Select(x => x.FirstOrDefault()).Where(x => x != null).ToList(); } //Need add product price for all store currencies (even if not returned from api need make it by currency exchange convertation) foreach (var storeCurrency in workContext.CurrentStore.Currencies) { var price = product.Prices.FirstOrDefault(x => x.Currency == storeCurrency); if (price == null) { price = new ProductPrice(storeCurrency); if (product.Prices.Any()) { price = product.Prices.First().ConvertTo(storeCurrency); } product.Prices.Add(price); } } product.Currency = workContext.CurrentCurrency; product.Price = product.Prices.FirstOrDefault(x => x.Currency.Equals(workContext.CurrentCurrency)); } }
public ShoppingCartItem AddItem(ShoppingCart cart, Product product, ProductPrice productPrice, int quantity) { Require.NotNull(cart, "cart"); Require.NotNull(product, "product"); Require.NotNull(productPrice, "productPrice"); Require.That(quantity > 0, "quantity", "Quantity should be greater than zero."); var item = cart.Items.FirstOrDefault(i => i.ProductPrice.Id == productPrice.Id); if (item == null) { item = new ShoppingCartItem(productPrice, quantity, cart); AddItem(cart, item); } else { ChangeItemQuantity(cart, item, item.Quantity + quantity); } return item; }
public ActionResult Confirm(int id) { PurchaseOrder item = PurchaseOrder.Find (id); var qry = from x in item.Details group x by x.Warehouse into g select new { Warehouse = g.Key, Details = g.ToList () }; var dt = DateTime.Now; var employee = CurrentUser.Employee; using (var scope = new TransactionScope ()) { foreach (var x in qry) { var master = new InventoryReceipt { Order = item, Warehouse = x.Warehouse, CreationTime = dt, ModificationTime = dt, Creator = employee, Updater = employee, Store = x.Warehouse.Store }; master.Create (); foreach (var y in x.Details) { var detail = new InventoryReceiptDetail { Receipt = master, Product = y.Product, QuantityOrdered = y.Quantity, Quantity = y.Quantity, ProductCode = y.ProductCode, ProductName = y.ProductName }; detail.Create (); InventoryHelpers.ChangeNotification (TransactionType.PurchaseOrder, item.Id, item.ModificationTime, x.Warehouse, null, y.Product, y.Quantity); } } foreach (var x in item.Details) { var price = x.Product.Prices.SingleOrDefault (t => t.List.Id == 0); if (price == null) { price = new ProductPrice { List = PriceList.Find (0), Product = x.Product }; } price.Value = x.Price; price.Save (); } item.IsCompleted = true; item.ModificationTime = DateTime.Now; item.UpdateAndFlush (); } return RedirectToAction ("Index"); }
public ProductPriceVariantValue(ProductPrice price, int fieldId, string value) { ProductPrice = price; CustomFieldId = fieldId; FieldValue = value; }
public ProductPriceDeleted(Product product, ProductPrice price) { ProductId = product.Id; ProductPriceId = price.Id; }
public bool UpdatePrice(Product product, int priceId, ProductPrice newPrice) { var price = product.FindPrice(priceId); if (price == null) { return false; } price.UpdateFrom(newPrice); _db.SaveChanges(); price.NotifyUpdated(); return true; }
public void AddPrice(Product product, ProductPrice price) { product.PriceList.Add(price); _db.SaveChanges(); Event.Raise(new ProductPriceAdded(product, price)); }
public ActionResult Create(Product item) { item.Supplier = Supplier.TryFind (item.SupplierId); if (!ModelState.IsValid) { return PartialView ("_Create", item); } item.MinimumOrderQuantity = 1; item.TaxRate = WebConfig.DefaultVAT; item.IsTaxIncluded = WebConfig.IsTaxIncluded; item.PriceType = WebConfig.DefaultPriceType; item.Photo = WebConfig.DefaultPhotoFile; using (var scope = new TransactionScope ()) { item.Create (); foreach (var l in PriceList.Queryable.ToList ()) { var price = new ProductPrice { Product = item, List = l, Value = WebConfig.DefaultPrice }; price.Create (); } scope.Flush (); } return PartialView ("_CreateSuccesful", item); }
public JsonResult SetPrice(int product, int list, string value) { decimal val; bool success; var p = Product.TryFind (product); var l = PriceList.TryFind (list); var item = ProductPrice.Queryable.SingleOrDefault (x => x.Product.Id == product && x.List.Id == list); if (item == null) { item = new ProductPrice { Product = p, List = l }; } success = decimal.TryParse (value.Trim (), System.Globalization.NumberStyles.Currency, null, out val); if (success && val >= 0) { item.Value = val; using (var scope = new TransactionScope ()) { item.SaveAndFlush (); } } return Json (new { id = item.Id, value = item.FormattedValueFor (x => x.Value) }); }
/// <summary> /// Excel to List of VOProductPrice /// </summary> public List<ProductPrice> ReadXlsFile(string fileLocation) { Application app = null; Workbook book = null; Worksheet sheet = null; var result = new List<ProductPrice>(); try { app = new ApplicationClass(); app.DisplayAlerts = false; book = app.Workbooks.Open(Server.MapPath(fileLocation), Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); sheet = (Worksheet)book.Sheets[1]; var rowCount = sheet.UsedRange.Rows.Count; Log.Info("rowCount " + rowCount); for (var i = 2; i <= rowCount; i++) { var price = new ProductPrice(); var priceId = (Range)sheet.Cells[i, 1]; if (priceId == null || string.IsNullOrEmpty(priceId.Text.ToString())) continue; price.PricingId = priceId.Text.ToString(); Marshal.FinalReleaseComObject(priceId); var productId = (Range)sheet.Cells[i, 3]; if (productId == null || string.IsNullOrEmpty(productId.Text.ToString())) continue; //store the product ID from the 3rd party system temporarily in the TcmId field. this will be converted later price.Product.TcmId = productId.Text.ToString(); Marshal.FinalReleaseComObject(productId); var threeRate = (Range)sheet.Cells[i, 4]; if (threeRate == null || string.IsNullOrEmpty(threeRate.Text.ToString())) continue; price.ThreeMonthRate = Convert.ToDecimal(threeRate.Text.ToString()); Marshal.FinalReleaseComObject(threeRate); var twelveRate = (Range)sheet.Cells[i, 7]; if (twelveRate == null || string.IsNullOrEmpty(twelveRate.Text.ToString())) continue; price.TwelveMonthRate = Convert.ToDecimal(twelveRate.Text.ToString()); Marshal.FinalReleaseComObject(twelveRate); result.Add(price); } } catch (Exception ex) { Log.Error("PricingManagement.ReadXlsFile: Error Reading XLS File", ex); return null; } finally { //all COM objects must be explicitly destroyed otherwise EXCEL.EXE stays open GC.Collect(); GC.WaitForPendingFinalizers(); if (sheet != null) { Marshal.FinalReleaseComObject(sheet); } if (book != null) { book.Close(Missing.Value, Missing.Value, Missing.Value); Marshal.FinalReleaseComObject(book); } if (app != null) { app.Quit(); Marshal.FinalReleaseComObject(app); } } return result; }
/// <summary> /// Apply prices to product /// </summary> /// <param name="prices"></param> /// <param name="currentCurrency"></param> public void ApplyPrices(IEnumerable<ProductPrice> prices, Currency currentCurrency, IEnumerable<Currency> allCurrencies) { Prices.Clear(); Price = null; Currency = currentCurrency; //group prices by currency var groupByCurrencyPrices = prices.GroupBy(x => x.Currency).Where(x => x.Any()); foreach (var currencyGroup in groupByCurrencyPrices) { //For each currency need get nominal price (with min qty) var orderedPrices = currencyGroup.OrderBy(x => x.MinQuantity ?? 0).ThenBy(x => x.ListPrice); var nominalPrice = orderedPrices.FirstOrDefault(); //and add to nominal price other prices as tier prices nominalPrice.TierPrices.AddRange(orderedPrices.Select(x => new TierPrice(x.SalePrice, x.MinQuantity ?? 1))); //Add nominal price to product prices list Prices.Add(nominalPrice); } //Need add product price for all currencies (even if not returned from API need make it by currency exchange conversation) foreach (var currency in allCurrencies) { var price = Prices.FirstOrDefault(x => x.Currency == currency); if (price == null) { price = new ProductPrice(currency); //Convert exist price to new currency if (Prices.Any()) { price = Prices.First().ConvertTo(currency); price.TierPrices.Add(new TierPrice(price.SalePrice, 1)); } Prices.Add(price); } } //Set current product price for current currency Price = Prices.FirstOrDefault(x => x.Currency == currentCurrency); }