public ActionResult Save() { try { if (SessionPersister.account == null) { return(RedirectToAction("Index", "Login", new { Area = "Customer" })); } else { var account = SessionPersister.account; if (account is Account && !((Clitzy.Models.Account)account).IsAdmin) { var customer = (Clitzy.Models.Account)account; List <Item> cart = (List <Item>)Session["cart"]; var vendorIds = cart.Select(i => i.product.VendorId).Distinct().ToList(); vendorIds.ForEach(id => { var currentVendor = ocmde.Vendors.Find(id); // Create new order Order order = new Order() { CustomerId = customer.Id, DateCreation = DateTime.Now, Name = Resources.Vendor.New_Order_for_Vendor + " " + currentVendor.Name, OrderStatusId = 1, VendorId = id }; ocmde.Orders.Add(order); ocmde.SaveChanges(); // Create order details cart.Where(i => i.product.VendorId == id).ToList().ForEach(i => { OrdersDetail ordersDetail = new OrdersDetail() { OrderId = order.Id, Price = i.product.Price, Quantity = i.quantity, ProductId = i.product.Id }; ocmde.OrdersDetails.Add(ordersDetail); ocmde.SaveChanges(); }); }); // Remove Cart Session.Remove("Cart"); return(RedirectToAction("Index", "Orders", new { Area = "Customer" })); } return(RedirectToAction("Index", "Login", new { Area = "Customer" })); } } catch (Exception e) { return(View("Error", new HandleErrorInfo(e, "Home", "Index"))); } }
public List <OrdersDetail> ViewCustOrdersDetail(int OrderID) { using (IDbConnection connection = new SqlConnection(connectionString)) { connection.Open(); var command = connection.CreateCommand(); command.CommandText = "exec CustOrdersDetail @SelectOrderId"; AddParameter <int>(command, "@SelectOrderId", OrderID, DbType.Int32); IDataReader reader = command.ExecuteReader(); List <OrdersDetail> list = new List <OrdersDetail>(); while (reader.Read()) { string a = reader.GetString(0); decimal b = reader.GetDecimal(1); int c = reader.GetInt16(2); int d = reader.GetInt32(3); decimal e = reader.GetDecimal(4); OrdersDetail od = new OrdersDetail( reader.GetString(0), reader.GetDecimal(1), reader.GetInt16(2), reader.GetInt32(3), reader.GetDecimal(4) ); list.Add(od); } return(list); } }
public async Task <IActionResult> PutOrdersDetail(int id, OrdersDetail ordersDetail) { if (id != ordersDetail.OrdersDetailId) { return(BadRequest()); } _context.Entry(ordersDetail).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!OrdersDetailExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public ActionResult Payment(string shipId, string amount, string shipNote) { var order = new Order(); order.date_created = DateTime.Now; order.id_User = Convert.ToInt32(shipId); order.note = shipNote; order.status = 0; order.amount = Convert.ToDouble(amount); try { var id = new OrderDAO().Insert(order); var cart = (List <CartItemModel>)Session[CartSession]; var detail = new OrdersDetailDAO(); foreach (var item in cart) { var ordersDetail = new OrdersDetail(); ordersDetail.id_Product = item.Product.id; ordersDetail.id_Bill = (int)id; ordersDetail.price = item.Product.price; ordersDetail.qty = item.Qty; ordersDetail.date_created = DateTime.Now; detail.Insert(ordersDetail); } } catch { return(RedirectToAction("Error", "CartClient")); } return(RedirectToAction("Sussecc", "CartClient")); }
public async Task <ActionResult <OrdersDetail> > PostOrdersDetail(OrdersDetail ordersDetail) { _context.OrdersDetail.Add(ordersDetail); await _context.SaveChangesAsync(); return(CreatedAtAction("GetOrdersDetail", new { id = ordersDetail.OrdersDetailId }, ordersDetail)); }
/// <summary> /// 消費者付款 /// </summary> public static void CartPayment(cvmOrders model) { OrderNo = CreateNewOrderNo(model); using (goshoppingEntities db = new goshoppingEntities()) { var datas = db.Carts .Where(m => m.user_no == UserAccount.UserNo) .ToList(); if (datas != null) { foreach (var item in datas) { OrdersDetail detail = new OrdersDetail(); detail.order_no = OrderNo; detail.product_no = item.product_no; detail.product_name = item.product_name; detail.vendor_no = Shop.GetVendorNoByProduct(item.product_no); detail.category_name = Shop.GetCategoryName(item.product_no); detail.product_spec = item.product_spec; detail.qty = item.qty; detail.price = item.price; detail.amount = item.amount; detail.remark = ""; db.OrdersDetail.Add(detail); db.SaveChanges(); db.Carts.Remove(item); db.SaveChanges(); } } } }
public ActionResult Checkout() { if (Session["username"] == null) { return(RedirectToAction("MyAccount", "Account")); } else { List <Item> cart = (List <Item>)Session["cart"]; // save order Order order = new Order(); order.creationDate = DateTime.Now; order.name = "New Oreder"; order.payment = "Paypal"; order.status = true; order.username = Session["username"].ToString(); int orderId = iOrdersRepository.creat(order); //save order details foreach (var item in cart) { OrdersDetail ordersDetail = new OrdersDetail(); ordersDetail.ordersId = orderId; ordersDetail.productId = item.product.id; ordersDetail.price = item.product.price; ordersDetail.quantity = item.quantity; iOrdersDetailRepository.creat(ordersDetail); } //remove cart Session.Remove("cart"); return(View("Thanks")); } }
public ActionResult Success(FormCollection fc) { List <Item> list = (List <Item>)Session["cart"]; Order order = new Order { CreationDate = DateTime.Now, Status = false, Name = fc["cusName"] }; _mde.Orders.Add(order); _mde.SaveChanges(); foreach (var item in list) { OrdersDetail detail = new OrdersDetail { OrdersId = order.Id, ProductId = item.Product.Id, Quantity = item.Quantity, Price = item.Product.Price }; _mde.OrdersDetails.Add(detail); _mde.SaveChanges(); } Session.Remove("cart"); return(View()); }
public ActionResult DeleteConfirmed(int id) { OrdersDetail ordersDetail = db.OrdersDetails.Find(id); db.OrdersDetails.Remove(ordersDetail); db.SaveChanges(); return(RedirectToAction("Index")); }
public IActionResult DatHang(int IdUser, Decimal TotalCost, String DeliveryAddress, DateTime DeliveryDate) { Order order = new Order(); order.IdUser = IdUser; order.TotalCost = TotalCost; order.DeliveryAddress = DeliveryAddress; order.DeliveryDate = DeliveryDate; context.Add(order); context.SaveChanges(); var carts = context.Carts.Include(t => t.IdComboNavigation).Include(t => t.IdProductNavigation).Where(t => t.IdUser == IdUser); Console.WriteLine(order.Id); foreach (var item in carts) { if (item.IdCombo == null) { OrdersDetail ordersDetail = new OrdersDetail() { IdOrders = order.Id , IdCombo = item.IdCombo, IdProduct = item.IdProduct, Amount = item.Amount, Price = item.IdProductNavigation.Price }; var ud = context.Products.Find(ordersDetail.IdProduct); ud.Amount = ud.Amount - ordersDetail.Amount; contextWrite.Add(ordersDetail); contextWrite.SaveChanges(); contextWrite.Update(ud); contextWrite.SaveChanges(); contextWrite.Remove(item); contextWrite.SaveChanges(); } else { OrdersDetail ordersDetail = new OrdersDetail() { IdOrders = order.Id , IdCombo = item.IdCombo, IdProduct = item.IdProduct, Amount = item.Amount, Price = item.IdComboNavigation.Price }; contextWrite.Add(ordersDetail); contextWrite.SaveChanges(); contextWrite.Remove(item); contextWrite.SaveChanges(); } } return(new JsonResult("Đặt hàng thành công")); }
public IActionResult Save() { try { if (HttpContext.Session.GetString("username_customer") == null) { return(RedirectToAction("Index", "Login", new { Area = "CustomerPanel" })); } else { var customer = ocmde.AccountCustomer.SingleOrDefault(a => a.Email.Equals(HttpContext.Session.GetString("email_customer"))); var cart = SessionHelper.GetObjectFromJson <List <Item> >(HttpContext.Session, "cart"); var vendorIds = cart.Select(i => i.VendorId).Distinct().ToList(); vendorIds.ForEach(id => { var currentVendor = ocmde.Vendors.Find(id); // Create new order Orders order = new Orders() { CustomerId = customer.Id, DateCreation = DateTime.Now, Name = sharedLocalizer["New_Order_for_Vendor"] + " " + currentVendor.Name, OrderStatusId = 1, VendorId = id }; ocmde.Orderss.Add(order); ocmde.SaveChanges(); // Create order details cart.Where(i => i.VendorId == id).ToList().ForEach(i => { OrdersDetail ordersDetail = new OrdersDetail() { OrderId = order.Id, Price = i.Price, Quantity = i.Quantity, ProductId = i.Id }; ocmde.OrdersDetails.Add(ordersDetail); ocmde.SaveChanges(); }); }); // Remove Cart HttpContext.Session.Remove("Cart"); return(RedirectToAction("Index", "Orders", new { Area = "CustomerPanel" })); } } catch (Exception e) { throw; } }
public ActionResult DeleteOrderDetail(int?Productid, int?orderid) { OrdersDetail p = db.OrdersDetails.Where(s => s.ProductID == Productid && s.OrderID == orderid).FirstOrDefault(); OrderViewModel odm = new OrderViewModel(); odm.OrderID = p.OrderID; odm.Price = p.Price.ToString(); odm.Quantity = (int)p.Quantity; odm.Product = p.Product; return(View(odm)); }
public ActionResult Checkout() { var cart = ShoppingCart.GetCart(this.HttpContext); // Set up our ViewModel var viewModel = new ShoppingCartViewModel { CartItems = cart.GetCartItems(), CartTotal = cart.GetTotal() }; var customer = (from cust in storeDB.Customers where cust.Email == User.Identity.Name select new { cust.ID, cust.Name }).FirstOrDefault(); int orderId = 1; var order = (from ord in storeDB.Orders select new { ord.OrderNumber, ord.OrderDate }).OrderByDescending(a => a.OrderDate).FirstOrDefault(); if (order != null) { orderId = Int32.Parse(order.OrderNumber) + 1; } Order or = new Order(); or.OrderNumber = orderId.ToString(); or.Customer_Id = customer.ID; or.OrderDate = DateTime.Now; or.total = decimal.Parse(viewModel.CartTotal.ToString()); or.Username = customer.Name; storeDB.Orders.Add(or); storeDB.SaveChanges(); foreach (var item in viewModel.CartItems) { OrdersDetail od = new OrdersDetail(); od.OrderNumber = orderId.ToString(); od.ProductId = item.ProductId; od.Unitprice = decimal.Parse(item.Product.Price.ToString()); od.Quantity = item.Count; storeDB.OrdersDetails.Add(od); storeDB.SaveChanges(); for (int i = 0; i < item.Count; i++) { RemoveFromCart(item.RecordId); } } return(RedirectToAction("Index")); }
/// <summary> /// 非事务订单 /// </summary> /// <returns></returns> public bool InsertOrders(Model.Orders orders, List <Model.OrdersDetails> ordersDetailList, Model.OrdersLog ordersLog) { const string sql = @"insert into Orders (OrderId,SellingPrice,CostPrice,profit,UsersId,ConsigneeName,ConsigneePhone,ConsigneAaddress,OrdersState,GoodsSum) values(@OrderId,@SellingPrice,@CostPrice,@profit,@UsersId,@ConsigneeName,@ConsigneePhone,@ConsigneAaddress,@OrdersState,@GoodsSum)"; Factory.DBHelper.ExecSQL(SQLConString, sql.ToString(), new DynamicParameters(new { orders.OrderId, orders.SellingPrice, orders.CostPrice, orders.profit, orders.UsersId, orders.ConsigneeName, orders.ConsigneePhone, orders.ConsigneAaddress, orders.OrdersState, orders.GoodsSum, })); const string OrdersLog = @"insert into OrdersLog(OrdersId,UserName,OrdersState,Remark) values(@OrdersId,@UserName,@OrdersState,@Remark)"; Factory.DBHelper.ExecSQL(SQLConString, OrdersLog.ToString(), new DynamicParameters(new { ordersLog.OrdersId, ordersLog.UserName, ordersLog.OrdersState, ordersLog.Remark, })); // foreach (Model.OrdersDetails item in ordersDetailList) { const string OrdersDetail = @"insert into OrdersDetails(OrderId,FlowerWatchName,FlowerWatchPhoto,FlowerNumber, SellingPrice,CostPrice,profit,SellingNum) values(@OrderId,@FlowerWatchName,@FlowerWatchPhoto,@FlowerNumber,@SellingPrice, @CostPrice,@profit,@SellingNum)"; Factory.DBHelper.ExecSQL(SQLConString, OrdersDetail.ToString(), new DynamicParameters(new { item.OrderId, item.FlowerWatchName, item.FlowerWatchPhoto, item.FlowerNumber, item.SellingPrice, item.CostPrice, item.profit, item.SellingNum, })); } return(true); }
public ActionResult CreateOrderDetail(OrderViewModel orderViewModel, FormCollection fc, int id) { List <Product> Proc = db.Products.ToList(); SelectList ProcList = new SelectList(Proc, "ProductID", "ProductName"); ViewBag.procList = ProcList; if (ModelState.IsValid) { bool flag = false; int product_id = int.Parse(fc["ProductID"].ToString()); Order od = db.Orders.Where(s => s.OrderID == id).FirstOrDefault(); Product pd = db.Products.Where(s => s.ProductID == product_id).FirstOrDefault(); List <int> listIdProduct = db.OrdersDetails.Where(s => s.OrderID == id).Select(s => s.ProductID).ToList(); foreach (int idproduct in listIdProduct) { if (idproduct == product_id) { flag = true; break; } } if (flag == true) { TempData["status"] = "Sản phẩm bạn thêm đã có trong giỏ hàng"; TempData["orderID"] = id; return(RedirectToAction("Problem", "Problem")); } if (pd.InStock == 0 || pd.InStock < orderViewModel.Quantity) { ViewBag.ProductIDerror = "Số lượng không đủ đáp ứng!!!"; return(View()); } else { OrdersDetail odetails = new OrdersDetail(); odetails.OrderID = id; odetails.Quantity = orderViewModel.Quantity; odetails.ProductID = product_id; odetails.Price = pd.UnitPrice * orderViewModel.Quantity; db.OrdersDetails.Add(odetails); od.TongTien = (decimal.Parse(od.TongTien) + orderViewModel.Quantity * pd.UnitPrice).ToString(); pd.InStock = pd.InStock - orderViewModel.Quantity; db.SaveChanges(); return(RedirectToAction("Details", new { id = id })); } } else { return(View(orderViewModel)); //return RedirectToAction("CreateOrderDetail", id); } }
public bool Insert(OrdersDetail entity) { try { db.OrdersDetails.Add(entity); db.SaveChanges(); return(true); } catch { return(false); } }
public ActionResult Edit([Bind(Include = "OrderId,ProductId,ColorId,SizeId,Quantity,OldPrice")] OrdersDetail ordersDetail) { if (ModelState.IsValid) { db.Entry(ordersDetail).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.ColorId = new SelectList(db.Colors, "ColorId", "ColorValue", ordersDetail.ColorId); ViewBag.OrderId = new SelectList(db.Orders, "OrderId", "Address", ordersDetail.OrderId); ViewBag.ProductId = new SelectList(db.Products, "ProductId", "ProductName", ordersDetail.ProductId); ViewBag.SizeId = new SelectList(db.Sizes, "SizeId", "SizeValue", ordersDetail.SizeId); return(View(ordersDetail)); }
// GET: Admin/OrdersDetails/Details/5 public ActionResult Details(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } OrdersDetail ordersDetail = db.OrdersDetails.Find(id); if (ordersDetail == null) { return(HttpNotFound()); } return(View(ordersDetail)); }
public ActionResult DeleteOrderDetailConfirmed(int Productid, int orderid) { Order od = db.Orders.Where(s => s.OrderID == orderid).FirstOrDefault(); OrdersDetail p = db.OrdersDetails.Where(s => s.ProductID == Productid && s.OrderID == orderid).FirstOrDefault(); Product pd = db.Products.Where(s => s.ProductID == p.ProductID).FirstOrDefault(); int orderId = p.OrderID; db.OrdersDetails.Remove(p); db.SaveChanges(); od.TongTien = (decimal.Parse((od.TongTien)) - (pd.UnitPrice * p.Quantity)).ToString(); db.Entry(od).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Details", new { id = orderId })); }
public bool Insert(OrdersDetail temp) { try { db.OrdersDetails.Add(temp); db.SaveChanges(); return(true); } catch (Exception) { return(false); throw; } }
/// <summary> /// 消費者付款 /// </summary> public static void CartPayment(cvmOrders model) { OrderNo = CreateNewOrderNo(model); using (ZONYEntities db = new ZONYEntities()) { var datas = db.Carts .Where(m => m.user_no == UserAccount.UserNo) .ToList(); if (datas != null) { int int_amount = datas.Sum(m => m.amount).GetValueOrDefault(); decimal dec_tax = 0; if (int_amount > 0) { dec_tax = Math.Round((decimal)(int_amount * 5 / 100), 0); } int int_total = int_amount + (int)dec_tax; var data = db.Orders.Where(m => m.order_no == OrderNo).FirstOrDefault(); if (data != null) { data.amounts = int_amount; data.taxs = (int)dec_tax; data.totals = int_total; db.SaveChanges(); } foreach (var item in datas) { OrdersDetail detail = new OrdersDetail(); detail.order_no = OrderNo; detail.product_no = item.product_no; detail.product_name = item.product_name; detail.vendor_no = ShopContent.GetVendorNoByProduct(item.product_no); detail.category_name = ShopContent.GetCategoryName(item.product_no); detail.product_spec = item.product_spec; detail.qty = item.qty; detail.price = item.price; detail.amount = item.amount; detail.remark = ""; db.OrdersDetail.Add(detail); db.SaveChanges(); db.Carts.Remove(item); db.SaveChanges(); } } } }
public ActionResult Create() { List <Item> cart = (List <Item>)Session["cart"]; Order order = new Order(); order.CreationDate = DateTime.Now; _mde.Orders.Add(order); _mde.SaveChanges(); List <OrdersDetail> ordersDetails = new List <OrdersDetail>(); foreach (var item in cart) { OrdersDetail ordersDetail = new OrdersDetail(); ordersDetail.OrdersId = order.Id; ordersDetail.ProductId = item.Product.Id; ordersDetail.Quantity = item.Quantity; ordersDetail.Price = item.Quantity * item.Product.Price; ordersDetails.Add(ordersDetail); } return(View(ordersDetails)); }
static void TestGetOrdersDetail(Account account) { InsureAccount(account); Console.WriteLine("To GetOrders, please input symbol, such as btcbitcny, bchbtc, eoseth ..."); Console.Write(" symbol = "); string symbol = Console.ReadLine(); Console.WriteLine(" types = all (default)"); Console.WriteLine(" states = new,part_filled,filled,canceled,expired"); OrdersDetail ordersDetail = Api.GetOrdersDetail(account, symbol, null, "new,part_filled,filled,canceled,expired"); if (ordersDetail == null) { Console.WriteLine("GetOrders Failed!"); return; } Console.WriteLine("GetOrders Succeed: ({0} items)", ordersDetail.items.Count); for (int i = 0; i < ordersDetail.items.Count; i++) { OrderDetail item = ordersDetail.items[i]; Console.WriteLine(" {0}.\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}\t{10}\t{11}\t{12}\t{13}\t{14}", i + 1, item.user_id, item.symbol, item.id, item.type, item.volume, item.price, item.avg_price, item.status, item.deal_volume, item.deal_money, item.fee, item.source, item.ctime, item.mtime); } }
public ActionResult Payment(string CustName, string CustPhone, string CustAdd, string CustEmail) { var orderBook = new OrdersBook(); int userID = Convert.ToInt32(Session["userID"]); //Lưu vào trong db OrderBook orderBook.FoundedDate = DateTime.Now; orderBook.UserID = userID; orderBook.Status = 0; //đơn hàng vừa được đặt sẽ có trạng thái là đang giao orderBook.Address = CustAdd; orderBook.Phone = CustPhone; orderBook.Email = CustEmail; var id = new OrderBookDAO().Insert(orderBook); int tempID = new OrderBookDAO().GetID(); try { var cart = (List <CartItem>)Session[CommonConstant.cartSession]; var detailDAO = new OrdersDetailsDAO(); foreach (var item in cart) { var orderDetail = new OrdersDetail(); orderDetail.OrderID = tempID; orderDetail.BookID = item.Books.BookID; orderDetail.Total = (item.Quantity * item.Books.Price); orderDetail.Quantity = item.Quantity; orderDetail.CreatedDate = DateTime.Now; orderDetail.Status = 1; detailDAO.Insert(orderDetail); } Session[CommonConstant.cartSession] = null; } catch (Exception ex) { throw; } return(Redirect("/hoan-thanh")); }
public ActionResult Payment(string CustName, string CustPhone, string CustAdd, string CustEmail, bool?thanhtoantructuyenNL, bool?thanhtoantructuyenPP) { if (Session["userName"] == null) { return(RedirectToAction("LoginUsernormal", "LoginUser")); } var orderBook = new OrdersBook(); int userID = Convert.ToInt32(Session["userID"]); //Lưu vào trong db OrderBook orderBook.FoundedDate = DateTime.Now; orderBook.UserID = userID; orderBook.Status = 0; orderBook.Address = CustAdd; orderBook.Phone = CustPhone; orderBook.Email = CustEmail; orderBook.FullName = CustName; orderBook.Paid = false; // Mặc định là chưa thanh toán bool result = new OrderBookDAO().Insert(orderBook); try { if (result) { int tempID = orderBook.OrderID; var cart = (List <CartItem>)Session[CommonConstant.cartSession]; var detailDAO = new OrdersDetailsDAO(); double sum = 0; foreach (var item in cart) { var orderDetail = new OrdersDetail(); orderDetail.OrderID = tempID; orderDetail.BookID = item.Books.BookID; orderDetail.Total = (item.Quantity * item.Books.Price); orderDetail.Quantity = item.Quantity; orderDetail.Status = 0; detailDAO.Insert(orderDetail); sum += (item.Books.Price.GetValueOrDefault(0) * item.Quantity); } //Gửi mail thông báo đơn hàng cho Khách hàng string content = System.IO.File.ReadAllText(Server.MapPath("~/Areas/Store/Views/template/newOrder.cshtml")); content = content.Replace("{{CustomerName}}", CustName); content = content.Replace("{{Phone}}", CustPhone); content = content.Replace("{{Email}}", CustEmail); content = content.Replace("{{Address}}", CustAdd); content = content.Replace("{{Total}}", sum.ToString("N0")); new MailHelper().SendMail(CustEmail, "Đơn hàng mới từ QT BookStore", content, "Thông báo Đơn Đặt hàng từ QT BookStore"); if ((thanhtoantructuyenNL == null || thanhtoantructuyenNL == false) && (thanhtoantructuyenPP == null || thanhtoantructuyenPP == false)) { Session[CommonConstant.cartSession] = null; return(Redirect("/hoan-thanh")); } else if (thanhtoantructuyenPP != null || thanhtoantructuyenPP == true) { var model = new CommonConstant.InforPaypal { OrderId = tempID, Total = cart.Sum(m => m.Quantity * m.Books.Price) ?? 0 }; TempData["InforPaypal"] = model; return(RedirectToAction("PaymentWithPaypal", "Paypal")); } else { NL_Checkout nganluong = new NL_Checkout(); double total = cart.Sum(m => m.Quantity * m.Books.Price) ?? 0; string urlThanhToan = nganluong.buildCheckoutUrlNew(Url.Action("PaymentConfirmed", "OrderBook", null, Request.Url.Scheme), ConfigurationManager.AppSettings["email_nganluong"].ToString(), "Thanh toán " + total.ToString("#,##0").Replace(',', '.') + " đồng", tempID.ToString(), total.ToString(), "vnd", 1, 0, 0, 0, 0, "Thanh toán " + total.ToString("#,##0").Replace(',', '.') + " đồng", "Thanh toán " + total.ToString("#,##0").Replace(',', '.') + " đồng", ""); return(Redirect(urlThanhToan)); } } else { ModelState.AddModelError("", "Không thể thêm đơn hàng vì xảy ra lỗi ở server!"); return(View("ThongBaoLoi")); } } catch (Exception ex) { ModelState.AddModelError("", ex.Message); return(View("ThongBaoLoi")); } }
partial void DeleteOrdersDetail(OrdersDetail instance);
public void Insert(int? MenuId,string MenuName,int? OrderId,int? OrderQty,decimal? OrderPrice,bool? IsChgPrice,bool? IsOutOfStock,string ItemInfo) { OrdersDetail item = new OrdersDetail(); item.MenuId = MenuId; item.MenuName = MenuName; item.OrderId = OrderId; item.OrderQty = OrderQty; item.OrderPrice = OrderPrice; item.IsChgPrice = IsChgPrice; item.IsOutOfStock = IsOutOfStock; item.ItemInfo = ItemInfo; item.Save(UserName); }
protected void btnMuaHang_Click(object sender, EventArgs e) { SanacoDataContext ctx = new SanacoDataContext(); //Theme đơn hàng mới Order order = new Order(); order.SessionID = Session["SID"].ToString(); Customer cus = (Customer)Session["Customer"]; order.HoTen = cus.FullName; order.DiaChi = cus.Address; order.SDT = cus.Phone; order.Email = cus.Email; order.YeuCauThem = cus.OtherRequire; order.TongHoaDon = Convert.ToDecimal(Session["Total"].ToString()); order.TrangThai = 0; order.NgayOrder = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")); ctx.Orders.InsertOnSubmit(order); ctx.SubmitChanges(); //Theme vào chi tiết order String sSessionId = Session["SID"].ToString(); var oldOrder = (from ord in ctx.Orders where ord.SessionID == sSessionId select ord).First(); List<OrdersDetail> listProductOrder = new List<OrdersDetail>(); var DSCart = (from s in ctx.SessionCarts where s.SessionId == sSessionId select s); if (DSCart.Count() > 0) { foreach (var item in DSCart) { var SanPham = (from sp in ctx.Products where sp.ID == item.ProductId select sp).First(); OrdersDetail orderDetail = new OrdersDetail(); orderDetail.OrderID = oldOrder.ID; orderDetail.ProductID = SanPham.ID; orderDetail.Quantity = item.Quantity; orderDetail.SellPrice = SanPham.NewPrice; orderDetail.Total = item.Quantity * SanPham.NewPrice; listProductOrder.Add(orderDetail); } } ctx.OrdersDetails.InsertAllOnSubmit(listProductOrder); ctx.SubmitChanges(); //Xóa Session cart lưu tạm var DSSCToDelete = (from sc in ctx.SessionCarts where sc.SessionId == sSessionId select sc); if (DSSCToDelete.Count() > 0) { ctx.SessionCarts.DeleteAllOnSubmit(DSSCToDelete); } ctx.SubmitChanges(); Session.Abandon(); Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", "")); Session["SID"] = Session.SessionID; confirm.Visible = false; InforConfirmPanel.Visible = false; lbMessage.Text = "<span style=\"color:blue; text-align:center; float:left; width: 100%; font-size:15px !important; font-weight: bod; margin-top:20%;\"> Đơn hàng của bạn đã được gửi đi, chúng tôi sẽ xử lý đơn hàng và liên hệ với bạn trong thời gian sớm nhất <br/>Chân thành cảm ơn bạn đã mua sắm tại cửa hàng của chúng tôi</span>"; }
public void creat(OrdersDetail orderDetail) { this.ecommercEntities.OrdersDetails.Add(orderDetail); this.ecommercEntities.SaveChanges(); }
partial void InsertOrdersDetail(OrdersDetail instance);
private static int SaveOrder(OrderMealUserData userData, List<OrderMealData> orderData, Order order, SysCompany company, SysCompanyItem companyItem, decimal orderSum, int qty, bool isNewOrder, out int orderId, out string message) { orderId = -1; bool isLogin = AppContextBase.Context.CurrentSubSys != SubSystem.ALL; decimal servicesSum = company.ServiceSum.HasValue ? company.ServiceSum.Value : 0; SysMember user = isLogin ? AppContextBase.Context.User : null; bool isNeedCheckPhone; if (!isLogin || !Utilities.Compare(user.MemberPhoneNumber, userData.userPhone)) isNeedCheckPhone = true; else isNeedCheckPhone = MsnBLL.IsPhoneNumNeedCheck(userData.userPhone); decimal userOrderAvgSum = 0; if (isLogin && companyItem != null && !CompanyItemBLL.CanClickCompanyMealItem(company, user, companyItem, userData.orderId, out userOrderAvgSum, out message)) return -1; bool isNew = false; using (TransactionScope ts = new TransactionScope( )) { using (SharedDbConnectionScope ss = new SharedDbConnectionScope( )) { if (isNeedCheckPhone && !MsnBLL.CheckPhoneNumCode(userData.userPhone, userData.checkCode, userData.msnLogId)) { message = "验证码有误或已超时,请重新验证。"; return -1; } user = user ?? UserBLL.GetOrNewMemberByPhoneNumber(userData.userPhone, company, out isNew); if (isNew) user.AreaDepth2 = company.AreaDepth; //第一次订快餐的地址,默认该地址所属商圈为其工作圈 else if (!Utilities.Compare(user.AreaDepth2, company.AreaDepth)) { if (string.IsNullOrEmpty(user.AreaDepth1)) user.AreaDepth1 = company.AreaDepth; else if (string.IsNullOrEmpty(user.AreaDepth3)) user.AreaDepth3 = company.AreaDepth; } if (!isNewOrder) { if (order.OrderMemberID != user.Id) { message = "你不能修改其他会员的订单."; return -1; } ClearOrderMenuDetail(order.Id); if (Utilities.ToDecimal(order.OrderPoint) > 0) RewardBLL.RewardMemberPointForOrderMeal(user, company, order); order.OrderStatus = (int)OrderStatus.Modified; } else { order.OrderNum = GetOrderNum( ); order.OrderStatus = (int)OrderStatus.NotStart; order.OrderPoint = 0; } var dtNow = DateTime.Now; //order.OrderCode = orderCode; order.OrderCard = string.Empty; order.OrderDate = dtNow; order.OrderDateDeliver = dtNow; order.OrderDateUpload = dtNow; order.OrderMemberID = user.Id; order.OrderMemo = userData.memo; order.OrderProduct = userData.address; //送餐地址 order.OrderQty = qty; order.OrderRateSale = 0; // 折扣 order.OrderRate = RewardBLL.OrderMealRewardRate(company) / 100M; //赠送比例 order.OrderPrePoint = (RewardBLL.OrderMealRewardRate(company) / 100M) * orderSum; //赠送积分 order.OrderSellerID = company.Id; order.OrderSum = orderSum; //订单总额 order.OrderSumOk = orderSum + servicesSum; //订单总额 order.OrderPay = orderSum + servicesSum; //现金支付 order.OrderPayCash = 0; //储值支付 order.OrderPayPoint = companyItem != null ? companyItem.ItemPoint : 0;//积分支付 order.OrderType = (int)OrderType.OrderMeal; order.ServiceSum = servicesSum; order.MansionId = userData.mansionId; order.OrderModel = company.IsUseMsg.HasValue && company.IsUseMsg.Value ? (int)OrderModel.Auto : (int)OrderModel.Manual; order.OrderUpdateOn = DateTime.Now; order.IsNonOut = false; order.HasOutOfStock = false; order.Save( ); //RewardBLL.RewardMemberPointForOrderMeal(user, company, order); //save detail List<OrdersDetail> details = new List<OrdersDetail>( ); foreach (var pair in orderData) { var d = new OrdersDetail( ) { MenuId = pair.menudId, MenuName = pair.menuName, OrderId = order.Id, OrderQty = pair.menuAmount, OrderPrice = pair.menuPrice.Value, IsChgPrice = false, IsOutOfStock = false, ItemInfo = pair.isCompanyItem && companyItem != null ? companyItem.ItemInfo : null }; d.Save( ); details.Add(d); } if (isLogin && companyItem != null) CompanyItemBLL.ClickCompanyMealItem(company, user, companyItem, order, userOrderAvgSum); UserBLL.AddUserFavAddress(user.Id, userData.mansionId, userData.address); //UserBLL.AddUserFavCompany(user.Id, company.Id); //OrderBLL.UpdateBalance( ); ts.Complete( ); //SendOrderMealMessage(company, user, order, details, out message); if (userData.orderId > 0) OrderProgressBLL.ClearOrderLog(order.Id); OrderProgressBLL.InitOrderLogProgress(order, company); message = "订餐成功."; orderId = order.Id; } } //Auto login if (!isLogin) { if (user != null) { if (user.MemberRoleId > 0) user.LastLoginSubSys = (int)SubSystem.Member; else if (user.CompanyRoleId > 0) user.LastLoginSubSys = (int)SubSystem.Company; else if (user.AdminRoleId > 0) user.LastLoginSubSys = (int)SubSystem.Admin; user.LastLoginDate = DateTime.Now; user.Save( ); Utilities.LoginSigIn(user.Id, (SubSystem)user.LastLoginSubSys); if (isNew) { message = "下次订餐您可以直接登录,账号是您的手机号码,密码为手机后6位数,记得及时修改密码哦!"; return 2; } return 1; } } return 1; }
public static IEnumerable<OrdersDetail> GetOrderNonOutOfStockDetailByOrderId(int orderId) { var query = DB.Select(Utilities.GetTableColumns(OrdersDetail.Schema)).From<OrdersDetail>( ) .Where(OrdersDetail.OrderIdColumn).IsEqualTo(orderId) .And(OrdersDetail.IsOutOfStockColumn).IsEqualTo(false) .OrderAsc(OrdersDetail.IdColumn.QualifiedName); using (var dr = query.ExecuteReader( )) { while (dr.Read( )) { OrdersDetail d = new OrdersDetail( ); d.Load(dr); yield return d; } } }
public ActionResult CartAddress(Order or, string code) { try { if (Session["Cart"] != null) { int u = (int)Session["UserId"]; var voucher = db.Vouchers.SingleOrDefault(x => x.Code.Equals(code) && x.Remain > 0 && (x.ExpiredAt >= DateTime.Now || x.ExpiredAt == null)); User us = db.Users.SingleOrDefault(x => x.UserId == u); if (voucher != null) { or.UserId = us.UserId; or.VoucherId = voucher.VoucherId; or.CreatedAt = DateTime.Now.ToLocalTime(); db.Orders.Add(or); db.SaveChanges(); Session["OrderId"] = or.OrderId; var lst = (List <CartItem>)Session["Cart"]; foreach (var item in lst) { var ordetail = new OrdersDetail(); ordetail.OrderId = or.OrderId; ordetail.ProductId = item.Product.ProductId; ordetail.ColorId = item.Color.ColorId; ordetail.SizeId = item.Size.SizeId; ordetail.Quantity = item.Quantity; if (item.Product.ProductDiscount != null) { ordetail.OldPrice = item.Product.ProductPrice - ((item.Product.ProductPrice * (int)item.Product.ProductDiscount) / 100); } else { ordetail.OldPrice = item.Product.ProductPrice; } db.OrdersDetails.Add(ordetail); db.SaveChanges(); } Session["Cart"] = null; } else { or.UserId = us.UserId; or.VoucherId = 1; or.CreatedAt = DateTime.Now.ToLocalTime(); db.Orders.Add(or); db.SaveChanges(); Session["OrderId"] = or.OrderId; var lst = (List <CartItem>)Session["Cart"]; foreach (var item in lst) { var ordetail = new OrdersDetail(); ordetail.OrderId = or.OrderId; ordetail.ProductId = item.Product.ProductId; ordetail.ColorId = item.Color.ColorId; ordetail.SizeId = item.Size.SizeId; ordetail.Quantity = item.Quantity; if (item.Product.ProductDiscount != null) { ordetail.OldPrice = item.Product.ProductPrice - ((item.Product.ProductPrice * (int)item.Product.ProductDiscount) / 100); } else { ordetail.OldPrice = item.Product.ProductPrice; } db.OrdersDetails.Add(ordetail); db.SaveChanges(); } Session["Cart"] = null; } return(RedirectToAction("CartPayment")); } else { return(RedirectToAction("Index", "Home")); } } catch (Exception ex) { ViewBag.aaa = " loi " + ex; return(View()); throw; } }
public static IEnumerable<OrdersDetail> GetOutOfStockDeitalByOrderId(int orderId) { var query = DB.Select( ).From<OrdersDetail>( ) .Where(OrdersDetail.OrderIdColumn).IsEqualTo(orderId) .And(OrdersDetail.IsOutOfStockColumn).IsEqualTo(true); using (var dr = query.ExecuteReader( )) { while (dr.Read( )) { OrdersDetail d = new OrdersDetail( ); d.Load(dr); yield return d; } } }
public int CrearTransferencia(int idCliente, List<DetalleOrdenRecargaPrepago> detalleOrden) { int idOrden = 0; using (LealtadEntities db = new LealtadEntities()) { db.Database.Connection.ConnectionString = AppModule.ConnectionString("SumaLealtad"); //ENTIDAD Order Order Order = new Order() { id = repOrden.OrderId(), prepaidcustomerid = idCliente, totalamount = 0, paymenttype = "", creationdate = DateTime.Now, creationuserid = (int)HttpContext.Current.Session["userid"], processdate = DateTime.Now, comments = detalleOrden.First().tipoOrden, sumastatusid = db.SumaStatuses.FirstOrDefault(s => (s.value == Globals.ID_ESTATUS_ORDEN_NUEVA) && (s.tablename == "Orders")).id }; db.Orders.Add(Order); idOrden = Order.id; int idbase = repOrden.OrdersDetailId(); foreach (DetalleOrdenRecargaPrepago item in detalleOrden) { idbase = idbase + 1; //ENTIDAD OrderDetail OrdersDetail OrderDetail = new OrdersDetail() { id = idbase, orderid = Order.id, customerid = item.idAfiliado, amount = item.montoRecarga, sumastatusid = db.SumaStatuses.FirstOrDefault(s => (s.value == Globals.ID_ESTATUS_DETALLEORDEN_INCLUIDO) && (s.tablename == "OrdersDetail")).id }; if (detalleOrden.First().tipoOrden == "Orden de Anulación de Transferencia") { long number1 = 0; bool canConvert = long.TryParse(item.batchid, out number1); //si la transferencia no fue exitosa, creo el renglon de la orden con monto 0 if (canConvert == false) { OrderDetail.amount = 0; } else { OrderDetail.amount = item.montoRecarga; OrderDetail.comments = item.batchid; } } db.OrdersDetails.Add(OrderDetail); } //Entidad OrderHistory int idOrderHistory = repOrden.OrdersHistoryId(); OrdersHistory orderhistory = new OrdersHistory() { id = idOrderHistory, orderid = idOrden, estatusid = Order.sumastatusid, userid = (int)HttpContext.Current.Session["userid"], creationdate = DateTime.Now, comments = "orden creada" }; db.OrdersHistories.Add(orderhistory); db.SaveChanges(); return idOrden; } }
private void attach_OrdersDetails(OrdersDetail entity) { this.SendPropertyChanging(); entity.Order = this; }
public void creat(OrdersDetail orderDetail) { this.clothesMarketEntities.OrdersDetails.Add(orderDetail); this.clothesMarketEntities.SaveChanges(); }
partial void UpdateOrdersDetail(OrdersDetail instance);
public async Task <IActionResult> SubmitOrder(IFormCollection Form /*表单集合传参*/)//提交订单 { if (string.IsNullOrEmpty(HttpContext.Session.GetString("LoginUserId"))) { return(RedirectToAction("Index", "Login")); } if (Form["ProductId"].Count == 0) { return(RedirectToAction("Index", "Home")); } if (!string.IsNullOrEmpty(HttpContext.Session.GetString("LoginUser"))) { ViewBag.LoginName = HttpContext.Session.GetString("LoginUser"); //显示界面当前登录用户 ViewBag.LoginId = HttpContext.Session.GetString("LoginUserId"); //显示界面当前登录用户 } HttpClient client = new HttpClient(); var resultC = await client.GetStringAsync("http://localhost:8080/api/Categories"); IEnumerable <Category> listC = JsonConvert.DeserializeObject <IEnumerable <Category> >(resultC); ViewData["Category"] = listC.Where(p => p.ParentId != p.CategoryId); Orders order = new Orders(); // [OrdersId] //,[Orderdate] //,[UsersId] //,[Total] //,[DeliveryId] //,[DeliveryDate] //,[States] //,[Remark] order.OrdersId = int.Parse(Form["OrdersId"][0]); order.Orderdate = DateTime.Parse(DateTime.Now.ToString("yyyyMMddHHmmssfff")); order.UsersId = int.Parse(HttpContext.Session.GetString("LoginUserId")); order.Total = decimal.Parse(Form["Total"][0]); order.DeliveryId = int.Parse(Form["DeliveryId"][0]);//用户收货地址编号 order.States = 0; order.Remark = Form["Remark"][0]; var jsonString = JsonConvert.SerializeObject(order); HttpContent httpContent = new StringContent(jsonString); httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); var resMsg = await client.PostAsync("http://localhost:8080/api/Orders", httpContent); ViewBag.OrdersId = order.OrdersId; ViewBag.Total = order.Total; //List<OrdersDetail> listOD = new List<OrdersDetail>(); // [OrdersId] //,[ProductId] //,[Quantity] //,[States] //,[PhotoUrl] //,[Title] //,[Price] for (int i = 0; i < Form["ProductId"].Count; i++) { OrdersDetail od = new OrdersDetail(); od.OrdersId = order.OrdersId; od.ProductId = int.Parse(Form["ProductId"][i]); od.Quantity = int.Parse(Form["ProductNum"][i]); od.States = 0;//0正常,1退货中,2已退货 od.PhotoUrl = Form["PhotoUrl"][i]; od.Title = Form["Title"][i]; od.Price = decimal.Parse(Form["Price"][i]); //listOD.Add(od); jsonString = JsonConvert.SerializeObject(od); httpContent = new StringContent(jsonString); httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); resMsg = await client.PostAsync("http://localhost:8080/api/OrdersDetails", httpContent); //清除购物车里面的商品 resMsg = await client.DeleteAsync("http://localhost:8080/api/Cars/" + od.ProductId); } return(View()); }
private void detach_OrdersDetails(OrdersDetail entity) { this.SendPropertyChanging(); entity.Product = null; }
/// <summary> /// 添加订单 /// </summary> /// <param name="userId">用户编号</param> /// <param name="list">列表</param> public bool AddOrder(long userId, string adress, string tel, string contacts, List <PayProductInfoEntity> list) { bool flag = false; string idList = list.Select(e => e.Id).ToArray().ToSQLInChar(); var productList = new BookService().GetPayInfoList(idList); Orders order = new Orders { Address = adress, Contacts = contacts, CreateTime = DateTime.Now, OrderNo = SysHelper.GetPrimaryKey(), StateFlag = FlagMgr.Order.OrderSateFlag.Pay.ToInt(), Tel = tel, TotalPrice = 0, UserId = userId }; decimal total = 0; List <OrdersDetail> detailList = new List <OrdersDetail>(); foreach (var item in productList) { int number = 0; var payItem = list.Find(e => e.Id == item.Id); if (payItem != null) { number = payItem.BuyNum; } OrdersDetail model = new OrdersDetail() { ProductId = item.Id, Quantity = number, UnitPrice = item.UnitPrice }; total += number * item.UnitPrice; detailList.Add(model); } order.TotalPrice = total; using (var ctx = new BookShopContext()) { using (DbContextTransaction transaction = ctx.Database.BeginTransaction()) { try { ctx.Orders.Add(order); if (ctx.SaveChanges() > 0) { flag = true; foreach (var item in detailList) { item.OrderId = order.Id; } ctx.OrdersDetail.AddRange(detailList); ctx.SaveChanges(); ctx.Database.ExecuteSqlCommand(string.Format("delete from [dbo].[ShopingCart] where [UserId]={0} and [ProductId] in({1})", userId, idList)); } transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); Console.WriteLine("Error occurred."); } } } return(flag); }