private void SortAndBind() { CouponController couponController = new CouponController(); _couponList = couponController.GetAll(PortalId); switch (CouponsSortExpression) { case "Code": _couponList.Sort(); break; case "Description": _couponList.Sort(CouponInfo.DescriptionSorter); break; case "StartDate": _couponList.Sort(CouponInfo.StartDateSorter); break; default: break; } if (CouponsSortDirection == SortDirection.Descending) { _couponList.Reverse(); } gvCoupons.PageIndex = CouponsPageIndex; gvCoupons.DataSource = _couponList; gvCoupons.DataBind(); }
private void BindCoupon() { if (CouponID != Null.NullInteger) { var objCouponController = new CouponController(); var objCoupon = objCouponController.GetCoupon(CouponID, ModuleId); if (objCoupon == null) { Response.Redirect(EditUrl("EditCoupons")); } else { txtCode.Text = objCoupon.Code; if (lstDiscountType.Items.FindByValue(objCoupon.DiscountType.ToString()) != null) { lstDiscountType.SelectedValue = objCoupon.DiscountType.ToString(); } txtAmount.Text = objCoupon.Amount.ToString(); txtQuantity.Text = objCoupon.Quantity.ToString(); txtStartDate.SelectedDate = objCoupon.StartDate; txtEndDate.SelectedDate = objCoupon.EndDate; chkIsActive.Checked = objCoupon.IsActive; // Allow users to delete coupon cmdDelete.Visible = true; } } }
public async Task RespondsWithCreated_PostNewCoupon() { var couponRepository = new InMemoryCouponRepository(); var couponController = new CouponController(couponRepository) .BootstrapForTests(urlHelper: new ActionNameOnlyUrlHelper()); var postRequestDto = new PostRequestDto { Code = "GRAND_SALE", PercentOff = 50 }; var postResponse = (CreatedResult)await couponController.Post(postRequestDto); Assert.Equal((int)HttpStatusCode.Created, postResponse.StatusCode); var couponDto = (CouponDto)postResponse.Value; Assert.Equal(nameof(CouponController.Get), postResponse.Location); Assert.Equal("GRAND_SALE", couponDto.Code); Assert.Equal(50, couponDto.PercentOff); }
protected void CouponButton_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(CouponTextBox.Text)) { MessageUserControl.ShowInfo("Please enter a valid coupon."); } else { CouponController sysmgr = new CouponController(); Coupon coupon = sysmgr.ValidateCoupon(CouponTextBox.Text); if (coupon == null) { MessageUserControl.ShowInfo("Please enter a valid coupon."); } else { MessageUserControl.TryRun(() => { decimal couponDiscount = decimal.Parse(coupon.CouponDiscount.ToString()); decimal discount = couponDiscount / 100; CouponIDLabel.Text = coupon.CouponID.ToString(); Label3.Visible = true; decimal discountValue = decimal.Parse(SubTotalLabel.Text) * discount; DiscountLabel.Text = discountValue.ToString(); decimal total = decimal.Parse(TotalLabel.Text); total -= discountValue; TotalLabel.Text = total.ToString(); }, "Coupon", "Coupon successfully applied."); MainView.ActiveViewIndex = 2; } } }
public static string checkCouponG25(int customerID) { // check customer var customer = CustomerController.GetByID(customerID); if (customer == null) { return("customerNotFound"); } // check coupon var coupon = CouponController.getByName("G25"); if (coupon == null) { return("couponNotFound"); } else { if (coupon.Active == false) { return("couponNotActived"); } } // check user app var userPhone = UserController.getByPhone(customer.CustomerPhone); var userPhone2 = UserController.getByPhone(customer.CustomerPhone2); if (userPhone == null && userPhone2 == null) { return("userNotFound"); } // kiểm tra đã tạo mã cho khách này chưa var customerCoupon = CouponController.getCouponByCustomer(coupon.ID, customer.ID, customer.CustomerPhone); if (customerCoupon.Count == 0) { return("noCouponGeneratedYet"); } // kiểm tra mã đã tạo còn cái nào actice không int activeCoupon = customerCoupon.Where(x => x.Active == true).Count(); if (activeCoupon > 0) { return("activeCouponExists"); } // kiểm tra khách đã sử dụng bao nhiêu mã int inactiveCoupon = customerCoupon.Where(x => x.Active == false).Count(); if (inactiveCoupon == 1) { return("couponUsageLimitExceeded"); } return("false"); }
protected void CheckCouponButton_Click(object sender, EventArgs e) { double totalprice = double.Parse(subtotalLabel.Text.Replace(@"$", string.Empty)); double taxprice = double.Parse(TaxLabel.Text.Replace(@"$", string.Empty)); CouponController sysmgr = new CouponController(); Coupon info = sysmgr.Coupons_Get(CouponTextBox.Text); if (info == null) { PercentageLabel.Text = ""; DiscountLabel.Text = "0"; MessageUserControl.ShowInfo("Warning", "Your coupon does not exist"); } else { if (DateTime.Now > info.EndDate) { PercentageLabel.Text = ""; DiscountLabel.Text = "0"; MessageUserControl.ShowInfo("Warning", "Your coupon seems already expired"); } else { MessageUserControl.TryRun(() => { PercentageLabel.Text = info.CouponDiscount.ToString(); int discountTemp = info.CouponDiscount; DiscountLabel.Text = "$" + (totalprice * (double)discountTemp * 0.01).ToString(); totalLabel2.Text = "$" + ((totalprice + taxprice - (totalprice * (double)discountTemp * 0.01))).ToString(); }, "Success", "Your coupon is valid!"); } } }
public void CreateCoupon_couponCreated() { var repository = new CouponRepository(_databaseSettings); var target = new CouponController(new CouponManager(repository, _mapper)); var expiration = DateTime.Now.ToUniversalTime().Date; var createCouponDto = new CreateCouponDto( CouponType: CouponType.Amount, Value: 10, Expiration: expiration ); var result = target.CreateCoupon(createCouponDto); Assert.IsType <CreatedAtRouteResult>(result.Result); var couponId = ((CreatedAtRouteResult)result.Result).RouteValues["id"].ToString(); var actual = repository.FindById(couponId); var expected = new Coupon { Id = couponId, CouponType = CouponType.Amount, Value = 10, Expiration = expiration }; Assert.Equal(expected, actual); }
/// <summary> /// Loads the coupons. /// </summary> private void LoadCoupons() { CouponCollection couponCollection = new CouponController().FetchAll(); if (couponCollection.Count == 0) { Master.MessageCenter.DisplayInformationMessage(LocalizationUtility.GetText("lblNoCouponsConfigured")); dgCoupons.Visible = false; } else { dgCoupons.DataSource = couponCollection; dgCoupons.ItemDataBound += dgCoupons_ItemDataBound; HyperLinkColumn hlEditColumn = dgCoupons.Columns[0] as HyperLinkColumn; if (hlEditColumn != null) { hlEditColumn.Text = LocalizationUtility.GetText("lblEdit"); hlEditColumn.DataNavigateUrlFormatString = "~/admin/coupons.aspx?couponId={0}"; } dgCoupons.Columns[0].HeaderText = LocalizationUtility.GetText("hdrEdit"); dgCoupons.Columns[1].HeaderText = LocalizationUtility.GetText("hdrCouponCode"); dgCoupons.Columns[2].HeaderText = LocalizationUtility.GetText("hdrExpirationDate"); dgCoupons.Columns[3].HeaderText = LocalizationUtility.GetText("hdrType"); dgCoupons.Columns[4].HeaderText = LocalizationUtility.GetText("hdrDelete"); ButtonColumn btnColumn = dgCoupons.Columns[4] as ButtonColumn; if (btnColumn != null) { btnColumn.Text = LocalizationUtility.GetText("lblDelete"); } dgCoupons.DataBind(); } }
public async Task CanGetCoupon_PostNewCoupon() { var couponRepository = new InMemoryCouponRepository(); var couponController = new CouponController(couponRepository) .BootstrapForTests(); var postRequestDto = new PostRequestDto { Code = "GRAND_SALE", PercentOff = 50 }; var postResponse = await couponController.Post(postRequestDto); var postResponseCouponDto = (CouponDto)postResponse.Value; var getResponse = await couponController.Get(postResponseCouponDto.Id); Assert.Equal((int)HttpStatusCode.OK, getResponse.StatusCode); var couponDto = (CouponDto)getResponse.Value; Assert.Equal("GRAND_SALE", couponDto.Code); Assert.Equal(50, couponDto.PercentOff); }
protected void addRentalEquipment_Click(object sender, ListViewCommandEventArgs e) { MessageUserControl.TryRun(() => { if (string.IsNullOrEmpty(HIDDEN_LABEL_selectedCustomerID.Text)) { throw new Exception("Must have customer selected"); } else if (string.IsNullOrEmpty(creditcardinput.Text)) { throw new Exception("Must have credit card"); } else if (PendingRentalListView.Items.Count() == 0) { //Cont. RentalController Rmgr = new RentalController(); //Marshall Methods CouponController Cmgr = new CouponController(); //Test data //Chip Andale EmployeeID: 10 //Fuelling,Adolph 780.600.2840 CustomerID: 47 //int createAndReturnEmptyRentalID //selectedCustomerRental.Text = mgr.createAndReturnEmptyRentalID(47, 10, null, " ").ToString(); //public int createAndReturnEmptyRentalID(int customerid, int employeeid, int? couponid, string creditcard) selectedCustomerRental.Text = Rmgr.createAndReturnEmptyRentalID(int.Parse(HIDDEN_LABEL_selectedCustomerID.Text), 10, null, creditcardinput.Text).ToString(); //Cmgr.ValidateCoupon(string.IsNullOrEmpty(couponinput.Text) ? (int?)null : couponinput.Text).CouponID //Add selected equipment RentalDetailController __addmgr = new RentalDetailController(); __addmgr.addRentalEquipment(int.Parse(selectedCustomerRental.Text), int.Parse(e.CommandArgument.ToString())); RentalEquipmentListview.DataBind(); PendingRentalListView.DataBind(); if (string.IsNullOrEmpty(selectedCustomerRental.Text)) { throw new Exception("Equipment has not been added!!"); } MessageUserControl.ShowInfo("Form Created", "Item added to newly created form"); //newRental.Visible = true; } else { RentalDetailController mgr = new RentalDetailController(); mgr.addRentalEquipment(int.Parse(selectedCustomerRental.Text), int.Parse(e.CommandArgument.ToString())); RentalEquipmentListview.DataBind(); PendingRentalListView.DataBind(); MessageUserControl.ShowInfo("Equipment has been added."); } }); }
public void FindById_notFound_returnNotFoundResult() { var repository = new CouponRepository(_databaseSettings); var target = new CouponController(new CouponManager(repository, _mapper)); var actual = target.FindById(Invalid_ID); Assert.IsType <NotFoundResult>(actual.Result); }
public void Create_A_Coupon() { CouponController couponController = new CouponController(_couponRepository, null); var coupon = GenerateCoupon(); var actionResult = couponController.Create(coupon); var result = actionResult.Result as CreatedAtRouteResult; result.Should().NotBe(null); result?.StatusCode.Should().Be(201); }
public void Remove_A_Coupon() { CouponController couponController = new CouponController(_couponRepository, null); var coupon = GenerateCoupon(); var actionResult = couponController.Create(coupon); var response = actionResult.Result as CreatedAtRouteResult; var couponId = (response.Value as Coupon).Id; var result = couponController.DeleteCoupon(couponId); result.Should().BeOfType <NoContentResult>(); }
protected void FetchCouponList() { MessageUserControl.TryRun(() => { DateTime currentDate = DateTime.Now; CouponController sysmgr = new CouponController(); List <Coupon> currentCopns = sysmgr.GetListOfAvailableCoupons(currentDate); PromoCodeDropDownList.DataSource = currentCopns; PromoCodeDropDownList.DataValueField = "CouponID"; PromoCodeDropDownList.DataTextField = "CouponIDValue"; PromoCodeDropDownList.DataBind(); }); }
public void Setup() { mockUnitOfWork = Substitute.For <IUnitOfWork>(); var profile = new MappingProfile(); var configuration = new MapperConfiguration(cfg => cfg.AddProfile(profile)); mapper = new Mapper(configuration); uut = new CouponController(mockUnitOfWork, mapper); defaultList = new List <Coupon>() { new Coupon() { BarName = "TestBar", CouponID = "10 Kr af alt", ExpirationDate = DateTime.Now, Bar = null, }, new Coupon() { BarName = "TestBar", CouponID = "5 Kr af alt", ExpirationDate = DateTime.Now, Bar = null, } }; defaultCoupon = defaultList[0]; // Direct conversion without navigational property correctResultList = new List <CouponDto>() { new CouponDto() { BarName = "TestBar", CouponID = "10 Kr af alt", ExpirationDate = DateTime.Now, }, new CouponDto() { BarName = "TestBar", CouponID = "5 Kr af alt", ExpirationDate = DateTime.Now, } }; defaultCouponDto = correctResultList[0]; }
public static string generateCouponG25(int customerID) { var coupon = CouponController.getByName("G25"); if (coupon != null) { //generate coupon for customer var customerCoupon = CouponController.insertCustomerCoupon(customerID, coupon.ID); if (customerCoupon != null) { return("true"); } } return("false"); }
public static string generateCouponG15(int customerID, bool checkUser = false) { // check customer var customer = CustomerController.GetByID(customerID); if (customer == null) { return("customerNotFound"); } // check coupon var coupon = CouponController.getByName("G15"); if (coupon == null) { return("couponNotFound"); } else { if (coupon.Active == false) { return("couponNotActived"); } } // check user app if (checkUser == true) { var userPhone = UserController.getByPhone(customer.CustomerPhone); var userPhone2 = UserController.getByPhone(customer.CustomerPhone2); if (userPhone == null && userPhone2 == null) { return("userNotFound"); } } //generate coupon for customer var customerCoupon = CouponController.insertCustomerCoupon(customerID, coupon.ID); if (customerCoupon != null) { return("true"); } return("false"); }
public void FindById_HasOneCartWithSameId_returnAllShoppingCartsInformation() { var repository = new CouponRepository(_databaseSettings); var coupon = new Coupon { CouponType = CouponType.Percentage, Value = 10 }; repository.Create(coupon); var target = new CouponController(new CouponManager(repository, _mapper)); var actual = target.FindById(coupon.Id); var expected = new CouponDto(coupon.Id, CouponType.Percentage, 10, coupon.Expiration); Assert.Equal(expected, actual.Value); }
public void Delete_ReturnNoConentAndDeleteItem() { var repository = new CouponRepository(_databaseSettings); var coupon = new Coupon { CouponType = CouponType.Percentage, Value = 10 }; repository.Create(coupon); var target = new CouponController(new CouponManager(repository, _mapper)); var actual = target.DeleteCoupon(coupon.Id); Assert.IsType <NoContentResult>(actual); var couponFindResult = target.FindById(Invalid_ID); Assert.IsType <NotFoundResult>(couponFindResult.Result); }
protected void CouponUseButton_Click(object sender, EventArgs e) { MessageUserControl.TryRun(() => { CouponController csysmgr = new CouponController(); Coupon cinfo = csysmgr.Coupons_Get(CouponInput.Text); if (cinfo == null) { MessageUserControl.ShowInfo("Warning", "Please enter valid coupon value!"); } else { if (cinfo.StartDate > DateTime.Now || cinfo.EndDate < DateTime.Now) { MessageUserControl.ShowInfo("Warning", "This coupon cannot be used for now! Please check the valid date!"); } else { } } }, "Success", "Coupom has been used"); }
protected void CreateSaleBtn_Click(object sender, EventArgs e) { string username = User.Identity.Name; ShoppingCartController totalmgr = new ShoppingCartController(); decimal total = totalmgr.GetShoppingCartTotal(username); CouponController sysmgr = new CouponController(); decimal discountPercent = sysmgr.GetCouponAmount(int.Parse(PromoCodeDropDownList.SelectedValue)); decimal subtotal = total * (1 - discountPercent); string paymentType = PaymentTypeList.SelectedValue.ToUpper(); int couponId = int.Parse(PromoCodeDropDownList.SelectedValue); MessageUserControl.TryRun(() => { SalesController salemgr = new SalesController(); int sid = salemgr.CreatSaleFromCart(username, subtotal, couponId, paymentType); var url = String.Format("~/Pages/Sales/SaleConfirmation.aspx?sid={0}", sid); Response.Redirect(url); }); }
protected void PromoCodeDropDownList_SelectedIndexChanged(object sender, EventArgs e) { Label saleDiscount = new Label(); Label saleFinalTotal = new Label(); string username = User.Identity.Name.ToString(); ShoppingCartController totalmgr = new ShoppingCartController(); decimal total = totalmgr.GetShoppingCartTotal(username); if (PromoCodeDropDownList.SelectedValue == "0") { DiscountPercentValue.Text = "0.00 %"; DiscountValue.Text = "$0.00"; foreach (RepeaterItem item in CheckoutRepeaterView.Items) { saleDiscount = item.FindControl("SaleDiscountValue") as Label; saleDiscount.Text = "$0.00"; saleFinalTotal = item.FindControl("SaleFinalTotal") as Label; saleFinalTotal.Text = string.Format("{0:C2}", total); } } else { CouponController sysmgr = new CouponController(); decimal discountPercent = sysmgr.GetCouponAmount(int.Parse(PromoCodeDropDownList.SelectedValue)); DiscountPercentValue.Text = string.Format("{0:P2}", discountPercent); DiscountValue.Text = string.Format("{0:C2}", (total * discountPercent)); foreach (RepeaterItem item in CheckoutRepeaterView.Items) { saleDiscount = item.FindControl("SaleDiscountValue") as Label; saleDiscount.Text = string.Format("{0:C2}", (total * discountPercent)); saleFinalTotal = item.FindControl("SaleFinalTotal") as Label; saleFinalTotal.Text = string.Format("{0:C2}", (total * (1 - discountPercent))); } } }
protected void lbApplyCoupon_Click(object sender, EventArgs e) { string couponCode = txtCouponCode.Text; if (!string.IsNullOrEmpty(couponCode)) { CouponController controller = new CouponController(); CouponInfo coupon = controller.GetCouponByCode(PortalId, couponCode); if (ValidateCoupon(coupon, Order)) { SetCoupon(coupon); } else { SetCoupon(null); } } else { SetCoupon(null); lblDiscountMessage.Text = ""; } }
protected void OnDeleteClick(object sender, EventArgs e) { try { if (CouponID != Null.NullInteger) { // Update Coupon var objCouponController = new CouponController(); var objCoupon = objCouponController.GetCoupon(CouponID, ModuleId); if (objCoupon != null) { objCouponController.DeleteCoupon(objCoupon); } } Response.Redirect(EditUrl("EditCoupons")); } catch (Exception ex) { Exceptions.ProcessModuleLoadException(this, ex); } }
public ActionResult Shipping(ShippingViewModel model) { try { var currentUser = GetAuthenticatedUser(); var cartList = _context.Cart.Where(x => x.UserId == currentUser.id).ToList(); if (cartList.Count == 0) { return(Error("سبد خرید شما خالی است.")); } var addressList = _context.UserAddress.Where(x => x.StatusId == UserAddressStatus.Active.Id && x.UserId == currentUser.id).ToList(); var address = addressList.Single(x => x.Id == model.addressId); if (model.addressId > 0) { if (addressList.SingleOrDefault(x => x.Id == model.addressId) == null) { return(Error("آدرس انتخاب شده صحیح نیست.")); } else { addressList.ForEach(x => x.MainAddress = false); address.MainAddress = true; } } else { return(Error("لطفا آدرس تحویل سفارش خود را مشخص کنید.")); } if (model.deliveryType > 0) { if (model.deliveryType == 1 && string.IsNullOrEmpty(model.time) && model.time.Split(' ').Length != 2) { return(Error("لطفا زمان تحویل سفارش خود را مشخص کنید.")); } } else { return(Error("لطفا نحوه تحویل سفارش خود را مشخص کنید.")); } Response couponResponse = null; Coupon coupon = null; if (!string.IsNullOrEmpty(model.coupon)) { couponResponse = CouponController.CheckCoupon(_context, currentUser, model.coupon, out coupon); if (couponResponse.status != ResponseStatus.Ok) { return(Error(couponResponse.message)); } } var invoiceDetailList = new List <InvoiceDetail>(); foreach (var item in cartList) { var totalPrice = item.Product.Price - item.Product.Discount; var invoiceDetail = new InvoiceDetail() { ProductId = item.ProductId, ProductFeatureId = item.ProductFeatureId, Count = item.Count, Price = totalPrice, StatusId = InvoiceDetailStatus.Accepted.Id, CreateUserId = currentUser.id, ModifyUserId = currentUser.id, CreateDate = GetDatetime(), ModifyDate = GetDatetime(), CreateIp = GetCurrentIp(), ModifyIp = GetCurrentIp() }; invoiceDetailList.Add(invoiceDetail); } var price = invoiceDetailList.Sum(x => x.Count * x.Price); if (coupon != null) { if (coupon.TypeId == CouponType.Amount.Id) { price = price - coupon.Value; } else if (coupon.TypeId == CouponType.Percentage.Id) { price = price - ((price / 100) * coupon.Value); } if (price < 0) { price = 0; } } var keys = new string[] { BaseInformationKey.OrderGapDay, BaseInformationKey.MinDeliveryFreePrice, BaseInformationKey.DeliveryPrice, BaseInformationKey.DeliveryManCity }; var baseInformations = _context.BaseInformation.Where(x => keys.Any(y => y == x.Key)); var GapDay = int.Parse(baseInformations.SingleOrDefault(x => x.Key == BaseInformationKey.OrderGapDay)?.Value ?? AsefianMetadata.DefaultGapDay); var MinDeliveryFreePrice = long.Parse(baseInformations.SingleOrDefault(x => x.Key == BaseInformationKey.MinDeliveryFreePrice)?.Value ?? AsefianMetadata.DefaultMinDeliveryFreePrice); var DeliveryPrice = long.Parse(baseInformations.SingleOrDefault(x => x.Key == BaseInformationKey.DeliveryPrice)?.Value ?? AsefianMetadata.DefaultDeliveryPrice); if (model.deliveryType == DeliveryType.DeliveryMan.Id) { var deliveryManCity = baseInformations.SingleOrDefault(x => x.Key == BaseInformationKey.DeliveryManCity)?.Value.Split('-').Select(x => int.Parse(x)).ToArray() ?? new int[] { }; if (deliveryManCity.Count(x => x == address.CityId) == 0) { return(Error("برای آدرس مورد نظر شما امکان ارسال با پیک فراهم نیست.")); } } var deliveryPrice = DeliveryPrice; if (price >= MinDeliveryFreePrice) { deliveryPrice = 0; } DateTime?deliveryDate = null; if (!string.IsNullOrEmpty(model.time)) { deliveryDate = DateUtility.GetDateTime(model.time.Split(' ')[0]); } if (deliveryDate != null && DateTime.Today.AddDays(GapDay) > deliveryDate) { return(Error("تاریخ وارد شده برای تحویل سفارش صحیح نیست.")); } var invoice = new Invoice() { UserId = currentUser.id, InvoiceStatusId = InvoiceStatus.Registered.Id, PaymentTypeId = PaymentType.Unknown.Id, InvoiceNo = GetNewInvoiceNo(), Price = price, UnpaidPrice = price, DeliveryPrice = deliveryPrice, DeliveryTypeId = model.deliveryType, AddressId = model.addressId, DeliveryDate = deliveryDate, DeliveryTime = model.time?.Split(' ')[1], CouponId = coupon?.Id, CreateUserId = currentUser.id, ModifyUserId = currentUser.id, CreateDate = GetDatetime(), ModifyDate = GetDatetime(), CreateIp = GetCurrentIp(), ModifyIp = GetCurrentIp(), DetailList = invoiceDetailList }; _context.Cart.RemoveRange(cartList); _context.Invoice.Add(invoice); var invoiceLog = new InvoiceLog() { Invoice = invoice, StatusId = InvoiceStatus.Registered.Id, CreateUserId = currentUser.id, CreateDate = GetDatetime(), CreateIp = GetCurrentIp() }; _context.InvoiceLog.Add(invoiceLog); _context.SaveChanges(); return(Success("سفارش شما با موفقیت ثبت شد.", new { id = invoice.Id })); } catch (Exception ex) { return(ServerError(ex)); } }
public ActionResult SubmitPayment(SubmitPaymentViewModel model) { var currentUser = GetAuthenticatedUser(); if (model.paymentType <= 0) { TempData["SubmitPaymentError"] = "انتخاب نوع پرداخت اجباری است."; return(Redirect("/invoice/payment/" + model.id)); } var invoice = _context.Invoice.Where(x => x.InvoiceStatusId == InvoiceStatus.Registered.Id && x.Id == model.id && x.UserId == currentUser.id).SingleOrDefault(); if (invoice == null) { return(HttpNotFound()); } if (invoice.InvoiceStatusId == InvoiceStatus.InProgress.Id) { return(Redirect("/invoice/detail/" + model.id)); } if (invoice.CouponId != null && !string.IsNullOrEmpty(model.coupon)) { Response couponResponse = null; couponResponse = CouponController.CheckCoupon(_context, currentUser, model.coupon, out Coupon coupon); if (couponResponse.status != ResponseStatus.Ok) { TempData["SubmitPaymentError"] = "انتخاب نوع پرداخت اجباری است."; return(Redirect("/invoice/payment/" + model.id)); } if (coupon.TypeId == CouponType.Amount.Id) { invoice.Price -= coupon.Value; } else if (coupon.TypeId == CouponType.Percentage.Id) { invoice.Price -= ((invoice.Price / 100) * coupon.Value); } if (invoice.Price < 0) { invoice.Price = 0; } invoice.CouponId = coupon.Id; } invoice.InvoiceStatusId = InvoiceStatus.InProgress.Id; invoice.PaymentTypeId = model.paymentType; invoice.ModifyUserId = currentUser.id; invoice.ModifyDate = GetDatetime(); invoice.ModifyIp = GetCurrentIp(); var invoiceLog = new InvoiceLog() { InvoiceId = invoice.Id, StatusId = InvoiceStatus.InProgress.Id, CreateUserId = currentUser.id, CreateDate = GetDatetime(), CreateIp = GetCurrentIp() }; _context.InvoiceLog.Add(invoiceLog); _context.SaveChanges(); return(Redirect("/invoice/detail/" + model.id)); }
public static string getCoupon(int customerID, string code, int productNumber, decimal price) { return(CouponController.getCoupon(customerID, code, productNumber, price)); }
protected void btnOrder_Click(object sender, EventArgs e) { try { DateTime currentDate = DateTime.Now; string username = Request.Cookies["usernameLoginSystem"].Value; var acc = AccountController.GetByUsername(username); if (acc != null) { if (acc.RoleID == 0 || acc.RoleID == 2) { #region Lấy thông tin khởi tạo Order // Change user string UserHelp = ""; if (username != hdfUsernameCurrent.Value) { UserHelp = username; username = hdfUsernameCurrent.Value; } int AgentID = Convert.ToInt32(acc.AgentID); int OrderType = hdfOrderType.Value.ToInt(); string AdditionFee = "0"; string DisCount = "0"; int CustomerID = 0; string CustomerPhone = Regex.Replace(txtPhone.Text.Trim(), @"[^\d]", ""); string CustomerName = txtFullname.Text.Trim().ToLower().ToTitleCase(); string CustomerEmail = ""; string CustomerAddress = txtAddress.Text.Trim().ToTitleCase(); int ProvinceID = hdfProvinceID.Value.ToInt(0); int DistrictID = hdfDistrictID.Value.ToInt(0); int WardID = hdfWardID.Value.ToInt(0); var checkCustomer = CustomerController.GetByPhone(CustomerPhone); string kq = ""; #region Cập nhật thông tin khách hàng if (checkCustomer != null) { CustomerID = checkCustomer.ID; kq = CustomerController.Update(CustomerID, CustomerName, checkCustomer.CustomerPhone, CustomerAddress, "", checkCustomer.CustomerLevelID.Value, checkCustomer.Status.Value, checkCustomer.CreatedBy, currentDate, username, false, checkCustomer.Zalo, checkCustomer.Facebook, checkCustomer.Note, checkCustomer.Nick, checkCustomer.Avatar, checkCustomer.ShippingType.Value, checkCustomer.PaymentType.Value, checkCustomer.TransportCompanyID.Value, checkCustomer.TransportCompanySubID.Value, checkCustomer.CustomerPhone2, ProvinceID, DistrictID, WardID); } else { kq = CustomerController.Insert(CustomerName, CustomerPhone, CustomerAddress, CustomerEmail, 0, 0, currentDate, username, false, "", "", "", "", "", 0, 0, 0, 0, "", ProvinceID, DistrictID, WardID); if (kq.ToInt(0) > 0) { CustomerID = kq.ToInt(0); } } #endregion string totalPrice = hdfTotalPrice.Value.ToString(); string totalPriceNotDiscount = hdfTotalPriceNotDiscount.Value; int PaymentStatus = 3; int ExcuteStatus = 2; int PaymentType = 1; int ShippingType = 1; bool IsHidden = false; int WayIn = 1; double DiscountPerProduct = Convert.ToDouble(pDiscount.Value); double TotalDiscount = Convert.ToDouble(pDiscount.Value) * Convert.ToDouble(hdfTotalQuantity.Value); string FeeShipping = pFeeShip.Value.ToString(); double GuestPaid = Convert.ToDouble(pGuestPaid.Value); double GuestChange = Convert.ToDouble(totalPrice) - GuestPaid; var couponID = hdfCouponID.Value.ToInt(0); var couponValue = hdfCouponValue.Value.ToDecimal(0); tbl_Order order = new tbl_Order() { AgentID = AgentID, OrderType = OrderType, AdditionFee = AdditionFee, DisCount = DisCount, CustomerID = CustomerID, CustomerName = CustomerName, CustomerPhone = CustomerPhone, CustomerAddress = CustomerAddress, CustomerEmail = CustomerEmail, TotalPrice = totalPrice, TotalPriceNotDiscount = totalPriceNotDiscount, PaymentStatus = PaymentStatus, ExcuteStatus = ExcuteStatus, IsHidden = IsHidden, WayIn = WayIn, CreatedDate = currentDate, CreatedBy = username, DiscountPerProduct = DiscountPerProduct, TotalDiscount = TotalDiscount, FeeShipping = FeeShipping, GuestPaid = GuestPaid, GuestChange = GuestChange, PaymentType = PaymentType, ShippingType = ShippingType, OrderNote = String.Empty, DateDone = DateTime.Now, OtherFeeName = String.Empty, OtherFeeValue = 0, PostalDeliveryType = 1, UserHelp = UserHelp, CouponID = couponID, CouponValue = couponValue }; var ret = OrderController.InsertOnSystem(order); int OrderID = ret.ID; #endregion #region Khởi tạo Other Fee if (!String.IsNullOrEmpty(hdfOtherFees.Value)) { JavaScriptSerializer serializer = new JavaScriptSerializer(); var fees = serializer.Deserialize <List <Fee> >(hdfOtherFees.Value); if (fees != null) { foreach (var fee in fees) { fee.OrderID = ret.ID; fee.CreatedBy = acc.ID; fee.CreatedDate = DateTime.Now; fee.ModifiedBy = acc.ID; fee.ModifiedDate = DateTime.Now; } FeeController.Update(ret.ID, fees); } } #endregion #region Cập nhật Coupon if (order.CouponID.HasValue && order.CouponID.Value > 0) { CouponController.updateStatusCouponCustomer(CustomerID, order.CouponID.Value, false); } #endregion if (OrderID > 0) { #region Khởi tạo chi tiết đơn hàng ProductPOS POS = JsonConvert.DeserializeObject <ProductPOS>(hdfListProduct.Value); List <tbl_OrderDetail> orderDetails = new List <tbl_OrderDetail>(); List <tbl_StockManager> stockManager = new List <tbl_StockManager>(); // Reverser POS.productPOS.Reverse(); foreach (ProductGetOut item in POS.productPOS) { orderDetails.Add( new tbl_OrderDetail() { AgentID = AgentID, OrderID = OrderID, SKU = item.SKU, ProductID = item.ProductType == 1 ? item.ProductID : 0, ProductVariableID = item.ProductType == 1 ? 0 : item.ProductVariableID, ProductVariableDescrition = item.ProductVariableSave, Quantity = item.QuantityInstock, Price = item.Giabanle, Status = 1, DiscountPrice = 0, ProductType = item.ProductType, CreatedDate = currentDate, CreatedBy = username, IsCount = true } ); int parentID = item.ProductID; var variable = ProductVariableController.GetByID(item.ProductVariableID); if (variable != null) { parentID = Convert.ToInt32(variable.ProductID); } stockManager.Add( new tbl_StockManager() { AgentID = AgentID, ProductID = item.ProductType == 1 ? item.ProductID : 0, ProductVariableID = item.ProductType == 1 ? 0 : item.ProductVariableID, Quantity = item.QuantityInstock, QuantityCurrent = 0, Type = 2, NoteID = "Xuất kho bán POS", OrderID = OrderID, Status = 3, SKU = item.SKU, CreatedDate = currentDate, CreatedBy = username, MoveProID = 0, ParentID = parentID } ); } OrderDetailController.Insert(orderDetails); #endregion // Cập nhật lại sô lượng và giá vố vào đơn hàng OrderController.updateQuantityCOGS(OrderID); // Cập nhật lại thông tin kho hàng StockManagerController.Insert(stockManager); #region Khởi tạo đơn hàng đổi trả string refund = hdSession.Value; if (refund != "1") { string[] RefundID = refund.Split('|'); var update = RefundGoodController.UpdateStatus(RefundID[0].ToInt(), username, 2, OrderID); var updateor = OrderController.UpdateRefund(OrderID, RefundID[0].ToInt(), username); } #endregion // Hoàn thành khởi tạo đơn hàng nên gán lại giá trị trang lúc ban đầu hdStatusPage.Value = "Create"; ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "script", "$(function () { HoldOn.close(); printInvoice(" + OrderID + ") });", true); } } } } catch (Exception) { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "script", "$(function () { handleErrorSubmit(); });", true); } }
public void Setup() { mockCouponManagementHelper = new Mock <ICouponManagementHelper>(); mockCouponData = new CouponData(); couponController = new CouponController(mockCouponManagementHelper.Object); }
public void LoadData() { int ID = Request.QueryString["id"].ToInt(0); int mergeprint = 0; if (Request.QueryString["merge"] != null) { mergeprint = Request.QueryString["merge"].ToInt(0); } if (ID > 0) { var order = OrderController.GetByID(ID); if (order != null) { string error = ""; string Print = ""; double TotalQuantity = 0; double TotalOrder = 0; var orderdetails = OrderDetailController.GetByIDSortBySKU(ID); var numberOfOrders = OrderController.GetByCustomerID(Convert.ToInt32(order.CustomerID)); var customer = CustomerController.GetByID(Convert.ToInt32(order.CustomerID)); if (orderdetails.Count > 0) { printItemList(ref ID, ref mergeprint, ref TotalQuantity, ref TotalOrder, ref Print); string productPrint = ""; string shtml = ""; productPrint += "<div class='body'>"; productPrint += "<div class='table-1'>"; string mergeAlert = ""; if (mergeprint == 1) { mergeAlert += "<p class='merge-alert'>(Đã gộp sản phẩm)<p>"; } productPrint += "<h1>HÓA ĐƠN #" + order.ID + mergeAlert + "</h1>"; productPrint += "<table>"; productPrint += "<colgroup>"; productPrint += "<col class='col-left'/>"; productPrint += "<col class='col-right'/>"; productPrint += "</colgroup>"; productPrint += "<tbody>"; productPrint += "<tr>"; productPrint += "<td>Khách hàng</td>"; productPrint += "<td>" + order.CustomerName.ToTitleCase() + "</td>"; productPrint += "</tr>"; if (!string.IsNullOrEmpty(customer.Nick)) { if (order.ShippingType != 1) { productPrint += "<tr>"; productPrint += "<td>Nick</td>"; productPrint += "<td>" + customer.Nick.ToTitleCase() + "</td>"; productPrint += "</tr>"; } } productPrint += "<tr>"; productPrint += "<td>Điện thoại</td>"; productPrint += "<td>" + order.CustomerPhone + "</td>"; productPrint += "</tr>"; if (order.ExcuteStatus == 2 && !string.IsNullOrEmpty(order.DateDone.ToString())) { productPrint += "<tr>"; productPrint += "<td>Ngày hoàn tất</td>"; string datedone = string.Format("{0:dd/MM/yyyy HH:mm}", order.DateDone); productPrint += "<td>" + datedone + "</td>"; productPrint += "</tr>"; } else { error += "Đơn hàng chưa hoàn tất"; } productPrint += "<tr>"; productPrint += "<td>Nhân viên</td>"; productPrint += "<td>" + order.CreatedBy + "</td>"; productPrint += "</tr>"; if (!string.IsNullOrEmpty(order.OrderNote)) { productPrint += "<tr>"; productPrint += "<td>Ghi chú</td>"; productPrint += "<td>" + order.OrderNote + "</td>"; productPrint += "</tr>"; } productPrint += "</tbody>"; productPrint += "</table>"; productPrint += "</div>"; productPrint += "<div class='table-2'>"; productPrint += "<table>"; productPrint += "<colgroup>"; productPrint += "<col class='soluong' />"; productPrint += "<col class='gia' />"; productPrint += "<col class='tong' />"; productPrint += "</colgroup>"; productPrint += "<thead>"; productPrint += "<th>Số lượng</th>"; productPrint += "<th>Giá</th>"; productPrint += "<th>Tổng</th>"; productPrint += "</thead>"; productPrint += "<tbody>"; productPrint += Print; productPrint += "</tbody>"; productPrint += "</table>"; productPrint += "</div>"; productPrint += "<div class='table-3'>"; productPrint += "<table>"; productPrint += "<tr>"; productPrint += "<td colspan='2'>Số lượng</td>"; productPrint += "<td>" + TotalQuantity + " </td>"; productPrint += "</tr>"; productPrint += "<tr>"; productPrint += "<td colspan='2'>Thành tiền</td>"; productPrint += "<td>" + string.Format("{0:N0}", TotalOrder) + " </td>"; productPrint += "</tr>"; double TotalPrice = TotalOrder; if (order.DiscountPerProduct > 0) { var TotalDiscount = Convert.ToDouble(order.DiscountPerProduct) * Convert.ToDouble(TotalQuantity); TotalOrder = TotalOrder - TotalDiscount; TotalPrice = TotalPrice - TotalDiscount; productPrint += "<tr>"; productPrint += "<td colspan='2'>Chiết khấu mỗi cái </td>"; productPrint += "<td>" + string.Format("{0:N0}", Convert.ToDouble(order.DiscountPerProduct)) + " </td>"; productPrint += "</tr>"; productPrint += "<tr>"; productPrint += "<td colspan='2'>Trừ tổng chiết khấu</td>"; productPrint += "<td>-" + string.Format("{0:N0}", TotalDiscount) + " </td>"; productPrint += "</tr>"; productPrint += "<tr>"; productPrint += "<td colspan='2'>Sau chiết khấu</td>"; productPrint += "<td>" + string.Format("{0:N0}", TotalOrder) + " </td>"; productPrint += "</tr>"; } if (order.RefundsGoodsID != null) { var refund = RefundGoodController.GetByID(Convert.ToInt32(order.RefundsGoodsID)); if (refund != null) { TotalOrder = TotalOrder - Convert.ToDouble(refund.TotalPrice); productPrint += "<tr>"; productPrint += "<td colspan='2'>Trừ hàng trả (đơn " + order.RefundsGoodsID + ")</td>"; productPrint += "<td>-" + string.Format("{0:N0}", Convert.ToDouble(refund.TotalPrice)) + " </td>"; productPrint += "</tr>"; productPrint += "<tr>"; productPrint += "<td colspan='2'>Tổng tiền còn lại</td>"; productPrint += "<td>" + string.Format("{0:N0}", TotalOrder) + " </td>"; productPrint += "</tr>"; } else { error += "Không tìm thấy đơn hàng đổi trả " + order.RefundsGoodsID.ToString(); } } if (Convert.ToDouble(order.FeeShipping) > 0) { TotalOrder = TotalOrder + Convert.ToDouble(order.FeeShipping); TotalPrice = TotalPrice + Convert.ToDouble(order.FeeShipping); productPrint += "<tr>"; productPrint += "<td colspan='2'>Phí vận chuyển</td>"; productPrint += "<td>" + string.Format("{0:N0}", Convert.ToDouble(order.FeeShipping)) + " </td>"; productPrint += "</tr>"; } // Check fee var fees = FeeController.getFeeInfo(ID); foreach (var fee in fees) { TotalOrder = TotalOrder + Convert.ToDouble(fee.Price); TotalPrice = TotalPrice + Convert.ToDouble(fee.Price); productPrint += "<tr>"; productPrint += "<td colspan='2'>" + fee.Name + "</td>"; productPrint += "<td>" + string.Format("{0:N0}", Convert.ToDouble(fee.Price)) + " </td>"; productPrint += "</tr>"; } // Giảm giá if (order.CouponID.HasValue && order.CouponID.Value > 0) { var coupon = CouponController.getCoupon(order.CouponID.Value); TotalOrder = TotalOrder - Convert.ToDouble(coupon.Value); TotalPrice = TotalPrice - Convert.ToDouble(coupon.Value); productPrint += "<tr>"; productPrint += String.Format("<td colspan='2'>Mã giảm giá: {0}</td>", coupon.Code); productPrint += String.Format("<td>-{0:N0} </td>", Convert.ToDouble(coupon.Value)); productPrint += "</tr>"; } if (TotalPrice != Convert.ToDouble(order.TotalPrice)) { error += "Đơn hàng tính sai tổng tiền"; } productPrint += "<tr>"; productPrint += "<td class='strong' colspan='2'>TỔNG TIỀN</td>"; productPrint += "<td class='strong'>" + string.Format("{0:N0}", TotalOrder) + " </td>"; productPrint += "</tr>"; productPrint += "</tbody>"; productPrint += "</table>"; productPrint += "</div>"; productPrint += "</div>"; string address = ""; string phone = ""; string facebook = ""; var agent = AgentController.GetByID(Convert.ToInt32(order.AgentID)); if (agent != null) { address = agent.AgentAddress; phone = agent.AgentPhone; facebook = agent.AgentFacebook; } var acc = AccountController.GetByUsername(order.CreatedBy); if (acc != null) { var accountInfo = AccountInfoController.GetByUserID(acc.ID); if (accountInfo != null) { if (!string.IsNullOrEmpty(accountInfo.Phone)) { phone = accountInfo.Phone; } } } string dateOrder = string.Format("{0:dd/MM/yyyy HH:mm}", order.DateDone); shtml += "<div class='hoadon'>"; shtml += "<div class='all'>"; if (numberOfOrders.Count < 4) { shtml += "<div class='head'>"; shtml += "<div class='logo'><div class='img'><img src='App_Themes/Ann/image/logo.png' /></div></div>"; shtml += "<div class='info'>"; shtml += "<div class='ct'>"; shtml += "<div class='ct-title'></div>"; shtml += "<div class='ct-detail'> " + address + "</div>"; shtml += "</div>"; shtml += "<div class='ct'>"; shtml += "<div class='ct-title'> </div>"; shtml += "<div class='ct-detail'> " + phone + "</div>"; shtml += "</div>"; shtml += "<div class='ct'>"; shtml += "<div class='ct-title'></div>"; shtml += "<div class='ct-detail'>http://ann.com.vn</div>"; shtml += "</div>"; shtml += "</div>"; shtml += "</div>"; } shtml += productPrint; if (numberOfOrders.Count < 4) { var config = ConfigController.GetByTop1(); string rule = ""; if (order.OrderType == 2) { rule = config.ChangeGoodsRule; } else { rule = config.RetailReturnRule; } shtml += "<div class='footer'><h3>CẢM ƠN QUÝ KHÁCH! HẸN GẶP LẠI !</h3></div> "; shtml += "<div class='footer'>" + rule + "</div> "; } else { shtml += "<div class='footer'>"; shtml += "<p>ANN rất vui khi quý khách đã mua " + numberOfOrders.Count + " đơn hàng!</p>"; shtml += "</div>"; } shtml += "</div>"; shtml += "</div>"; if (error != "") { ltrPrintInvoice.Text = "Xảy ra lỗi: " + error; ltrPrintEnable.Text = ""; } else { ltrPrintInvoice.Text = shtml; ltrPrintEnable.Text = "<div class='print-enable true'></div>"; } } } else { ltrPrintInvoice.Text = "Không tìm thấy đơn hàng " + ID; } } else { ltrPrintInvoice.Text = "Xảy ra lỗi!!!"; } }