public HttpResponseMessage add(AdditionalService post, Int32 languageId = 0) { // Check for errors if (post == null) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The post is null")); } else if (Language.MasterPostExists(languageId) == false) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The language does not exist")); } else if (Unit.MasterPostExists(post.unit_id) == false) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The unit does not exist")); } else if (ValueAddedTax.MasterPostExists(post.value_added_tax_id) == false) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The value added tax does not exist")); } // Make sure that the data is valid post.product_code = AnnytabDataValidation.TruncateString(post.product_code, 50); post.name = AnnytabDataValidation.TruncateString(post.name, 100); post.fee = AnnytabDataValidation.TruncateDecimal(post.fee, 0, 9999999999.99M); post.account_code = AnnytabDataValidation.TruncateString(post.account_code, 10); // Add the post Int64 insertId = AdditionalService.AddMasterPost(post); post.id = Convert.ToInt32(insertId); AdditionalService.AddLanguagePost(post, languageId); // Return the success response return(Request.CreateResponse <string>(HttpStatusCode.OK, "The post has been added")); } // End of the add method
public HttpResponseMessage update(ValueAddedTax post) { // Check for errors if (post == null) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The post is null"); } // Make sure that the data is valid post.value = AnnytabDataValidation.TruncateDecimal(post.value, 0, 9.99999M); // Get the saved post ValueAddedTax savedPost = ValueAddedTax.GetOneById(post.id); // Check if the post exists if (savedPost == null) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The record does not exist"); } // Update the post ValueAddedTax.Update(post); // Return the success response return Request.CreateResponse<string>(HttpStatusCode.OK, "The update was successful"); } // End of the update method
public HttpResponseMessage update(ValueAddedTax post) { // Check for errors if (post == null) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The post is null")); } // Make sure that the data is valid post.value = AnnytabDataValidation.TruncateDecimal(post.value, 0, 9.99999M); // Get the saved post ValueAddedTax savedPost = ValueAddedTax.GetOneById(post.id); // Check if the post exists if (savedPost == null) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The record does not exist")); } // Update the post ValueAddedTax.Update(post); // Return the success response return(Request.CreateResponse <string>(HttpStatusCode.OK, "The update was successful")); } // End of the update method
} // End of the Add method #endregion #region Update methods /// <summary> /// Update a value added tax post /// </summary> /// <param name="post">A reference to a value added tax post</param> public static void Update(ValueAddedTax post) { // Create the connection and the sql statement string connection = Tools.GetConnectionString(); string sql = "UPDATE dbo.value_added_taxes SET value = @value WHERE id = @id;"; // The using block is used to call dispose automatically even if there are an exception. using (SqlConnection cn = new SqlConnection(connection)) { // The using block is used to call dispose automatically even if there are an exception. using (SqlCommand cmd = new SqlCommand(sql, cn)) { // Add parameters cmd.Parameters.AddWithValue("@id", post.id); cmd.Parameters.AddWithValue("@value", post.value); // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to // avoid having our application crash in such cases. try { // Open the connection. cn.Open(); // Execute the update cmd.ExecuteNonQuery(); } catch (Exception e) { throw e; } } } } // End of the Update method
} // End of the GetAll method /// <summary> /// Get all value added taxes as a dictionary /// </summary> /// <param name="sortField">The field to sort on</param> /// <param name="sortOrder">The sort order</param> /// <returns>A dictionary with value added taxes</returns> public static Dictionary<Int32, ValueAddedTax> GetAllAsDictionary(string sortField, string sortOrder) { // Make sure that sort variables are valid sortField = GetValidSortField(sortField); sortOrder = GetValidSortOrder(sortOrder); // Create the list to return Dictionary<Int32, ValueAddedTax> posts = new Dictionary<Int32, ValueAddedTax>(10); // Create the connection string and the sql statement string connection = Tools.GetConnectionString(); string sql = "SELECT * FROM dbo.value_added_taxes ORDER BY " + sortField + " " + sortOrder + ";"; // The using block is used to call dispose automatically even if there is a exception using (SqlConnection cn = new SqlConnection(connection)) { // The using block is used to call dispose automatically even if there is a exception using (SqlCommand cmd = new SqlCommand(sql, cn)) { // Create a reader SqlDataReader reader = null; // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to // avoid having our application crash in such cases try { // Open the connection. cn.Open(); // Fill the reader with data from the select command. reader = cmd.ExecuteReader(); // Loop through the reader as long as there is something to read while (reader.Read()) { ValueAddedTax valueAddedTax = new ValueAddedTax(reader); posts.Add(valueAddedTax.id, valueAddedTax); } } catch (Exception e) { throw e; } finally { // Call Close when done reading to avoid memory leakage. if (reader != null) { reader.Close(); } } } } // Return the dictionary return posts; } // End of the GetAllAsDictionary method
public HttpResponseMessage translate(Product post, Int32 languageId = 0) { // Check for errors if (post == null) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The post is null")); } else if (Language.MasterPostExists(languageId) == false) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The language does not exist")); } else if (Product.MasterPostExists(post.id) == false) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The product does not exist")); } else if (ValueAddedTax.MasterPostExists(post.value_added_tax_id) == false) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The value added tax does not exist")); } // Make sure that the data is valid post.title = AnnytabDataValidation.TruncateString(post.title, 200); post.meta_description = AnnytabDataValidation.TruncateString(post.meta_description, 200); post.meta_keywords = AnnytabDataValidation.TruncateString(post.meta_keywords, 200); post.page_name = AnnytabDataValidation.TruncateString(post.page_name, 100); post.delivery_time = AnnytabDataValidation.TruncateString(post.delivery_time, 50); post.affiliate_link = AnnytabDataValidation.TruncateString(post.affiliate_link, 100); post.rating = AnnytabDataValidation.TruncateDecimal(post.rating, 0, 999999.99M); post.toll_freight_addition = AnnytabDataValidation.TruncateDecimal(post.toll_freight_addition, 0, 9999999999.99M); post.account_code = AnnytabDataValidation.TruncateString(post.account_code, 10); post.google_category = AnnytabDataValidation.TruncateString(post.google_category, 300); post.availability_status = AnnytabDataValidation.TruncateString(post.availability_status, 50); post.availability_date = AnnytabDataValidation.TruncateDateTime(post.availability_date); // Get a product on page name Product productOnPageName = Product.GetOneByPageName(post.page_name, languageId); // Check if the page name exists if (productOnPageName != null && post.id != productOnPageName.id) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The page name is not unique for the language")); } // Get the post Product savedPost = Product.GetOneById(post.id, languageId); // Check if we should add or update the post if (savedPost == null) { Product.AddLanguagePost(post, languageId); } else { Product.UpdateLanguagePost(post, languageId); } // Return the success response return(Request.CreateResponse <string>(HttpStatusCode.OK, "The translate was successful")); } // End of the translate method
public List <ValueAddedTax> get_all(string sortField = "", string sortOrder = "") { // Create the list to return List <ValueAddedTax> posts = ValueAddedTax.GetAll(sortField, sortOrder); // Return the list return(posts); } // End of the get_all method
public ValueAddedTax get_by_id(Int32 id = 0) { // Create the post to return ValueAddedTax post = ValueAddedTax.GetOneById(id); // Return the post return(post); } // End of the get_by_id method
public Dictionary <Int32, ValueAddedTax> get_all_as_dictionary(string sortField = "", string sortOrder = "") { // Create the list to return Dictionary <Int32, ValueAddedTax> posts = ValueAddedTax.GetAllAsDictionary(sortField, sortOrder); // Return the list return(posts); } // End of the get_all_as_dictionary method
public void CreateSaleItem() { using (SimpleSaleDbContext _context = new SimpleSaleDbContext()) { //Handles product Qty int quantity = 1; if (txtgetItemQuantity.Text != null && txtgetItemQuantity.Text != "") { quantity = int.Parse(txtgetItemQuantity.Text); } Product product = _context.Products .FirstOrDefault(x => x.Barcode == txtgetAddItemToCartBarcode.Text .ToString()); if (product == null) { MessageBox.Show("Please enter a valid product barcode", "Error - No Value", MessageBoxButton.OK, MessageBoxImage.Error); txtgetAddItemToCartBarcode.Focus(); } else { ValueAddedTax vat = _context.ValueAddedTaxes.FirstOrDefault(y => y.Id == 4); DiscountProduct discountOnProduct = _context.DiscountOnProducts.FirstOrDefault(z => z.ProductId == product.Id); Discount discount = new Discount(); if (discountOnProduct == null) { discount.DiscountName = "No Discount"; discount.DiscountValue = 0; } else { discount = _context.Discounts.FirstOrDefault(z => z.Id == discountOnProduct.DiscountId); } SaleItem saleItem = new SaleItem(); saleItem.ProductId = product.Id; saleItem.ValueAddedTaxId = vat.Id; saleItem.DiscountId = discount.Id; saleItem.Item = product.ProductName; saleItem.Barcode = product.Barcode; saleItem.Quantity = quantity; saleItem.UnitPrice = product.SellingPrice; saleItem.Discount = (saleItem.UnitPrice * saleItem.Quantity) * (discount.DiscountValue / 100); saleItem.PriceVat = saleItem.UnitPrice + (saleItem.UnitPrice * vat.VATValue / 100); saleItem.ItemsPrice = (saleItem.Quantity * saleItem.PriceVat) - saleItem.Discount; dgSaleItem.Items.Add(saleItem); saleItemsList.Add(saleItem); } } }
public void TestStrategyValueAddedTax() { IProductTax productTax = new ValueAddedTax(); Product product = new Product(productTax); const int price = 100; const double taxRate = 5; //Get Price with Value Added Tax Assert.AreEqual(product.GetTax(price), ((taxRate / 100) * price)); }
public void Init() { numberA = "98"; var legalForm = new LegalForm("ООО", EconomicAgentType.JuridicalPerson); juridicalPersonA = new JuridicalPerson(legalForm); juridicalPersonB = new JuridicalPerson(legalForm); juridicalPersonC = new JuridicalPerson(legalForm); juridicalPersonD = new JuridicalPerson(legalForm); senderOrganizationA = new AccountOrganization("Тестовое юридическое лицо A", "Тестовое юридическое лицо A", juridicalPersonA); senderOrganizationB = new AccountOrganization("Тестовое юридическое лицо B", "Тестовое юридическое лицо B", juridicalPersonB); receiverOrganizationC = new AccountOrganization("Тестовое юридическое лицо C", "Тестовое юридическое лицо C", juridicalPersonC); receiverOrganizationD = new AccountOrganization("Тестовое юридическое лицо D", "Тестовое юридическое лицо D", juridicalPersonD); storageA = new Storage("Тестовое хранилище A", StorageType.DistributionCenter) { Id = 1 }; storageB = new Storage("Тестовое хранилище B", StorageType.TradePoint) { Id = 2 }; articleGroup = new ArticleGroup("Тестовая группа", "Тестовая группа"); measureUnit = new MeasureUnit("шт.", "Штука", "123", 0) { Id = 1 }; articleA = new Article("Тестовый товар A", articleGroup, measureUnit, true); articleB = new Article("Тестовый товар B", articleGroup, measureUnit, true); articleC = new Article("Тестовый товар C", articleGroup, measureUnit, true); valueAddedTax = new ValueAddedTax("18%", 18); receiptWaybillRowA1 = new ReceiptWaybillRow(articleA, 300, 3000, new ValueAddedTax("18%", 18)); receiptWaybillRowA2 = new ReceiptWaybillRow(articleA, 400, 4000, new ValueAddedTax("18%", 18)); receiptWaybillRowB = new ReceiptWaybillRow(articleB, 20, 250, new ValueAddedTax("18%", 18)); receiptWaybillRowC = new ReceiptWaybillRow(articleC, 20, 250, new ValueAddedTax("18%", 18)); rowA1_1 = new MovementWaybillRow(receiptWaybillRowA1, 60, valueAddedTax); rowA1_2 = new MovementWaybillRow(receiptWaybillRowA1, 22, valueAddedTax); rowA2_1 = new MovementWaybillRow(receiptWaybillRowA2, 40, valueAddedTax); rowA2_2 = new MovementWaybillRow(receiptWaybillRowA2, 55, valueAddedTax); rowB = new MovementWaybillRow(receiptWaybillRowB, 15, valueAddedTax); rowC = new MovementWaybillRow(receiptWaybillRowC, 18, valueAddedTax); priceLists = new List <ArticleAccountingPrice>() { new ArticleAccountingPrice(articleA, 100), new ArticleAccountingPrice(articleB, 200), new ArticleAccountingPrice(articleC, 300) }; user = new User(new Employee("Иван", "Иванов", "Иванович", new EmployeePost("Менеджер"), null), "Иванов Иван", "ivanov", "pa$$w0rd", new Team("Тестовая команда", null), null); }
} // End of the MasterPostExists method /// <summary> /// Get one value added tax based on id /// </summary> /// <param name="id">The id for the post</param> /// <returns>A reference to a value added tax post</returns> public static ValueAddedTax GetOneById(Int32 id) { // Create the post to return ValueAddedTax post = null; // Create the connection and the sql statement string connection = Tools.GetConnectionString(); string sql = "SELECT * FROM dbo.value_added_taxes WHERE id = @id;"; // The using block is used to call dispose automatically even if there are an exception. using (SqlConnection cn = new SqlConnection(connection)) { // The using block is used to call dispose automatically even if there are an exception. using (SqlCommand cmd = new SqlCommand(sql, cn)) { // Add parameters cmd.Parameters.AddWithValue("@id", id); // Create a reader SqlDataReader reader = null; // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to // avoid having our application crash in such cases. try { // Open the connection. cn.Open(); // Fill the reader with one row of data. reader = cmd.ExecuteReader(); // Loop through the reader as long as there is something to read and add values while (reader.Read()) { post = new ValueAddedTax(reader); } } catch (Exception e) { throw e; } finally { // Call Close when done reading to avoid memory leakage. if (reader != null) reader.Close(); } } } // Return the post return post; } // End of the GetOneById method
public void AddNewVat() { using (SimpleSaleDbContext _context = new SimpleSaleDbContext()) { ValueAddedTax vat = new ValueAddedTax(); vat.VATName = txtVatName.Text.ToString(); vat.VATValue = Convert.ToDecimal(txtVatValue.Text.ToString()); _context.ValueAddedTaxes.Add(vat); _context.SaveChanges(); txtVatName.Clear(); txtVatValue.Clear(); MessageBox.Show("VAT Successfully Added To Table", "VAT"); } }
public ActionResult delete(Int32 id = 0, string returnUrl = "") { // Get the current domain Domain currentDomain = Tools.GetCurrentDomain(); ViewBag.CurrentDomain = currentDomain; // Get query parameters ViewBag.QueryParams = new QueryParams(returnUrl); // Check if the administrator is authorized if (Administrator.IsAuthorized(new string[] { "Administrator" }) == true) { ViewBag.AdminSession = true; } else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true) { ViewBag.AdminSession = true; ViewBag.AdminErrorCode = 1; ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC"); return View("index"); } else { // Redirect the user to the start page return RedirectToAction("index", "admin_login"); } // Create an error code variable Int32 errorCode = 0; // Delete the value added tax post and all the connected posts (CASCADE) errorCode = ValueAddedTax.DeleteOnId(id); // Check if there is an error if (errorCode != 0) { ViewBag.AdminSession = true; ViewBag.AdminErrorCode = errorCode; ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC"); return View("index"); } // Redirect the user to the list return Redirect("/admin_value_added_taxes" + returnUrl); } // End of the delete method
public ActionResult edit(Int32 id = 0, string returnUrl = "") { // Get the current domain Domain currentDomain = Tools.GetCurrentDomain(); ViewBag.CurrentDomain = currentDomain; // Get query parameters ViewBag.QueryParams = new QueryParams(returnUrl); // Check if the administrator is authorized if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor" }) == true) { ViewBag.AdminSession = true; } else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true) { ViewBag.AdminSession = true; ViewBag.AdminErrorCode = 1; ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC"); return View("index"); } else { // Redirect the user to the start page return RedirectToAction("index", "admin_login"); } // Get the default admin language Int32 adminLanguageId = currentDomain.back_end_language; // Add data to the view ViewBag.TranslatedTexts = StaticText.GetAll(adminLanguageId, "id", "ASC"); ViewBag.ValueAddedTax = ValueAddedTax.GetOneById(id); ViewBag.ReturnUrl = returnUrl; // Create a new empty value added tax post if the value added taxt post does not exist if (ViewBag.ValueAddedTax == null) { // Add data to the view ViewBag.ValueAddedTax = new ValueAddedTax(); } // Return the edit view return View("edit"); } // End of the edit method
public HttpResponseMessage delete(Int32 id = 0) { // Create an error code variable Int32 errorCode = 0; // Delete the post errorCode = ValueAddedTax.DeleteOnId(id); // Check if there is an error if (errorCode != 0) { return(Request.CreateResponse <string>(HttpStatusCode.Conflict, "Foreign key constraint")); } // Return the success response return(Request.CreateResponse <string>(HttpStatusCode.OK, "The delete was successful")); } // End of the delete method
public HttpResponseMessage add(ValueAddedTax post) { // Check for errors if (post == null) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The post is null")); } // Make sure that the data is valid post.value = AnnytabDataValidation.TruncateDecimal(post.value, 0, 9.99999M); // Add the post ValueAddedTax.Add(post); // Return the success response return(Request.CreateResponse <string>(HttpStatusCode.OK, "The post has been added")); } // End of the add method
public Int32 get_count_by_search(string keywords = "") { // Create the string array string[] wordArray = new string[] { "" }; // Recreate the array if keywords is different from null if (keywords != null) { wordArray = keywords.Split(' '); } // Get the count Int32 count = ValueAddedTax.GetCountBySearch(wordArray); // Return the count return(count); } // End of the get_count_by_search method
public HttpResponseMessage add(ValueAddedTax post) { // Check for errors if (post == null) { return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The post is null"); } // Make sure that the data is valid post.value = AnnytabDataValidation.TruncateDecimal(post.value, 0, 9.99999M); // Add the post ValueAddedTax.Add(post); // Return the success response return Request.CreateResponse<string>(HttpStatusCode.OK, "The post has been added"); } // End of the add method
public List <ValueAddedTax> get_by_search(string keywords = "", Int32 pageSize = 0, Int32 pageNumber = 0, string sortField = "", string sortOrder = "") { // Create the string array string[] wordArray = new string[] { "" }; // Recreate the array if keywords is different from null if (keywords != null) { wordArray = keywords.Split(' '); } // Create the list to return List <ValueAddedTax> posts = ValueAddedTax.GetBySearch(wordArray, pageSize, pageNumber, sortField, sortOrder); // Return the list return(posts); } // End of the get_by_search method
public HttpResponseMessage update(PaymentOption post, Int32 languageId = 0) { // Check for errors if (post == null) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The post is null")); } else if (Language.MasterPostExists(languageId) == false) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The language does not exist")); } else if (Unit.MasterPostExists(post.unit_id) == false) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The unit does not exist")); } else if (ValueAddedTax.MasterPostExists(post.value_added_tax_id) == false) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The value added tax does not exist")); } // Make sure that the data is valid post.product_code = AnnytabDataValidation.TruncateString(post.product_code, 50); post.name = AnnytabDataValidation.TruncateString(post.name, 100); post.payment_term_code = AnnytabDataValidation.TruncateString(post.payment_term_code, 10); post.fee = AnnytabDataValidation.TruncateDecimal(post.fee, 0, 9999999999.99M); post.account_code = AnnytabDataValidation.TruncateString(post.account_code, 10); // Get the saved post PaymentOption savedPost = PaymentOption.GetOneById(post.id, languageId); // Check if the post exists if (savedPost == null) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The record does not exist")); } // Update the post PaymentOption.UpdateMasterPost(post); PaymentOption.UpdateLanguagePost(post, languageId); // Return the success response return(Request.CreateResponse <string>(HttpStatusCode.OK, "The update was successful")); } // End of the update method
public HttpResponseMessage translate(AdditionalService post, Int32 languageId = 0) { // Check for errors if (post == null) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The post is null")); } else if (Language.MasterPostExists(languageId) == false) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The language does not exist")); } else if (AdditionalService.MasterPostExists(post.id) == false) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The additional service does not exist")); } else if (ValueAddedTax.MasterPostExists(post.value_added_tax_id) == false) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The value added tax does not exist")); } // Make sure that the data is valid post.product_code = AnnytabDataValidation.TruncateString(post.product_code, 50); post.name = AnnytabDataValidation.TruncateString(post.name, 100); post.fee = AnnytabDataValidation.TruncateDecimal(post.fee, 0, 9999999999.99M); post.account_code = AnnytabDataValidation.TruncateString(post.account_code, 10); // Get the saved post AdditionalService savedPost = AdditionalService.GetOneById(post.id, languageId); // Check if we should add or update the post if (savedPost == null) { AdditionalService.AddLanguagePost(post, languageId); } else { AdditionalService.UpdateLanguagePost(post, languageId); } // Return the success response return(Request.CreateResponse <string>(HttpStatusCode.OK, "The translation was successful")); } // End of the translate method
public void Init() { creationDate = DateTime.Now; currentDate = DateTime.Now; storage = new Storage("qwe", StorageType.ExtraStorage); deal = new Mock <Deal>(); quota = new DealQuota("asd", 10, 45, 15000); user = new Mock <User>(); createdBy = new Mock <User>(); team = new Mock <Team>(); contract = new Mock <ClientContract>(); accountOrganization = new Mock <AccountOrganization>(); valueAddedTax = new ValueAddedTax("18%", 18); ag = new ArticleGroup("Группа товаров", "Группа товаров"); art1 = new Article("Товар 1", ag, new MeasureUnit("шт.", "штуки", "123", 1), false); art2 = new Article("Товар 2", ag, new MeasureUnit("шт.", "штуки", "123", 1), false); art3 = new Article("Товар 3", ag, new MeasureUnit("шт.", "штуки", "123", 1), false); prices = new List <ArticleAccountingPrice>(); prices.Add(new ArticleAccountingPrice(art1, 10M)); prices.Add(new ArticleAccountingPrice(art2, 13M)); prices.Add(new ArticleAccountingPrice(art3, 15M)); receiptWaybillRow = new ReceiptWaybillRow(art1, 150, valueAddedTax, 75); user.Setup(x => x.Id).Returns(43); createdBy.Setup(x => x.Id).Returns(1); team.Setup(x => x.Id).Returns(1); deal.Setup(x => x.IsActive).Returns(true); deal.Setup(x => x.IsClosed).Returns(false); deal.Setup(x => x.Quotas).Returns(new List <DealQuota> { quota }); deal.Setup(x => x.Contract).Returns(contract.Object); deal.Setup(x => x.Id).Returns(2); accountOrganization.Setup(x => x.Storages).Returns(new List <Storage> { storage }); contract.Setup(x => x.AccountOrganization).Returns(accountOrganization.Object); waybill = new ExpenditureWaybill("123", currentDate, storage, deal.Object, team.Object, quota, false, user.Object, DeliveryAddressType.CustomAddress, "qwerty", creationDate, createdBy.Object); waybillRow = new ExpenditureWaybillRow(receiptWaybillRow, 10, valueAddedTax); waybill.AddRow(waybillRow); }
} // End of the constructor #endregion #region Insert methods /// <summary> /// Add one value added tax post /// </summary> /// <param name="post">A reference to a value added tax post</param> public static long Add(ValueAddedTax post) { // Create the long to return long idOfInsert = 0; // Create the connection and the sql statement string connection = Tools.GetConnectionString(); string sql = "INSERT INTO dbo.value_added_taxes (value) VALUES (@value);SELECT SCOPE_IDENTITY();"; // The using block is used to call dispose automatically even if there is a exception. using (SqlConnection cn = new SqlConnection(connection)) { // The using block is used to call dispose automatically even if there is a exception. using (SqlCommand cmd = new SqlCommand(sql, cn)) { // Add parameters cmd.Parameters.AddWithValue("@value", post.value); // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to // avoid having our application crash in such cases try { // Open the connection cn.Open(); /// Execute the insert idOfInsert = Convert.ToInt64(cmd.ExecuteScalar()); } catch (Exception e) { throw e; } } } // Return the id of the inserted item return idOfInsert; } // End of the Add method
} // End of the constructor #endregion #region Insert methods /// <summary> /// Add one value added tax post /// </summary> /// <param name="post">A reference to a value added tax post</param> public static long Add(ValueAddedTax post) { // Create the long to return long idOfInsert = 0; // Create the connection and the sql statement string connection = Tools.GetConnectionString(); string sql = "INSERT INTO dbo.value_added_taxes (value) VALUES (@value);SELECT SCOPE_IDENTITY();"; // The using block is used to call dispose automatically even if there is a exception. using (SqlConnection cn = new SqlConnection(connection)) { // The using block is used to call dispose automatically even if there is a exception. using (SqlCommand cmd = new SqlCommand(sql, cn)) { // Add parameters cmd.Parameters.AddWithValue("@value", post.value); // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to // avoid having our application crash in such cases try { // Open the connection cn.Open(); /// Execute the insert idOfInsert = Convert.ToInt64(cmd.ExecuteScalar()); } catch (Exception e) { throw e; } } } // Return the id of the inserted item return idOfInsert; } // End of the Add method
public ActionResult ZeroReturn(ZerroReturnViewModel zerroReturnViewModel) { if (ModelState.IsValid) { var data = new ValueAddedTax { Date = zerroReturnViewModel.DateTime, ZeroReturns = true, Percentage = 0, TaxableGoodsSalePrice = 0, Bank = "null", Branch = "null", DateTime = DateTime.Today, InstitutionInfoId = zerroReturnViewModel.InstuteId }; DateTime now = zerroReturnViewModel.DateTime; var startDate = new DateTime(now.Year, now.Month, 1); var endDate = startDate.AddMonths(1).AddDays(-1); var confirmation = _context.ValueAddedTaxs.Where(c => c.InstitutionInfoId == zerroReturnViewModel.InstuteId && c.Date <= endDate && c.Date >= startDate); if (confirmation.Any()) { return(RedirectToAction("Error")); } _context.ValueAddedTaxs.Add(data); _context.SaveChanges(); return(RedirectToAction("Index", "Home")); } return(RedirectToAction("Index", "Instution")); }
public void Init() { // инициализация IoC IoCInitializer.Init(); setting = new Setting() { UseReadyToAcceptStateForReturnFromClientWaybill = false }; settingRepository = Mock.Get(IoCContainer.Resolve <ISettingRepository>()); settingRepository.Setup(x => x.Get()).Returns(setting); storage = new Storage("qwe", StorageType.ExtraStorage) { Id = 42 }; accOrgSender = new Mock <AccountOrganization>(); accOrgSender.Setup(x => x.Id).Returns(1); accOrgRecipient = new Mock <AccountOrganization>(); accOrgRecipient.Setup(x => x.Id).Returns(2); valueAddedTax = new ValueAddedTax(); user = new Mock <User>(); user.Setup(x => x.GetPermissionDistributionType(It.IsAny <Permission>())).Returns(PermissionDistributionType.All); createdBy = new Mock <User>(); createdBy.Setup(x => x.GetPermissionDistributionType(It.IsAny <Permission>())).Returns(PermissionDistributionType.All); acceptedBy = new Mock <User>(); acceptedBy.Setup(x => x.GetPermissionDistributionType(It.IsAny <Permission>())).Returns(PermissionDistributionType.All); receiptedBy = new Mock <User>(); receiptedBy.Setup(x => x.GetPermissionDistributionType(It.IsAny <Permission>())).Returns(PermissionDistributionType.All); var articleGroup = new ArticleGroup("Тестовая группа", "Тестовая группа"); var measureUnit = new MeasureUnit("шт.", "Штука", "123", 0) { Id = 1 }; articleA = new Article("Тестовый товар A", articleGroup, measureUnit, true) { Id = 1 }; articleB = new Article("Тестовый товар Б", articleGroup, measureUnit, true) { Id = 2 }; receiptWaybillRow1 = new Mock <ReceiptWaybillRow>(); receiptWaybillRow1.Setup(x => x.Article).Returns(articleA); receiptWaybillRow2 = new Mock <ReceiptWaybillRow>(); receiptWaybillRow2.Setup(x => x.Article).Returns(articleB); articleAccountingPrice = new List <ArticleAccountingPrice>() { new ArticleAccountingPrice(articleA, 100) }; returnFromClientWaybillRepository = Mock.Get(IoCContainer.Resolve <IReturnFromClientWaybillRepository>()); articlePriceService = Mock.Get(IoCContainer.Resolve <IArticlePriceService>()); articlePriceService.Setup(x => x.GetArticleAccountingPrices(It.Is <short>(y => y == storage.Id), It.IsAny <IEnumerable <int> >())).Returns(articleAccountingPrice); articlePriceService.Setup(x => x.GetArticleAccountingPrices(It.Is <short>(y => y == storage.Id), It.IsAny <ISubQuery>(), It.IsAny <DateTime>())).Returns(articleAccountingPrice); returnFromClientWaybillRepository = Mock.Get(IoCContainer.Resolve <IReturnFromClientWaybillRepository>()); expenditureWaybillIndicatorService = Mock.Get(IoCContainer.Resolve <IExpenditureWaybillIndicatorService>()); articleAvailabilityService = Mock.Get(IoCContainer.Resolve <IArticleAvailabilityService>()); returnFromClientWaybillService = new ReturnFromClientWaybillService( IoCContainer.Resolve <ISettingRepository>(), returnFromClientWaybillRepository.Object, IoCContainer.Resolve <ITeamRepository>(), IoCContainer.Resolve <IDealRepository>(), IoCContainer.Resolve <IStorageRepository>(), IoCContainer.Resolve <IUserRepository>(), IoCContainer.Resolve <IArticlePriceService>(), IoCContainer.Resolve <IAcceptedSaleIndicatorService>(), IoCContainer.Resolve <IReturnFromClientService>(), IoCContainer.Resolve <IFactualFinancialArticleMovementService>(), IoCContainer.Resolve <IArticleMovementOperationCountService>(), IoCContainer.Resolve <IArticleMovementService>(), IoCContainer.Resolve <IDealPaymentDocumentDistributionService>(), IoCContainer.Resolve <IDealIndicatorService>(), IoCContainer.Resolve <IArticleRevaluationService>(), expenditureWaybillIndicatorService.Object, articleAvailabilityService.Object ); deal = new Mock <Deal>(); quota = new DealQuota("asd", 10, 45, 15000); team = new Team("Тестовая команда", It.IsAny <User>()) { Id = 1 }; contract = new Mock <ClientContract>(); var economicAgent = new Mock <EconomicAgent>(); accountOrganization = new AccountOrganization("asd", "asd", economicAgent.Object); deal.Setup(x => x.IsActive).Returns(true); deal.Setup(x => x.IsClosed).Returns(false); deal.Setup(x => x.Quotas).Returns(new List <DealQuota> { quota }); deal.Setup(x => x.Contract).Returns(contract.Object); accountOrganization.AddStorage(storage); contract.Setup(x => x.AccountOrganization).Returns(accountOrganization); returnFromClientWaybill = new ReturnFromClientWaybill("123", DateTime.Now, accountOrganization, deal.Object, team, storage, new ReturnFromClientReason(), user.Object, createdBy.Object, DateTime.Now); sale = new Mock <ExpenditureWaybill>(); sale.Setup(x => x.Sender).Returns(accountOrganization); sale.Setup(x => x.Team).Returns(team); sale.Setup(x => x.Is <ExpenditureWaybill>()).Returns(true); sale.Setup(x => x.As <ExpenditureWaybill>()).Returns(sale.Object); #region Создание позиции 1 saleRow1 = new Mock <ExpenditureWaybillRow>(); saleRow1.Setup(x => x.ExpenditureWaybill).Returns(sale.Object); saleRow1.Setup(x => x.SaleWaybill).Returns(sale.Object); saleRow1.Setup(x => x.Id).Returns(Guid.NewGuid()); saleRow1.Setup(x => x.SellingCount).Returns(100); saleRow1.Setup(x => x.As <ExpenditureWaybillRow>()).Returns(saleRow1.Object); saleRow1.Setup(x => x.Is <ExpenditureWaybillRow>()).Returns(true); saleRow1.Setup(x => x.Article).Returns(articleA); saleRow1.Setup(x => x.SalePrice).Returns(128); saleRow1.Setup(x => x.ReceiptWaybillRow).Returns(receiptWaybillRow1.Object); #endregion #region Создание позиции 2 saleRow2 = new Mock <ExpenditureWaybillRow>(); saleRow2.Setup(x => x.ExpenditureWaybill).Returns(sale.Object); saleRow2.Setup(x => x.SaleWaybill).Returns(sale.Object); saleRow2.Setup(x => x.Id).Returns(Guid.NewGuid()); saleRow2.Setup(x => x.SellingCount).Returns(100); saleRow2.Setup(x => x.As <ExpenditureWaybillRow>()).Returns(saleRow2.Object); saleRow2.Setup(x => x.Is <ExpenditureWaybillRow>()).Returns(true); saleRow2.Setup(x => x.Article).Returns(articleA); saleRow2.Setup(x => x.SalePrice).Returns(128); saleRow2.Setup(x => x.ReceiptWaybillRow).Returns(receiptWaybillRow2.Object); #endregion ReturnFromClientWaybillRow row = new ReturnFromClientWaybillRow(saleRow1.Object, 1); returnFromClientWaybill.AddRow(row); articleMovementService = new Mock <IArticleMovementService>(); articleMovementService.Setup(x => x.CancelArticleAcceptance(It.IsAny <WriteoffWaybill>())) .Returns(new List <OutgoingWaybillRowSourceReservationInfo>() { new OutgoingWaybillRowSourceReservationInfo(row.Id, 1, 1) }); articleMovementService.Setup(x => x.AcceptArticles(It.IsAny <WriteoffWaybill>())) .Returns(new List <OutgoingWaybillRowSourceReservationInfo>() { new OutgoingWaybillRowSourceReservationInfo(row.Id, 1, 1) }); }
public void Init() { // инициализация IoC IoCInitializer.Init(); setting = new Setting() { UseReadyToAcceptStateForWriteOffWaybill = false }; settingRepository = Mock.Get(IoCContainer.Resolve <ISettingRepository>()); settingRepository.Setup(x => x.Get()).Returns(setting); storage = new Storage("qwe", StorageType.ExtraStorage) { Id = 42 }; accOrgSender = new Mock <AccountOrganization>(); accOrgSender.Setup(x => x.Id).Returns(1); accOrgRecipient = new Mock <AccountOrganization>(); accOrgRecipient.Setup(x => x.Id).Returns(2); valueAddedTax = new ValueAddedTax(); user = new Mock <User>(); user.Setup(x => x.GetPermissionDistributionType(It.IsAny <Permission>())).Returns(PermissionDistributionType.All); createdBy = new Mock <User>(); createdBy.Setup(x => x.GetPermissionDistributionType(It.IsAny <Permission>())).Returns(PermissionDistributionType.All); acceptedBy = new Mock <User>(); acceptedBy.Setup(x => x.GetPermissionDistributionType(It.IsAny <Permission>())).Returns(PermissionDistributionType.All); var articleGroup = new ArticleGroup("Тестовая группа", "Тестовая группа"); var measureUnit = new MeasureUnit("шт.", "Штука", "123", 0) { Id = 1 }; articleA = new Article("Тестовый товар A", articleGroup, measureUnit, true) { Id = 1 }; receiptWaybillRow = new Mock <ReceiptWaybillRow>(); receiptWaybillRow.Setup(x => x.Article).Returns(articleA); articleAccountingPrice = new List <ArticleAccountingPrice>() { new ArticleAccountingPrice(articleA, 100) }; writeoffWaybillRepository = Mock.Get(IoCContainer.Resolve <IWriteoffWaybillRepository>()); articleRepository = Mock.Get(IoCContainer.Resolve <IArticleRepository>()); articlePriceService = Mock.Get(IoCContainer.Resolve <IArticlePriceService>()); articlePriceService.Setup(x => x.GetArticleAccountingPrices(It.Is <short>(y => y == storage.Id), It.IsAny <IEnumerable <int> >())).Returns(articleAccountingPrice); articlePriceService.Setup(x => x.GetArticleAccountingPrices(It.Is <short>(y => y == storage.Id), It.IsAny <ISubQuery>(), It.IsAny <DateTime>())).Returns(articleAccountingPrice); articleAvailabilityService = Mock.Get(IoCContainer.Resolve <IArticleAvailabilityService>()); articleMovementService = Mock.Get(IoCContainer.Resolve <IArticleMovementService>()); receiptWaybillService = Mock.Get(IoCContainer.Resolve <IReceiptWaybillService>()); articleRevaluationService = Mock.Get(IoCContainer.Resolve <IArticleRevaluationService>()); factualFinancialArticleMovementService = new Mock <IFactualFinancialArticleMovementService>(); articleMovementOperationCountService = new Mock <IArticleMovementOperationCountService>(); storageRepository = Mock.Get(IoCContainer.Resolve <IStorageRepository>()); userRepository = Mock.Get(IoCContainer.Resolve <IUserRepository>()); writeoffWaybillService = new WriteoffWaybillService(settingRepository.Object, writeoffWaybillRepository.Object, storageRepository.Object, userRepository.Object, articleMovementService.Object, articlePriceService.Object, factualFinancialArticleMovementService.Object, articleMovementOperationCountService.Object, articleAvailabilityService.Object, receiptWaybillService.Object, articleRevaluationService.Object); waybill = new WriteoffWaybill("123", DateTime.Now, storage, accOrgSender.Object, new WriteoffReason(), user.Object, createdBy.Object, DateTime.Now); WriteoffWaybillRow row = new WriteoffWaybillRow(receiptWaybillRow.Object, 10); waybill.AddRow(row); articleMovementService.Setup(x => x.CancelArticleAcceptance(It.IsAny <WriteoffWaybill>())) .Returns(new List <OutgoingWaybillRowSourceReservationInfo>() { new OutgoingWaybillRowSourceReservationInfo(row.Id, 1, 1) }); articleMovementService.Setup(x => x.AcceptArticles(It.IsAny <WriteoffWaybill>())) .Returns(new List <OutgoingWaybillRowSourceReservationInfo>() { new OutgoingWaybillRowSourceReservationInfo(row.Id, 1, 1) }); }
public void Init() { // инициализация IoC IoCInitializer.Init(); receiptWaybillRepository = Mock.Get(IoCContainer.Resolve <IReceiptWaybillRepository>()); articleRepository = Mock.Get(IoCContainer.Resolve <IArticleRepository>()); storageRepository = Mock.Get(IoCContainer.Resolve <IStorageRepository>()); movementWaybillRepository = Mock.Get(IoCContainer.Resolve <IMovementWaybillRepository>()); changeOwnerWaybillRepository = Mock.Get(IoCContainer.Resolve <IChangeOwnerWaybillRepository>()); writeoffWaybillRepository = Mock.Get(IoCContainer.Resolve <IWriteoffWaybillRepository>()); expenditureWaybillRepository = Mock.Get(IoCContainer.Resolve <IExpenditureWaybillRepository>()); returnFromClientWaybillRepository = Mock.Get(IoCContainer.Resolve <IReturnFromClientWaybillRepository>()); waybillRowArticleMovementRepository = Mock.Get(IoCContainer.Resolve <IWaybillRowArticleMovementRepository>()); var incomingWaybillRowService = new IncomingWaybillRowService(receiptWaybillRepository.Object, movementWaybillRepository.Object, changeOwnerWaybillRepository.Object, returnFromClientWaybillRepository.Object); var outgoingWaybillRowService = new OutgoingWaybillRowService(movementWaybillRepository.Object, IoCContainer.Resolve <IWriteoffWaybillRepository>(), IoCContainer.Resolve <IExpenditureWaybillRepository>(), changeOwnerWaybillRepository.Object, waybillRowArticleMovementRepository.Object); var articleMovementService = new ArticleMovementService(waybillRowArticleMovementRepository.Object, receiptWaybillRepository.Object, movementWaybillRepository.Object, changeOwnerWaybillRepository.Object, returnFromClientWaybillRepository.Object, Mock.Get(IoCContainer.Resolve <IWriteoffWaybillRepository>()).Object, Mock.Get(IoCContainer.Resolve <IExpenditureWaybillRepository>()).Object, incomingWaybillRowService, outgoingWaybillRowService); articleAvailabilityService = new ArticleAvailabilityService(receiptWaybillRepository.Object, movementWaybillRepository.Object, changeOwnerWaybillRepository.Object, writeoffWaybillRepository.Object, expenditureWaybillRepository.Object, returnFromClientWaybillRepository.Object, articleRepository.Object, storageRepository.Object, IoCContainer.Resolve <IIncomingAcceptedArticleAvailabilityIndicatorService>(), IoCContainer.Resolve <IOutgoingAcceptedFromExactArticleAvailabilityIndicatorService>(), IoCContainer.Resolve <IOutgoingAcceptedFromIncomingAcceptedArticleAvailabilityIndicatorService>(), IoCContainer.Resolve <IExactArticleAvailabilityIndicatorService>(), incomingWaybillRowService); var juridicalLegalForm = new LegalForm("ООО", EconomicAgentType.JuridicalPerson); var physicalLegalForm = new LegalForm("ИП", EconomicAgentType.PhysicalPerson); juridicalPerson = new JuridicalPerson(juridicalLegalForm) { Id = 1 }; physicalPerson = new PhysicalPerson(physicalLegalForm) { Id = 2 }; accountOrganization = new AccountOrganization("Тестовое юридическое лицо", "Тестовое юридическое лицо", juridicalPerson) { Id = 1 }; providerOrganization = new ProviderOrganization("Тестовое физическое лицо", "Тестовое физическое лицо", physicalPerson) { Id = 2 }; provider = new Provider("Тестовый поставщик", new ProviderType("Тестовый тип поставщика"), ProviderReliability.Medium, 5); provider.AddContractorOrganization(providerOrganization); providerContract = new ProviderContract(accountOrganization, providerOrganization, "ABC", "123", DateTime.Now, DateTime.Today); provider.AddProviderContract(providerContract); articleGroup = new ArticleGroup("Тестовая группа", "Тестовая группа"); measureUnit = new MeasureUnit("шт.", "Штука", "123", 0) { Id = 1 }; storageG = new Storage("G", StorageType.DistributionCenter) { Id = 1 }; storageM = new Storage("M", StorageType.DistributionCenter) { Id = 2 }; storageN = new Storage("N", StorageType.DistributionCenter) { Id = 3 }; articleA = new Article("A", articleGroup, measureUnit, false) { Id = 101 }; articleB = new Article("B", articleGroup, measureUnit, false) { Id = 102 }; articleC = new Article("C", articleGroup, measureUnit, false) { Id = 103 }; valueAddedTax = new ValueAddedTax("18%", 18); priceLists = new List <ArticleAccountingPrice>() { new ArticleAccountingPrice(articleA, 100), new ArticleAccountingPrice(articleB, 200), new ArticleAccountingPrice(articleC, 300) }; }
public HttpResponseMessage add(Product post, Int32 languageId = 0) { // Check for errors if (post == null) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The post is null")); } else if (Language.MasterPostExists(languageId) == false) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The language does not exist")); } else if (Category.MasterPostExists(post.category_id) == false) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The category does not exist")); } else if (Unit.MasterPostExists(post.unit_id) == false) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The unit does not exist")); } else if (ValueAddedTax.MasterPostExists(post.value_added_tax_id) == false) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The value added tax does not exist")); } // Make sure that the data is valid post.product_code = AnnytabDataValidation.TruncateString(post.product_code, 20); post.manufacturer_code = AnnytabDataValidation.TruncateString(post.manufacturer_code, 20); post.gtin = AnnytabDataValidation.TruncateString(post.gtin, 20); post.unit_price = AnnytabDataValidation.TruncateDecimal(post.unit_price, 0, 9999999999.99M); post.unit_freight = AnnytabDataValidation.TruncateDecimal(post.unit_freight, 0, 9999999999.99M); post.mount_time_hours = AnnytabDataValidation.TruncateDecimal(post.mount_time_hours, 0, 9999.99M); post.brand = AnnytabDataValidation.TruncateString(post.brand, 50); post.supplier_erp_id = AnnytabDataValidation.TruncateString(post.supplier_erp_id, 20); post.meta_robots = AnnytabDataValidation.TruncateString(post.meta_robots, 20); post.buys = AnnytabDataValidation.TruncateDecimal(post.buys, 0, 9999999999.99M); post.condition = AnnytabDataValidation.TruncateString(post.condition, 20); post.variant_image_filename = AnnytabDataValidation.TruncateString(post.variant_image_filename, 50); post.availability_status = AnnytabDataValidation.TruncateString(post.availability_status, 50); post.availability_date = AnnytabDataValidation.TruncateDateTime(post.availability_date); post.gender = AnnytabDataValidation.TruncateString(post.gender, 20); post.age_group = AnnytabDataValidation.TruncateString(post.age_group, 20); post.title = AnnytabDataValidation.TruncateString(post.title, 200); post.meta_description = AnnytabDataValidation.TruncateString(post.meta_description, 200); post.meta_keywords = AnnytabDataValidation.TruncateString(post.meta_keywords, 200); post.page_name = AnnytabDataValidation.TruncateString(post.page_name, 100); post.delivery_time = AnnytabDataValidation.TruncateString(post.delivery_time, 50); post.affiliate_link = AnnytabDataValidation.TruncateString(post.affiliate_link, 100); post.rating = AnnytabDataValidation.TruncateDecimal(post.rating, 0, 999999.99M); post.toll_freight_addition = AnnytabDataValidation.TruncateDecimal(post.toll_freight_addition, 0, 9999999999.99M); post.account_code = AnnytabDataValidation.TruncateString(post.account_code, 10); post.google_category = AnnytabDataValidation.TruncateString(post.google_category, 300); post.unit_pricing_measure = AnnytabDataValidation.TruncateDecimal(post.unit_pricing_measure, 0, 99999.99999M); post.size_type = AnnytabDataValidation.TruncateString(post.size_type, 20); post.size_system = AnnytabDataValidation.TruncateString(post.size_system, 10); post.energy_efficiency_class = AnnytabDataValidation.TruncateString(post.energy_efficiency_class, 10); post.date_added = AnnytabDataValidation.TruncateDateTime(post.date_added); post.discount = AnnytabDataValidation.TruncateDecimal(post.discount, 0, 9.999M); // Get a product on page name Product productOnPageName = Product.GetOneByPageName(post.page_name, languageId); // Check if the page name exists if (productOnPageName != null && post.id != productOnPageName.id) { return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The page name is not unique for the language")); } // Add the post Int64 insertId = Product.AddMasterPost(post); post.id = Convert.ToInt32(insertId); Product.AddLanguagePost(post, languageId); // Return the success response return(Request.CreateResponse <string>(HttpStatusCode.OK, "The post has been added")); } // End of the add method
} // End of the Add method #endregion #region Update methods /// <summary> /// Update a value added tax post /// </summary> /// <param name="post">A reference to a value added tax post</param> public static void Update(ValueAddedTax post) { // Create the connection and the sql statement string connection = Tools.GetConnectionString(); string sql = "UPDATE dbo.value_added_taxes SET value = @value WHERE id = @id;"; // The using block is used to call dispose automatically even if there are an exception. using (SqlConnection cn = new SqlConnection(connection)) { // The using block is used to call dispose automatically even if there are an exception. using (SqlCommand cmd = new SqlCommand(sql, cn)) { // Add parameters cmd.Parameters.AddWithValue("@id", post.id); cmd.Parameters.AddWithValue("@value", post.value); // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to // avoid having our application crash in such cases. try { // Open the connection. cn.Open(); // Execute the update cmd.ExecuteNonQuery(); } catch (Exception e) { throw e; } } } } // End of the Update method
public ActionResult edit(FormCollection collection) { // Get the current domain Domain currentDomain = Tools.GetCurrentDomain(); ViewBag.CurrentDomain = currentDomain; // Get query parameters string returnUrl = collection["returnUrl"]; ViewBag.QueryParams = new QueryParams(returnUrl); // Check if the administrator is authorized if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor" }) == true) { ViewBag.AdminSession = true; } else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true) { ViewBag.AdminSession = true; ViewBag.AdminErrorCode = 1; ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC"); return View("index"); } else { // Redirect the user to the start page return RedirectToAction("index", "admin_login"); } // Get all the form values Int32 id = Convert.ToInt32(collection["txtId"]); decimal percent = 0; decimal.TryParse(collection["txtPercent"].Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture, out percent); // Get the default admin language id Int32 adminLanguageId = currentDomain.back_end_language; // Get translated texts KeyStringList tt = StaticText.GetAll(adminLanguageId, "id", "ASC"); // Get the value added tax ValueAddedTax valueAddedTax = ValueAddedTax.GetOneById(id); bool postExists = true; // Check if the value added tax exists if (valueAddedTax == null) { // Create an empty value added tax valueAddedTax = new ValueAddedTax(); postExists = false; } // Update values valueAddedTax.value = percent; // Create a error message string errorMessage = string.Empty; // Check for errors in the value added tax if (valueAddedTax.value < 0 || valueAddedTax.value > 9.99999M) { errorMessage += "• " + String.Format(tt.Get("error_field_range"), tt.Get("percent"), "9.99999") + "<br/>"; } // Check if there is errors if (errorMessage == string.Empty) { // Check if we should add or update the static text if (postExists == false) { // Add the value added tax ValueAddedTax.Add(valueAddedTax); } else { // Update the value added tax ValueAddedTax.Update(valueAddedTax); } // Redirect the user to the list return Redirect("/admin_value_added_taxes" + returnUrl); } else { // Set form values ViewBag.ErrorMessage = errorMessage; ViewBag.ValueAddedTax = valueAddedTax; ViewBag.TranslatedTexts = tt; ViewBag.ReturnUrl = returnUrl; // Return the edit view return View("edit"); } } // End of the edit method
} // End of the Create method /// <summary> /// Write one product item to the file /// </summary> /// <param name="writer">A reference to an stream writer</param> /// <param name="domain">A reference to a domain</param> /// <param name="country">A referende to a country</param> /// <param name="product">A reference to a product</param> /// <param name="currency">A reference to a currency</param> /// <param name="decimalMultiplier">The decimal multiplier</param> private static void WriteProductItem(StreamWriter writer, Domain domain, Country country, Product product, Currency currency, Int32 decimalMultiplier) { // Get the value added tax ValueAddedTax valueAddedTax = ValueAddedTax.GetOneById(product.value_added_tax_id); // Get the unit Unit unit = Unit.GetOneById(product.unit_id, domain.front_end_language); // Get the category Category category = Category.GetOneById(product.category_id, domain.front_end_language); // Get a chain of parent categories List<Category> parentCategoryChain = Category.GetParentCategoryChain(category, domain.front_end_language); // Create the category string string categoryString = ""; for (int i = 0; i < parentCategoryChain.Count; i++) { categoryString += parentCategoryChain[i].title; if (i < parentCategoryChain.Count - 1) { categoryString += " > "; } } // Remove html from the title and the main content string title = StringHtmlExtensions.StripHtml(product.title); title = title.Replace("|", ""); string main_content = Regex.Replace(product.main_content, @"(<br\s*[\/]>)+", " "); main_content = StringHtmlExtensions.StripHtml(main_content); main_content = Regex.Replace(main_content, @"\r\n?|\n", ""); main_content = main_content.Replace("|", ""); main_content = AnnytabDataValidation.TruncateString(main_content, 5000); // Calculate the price decimal basePrice = product.unit_price * (currency.currency_base / currency.conversion_rate); decimal regularPrice = Math.Round(basePrice * decimalMultiplier, MidpointRounding.AwayFromZero) / decimalMultiplier; decimal salePrice = Math.Round(basePrice * (1 - product.discount) * decimalMultiplier, MidpointRounding.AwayFromZero) / decimalMultiplier; // Get the country code as upper case letters string countryCodeUpperCase = country.country_code.ToUpper(); // Add value added tax to the price if (countryCodeUpperCase != "US" && countryCodeUpperCase != "CA" && countryCodeUpperCase != "IN") { regularPrice += Math.Round(regularPrice * valueAddedTax.value * decimalMultiplier, MidpointRounding.AwayFromZero) / decimalMultiplier; salePrice += Math.Round(salePrice * valueAddedTax.value * decimalMultiplier, MidpointRounding.AwayFromZero) / decimalMultiplier; } // Calculate the freight decimal freight = (product.unit_freight + product.toll_freight_addition) * (currency.currency_base / currency.conversion_rate); freight = Math.Round(freight * decimalMultiplier, MidpointRounding.AwayFromZero) / decimalMultiplier; // Add value added tax to the freight if (countryCodeUpperCase != "US" && countryCodeUpperCase != "CA" && countryCodeUpperCase != "IN") { freight += Math.Round(freight * valueAddedTax.value * decimalMultiplier, MidpointRounding.AwayFromZero) / decimalMultiplier; } // Create the line to write to // Category|Product name|SKU|Price|Shipping Cost|Product URL|Manufacturer SKU|Manufacturer|EAN or UPC|Description|Image URL|Stock Status|Delivery time|Product state|ISBN string line = ""; // Category line += categoryString + "|"; // Product name line += title + "|"; // SKU line += product.product_code + "|"; // Price line += salePrice.ToString(CultureInfo.InvariantCulture) + "|"; // Shipping Cost line += freight.ToString(CultureInfo.InvariantCulture) + "|"; // Product URL line += domain.web_address + "/home/product/" + product.page_name + "|"; // Manufacturer SKU line += product.manufacturer_code + "|"; // Manufacturer line += product.brand + "|"; // EAN or UPC line += product.gtin + "|"; // Description line += main_content + "|"; // Image URL line += domain.web_address + Tools.GetProductMainImageUrl(product.id, domain.front_end_language, product.variant_image_filename, product.use_local_images) + "|"; // Stock Status line += GetAvailabilityStatus(product.availability_status) + "|"; // Delivery time line += product.delivery_time + "|"; // Product state line += product.condition != "" ? product.condition + "|" : "new|"; // ISBN line += product.gtin; // Write the line to the file writer.WriteLine(line); } // End of the WriteProductItem method
} // End of the GetAll method /// <summary> /// Get all value added taxes as a dictionary /// </summary> /// <param name="sortField">The field to sort on</param> /// <param name="sortOrder">The sort order</param> /// <returns>A dictionary with value added taxes</returns> public static Dictionary<Int32, ValueAddedTax> GetAllAsDictionary(string sortField, string sortOrder) { // Make sure that sort variables are valid sortField = GetValidSortField(sortField); sortOrder = GetValidSortOrder(sortOrder); // Create the list to return Dictionary<Int32, ValueAddedTax> posts = new Dictionary<Int32, ValueAddedTax>(10); // Create the connection string and the sql statement string connection = Tools.GetConnectionString(); string sql = "SELECT * FROM dbo.value_added_taxes ORDER BY " + sortField + " " + sortOrder + ";"; // The using block is used to call dispose automatically even if there is a exception using (SqlConnection cn = new SqlConnection(connection)) { // The using block is used to call dispose automatically even if there is a exception using (SqlCommand cmd = new SqlCommand(sql, cn)) { // Create a reader SqlDataReader reader = null; // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to // avoid having our application crash in such cases try { // Open the connection. cn.Open(); // Fill the reader with data from the select command. reader = cmd.ExecuteReader(); // Loop through the reader as long as there is something to read while (reader.Read()) { ValueAddedTax valueAddedTax = new ValueAddedTax(reader); posts.Add(valueAddedTax.id, valueAddedTax); } } catch (Exception e) { throw e; } finally { // Call Close when done reading to avoid memory leakage. if (reader != null) { reader.Close(); } } } } // Return the dictionary return posts; } // End of the GetAllAsDictionary method
public ActionResult AddTaxInfo(ValueAddedTax valueAddedTax) { if (!ModelState.IsValid) { if (valueAddedTax.InstitutionInfoId != 0) { return(RedirectToAction("Index", "ValueAddedTax", new { id = valueAddedTax.InstitutionInfoId })); } return(RedirectToAction("Index", "Instution")); } // Check Value exist or not DateTime now = valueAddedTax.Date.GetValueOrDefault(); var startDate = new DateTime(now.Year, now.Month, 1); var endDate = startDate.AddMonths(1).AddDays(-1); var confirmation = _context.ValueAddedTaxs.Where(c => c.InstitutionInfoId == valueAddedTax.InstitutionInfoId && c.Date <= endDate && c.Date >= startDate).ToList(); if (confirmation.Any()) { return(RedirectToAction("Error")); } // End Section // Assagin Data double taxableGoodsSalePrice = valueAddedTax.TaxableGoodsSalePrice.GetValueOrDefault(); double taxableGoodsSupplementaryDuty = valueAddedTax.TaxableGoodsSupplementaryDuty.GetValueOrDefault(); double taxableGoodsValueAddedTax = valueAddedTax.TaxableGoodsValueAddedTax.GetValueOrDefault(); double zeroRatedSalePrice = valueAddedTax.ZeroRatedSalePrice.GetValueOrDefault(); double zeroRatedSupplementaryDuty = valueAddedTax.ZeroRatedSupplementaryDuty.GetValueOrDefault(); double zeroRatedValueAddedTax = valueAddedTax.ZeroRatedValueAddedTax.GetValueOrDefault(); double exemptSalePrice = valueAddedTax.ExemptSalePrice.GetValueOrDefault(); double exemptSupplementaryDuty = valueAddedTax.ExemptSupplementaryDuty.GetValueOrDefault(); double exemptValueAddedTax = valueAddedTax.ExemptValueAddedTax.GetValueOrDefault(); double otherConsolidation = valueAddedTax.OtherConsolidation.GetValueOrDefault(); double totalTaxPayable = valueAddedTax.TotalTaxPayable.GetValueOrDefault(); double totalPayable = valueAddedTax.TotalPayable.GetValueOrDefault(); double sourceCut = valueAddedTax.SourceCut.GetValueOrDefault(); double owing = valueAddedTax.Owing.GetValueOrDefault(); double amercement = valueAddedTax.Amercement.GetValueOrDefault(); double fine = valueAddedTax.Fine.GetValueOrDefault(); double rentSppace = valueAddedTax.RentSppace.GetValueOrDefault(); if (valueAddedTax.Percentage != null && valueAddedTax.Percentage == 15) { //For number 1 taxableGoodsValueAddedTax = (taxableGoodsSalePrice + taxableGoodsSupplementaryDuty) * 15 / 100; //For number 4 totalTaxPayable = taxableGoodsSupplementaryDuty + zeroRatedSupplementaryDuty + exemptSupplementaryDuty + taxableGoodsValueAddedTax + zeroRatedValueAddedTax + exemptValueAddedTax; //For number 5 otherConsolidation = sourceCut + owing + amercement + fine + rentSppace; //For number 6 totalPayable = totalTaxPayable + otherConsolidation; } else if (valueAddedTax.Percentage != null && valueAddedTax.Percentage == 4) { //For number 1 taxableGoodsValueAddedTax = (taxableGoodsSalePrice + taxableGoodsSupplementaryDuty) * 4 / 100; //For number 4 totalTaxPayable = taxableGoodsSupplementaryDuty + zeroRatedSupplementaryDuty + exemptSupplementaryDuty + taxableGoodsValueAddedTax + zeroRatedValueAddedTax + exemptValueAddedTax; //For number 5 otherConsolidation = sourceCut + owing + amercement + fine + rentSppace; //For number 6 totalPayable = totalTaxPayable + otherConsolidation; } var data = new ValueAddedTax { Id = valueAddedTax.Id, Date = valueAddedTax.Date, ZeroReturns = false, Percentage = valueAddedTax.Percentage, TaxableGoodsSalePrice = taxableGoodsSalePrice, TaxableGoodsSupplementaryDuty = taxableGoodsSupplementaryDuty, TaxableGoodsValueAddedTax = taxableGoodsValueAddedTax, ZeroRatedSalePrice = zeroRatedSalePrice, ZeroRatedSupplementaryDuty = zeroRatedSupplementaryDuty, ZeroRatedValueAddedTax = zeroRatedValueAddedTax, ExemptSalePrice = exemptSalePrice, ExemptSupplementaryDuty = exemptSupplementaryDuty, ExemptValueAddedTax = exemptValueAddedTax, TotalTaxPayable = totalTaxPayable, SourceCut = sourceCut, Owing = owing, Amercement = amercement, Fine = fine, RentSppace = rentSppace, OtherConsolidation = otherConsolidation, TotalPayable = totalPayable, DateTime = valueAddedTax.DateTime, InstitutionInfoId = valueAddedTax.InstitutionInfoId, Branch = valueAddedTax.Branch, Bank = valueAddedTax.Bank }; Session.Remove("ValueAddedTax"); Session["ValueAddedTax"] = data; return(RedirectToAction("Index", "LocalLvlTaxes", new { id = valueAddedTax.InstitutionInfoId })); }
} // End of the MasterPostExists method /// <summary> /// Get one value added tax based on id /// </summary> /// <param name="id">The id for the post</param> /// <returns>A reference to a value added tax post</returns> public static ValueAddedTax GetOneById(Int32 id) { // Create the post to return ValueAddedTax post = null; // Create the connection and the sql statement string connection = Tools.GetConnectionString(); string sql = "SELECT * FROM dbo.value_added_taxes WHERE id = @id;"; // The using block is used to call dispose automatically even if there are an exception. using (SqlConnection cn = new SqlConnection(connection)) { // The using block is used to call dispose automatically even if there are an exception. using (SqlCommand cmd = new SqlCommand(sql, cn)) { // Add parameters cmd.Parameters.AddWithValue("@id", id); // Create a reader SqlDataReader reader = null; // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to // avoid having our application crash in such cases. try { // Open the connection. cn.Open(); // Fill the reader with one row of data. reader = cmd.ExecuteReader(); // Loop through the reader as long as there is something to read and add values while (reader.Read()) { post = new ValueAddedTax(reader); } } catch (Exception e) { throw e; } finally { // Call Close when done reading to avoid memory leakage. if (reader != null) reader.Close(); } } } // Return the post return post; } // End of the GetOneById method