protected override void Seed(ApplicationDbContext context) { base.Seed(context); if (context.Products.Count() == 0) { Product p1 = new Product("prod1", 3.11); Product p2 = new Product("prod2", 23.52); Product p3 = new Product("prod3", 355.21); Product p4 = new Product("prod4", 37.45); Product p5 = new Product("prod5", 123.48); context.Products.AddOrUpdate(p5); Invoice i1 = new Invoice("Invoice 1", DateTime.Now.AddDays(-2)); Invoice i2 = new Invoice("Invoice 2", DateTime.Now.AddDays(-50)); Invoice i3 = new Invoice("Invoice 3", DateTime.Now.AddDays(-10)); ProductInvoice pi1 = new ProductInvoice(p1, i1, 4); ProductInvoice pi2 = new ProductInvoice(p2, i1, 8); ProductInvoice pi3 = new ProductInvoice(p3, i1, 16); ProductInvoice pi4 = new ProductInvoice(p4, i2, 456); ProductInvoice pi5 = new ProductInvoice(p2, i3, 2); ProductInvoice pi6 = new ProductInvoice(p3, i3, 1); ProductInvoice pi7 = new ProductInvoice(p4, i3, 18); context.ProductsInvoices.AddOrUpdate(new[] { pi1, pi2, pi3, pi4, pi5, pi6, pi7 }); context.SaveChanges(); } }
public async Task <ActionResult <ProductInvoiceViewModel> > PutProductInvoice(int id, ProductInvoiceEditModel productInvoiceModel) { ProductInvoice productInvoice = await _productInvoicesRepository.FindByIdAsync(id); if (productInvoice == null) { return(BadRequest($"No existe ninguna factura de productos con el código {id}.")); } _mapper.Map(productInvoiceModel, productInvoice); _productInvoicesRepository.Update(productInvoice); try { await _unitWork.SaveAsync(); } catch (DbUpdateConcurrencyException) { if (!ProductInvoiceExists(id)) { return(NotFound( $"Error de actialización. No existe ninguna factura de productos con el código {id}.")); } throw; } return(_mapper.Map <ProductInvoiceViewModel>(productInvoice)); }
public async Task <IActionResult> Edit(int productID, int invoiceID, [Bind("ProductID,InvoiceID,Quantity")] ProductInvoice productInvoice) { if (productID != productInvoice.ProductID || invoiceID != productInvoice.InvoiceID) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(productInvoice); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ProductInvoiceExists(productInvoice.ProductID)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["InvoiceID"] = new SelectList(_context.Invoices, "InvoiceNumber", "InvoiceNumber", productInvoice.InvoiceID); ViewData["ProductID"] = new SelectList(_context.Products, "ProductID", "Name", productInvoice.ProductID); return(View(productInvoice)); }
public async Task CheckProductQuantityAsync(ProductInvoice invoiceProduct, int productsCount) { if (invoiceProduct.Product.Quantity >= invoiceProduct.Quantity) { return; } var errorMessage = string.Empty; if (invoiceProduct.Product.Quantity == 0) { errorMessage = $"We are sorry. Product {invoiceProduct.Product.Title} ended and we removed it from your order!"; if (productsCount > 1) { string.Concat(errorMessage, " If you still want to complete the payment, you can pay now."); } this.db.ProductsInvoices.Remove(invoiceProduct); await this.db.SaveChangesAsync(); } else { errorMessage = $"Currently the available quantity of {invoiceProduct.Product.Title} is {invoiceProduct.Product.Quantity}! We updated the quantity with the maximal possible at this momment. If you still want to pay for the rest of your items you can do it now."; invoiceProduct.Quantity = invoiceProduct.Product.Quantity; await this.db.SaveChangesAsync(); } throw new InvalidOperationException(errorMessage); }
public async Task Search_Existing_ProductInvoice() { ProductInvoice productInvoice = await _productInvoicesRepository.FindByIdAsync(1); Assert.IsNotNull(productInvoice); Assert.AreEqual(InvoiceState.Generated, productInvoice.State); Assert.AreEqual("12345678", productInvoice.ClientId); }
public async Task <ActionResult <ProductInvoiceViewModel> > PayProductInvoice(int id, [FromBody] PaymentModel paymentModel) { ProductInvoice productInvoice = await _productInvoicesRepository.FindByIdAsync(id); if (productInvoice is null) { return(NotFound($"No existe ninguna factura de producto con el código {id}")); } productInvoice.CalculateTotal(); PaymentCreateRequest paymentCreateRequest = new PaymentCreateRequest { Token = paymentModel.Token, PaymentMethodId = paymentModel.PaymentMethodId, TransactionAmount = productInvoice.Total, Description = $"Pay for product invoice {id}", Installments = 1, Payer = new PaymentPayerRequest { FirstName = productInvoice.Client.FirstName, LastName = productInvoice.Client.LastName, Email = paymentModel.Email } }; Payment payment = await _paymentClient.CreateAsync(paymentCreateRequest); if (payment.Status == PaymentStatus.Rejected) { return(BadRequest("El pago no pudo ser procesado.")); } productInvoice.PublishEvent(new PaidInvoice(productInvoice)); productInvoice.State = InvoiceState.Paid; productInvoice.PaymentDate = DateTime.Now; productInvoice.PaymentMethod = PaymentMethod.CreditCard; _productInvoicesRepository.Update(productInvoice); try { await _unitWork.SaveAsync(); } catch (DbUpdateConcurrencyException) { if (!ProductInvoiceExists(id)) { return(NotFound( $"Error de actualizacón. No existe ninguna factura de producto con el código {id}.")); } throw; } return(_mapper.Map <ProductInvoiceViewModel>(productInvoice)); }
public void PrintProductInvoice(ProductsModel products, List <ProductDetails> details) { ProductInvoice pinvoice = new ProductInvoice(); //foreach (DevExpress.XtraReports.Parameters.Parameter p2 in pinvoice.Parameters) // p2.Visible = false; pinvoice.InitData(details); documentViewer1.DocumentSource = pinvoice; pinvoice.CreateDocument(); }
public async Task <ActionResult <ProductInvoiceViewModel> > PostProductInvoice( ProductInvoiceInputModel productInvoiceModel) { ProductInvoice productInvoice = _mapper.Map <ProductInvoice>(productInvoiceModel); await _productInvoicesRepository.Insert(productInvoice); await _unitWork.SaveAsync(); return(_mapper.Map <ProductInvoiceViewModel>(productInvoice)); }
public async Task <IActionResult> Edit(int id, Invoice invoice) { if (id != invoice.InvoiceNumber) { return(NotFound()); } if (ModelState.IsValid) { try { if (!_context.Invoices.Any(i => i.InvoiceNumber == invoice.InvoiceNumber)) { _context.Invoices.Add(invoice); _context.SaveChanges(); id = invoice.InvoiceNumber; foreach (ProductInvoice productInvoice in invoice.SelectedProducts) { productInvoice.InvoiceID = invoice.InvoiceNumber; } } var RemovedPositions = _context.ProductInvoice.Where(pi => pi.InvoiceID == id).ToList().Where(pi => !invoice.SelectedProducts.Any(sp => sp.InvoiceID == pi.InvoiceID && sp.ProductID == pi.ProductID)); foreach (ProductInvoice position in RemovedPositions) { _context.ProductInvoice.Remove(position); } foreach (ProductInvoice position in invoice.SelectedProducts) { ProductInvoice oldPosition = _context.ProductInvoice.Where(pi => pi.InvoiceID == position.InvoiceID && pi.ProductID == position.ProductID).SingleOrDefault(); if (oldPosition == null) { _context.ProductInvoice.Add(position); } else if (oldPosition.Quantity != position.Quantity) { oldPosition.Quantity = position.Quantity; } } await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!InvoiceExists(invoice.InvoiceNumber)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(invoice)); }
public async Task <int> RemoveProductFromInvoiceAsync(ProductInvoice invoiceProduct) { this.db.ProductsInvoices.Remove(invoiceProduct); await this.db.SaveChangesAsync(); var remainedProductsCount = this.db.ProductsInvoices .Where(pi => pi.InvoiceId == invoiceProduct.InvoiceId) .Count(); return(remainedProductsCount); }
public async Task <ActionResult <ProductInvoiceViewModel> > GetProductInvoice(int id) { ProductInvoice productInvoice = await _productInvoicesRepository.FindByIdAsync(id); if (productInvoice == null) { return(NotFound($"No existe ninguna factura de productos con el código {id}.")); } return(_mapper.Map <ProductInvoiceViewModel>(productInvoice)); }
public bool CreateInvoice(Invoice invoice, ProductInvoice productInvoice) { if (invoice != null && productInvoice != null) { _context.Invoices.Add(invoice); _context.ProductInvoices.Add(productInvoice); _context.SaveChanges(); return(true); } return(false); }
public async Task <IActionResult> Create([Bind("ProductID,InvoiceID,Quantity")] ProductInvoice productInvoice) { if (ModelState.IsValid) { _context.Add(productInvoice); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["InvoiceID"] = new SelectList(_context.Invoices, "InvoiceNumber", "InvoiceNumber", productInvoice.InvoiceID); ViewData["ProductID"] = new SelectList(_context.Products, "ProductID", "Name", productInvoice.ProductID); return(View(productInvoice)); }
protected override void Seed(ApplicationDbContext context) { base.Seed(context); if (context.Invoices.Count() == 0) { Product prod = new Product("A", 3.45); Product prod1 = new Product("D", 6.44); Product prod2 = new Product("F", 7.45); Product prod3 = new Product("FF", 8.25); Product prod4 = new Product("B", 35.28); Product prod5 = new Product("X", 123.45); context.Products.AddOrUpdate(new[] { prod5 }); Invoice inv = new Invoice("INVOICE 1", DateTime.Now); Invoice inv1 = new Invoice("INVOICE 2", DateTime.Now); Invoice inv2 = new Invoice("INVOICE 3", DateTime.Now); ProductInvoice prod_inv = new ProductInvoice(prod, inv, 2); ProductInvoice prod_inv1 = new ProductInvoice(prod1, inv, 5); ProductInvoice prod_inv2 = new ProductInvoice(prod3, inv, 87); ProductInvoice prod_inv3 = new ProductInvoice(prod4, inv1, 28); ProductInvoice prod_inv4 = new ProductInvoice(prod, inv1, 82); ProductInvoice prod_inv5 = new ProductInvoice(prod2, inv2, 92); ProductInvoice prod_inv6 = new ProductInvoice(prod3, inv2, 452); ProductInvoice prod_inv7 = new ProductInvoice(prod4, inv2, 12); context.ProductsInvoices.AddOrUpdate(new[] { prod_inv, prod_inv1, prod_inv2, prod_inv3, prod_inv4, prod_inv5, prod_inv6, prod_inv7 }); context.SaveChanges(); //CREATE PROCEDURE dbo.GetInvoiceGross // @InvoiceID int //AS //BEGIN // select SUM(pri.Quantity * p.Price) as Invoice_gross // from Invoices i // join ProductInvoices pri // on i.ID = pri.InvoiceID // join Products p // on pri.ProductID = p.ID // where i.ID = @InvoiceID // group By i.ID //END //GO //--exec GetInvoiceGross @InvoiceID = 1 } }
public async Task Update_Existent_ProductInvoice() { ProductInvoice productInvoice = await _productInvoicesRepository.FindByIdAsync(1); Assert.IsNotNull(productInvoice); productInvoice.State = InvoiceState.Paid; productInvoice.PaymentMethod = PaymentMethod.Cash; _productInvoicesRepository.Update(productInvoice); await _dbContext.SaveChangesAsync(); productInvoice = await _productInvoicesRepository.FindByIdAsync(1); Assert.AreEqual(InvoiceState.Paid, productInvoice.State); Assert.AreEqual(PaymentMethod.Cash, productInvoice.PaymentMethod); }
public void ProductInvoiceTest() { // Arrange string name = Guid.NewGuid().ToString(); int random = new Random().Next(111); int random2 = new Random().Next(111); // Act // Act ProductInvoice productInvoice = this.CreateProductInvoice(); productInvoice.Id = random; productInvoice.Product = new Product(); productInvoice.Product.Id = random; productInvoice.Qty = random2; // Assert Assert.IsTrue(productInvoice.Id == random); Assert.IsTrue(productInvoice.Product.Id == random); Assert.IsTrue(productInvoice.Qty == random2); }
public async Task Save_Valid_ProductInvoice() { try { ProductInvoice productInvoice = new ProductInvoice { State = InvoiceState.Generated, ClientId = "12345678", }; productInvoice.CalculateTotal(); await _productInvoicesRepository.Insert(productInvoice); await _dbContext.SaveChangesAsync(); Assert.Pass(); } catch (DbUpdateException e) { Assert.Fail(e.Message); } }
public IActionResult CreateInvoice(InvoiceForCreate invoiceForCreate) { Invoice invoice = new Invoice { Code = invoiceForCreate.Code, Date = invoiceForCreate.Date, Net = invoiceForCreate.Net, ProductInvoices = invoiceForCreate.ProductInvoices, Taxes = invoiceForCreate.Taxes, Total = invoiceForCreate.Total }; ProductInvoice productInvoice = new ProductInvoice { ProductInvoiceId = invoiceForCreate.ProductInvoiceId, InvoiceId = invoiceForCreate.InvoiceId, ProductId = invoiceForCreate.ProductId, UnitId = invoiceForCreate.UnitId, SotreId = invoiceForCreate.SotreId, Code = invoiceForCreate.Code, Invoice = invoiceForCreate.Invoice, Discount = invoiceForCreate.Discount, Net = invoiceForCreate.Net, Price = invoiceForCreate.Price, Product = invoiceForCreate.Product, Quantity = invoiceForCreate.Quantity, Total = invoiceForCreate.Total }; bool created = _invoiceRepository.CreateInvoice(invoice, productInvoice); if (created) { return(Ok(created)); } return(BadRequest()); }
public static void SyncCommissionStaff(ProductInvoice model, int?CurrentUserId) { try { ProductInvoiceRepository productInvoiceRepository = new ProductInvoiceRepository(new ErpSaleDbContext()); StaffsRepository staffRepository = new StaffsRepository(new ErpStaffDbContext()); HistoryCommissionStaffRepository historyCommissionStaffRepository = new HistoryCommissionStaffRepository(new ErpStaffDbContext()); //lấy danh sách nhà thuốc ra để bắt đầu đồng bộ dữ liệu var list_staff = staffRepository.GetvwAllStaffs().Where(x => (x.PositionCode == "ASM" || x.PositionCode == "TDV")).ToList(); list_staff = list_staff.Where(x => ("," + x.DrugStore + ",").Contains("," + model.BranchId.ToString() + ",") == true).ToList(); //lấy toàn bộ danh sách hóa đơn trong 1 tháng của tất cả nhà thuốc ra để xử lý 1 lần. var list_productInvoice = productInvoiceRepository.GetAllvwProductInvoice().Where(x => x.Month == model.CreatedDate.Value.Month && x.Year == model.CreatedDate.Value.Year && x.IsArchive == true).ToList(); //lấy list đã insert nếu có var list_old = historyCommissionStaffRepository.GetAllHistoryCommissionStaffFull().Where(x => x.Month == model.CreatedDate.Value.Month && x.Year == model.CreatedDate.Value.Year).ToList(); foreach (var item in list_staff) { //lấy danh sách đơn bán hàng của nhà thuốc trong tháng var list_invoice_by_drugStore = list_productInvoice.Where(x => ("," + item.DrugStore + ",").Contains("," + x.BranchId.ToString() + ",") == true).ToList(); decimal RevenueDS = list_invoice_by_drugStore.Sum(x => x.TotalAmount); decimal CommissionPercent = item.CommissionPercent == null ? 0 : item.CommissionPercent.Value; decimal MinimumRevenue = item.MinimumRevenue == null ? 0 : item.MinimumRevenue.Value; decimal AmountCommission = (CommissionPercent * RevenueDS) / 100; if (list_old.Where(x => x.StaffId == item.Id).Count() > 0) { var update = list_old.Where(x => x.StaffId == item.Id).FirstOrDefault(); update.IsDeleted = MinimumRevenue > RevenueDS ? true : false; update.ModifiedUserId = CurrentUserId; update.ModifiedDate = DateTime.Now; update.StaffId = item.Id; update.PositionName = item.PositionName; update.Month = model.CreatedDate.Value.Month; update.Year = model.CreatedDate.Value.Year; update.CommissionPercent = CommissionPercent; update.MinimumRevenue = MinimumRevenue; update.RevenueDS = RevenueDS; update.AmountCommission = AmountCommission; update.StaffName = item.Name; update.StaffParentId = item.StaffParentId; historyCommissionStaffRepository.UpdateHistoryCommissionStaff(update); } else { //thêm mới vào data. var add = new HistoryCommissionStaff(); add.IsDeleted = MinimumRevenue > RevenueDS ? true : false; add.CreatedUserId = CurrentUserId; add.ModifiedUserId = CurrentUserId; add.AssignedUserId = CurrentUserId; add.CreatedDate = DateTime.Now; add.ModifiedDate = DateTime.Now; add.StaffId = item.Id; add.PositionName = item.PositionName; add.Month = model.CreatedDate.Value.Month; add.Year = model.CreatedDate.Value.Year; add.CommissionPercent = item.CommissionPercent; add.MinimumRevenue = item.MinimumRevenue; add.RevenueDS = RevenueDS; add.AmountCommission = AmountCommission; add.StaffName = item.Name; add.StaffParentId = item.StaffParentId; historyCommissionStaffRepository.InsertHistoryCommissionStaff(add); } } } catch (Exception ex) { throw ex; } }
public async Task Search_Non_Existent_ProductInvoice() { ProductInvoice productInvoice = await _productInvoicesRepository.FindByIdAsync(2); Assert.IsNull(productInvoice); }
public static void SyncTotalDisCountMoneyNT(ProductInvoice model, int?CreatedUserId) { try { ProductInvoiceRepository productInvoiceRepository = new ProductInvoiceRepository(new ErpSaleDbContext()); BranchRepository branchRepository = new BranchRepository(new ErpStaffDbContext()); TotalDiscountMoneyNTRepository totalDiscountMoneyNTRepository = new TotalDiscountMoneyNTRepository(new ErpSaleDbContext()); //tìm ngày đầu tháng DateTime aDateTime = new DateTime(model.CreatedDate.Value.Year, model.CreatedDate.Value.Month, 1); //tìm ngày cuối tháng DateTime retDateTime = aDateTime.AddMonths(1).AddDays(-1); //tìm số ngày của 1 tháng var count_day_of_month = retDateTime.Day; //lấy toàn bộ danh sách hóa đơn trong 1 tháng của tất cả nhà thuốc ra để xử lý 1 lần. var list_invoice_by_drugStore = productInvoiceRepository.GetAllvwProductInvoice().Where(x => x.BranchId == model.BranchId && x.Month == model.CreatedDate.Value.Month && x.Year == model.CreatedDate.Value.Year && x.IsArchive == true).ToList(); //lấy list đã insert nếu có var list_old = totalDiscountMoneyNTRepository.GetAllTotalDiscountMoneyNT().Where(x => x.Month == model.CreatedDate.Value.Month && x.Year == model.CreatedDate.Value.Year).ToList(); var date_percent = Helpers.Common.GetSetting("date_percent_decrease_NT"); var percent_decrease = Helpers.Common.GetSetting("percent_decrease_NT"); //đếm số ngày tạo đơn thuốc trong 1 tháng var count_day = list_invoice_by_drugStore.GroupBy(z => z.Day).Count(); //nếu số ngày đăng nhập lớn hơn cài đặt thì lấy tổng ngày đăng nhập theo cài đặt var count_day_setting = count_day > Convert.ToInt32(date_percent) ? Convert.ToInt32(date_percent) : count_day; //tính số ngày không tạo đơn hàng trong tháng theo cài đặt decimal count_day_off = Convert.ToInt32(date_percent) - count_day_setting; //tinh % trừ chiết khấu decimal percent = 0; decimal DiscountAmount = list_invoice_by_drugStore.Sum(x => (x.FixedDiscount + x.IrregularDiscount)); if (count_day_off > 0) { decimal pe_countday = count_day_setting / 5; var p_last = pe_countday / Convert.ToInt32(percent_decrease); string[] arrVal_percent_last = p_last.ToString().IndexOf(".") > 0 ? p_last.ToString().Split('.') : p_last.ToString().Split(','); var vl = int.Parse(arrVal_percent_last[0], CultureInfo.InstalledUICulture); if (vl == 0) { vl = 1; } decimal p_dayoff = count_day_off / 5; string[] arrVal = p_dayoff.ToString().IndexOf(".") > 0 ? p_dayoff.ToString().Split('.') : p_dayoff.ToString().Split(','); var value = int.Parse(arrVal[0], CultureInfo.InstalledUICulture); if (arrVal.Count() >= 2) { var aa = int.Parse(arrVal[1], CultureInfo.InstalledUICulture); if (aa > 0) { value = value + 1; } } var percent_off = value * Convert.ToInt32(percent_decrease) / vl; percent = percent_off; } var ds_ = list_invoice_by_drugStore.Sum(x => x.TotalAmount); var ds_tru = ds_ * percent / 100; decimal RemainingAmount = DiscountAmount - ds_tru; var branch_parent = branchRepository.GetBranchById(model.BranchId); if (list_old.Where(x => x.DrugStoreId == model.BranchId).Count() > 0) { var add = list_old.Where(x => x.DrugStoreId == model.BranchId).FirstOrDefault(); add.ModifiedUserId = CreatedUserId; add.ModifiedDate = DateTime.Now; add.DrugStoreId = model.BranchId; add.BranchId = branch_parent.ParentId; add.UserManagerId = CreatedUserId; add.Month = model.CreatedDate.Value.Month; add.Year = model.CreatedDate.Value.Year; add.QuantityDay = count_day; add.PercentDecrease = Math.Round(percent, 2); add.DiscountAmount = DiscountAmount; add.DecreaseAmount = ds_tru; add.RemainingAmount = RemainingAmount; add.Status = App_GlobalResources.Wording.New; totalDiscountMoneyNTRepository.UpdateTotalDiscountMoneyNT(add); } else { //thêm mới vào data. var add = new TotalDiscountMoneyNT(); add.IsDeleted = false; add.CreatedUserId = CreatedUserId; add.ModifiedUserId = CreatedUserId; add.AssignedUserId = CreatedUserId; add.CreatedDate = DateTime.Now; add.ModifiedDate = DateTime.Now; add.DrugStoreId = model.BranchId; add.BranchId = branch_parent.ParentId; add.UserManagerId = WebSecurity.CurrentUserId; add.Month = model.CreatedDate.Value.Month; add.Year = model.CreatedDate.Value.Year; add.QuantityDay = count_day; add.PercentDecrease = Math.Round(percent, 2); add.DiscountAmount = DiscountAmount; add.DecreaseAmount = ds_tru; add.RemainingAmount = RemainingAmount; add.Status = App_GlobalResources.Wording.New; totalDiscountMoneyNTRepository.InsertTotalDiscountMoneyNT(add); } } catch (Exception ex) { throw ex; } }