public AddOrderProxy() { OrderModel = new OrderDao(context); CustomerModel = new CustomerDao(context); GoodsModel = new GoodsDao(context); GoodsRowModel = new GoodsRowDao(context); OrderStatusModel = new OrderStatusDao(context); CommentModel = new CommentDao(context); }
public OrderViewModel(EmailSender emailSender, ReceiptPrinter receiptPrinter, OrderDao orderDao, RecommendationEngine engine, ReceiptDao receiptDao) { _emailSender = emailSender; _receiptPrinter = receiptPrinter; _orderDao = orderDao; _recommendationEngine = engine; _receiptDao = receiptDao; Recommendations = new ObservableCollection<Recommendation>(); }
public object Do_PreOrder(BaseApi baseApi) { List <PreOrderParam> preOrderParamList = JsonConvert.DeserializeObject <List <PreOrderParam> >(baseApi.param.ToString()); if (preOrderParamList == null || preOrderParamList.Count == 0) { throw new ApiException(CodeMessage.InvalidParam, "InvalidParam"); } PreOrder preOrder = new PreOrder(); OrderDao orderDao = new OrderDao(); string memberId = Utils.GetMemberID(baseApi.token); Store store = orderDao.GetStoreByMemberId(memberId); if (store == null) { throw new ApiException(CodeMessage.BindStoreFirst, "BindStoreFirst"); } preOrder.addr = store.storeAddr; string[] goodsIds = new string[preOrderParamList.Count]; for (int i = 0; i < preOrderParamList.Count; i++) { goodsIds[i] = preOrderParamList[i].goodsId; } List <Goods> goodsList = orderDao.GetGoodsByGoodsIds(goodsIds); int total = 0; List <PreOrderGoods> list = new List <PreOrderGoods>(); foreach (Goods goods in goodsList) { var preOrderParam = preOrderParamList.Find ( item => item.goodsId.Equals(goods.goodsId) ); if (preOrderParam == null) { throw new ApiException(CodeMessage.InvalidGoods, "InvalidGoods"); } if (preOrderParam.goodsNum < 0) { throw new ApiException(CodeMessage.ErrorNum, "ErrorNum"); } if (preOrderParam.goodsNum <= goods.goodsStock) { total += goods.goodsPrice * preOrderParam.goodsNum; PreOrderGoods preOrderGoods = new PreOrderGoods { cartId = preOrderParam.cartId, goodsNum = preOrderParam.goodsNum, goodsId = goods.goodsId, goodsImg = goods.goodsImg, goodsName = goods.goodsName, goodsPrice = goods.goodsPrice, }; list.Add(preOrderGoods); } else { throw new ApiException(CodeMessage.NotEnoughGoods, "NotEnoughGoods"); } } preOrder.list = list; preOrder.total = total; preOrder.storeCode = store.storeCode; preOrder.preOrderId = Guid.NewGuid().ToString(); Utils.SetCache(preOrder.preOrderId, preOrder, 0, 5, 0); return(preOrder); }
// get order by id public ActionResult GetOrder(long id) { var model = new OrderDao().GetOrderByID(id); return(View(model)); }
public ActionResult Detail1Ship(long id) { var model = new OrderDao().View1Ship(id); return(View(model)); }
public ActionResult ThanhToan(string shipName, string address, string mobile, string httt, string htgh) { var od = new OrderDao(); var session = (UserLogin)Session[CommonConstants.SESSION]; var dondathang = new DONDATHANG(); dondathang.MaKH = new UserDao().GetByName(session.TenDN).MaKH; dondathang.NgayDH = DateTime.Now; dondathang.TenNguoiNhan = shipName; dondathang.DiaChiNhan = address; dondathang.DienThoaiNhan = mobile; dondathang.HTThanhToan = httt; dondathang.HTGiaoHang = htgh; var soDH = od.Insert(dondathang); var cart = (List <CartItem>)Session[CartSession]; var chitietDao = new OrderDetailDao(); decimal total = 0; //string tenmonan = null, gia = null; foreach (var item in cart) { var chitiet = new CTDATHANG(); chitiet.SoDH = soDH; chitiet.MaMonAn = item.MonAn.MaMonAn; chitiet.DonGia = item.MonAn.DonGia; chitiet.SoLuong = item.SoLuong; chitiet.ThanhTien = item.MonAn.DonGia * item.SoLuong; od.InsertSLBan(item.MonAn.MaMonAn, item.SoLuong); chitietDao.Insert(chitiet); total += (item.MonAn.DonGia.GetValueOrDefault(0) * item.SoLuong); //tenmonan += item.MonAn.TenMonAn + "<br />"; //gia += item.MonAn.DonGia.GetValueOrDefault(0).ToString("N0") + "<br />"; } od.InsertTotal(soDH, total); //try //{ // var content = System.IO.File.ReadAllText(Server.MapPath("/Template/MailOrder.html")); // var toEmail_User = new UserDao().GetByName(session.TenDN).Email; // string time = DateTime.Now.ToString("dd MMMM yyyy hh:mm:ss tt"); // content = content.Replace("{{SoDH}}", soDH.ToString()); // content = content.Replace("{{Time}}", time); // content = content.Replace("{{CustomerName}}", shipName); // content = content.Replace("{{Phone}}", mobile); // content = content.Replace("{{Address}}", address); // content = content.Replace("{{Email}}", toEmail_User); // content = content.Replace("{{Item}}", tenmonan); // content = content.Replace("{{Price}}", gia); // content = content.Replace("{{Total}}", total.ToString("N0")); // var mailHelper = new MailHelper(); // mailHelper.SendMail(toEmail_User, "Đơn hàng mới từ CD Food", content); // Session[CartSession] = null; //} //catch (Exception ex) //{ // ViewBag.LoiThanhToan = ex; // return View(cart); //} Session[CartSession] = null; return(Redirect("/hoan-thanh")); }
//Metodo para crear el reporte de ventas public void createSalesOrderReport(DateTime fromDate, DateTime toDate) { //Implementar fechas reportDate = DateTime.Now; startDate = fromDate; endDate = toDate; //Crear sales listing var orderDao = new OrderDao(); var result = orderDao.getSalesOrder(fromDate, toDate); salesListing = new List <SalesListing>(); foreach (System.Data.DataRow rows in result.Rows) { var salesModel = new SalesListing() { orderId = Convert.ToInt32(rows[0]), orderDate = Convert.ToDateTime(rows[1]), customer = Convert.ToString(rows[2]), products = Convert.ToString(rows[3]), totalAmount = Convert.ToDouble(rows[4]) }; salesListing.Add(salesModel); //Calcular total net sales totalNetSales += Convert.ToDouble(rows[4]); } //Crear net sales por periodo //creamos lista temporal net sales por fecha var listSalesByDate = (from sales in salesListing group sales by sales.orderDate into listSales select new { date = listSales.Key, amount = listSales.Sum(item => item.totalAmount) }).AsEnumerable(); //Obtener numero de dias int totalDays = Convert.ToInt32((toDate - fromDate).Days); //Agrupar periodo por dias if (totalDays <= 7) { netSalesByPeriod = (from sales in listSalesByDate group sales by sales.date.ToString("dd-MMM-yyyy") into listSales select new NetSalesByPeriod { period = listSales.Key, netSales = listSales.Sum(item => item.amount) }).ToList(); } //Agrupar peridods por semanas else if (totalDays <= 30) { netSalesByPeriod = (from sales in listSalesByDate group sales by System.Globalization.CultureInfo.CurrentCulture.Calendar.GetWeekOfYear( sales.date, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Monday) into listSales select new NetSalesByPeriod { period = "Semana: " + listSales.Key.ToString(), netSales = listSales.Sum(item => item.amount) }).ToList(); } //agrupar periodos por meses else if (totalDays <= 365) { netSalesByPeriod = (from sales in listSalesByDate group sales by sales.date.ToString("MMM-yyyy") into listSales select new NetSalesByPeriod { period = listSales.Key, netSales = listSales.Sum(item => item.amount) }).ToList(); } //agrupar periodos por anos else { netSalesByPeriod = (from sales in listSalesByDate group sales by sales.date.ToString("yyyy") into listSales select new NetSalesByPeriod { period = listSales.Key, netSales = listSales.Sum(item => item.amount) }).ToList(); } }
public static bool UserPayOrder(OrderInfo order) { OrderDao dao = new OrderDao(); order.OrderStatus = OrderStatus.BuyerAlreadyPaid; order.PayDate = new DateTime?(DateTime.Now); bool flag = dao.UpdateOrder(order, null); string str = ""; if (flag) { dao.UpdatePayOrderStock(order.OrderId); foreach (LineItemInfo info in order.LineItems.Values) { ProductDao dao2 = new ProductDao(); str = str + "'" + info.SkuId + "',"; ProductInfo productDetails = dao2.GetProductDetails(info.ProductId); productDetails.SaleCounts += info.Quantity; productDetails.ShowSaleCounts += info.Quantity; dao2.UpdateProduct(productDetails, null); } if (!string.IsNullOrEmpty(str)) { dao.UpdateItemsStatus(order.OrderId, 2, str.Substring(0, str.Length - 1)); } if (!string.IsNullOrEmpty(order.ActivitiesId)) { new ActivitiesDao().UpdateActivitiesTakeEffect(order.ActivitiesId); } MemberInfo member = GetMember(order.UserId); if (member == null) { return(flag); } MemberDao dao4 = new MemberDao(); PointDetailInfo point = new PointDetailInfo { OrderId = order.OrderId, UserId = member.UserId, TradeDate = DateTime.Now, TradeType = PointTradeType.Bounty, Increased = new int?(order.Points), Points = order.Points + member.Points }; if ((point.Points > 0x7fffffff) || (point.Points < 0)) { point.Points = 0x7fffffff; } PointDetailDao dao5 = new PointDetailDao(); dao5.AddPointDetail(point); member.Expenditure += order.GetTotal(); member.OrderNumber++; dao4.Update(member); Messenger.OrderPayment(member, order.OrderId, order.GetTotal()); int historyPoint = dao5.GetHistoryPoint(member.UserId); MemberGradeInfo memberGrade = GetMemberGrade(member.GradeId); if ((memberGrade != null) && (memberGrade.Points > historyPoint)) { return(flag); } List <MemberGradeInfo> memberGrades = new MemberGradeDao().GetMemberGrades() as List <MemberGradeInfo>; foreach (MemberGradeInfo info6 in from item in memberGrades orderby item.Points descending select item) { if (member.GradeId == info6.GradeId) { return(flag); } if (info6.Points <= historyPoint) { member.GradeId = info6.GradeId; dao4.Update(member); return(flag); } } } return(flag); }
public static bool UserPayOrder(OrderInfo order) { OrderDao orderDao = new OrderDao(); order.OrderStatus = OrderStatus.BuyerAlreadyPaid; order.PayDate = new DateTime?(DateTime.Now); bool flag = orderDao.UpdateOrder(order, null); string text = ""; Globals.Debuglog(string.Concat(new string[] { "调用付款:", order.OrderId, ",成功否:", flag.ToString(), ",order.UserId:", order.UserId.ToString() }), "_DebuglogPaymentTest.txt"); if (flag) { orderDao.UpdatePayOrderStock(order); SiteSettings masterSettings = SettingsManager.GetMasterSettings(true); MemberInfo member = MemberProcessor.GetMember(order.UserId, true); bool flag2 = VshopBrowser.IsPassAutoToDistributor(member, true); if (flag2) { DistributorsBrower.MemberAutoToDistributor(member); } new MemberDao().SetOrderDate(order.UserId, 1); foreach (LineItemInfo current in order.LineItems.Values) { ProductDao productDao = new ProductDao(); text = text + "'" + current.SkuId + "',"; ProductInfo productDetails = productDao.GetProductDetails(current.ProductId); productDetails.SaleCounts += current.Quantity; productDetails.ShowSaleCounts += current.Quantity; productDao.UpdateProduct(productDetails, null); } if (!string.IsNullOrEmpty(text)) { orderDao.UpdateItemsStatus(order.OrderId, 2, text.Substring(0, text.Length - 1)); } if (!string.IsNullOrEmpty(order.ActivitiesId)) { ActivitiesDao activitiesDao = new ActivitiesDao(); activitiesDao.UpdateActivitiesTakeEffect(order.ActivitiesId); } if (member != null) { Globals.Debuglog(string.Concat(new string[] { "发微信消息:", order.OrderId, ",成功:", flag.ToString(), ",order.UserId:", order.UserId.ToString() }), "_DebuglogPaymentTest.txt"); try { Messenger.SendWeiXinMsg_OrderPay(order); } catch { } } } return(flag); }
public static bool SubmitOrder(int?id) { int res = OrderDao.SubmitOrder(id); return(res > 0); }
/// <summary> /// 清除历史数据,并下载数据。 /// </summary> /// <param name="orderDate"></param> /// <param name="batchNo"></param> public void DownloadData(string orderDate, int batchNo, string dataBase) { try { ProcessState.Status = "PROCESSING"; ProcessState.TotalCount = 15; ProcessState.Step = 1; DateTime dtOrder = DateTime.Parse(orderDate); string historyDate = dtOrder.AddDays(-7).ToShortDateString(); using (PersistentManager pm = new PersistentManager()) { BatchDao batchDao = new BatchDao(); using (PersistentManager ssPM = new PersistentManager(dataBase)) { SalesSystemDao ssDao = new SalesSystemDao(); ssDao.SetPersistentManager(ssPM); try { pm.BeginTransaction(); //AS_BI_BATCH batchDao.DeleteHistory(historyDate); ProcessState.CompleteCount = 1; //AS_SC_CHANNELUSED ChannelScheduleDao csDao = new ChannelScheduleDao(); csDao.DeleteHistory(historyDate); ProcessState.CompleteCount = 2; //AS_SC_LINE LineScheduleDao lsDao = new LineScheduleDao(); lsDao.DeleteHistory(historyDate); ProcessState.CompleteCount = 3; //AS_SC_PALLETMASTER ,AS_SC_ORDER OrderScheduleDao osDao = new OrderScheduleDao(); osDao.DeleteHistory(historyDate); ProcessState.CompleteCount = 4; //AS_I_ORDERMASTER,AS_I_ORDERDETAIL, OrderDao orderDao = new OrderDao(); orderDao.DeleteHistory(historyDate); ProcessState.CompleteCount = 5; //AS_SC_STOCKMIXCHANNEL StockChannelDao scDao = new StockChannelDao(); scDao.DeleteHistory(historyDate); ProcessState.CompleteCount = 6; //AS_SC_SUPPLY SupplyDao supplyDao = new SupplyDao(); supplyDao.DeleteHistory(historyDate); ProcessState.CompleteCount = 7; //AS_SC_HANDLESUPPLY HandleSupplyDao handleSupplyDao = new HandleSupplyDao(); handleSupplyDao.DeleteHistory(historyDate); ProcessState.CompleteCount = 8; ClearSchedule(orderDate, batchNo); ////////////////////////////////////////////////////////////////////////// //下载区域表 AreaDao areaDao = new AreaDao(); DataTable areaTable = ssDao.FindArea(); areaDao.SynchronizeArea(areaTable); ProcessState.CompleteCount = 9; //下载配送线路表 RouteDao routeDao = new RouteDao(); DataTable routeTable = ssDao.FindRoute(); routeDao.SynchronizeRoute(routeTable); ProcessState.CompleteCount = 10; //下载客户表 CustomerDao customerDao = new CustomerDao(); DataTable customerTable = ssDao.FindCustomer(dtOrder); customerDao.SynchronizeCustomer(customerTable); ProcessState.CompleteCount = 11; //下载卷烟表 进行同步 CigaretteDao cigaretteDao = new CigaretteDao(); DataTable cigaretteTable = ssDao.FindCigarette(dtOrder); cigaretteDao.SynchronizeCigarette(cigaretteTable); ProcessState.CompleteCount = 12; //查询已优化过的线路,以进行排除。 string routes = lsDao.FindRoutes(orderDate); //下载订单主表 DataTable masterTable = ssDao.FindOrderMaster(dtOrder, batchNo, routes); orderDao.BatchInsertMaster(masterTable); ProcessState.CompleteCount = 13; //下载订单明细 DataTable detailTable = ssDao.FindOrderDetail(dtOrder, batchNo, routes); orderDao.BatchInsertDetail(detailTable); ProcessState.CompleteCount = 14; pm.Commit(); } catch (Exception e) { pm.Rollback(); throw e; } } } } catch (Exception ee) { ProcessState.Status = "ERROR"; ProcessState.Message = ee.Message; } }
public UserCRUDService(IUnitOfWork unitOfWork) : base(unitOfWork) { _userDao = new UserDao(unitOfWork); _orderDao = new OrderDao(unitOfWork); }
public ActionResult ApprovedOrders(List <OrderDetail> orderDetails, int orderId) { OrderDao.ReceiveStocks(orderDetails, orderId); return(RedirectToAction("ApprovedOrders")); }
public void ConfirmPay(HttpContext context) { string text = context.Request["id"]; if (string.IsNullOrWhiteSpace(text)) { throw new HidistroAshxException("错误的编号"); } OrderInfo orderInfo = new OrderDao().GetOrderInfo(text); if (orderInfo == null) { throw new HidistroAshxException("错误的编号"); } if (!orderInfo.CheckAction(OrderActions.SELLER_CONFIRM_PAY)) { throw new HidistroAshxException("权限不足"); } PaymentModeInfo paymentMode = SalesHelper.GetPaymentMode("hishop.plugins.payment.bankrequest"); if (paymentMode != null) { orderInfo.Gateway = paymentMode.Gateway; orderInfo.PaymentType = paymentMode.Name; orderInfo.PaymentTypeId = paymentMode.ModeId; } else { orderInfo.Gateway = "hishop.plugins.payment.bankrequest"; orderInfo.PaymentType = "线下支付"; orderInfo.PaymentTypeId = 0; } if (orderInfo.PaymentType.Length > 8) { orderInfo.PaymentType = orderInfo.PaymentType.Substring(0, 8) + "..."; } int num = 0; int num2 = 0; int num3 = 0; if (orderInfo.CountDownBuyId > 0) { string empty = string.Empty; foreach (KeyValuePair <string, LineItemInfo> lineItem in orderInfo.LineItems) { CountDownInfo countDownInfo = TradeHelper.CheckUserCountDown(lineItem.Value.ProductId, orderInfo.CountDownBuyId, lineItem.Value.SkuId, orderInfo.UserId, orderInfo.GetAllQuantity(true), orderInfo.OrderId, out empty, orderInfo.StoreId); if (countDownInfo == null) { throw new HidistroAshxException(empty); } } } if (orderInfo.FightGroupId > 0) { string empty2 = string.Empty; foreach (KeyValuePair <string, LineItemInfo> lineItem2 in orderInfo.LineItems) { FightGroupActivityInfo fightGroupActivityInfo = VShopHelper.CheckUserFightGroup(lineItem2.Value.ProductId, orderInfo.FightGroupActivityId, orderInfo.FightGroupId, lineItem2.Value.SkuId, orderInfo.UserId, orderInfo.GetAllQuantity(true), orderInfo.OrderId, lineItem2.Value.Quantity, out empty2); if (fightGroupActivityInfo == null) { throw new HidistroAshxException(empty2); } } } if (orderInfo.GroupBuyId > 0) { GroupBuyInfo groupBuy = PromoteHelper.GetGroupBuy(orderInfo.GroupBuyId); if (groupBuy == null || groupBuy.Status != GroupBuyStatus.UnderWay) { throw new HidistroAshxException("当前的订单为团购订单,此团购活动已结束,所以不能支付"); } num2 = PromoteHelper.GetOrderCount(orderInfo.GroupBuyId); num = groupBuy.MaxCount; num3 = orderInfo.GetGroupBuyOerderNumber(); if (num < num2 + num3) { throw new HidistroAshxException("当前的订单为团购订单,订购数量已超过订购总数,所以不能支付"); } } if (orderInfo.PreSaleId > 0) { ProductPreSaleInfo productPreSaleInfo = ProductPreSaleHelper.GetProductPreSaleInfo(orderInfo.PreSaleId); if (productPreSaleInfo == null) { throw new HidistroAshxException("预售活动不存在"); } if (!orderInfo.DepositDate.HasValue && productPreSaleInfo.PreSaleEndDate < DateTime.Now) { throw new HidistroAshxException("预售活动已结束不能支付定金,所以不能确认收款"); } } string empty3 = string.Empty; switch (TradeHelper.CheckOrderBeforePay(orderInfo, out empty3)) { case 1: throw new HidistroAshxException($"当前有商品{empty3}下架或者被删除,不能确认收款"); case 2: if ((orderInfo.PreSaleId <= 0 || orderInfo.DepositDate.HasValue) && orderInfo.PreSaleId > 0) { break; } throw new HidistroAshxException($"当前有商品{empty3}库存不足,不能确认收款"); } if (OrderHelper.ConfirmPay(orderInfo)) { if (orderInfo.GroupBuyId > 0 && num == num2 + num3) { PromoteHelper.SetGroupBuyEndUntreated(orderInfo.GroupBuyId); } if (orderInfo.ParentOrderId == "-1") { OrderQuery orderQuery = new OrderQuery(); orderQuery.ParentOrderId = orderInfo.OrderId; IList <OrderInfo> listUserOrder = MemberProcessor.GetListUserOrder(orderInfo.UserId, orderQuery); foreach (OrderInfo item in listUserOrder) { OrderHelper.OrderConfirmPaySendMessage(item); } } else { OrderHelper.OrderConfirmPaySendMessage(orderInfo); } base.ReturnSuccessResult(context, "成功的确认了订单收款", 0, true); return; } throw new HidistroAshxException("确认订单收款失败"); }
/// <summary> /// Odświezanie danych /// </summary> private void RefreshGrid() { OrdersDataGrid.ItemsSource = OrderDao.LoadAll(); }
public ActionResult DiaryOrder(Guid userID) { var model = new OrderDao().ListByUser(userID); return(View(model)); }
// GET: Admin/Default public ActionResult Index() { List <decimal?> doanhthu = new List <decimal?>() { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; List <decimal?> doanhthunam = new List <decimal?>() { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; List <decimal?> OrderChoXacNhan = new List <decimal?>() { 0 }; List <decimal?> CountProduct = new List <decimal?>() { 0 }; var order = new OrderDao().GetListOrder(); var detail = new OrderDao().GetListDetail(); decimal sanpham = new ProductDao().CountProduct(); CountProduct[0] = sanpham; ViewBag.CountProduct = CountProduct; decimal?price = 0; decimal?pricenam = 0; foreach (var item in order) { price = 0; foreach (var temp in detail) { if (temp.OrderID == item.OrderID) { price = price + (Convert.ToDecimal(temp.Price) * Convert.ToDecimal(temp.Quantity)); } } if (item.CreatedDate.Year == DateTime.Now.Year && item.Status != "5") { switch (item.CreatedDate.Month) { case 1: doanhthu[0] = doanhthu[0] + price; break; case 2: doanhthu[1] = doanhthu[1] + price; break; case 3: doanhthu[2] = doanhthu[2] + price; break; case 4: doanhthu[3] = doanhthu[3] + price; break; case 5: doanhthu[4] = doanhthu[4] + price; break; case 6: doanhthu[5] = doanhthu[5] + price; break; case 7: doanhthu[6] = doanhthu[6] + price; break; case 8: doanhthu[7] = doanhthu[7] + price; break; case 9: doanhthu[8] = doanhthu[8] + price; break; case 10: doanhthu[9] = doanhthu[9] + price; break; case 11: doanhthu[10] = doanhthu[10] + price; break; default: doanhthu[11] = doanhthu[11] + price; break; } } } ViewBag.DoanhThu = doanhthu; Chart a = new Chart(); int choxacnhan = 0; foreach (var item in order) { if (item.Status == "1") { choxacnhan++; } pricenam = 0; foreach (var temp in detail) { if (temp.OrderID == item.OrderID) { pricenam = pricenam + Convert.ToDecimal(temp.Price) * Convert.ToDecimal(temp.Quantity); } } if (item.Status != "5") { switch (item.CreatedDate.Year) { case 2015: doanhthunam[0] = doanhthunam[0] + pricenam; break; case 2016: doanhthunam[1] = doanhthunam[1] + pricenam; break; case 2017: doanhthunam[2] = doanhthunam[2] + pricenam; break; case 2018: doanhthunam[3] = doanhthunam[3] + pricenam; break; case 2019: doanhthunam[4] = doanhthunam[4] + pricenam; break; } } } decimal?tong = 0; for (int i = 0; i <= 4; i++) { if (doanhthunam[i] >= tong) { tong = doanhthunam[i]; } } a.nam2015 = doanhthunam[0]; a.nam2016 = doanhthunam[1]; a.nam2017 = doanhthunam[2]; a.nam2018 = doanhthunam[3]; a.nam2019 = doanhthunam[4]; OrderChoXacNhan[0] = choxacnhan; ViewBag.ChoXacNhan = OrderChoXacNhan; ViewBag.DoanhThuNam = doanhthunam; ViewBag.TongDoanhThuNam = tong; return(View()); }
public OrderService() { OrderDao = new OrderDao(); }
// get chi tiết đơn hàng public ActionResult GetOrderDetail(long id) { var model = new OrderDao().ViewDetail(id); return(View(model)); }
public static string UpdateAndCreateOrderByOrderSplitInfo(IList <OrderSplitInfo> infoList, OrderInfo oldorderinfo) { string str = "1"; using (DbConnection connection = DatabaseFactory.CreateDatabase().CreateConnection()) { connection.Open(); DbTransaction dbTran = connection.BeginTransaction(); StringBuilder builder = new StringBuilder(); try { decimal num = 0M; foreach (OrderSplitInfo info in infoList) { OrderInfo orderInfo = new OrderInfo(); if (info.OrderIDNum != 1) { string itemList = info.ItemList; if (string.IsNullOrEmpty(itemList)) { dbTran.Rollback(); return("订单拆分失败"); } string orderid = oldorderinfo.OrderId + "-" + info.OrderIDNum.ToString(); decimal num2 = 0M; decimal num3 = 0M; string[] strArray = itemList.Split(new char[] { ',' }); foreach (string str4 in strArray) { LineItemInfo lineItemInfo = new LineItemDao().GetLineItemInfo(Globals.ToNum(str4), ""); if (lineItemInfo != null) { num2 += lineItemInfo.ItemWeight * lineItemInfo.Quantity; num += num2; num3 += lineItemInfo.ItemAdjustedPrice * lineItemInfo.Quantity; } else { dbTran.Rollback(); return("订单详情更新失败"); } } builder.Append("," + itemList.Trim(new char[] { ',' })); if (!new LineItemDao().UpdateLineItemOrderID(itemList, orderid, dbTran)) { dbTran.Rollback(); return("订单详情更新失败"); } orderInfo.OrderId = orderid; orderInfo.OrderMarking = oldorderinfo.OrderMarking; orderInfo.ClientShortType = oldorderinfo.ClientShortType; orderInfo.Remark = oldorderinfo.Remark; orderInfo.ManagerMark = oldorderinfo.ManagerMark; orderInfo.AdjustedDiscount = 0M; orderInfo.OrderStatus = oldorderinfo.OrderStatus; orderInfo.CloseReason = oldorderinfo.CloseReason; orderInfo.OrderDate = oldorderinfo.OrderDate; orderInfo.PayDate = oldorderinfo.PayDate; orderInfo.ShippingDate = oldorderinfo.ShippingDate; orderInfo.FinishDate = oldorderinfo.FinishDate; orderInfo.UserId = oldorderinfo.UserId; orderInfo.Username = oldorderinfo.Username; orderInfo.EmailAddress = oldorderinfo.EmailAddress; orderInfo.RealName = oldorderinfo.RealName; orderInfo.QQ = oldorderinfo.QQ; orderInfo.Wangwang = oldorderinfo.Wangwang; orderInfo.MSN = oldorderinfo.MSN; orderInfo.ShippingRegion = oldorderinfo.ShippingRegion; orderInfo.Address = oldorderinfo.Address; orderInfo.ZipCode = oldorderinfo.ZipCode; orderInfo.ShipTo = oldorderinfo.ShipTo; orderInfo.TelPhone = oldorderinfo.TelPhone; orderInfo.CellPhone = oldorderinfo.CellPhone; orderInfo.ShipToDate = oldorderinfo.ShipToDate; orderInfo.ShippingModeId = oldorderinfo.ShippingModeId; orderInfo.ModeName = oldorderinfo.ModeName; orderInfo.RealShippingModeId = oldorderinfo.RealShippingModeId; orderInfo.RealModeName = oldorderinfo.RealModeName; orderInfo.RegionId = oldorderinfo.RegionId; orderInfo.Freight = info.AdjustedFreight; orderInfo.AdjustedFreight = info.AdjustedFreight; orderInfo.ShipOrderNumber = oldorderinfo.ShipOrderNumber; orderInfo.Weight = num2; orderInfo.Weight = oldorderinfo.Weight; orderInfo.ExpressCompanyName = oldorderinfo.ExpressCompanyName; orderInfo.ExpressCompanyAbb = oldorderinfo.ExpressCompanyAbb; orderInfo.PaymentTypeId = oldorderinfo.PaymentTypeId; orderInfo.PaymentType = oldorderinfo.PaymentType; orderInfo.PayCharge = oldorderinfo.PayCharge; orderInfo.RefundStatus = oldorderinfo.RefundStatus; orderInfo.RefundAmount = oldorderinfo.RefundAmount; orderInfo.RefundRemark = oldorderinfo.RefundRemark; orderInfo.Gateway = oldorderinfo.Gateway; orderInfo.Points = 0; orderInfo.DiscountAmount = 0M; orderInfo.ActivitiesId = ""; orderInfo.ActivitiesName = ""; orderInfo.ReducedPromotionId = 0; orderInfo.ReducedPromotionName = ""; orderInfo.ReducedPromotionAmount = 0M; orderInfo.IsReduced = false; orderInfo.SentTimesPointPromotionId = 0; orderInfo.SentTimesPointPromotionName = ""; orderInfo.FreightFreePromotionId = 0; orderInfo.FreightFreePromotionName = ""; orderInfo.IsFreightFree = oldorderinfo.IsFreightFree; orderInfo.GatewayOrderId = oldorderinfo.GatewayOrderId; orderInfo.IsPrinted = oldorderinfo.IsPrinted; orderInfo.InvoiceTitle = oldorderinfo.InvoiceTitle; orderInfo.ReferralUserId = oldorderinfo.ReferralUserId; orderInfo.ReferralPath = oldorderinfo.ReferralPath; orderInfo.RedPagerID = null; orderInfo.RedPagerActivityName = ""; orderInfo.RedPagerOrderAmountCanUse = 0M; orderInfo.RedPagerAmount = 0M; orderInfo.PointToCash = 0M; orderInfo.PointExchange = 0; if (!new OrderDao().CreatOrder(orderInfo, dbTran)) { dbTran.Rollback(); return("生成新订单失败"); } if (!new OrderDao().UpdateOrderSplitState(orderInfo.OrderId, 2, dbTran)) { dbTran.Rollback(); return("更新订单状态失败"); } } } foreach (OrderSplitInfo info in infoList) { if (info.OrderIDNum == 1) { decimal num4 = oldorderinfo.Weight - num; if (num4 > 0M) { oldorderinfo.Weight = num4; } oldorderinfo.AdjustedFreight = info.AdjustedFreight; if (!new OrderDao().UpdateOrder(oldorderinfo, dbTran)) { dbTran.Rollback(); return("更新订单失败"); } if (!new OrderDao().UpdateOrderSplitState(oldorderinfo.OrderId, 1, dbTran)) { dbTran.Rollback(); return("更新主订单状态失败"); } if (!new OrderSplitDao().DelOrderSplitByOrderID(oldorderinfo.OrderId, dbTran)) { dbTran.Rollback(); return("删除拆分记录失败"); } } } dbTran.Commit(); foreach (OrderSplitInfo info in infoList) { OrderInfo order = new OrderDao().GetOrderInfo(info.OldOrderId + ((info.OrderIDNum == 1) ? "" : ("-" + info.OrderIDNum.ToString()))); if (order != null) { if (oldorderinfo.PayDate.HasValue) { order.PayDate = oldorderinfo.PayDate; } int num5 = 0; foreach (LineItemInfo info5 in order.LineItems.Values) { if ((info5.OrderItemsStatus.ToString() == OrderStatus.Refunded.ToString()) || (info5.OrderItemsStatus.ToString() == OrderStatus.Returned.ToString())) { num5++; } } if (order.LineItems.Values.Count == num5) { order.OrderStatus = OrderStatus.Closed; } new OrderDao().UpdateOrder(order, null); } } return(str); } catch { dbTran.Rollback(); str = "系统错误"; } finally { connection.Close(); } } return(str); }
public ActionResult Edit(long id) { var od = new OrderDao().ViewDetail(id); return(View(od)); }
public static void ClearOrder(int userID) { OrderDao.ClearOrder(userID); }
public static object ApiPay(IRequest context) { var siteId = context.GetPostInt("siteId"); var sessionId = context.GetPostString("sessionId"); var addressId = context.GetPostInt("addressId"); var channel = context.GetPostString("channel"); var totalFee = context.GetPostDecimal("totalFee"); var deliveryFee = context.GetPostDecimal("deliveryFee"); var totalCount = context.GetPostInt("totalCount"); var message = context.GetPostString("message"); var cartIdList = context.GetPostObject <List <string> >("cartIdList").Select(cartId => Utils.ParseInt(cartId)).ToList(); var isMobile = context.GetPostBool("isMobile"); var successUrl = context.GetPostString("successUrl"); if (string.IsNullOrEmpty(successUrl)) { successUrl = Context.SiteApi.GetSiteUrl(siteId); } var guid = Regex.Replace(Convert.ToBase64String(Guid.NewGuid().ToByteArray()), "[/+=]", ""); var paymentApi = new PaymentApi(siteId); var siteInfo = Context.SiteApi.GetSiteInfo(siteId); var addressInfo = AddressDao.GetAddressInfo(addressId); var orderInfo = new OrderInfo { SiteId = siteId, Guid = guid, AddDate = DateTime.Now, Address = addressInfo.Address, ZipCode = addressInfo.ZipCode, Location = addressInfo.Location, Message = message, Mobile = addressInfo.Mobile, Channel = channel, TotalFee = totalFee, ExpressCost = deliveryFee, RealName = addressInfo.RealName, UserName = context.UserName, SessionId = sessionId, IsPaied = false, State = string.Empty, Tel = addressInfo.Tel, TotalCount = totalCount }; orderInfo.Id = OrderDao.Insert(orderInfo); var cartInfoList = CartDao.GetCartInfoList(siteId, context.UserName, sessionId); var newCardIdList = new List <int>(); foreach (var newCardInfo in cartInfoList) { newCardIdList.Add(newCardInfo.Id); } //CartDao.UpdateOrderId(cartIdList, orderInfo.Id); CartDao.UpdateOrderId(newCardIdList, orderInfo.Id); var amount = totalFee + deliveryFee; var orderNo = guid; successUrl = $"{successUrl}?guid={guid}"; if (channel == "alipay") { return(isMobile ? paymentApi.ChargeByAlipayMobi(siteInfo.SiteName, amount, orderNo, successUrl) : paymentApi.ChargeByAlipayPc(siteInfo.SiteName, amount, orderNo, successUrl)); } if (channel == "weixin") { var apiUrl = Context.PluginApi.GetPluginApiUrl(Main.PluginId); var notifyUrl = $"{apiUrl}/{nameof(ApiPayWeixinNotify)}/{orderNo}"; var url = HttpUtility.UrlEncode(paymentApi.ChargeByWeixin(siteInfo.SiteName, amount, orderNo, notifyUrl)); var qrCodeUrl = $"{apiUrl}/{nameof(ApiPayQrCode)}?qrcode={url}"; return(new { qrCodeUrl, orderNo }); } if (channel == "jdpay") { return(paymentApi.ChargeByJdpay(siteInfo.SiteName, amount, orderNo, successUrl)); } return(new { guid, amount }); }
public static bool IsPassAutoToDistributor(MemberInfo cuser, bool isNeedToCheckAutoToDistributor = true) { bool flag = false; SiteSettings masterSettings = SettingsManager.GetMasterSettings(true); if (masterSettings.DistributorApplicationCondition) { decimal expenditure = cuser.Expenditure; int finishedOrderMoney = masterSettings.FinishedOrderMoney; if (finishedOrderMoney > 0) { decimal num = 0m; System.Data.DataTable userOrderPaidWaitFinish = new OrderDao().GetUserOrderPaidWaitFinish(cuser.UserId); for (int i = 0; i < userOrderPaidWaitFinish.Rows.Count; i++) { OrderInfo orderInfo = new OrderDao().GetOrderInfo(userOrderPaidWaitFinish.Rows[i]["orderid"].ToString()); if (orderInfo != null) { decimal total = orderInfo.GetTotal(); if (total > 0m) { num += total; } } } if (cuser.Expenditure + num >= finishedOrderMoney) { flag = true; } } if (!flag) { if (masterSettings.EnableDistributorApplicationCondition) { if (!string.IsNullOrEmpty(masterSettings.DistributorProductsDate) && !string.IsNullOrEmpty(masterSettings.DistributorProducts)) { if (masterSettings.DistributorProductsDate.Contains("|")) { DateTime value = default(DateTime); DateTime value2 = default(DateTime); bool flag2 = DateTime.TryParse(masterSettings.DistributorProductsDate.Split(new char[] { '|' })[0].ToString(), out value); bool flag3 = DateTime.TryParse(masterSettings.DistributorProductsDate.Split(new char[] { '|' })[1].ToString(), out value2); if (flag2 && flag3 && DateTime.Now.CompareTo(value) >= 0 && DateTime.Now.CompareTo(value2) < 0) { if (MemberProcessor.CheckMemberIsBuyProds(cuser.UserId, masterSettings.DistributorProducts, new DateTime?(value), new DateTime?(value2))) { flag = true; } } } } } } if (!flag && masterSettings.RechargeMoneyToDistributor > 0m && MemberAmountProcessor.GetUserMaxAmountDetailed(cuser.UserId) >= masterSettings.RechargeMoneyToDistributor) { flag = true; } } else { flag = true; } if (isNeedToCheckAutoToDistributor && flag) { flag = masterSettings.EnableMemberAutoToDistributor; } return(flag); }
public static bool SendGoods(OrderInfo order) { ManagerHelper.CheckPrivilege(Privilege.OrderSendGoods); bool flag = false; if (order.CheckAction(OrderActions.SELLER_SEND_GOODS)) { OrderDao dao = new OrderDao(); order.OrderStatus = OrderStatus.SellerAlreadySent; order.ShippingDate = new DateTime?(DateTime.Now); //线下支付,发货时更新付款时间 if (order.Gateway == "hishop.plugins.payment.offlinerequest") { order.PayDate = new DateTime?(DateTime.Now); } flag = dao.UpdateOrder(order, null); string str = ""; if (!flag) { return(flag); } bool flag2 = false; foreach (LineItemInfo info in order.LineItems.Values) { OrderStatus orderItemsStatus = info.OrderItemsStatus; switch (orderItemsStatus) { case OrderStatus.WaitBuyerPay: case OrderStatus.BuyerAlreadyPaid: break; default: { if (orderItemsStatus == OrderStatus.ApplyForRefund) { flag2 = true; str = str + "'" + info.SkuId + "',"; } continue; } } str = str + "'" + info.SkuId + "',"; } if (flag2) { dao.DeleteReturnRecordForSendGoods(order.OrderId); } if (!string.IsNullOrEmpty(str)) { dao.UpdateItemsStatus(order.OrderId, 3, str.Substring(0, str.Length - 1)); } //货到付款 更新库存 if (order.Gateway.ToLower() == "hishop.plugins.payment.podrequest") { dao.UpdatePayOrderStock(order.OrderId); foreach (LineItemInfo info2 in order.LineItems.Values) { str = str + info2.SkuId + ","; ProductDao dao2 = new ProductDao(); ProductInfo productDetails = dao2.GetProductDetails(info2.ProductId); productDetails.SaleCounts += info2.Quantity; productDetails.ShowSaleCounts += info2.Quantity; dao2.UpdateProduct(productDetails, null); } } MemberInfo member = MemberHelper.GetMember(order.UserId); Messenger.OrderShipping(order, member, order.wid); EventLogs.WriteOperationLog(Privilege.OrderSendGoods, string.Format(CultureInfo.InvariantCulture, "发货编号为\"{0}\"的订单", new object[] { order.OrderId })); } return(flag); }
public static bool SendGoods(OrderInfo order) { ManagerHelper.CheckPrivilege(Privilege.OrderSendGoods); bool flag = false; if (order.CheckAction(OrderActions.SELLER_SEND_GOODS)) { OrderDao orderDao = new OrderDao(); order.OrderStatus = OrderStatus.SellerAlreadySent; order.ShippingDate = new DateTime?(DateTime.Now); flag = orderDao.UpdateOrder(order, null); string text = ""; if (flag) { bool flag2 = false; foreach (LineItemInfo current in order.LineItems.Values) { OrderStatus orderItemsStatus = current.OrderItemsStatus; switch (orderItemsStatus) { case OrderStatus.WaitBuyerPay: case OrderStatus.BuyerAlreadyPaid: text = text + "'" + current.SkuId + "',"; break; default: if (orderItemsStatus == OrderStatus.ApplyForRefund) { flag2 = true; text = text + "'" + current.SkuId + "',"; } break; } } if (flag2) { orderDao.DeleteReturnRecordForSendGoods(order.OrderId); } if (!string.IsNullOrEmpty(text)) { orderDao.UpdateItemsStatus(order.OrderId, 3, text.Substring(0, text.Length - 1)); } bool flag3 = true; foreach (LineItemInfo current in order.LineItems.Values) { if (current.Type == 0) { flag3 = false; break; } } if (order.Gateway.ToLower() == "hishop.plugins.payment.podrequest" || flag3) { orderDao.UpdatePayOrderStock(order); foreach (LineItemInfo current in order.LineItems.Values) { text = text + current.SkuId + ","; ProductDao productDao = new ProductDao(); ProductInfo productDetails = productDao.GetProductDetails(current.ProductId); productDetails.SaleCounts += current.Quantity; productDetails.ShowSaleCounts += current.Quantity; productDao.UpdateProduct(productDetails, null); } } MemberInfo member = MemberHelper.GetMember(order.UserId); try { if (order != null) { Messenger.SendWeiXinMsg_OrderDeliver(order); } } catch (Exception var_10_293) { } EventLogs.WriteOperationLog(Privilege.OrderSendGoods, string.Format(CultureInfo.InvariantCulture, "发货编号为\"{0}\"的订单", new object[] { order.OrderId })); } } return(flag); }
public ActionResult Index() { var model = new OrderDao().ListAll(); return(View(model)); }
private void LoadMemberInfo() { insurance = dao.GetModel(this.currentUserId); this.dropCashBackTypes.SelectedValue = insurance.InsuranceOrderStatu; if (insurance == null) { base.GotoResourceNotFound(); } else { if (Request.Params["ctl00$ContentPlaceHolder1$dropCashBackTypes"] != null) { if (insurance.InsuranceOrderStatu != int.Parse(Request.Params["ctl00$ContentPlaceHolder1$dropCashBackTypes"])) { int tmpstatus = int.Parse(Request.Params["ctl00$ContentPlaceHolder1$dropCashBackTypes"]); insurance.InsuranceOrderStatu = tmpstatus; if (tmpstatus == 2) { int JiaoQiangXian = 0, ShangYeSanXian = 0, SiJiXian = 0, ChengKeXian = 0, SunShiXian = 0, DaoQiangXian = 0, BoliXian = 0, ZiRanXian = 0, SheShuiXian = 0, TeYueXian = 0, SanFangZenRenXian = 0, HuaHenXian = 0; if (Request.Params["JiaoQiangXian"] != null) { JiaoQiangXian = int.Parse(Request.Params["JiaoQiangXian"]); insurance.InsuranceOrderJiaoQiangXian = "1" + "|" + int.Parse(Request.Params["JiaoQiangXian"]).ToString(); } if (Request.Params["ShangYeSanXian"] != null) { ShangYeSanXian = int.Parse(Request.Params["ShangYeSanXian"]); insurance.InsuranceOrderShangYeSanXian = "1" + "|" + int.Parse(Request.Params["ShangYeSanXian"]).ToString(); } if (Request.Params["SiJiXian"] != null) { SiJiXian = int.Parse(Request.Params["SiJiXian"]); insurance.InsuranceOrderCheShangRenYuanSiJiXian = "1" + "|" + int.Parse(Request.Params["SiJiXian"]).ToString(); } if (Request.Params["ChengKeXian"] != null) { ChengKeXian = int.Parse(Request.Params["ChengKeXian"]); insurance.InsuranceOrderCheShangRenYuanChengKeXian = "1" + "|" + int.Parse(Request.Params["ChengKeXian"]).ToString(); } if (Request.Params["SunShiXian"] != null) { SunShiXian = int.Parse(Request.Params["SunShiXian"]); insurance.InsuranceOrderCheLiangSunShiXian = "1" + "|" + int.Parse(Request.Params["SunShiXian"]).ToString(); } if (Request.Params["DaoQiangXian"] != null) { DaoQiangXian = int.Parse(Request.Params["DaoQiangXian"]); insurance.InsuranceOrderDaoQiangXian = "1" + "|" + int.Parse(Request.Params["DaoQiangXian"]).ToString(); } if (Request.Params["BoliXian"] != null) { BoliXian = int.Parse(Request.Params["BoliXian"]); insurance.InsuranceOrderBoliXian = "1" + "|" + int.Parse(Request.Params["BoliXian"]).ToString(); } if (Request.Params["ZiRanXian"] != null) { ZiRanXian = int.Parse(Request.Params["ZiRanXian"]); insurance.InsuranceOrderZiRanXian = "1" + "|" + int.Parse(Request.Params["ZiRanXian"]).ToString(); } if (Request.Params["SheShuiXian"] != null) { SheShuiXian = int.Parse(Request.Params["SheShuiXian"]); insurance.InsuranceOrderSheShuiXian = "1" + "|" + int.Parse(Request.Params["SheShuiXian"]).ToString(); } if (Request.Params["TeYueXian"] != null) { TeYueXian = int.Parse(Request.Params["TeYueXian"]); insurance.InsuranceOrderTeYueXian = "1" + "|" + int.Parse(Request.Params["TeYueXian"]).ToString(); } if (Request.Params["SanFangZenRenXian"] != null) { SanFangZenRenXian = int.Parse(Request.Params["SanFangZenRenXian"]); insurance.InsuranceOrderSanFangZenRenXian = "1" + "|" + int.Parse(Request.Params["SanFangZenRenXian"]).ToString(); } if (Request.Params["HuaHenXian"] != null) { HuaHenXian = int.Parse(Request.Params["HuaHenXian"]); insurance.InsuranceOrderHuaHenXian = "1" + "|" + int.Parse(Request.Params["HuaHenXian"]).ToString(); } insurance.InsuranceOrderAmount = JiaoQiangXian + ShangYeSanXian + SiJiXian + ChengKeXian + SunShiXian + DaoQiangXian + BoliXian + ZiRanXian + SheShuiXian + TeYueXian + SanFangZenRenXian + HuaHenXian; //新增一个订单表 OrderTmpInfo order = new OrderTmpInfo(); order.OrderId = this.GenerateOrderId(); order.OrderMarking = this.GenerateOrderId(); order.OrderDate = DateTime.Now; order.UserId = 0; order.Username = ""; order.OrderStatus = 1; order.PointToCash = 0; order.PointExchange = 0; order.SplitState = 0; order.DeleteBeforeState = 0; order.ClientShortType = 1; order.BargainDetialId = 0; order.BalancePayMoneyTotal = 0; order.BalancePayFreightMoneyTotal = 0; order.CouponFreightMoneyTotal = 0; order.UpdateDate = DateTime.Now; order.LogisticsTools = 1; order.Amount = order.OrderTotal = insurance.InsuranceOrderAmount; order.Gateway = "hishop.plugins.payment.weixinrequest"; order.CouponCode = insurance.InsuranceOrderId.ToString(); order.PaymentTypeId = 88; bool num17 = new OrderDao().Add(order); } if (dao.Update(insurance)) { string content = Request.Params["msgcontent"]; string ordernum = insurance.InsuranceOrderCreatDate.Value.ToString("yyyyMMddHHmmss") + insurance.InsuranceOrderId; string orderstatus = ((Hidistro.Entities.Insurance.InsuranceOrderTypes)insurance.InsuranceOrderStatu.Value).ToString(); Messenger.SendWeiXinMsg_InsuranceOrder(insurance.InsuranceOrderOpenId, ordernum, orderstatus, content); ifsuc = "1"; } else { ifsuc = "2"; } } } } }
public ActionResult Edit(int id) { var order = new OrderDao().ViewDetail(id); return(View(order)); }
public static void AddCountDownBoughtCount(OrderInfo order) { OrderDao orderDao = new OrderDao(); orderDao.AddCountDownBoughtCount(order); }
//Pay=paypal public ActionResult PaymentWithPaypal(string Cancel = null) { UserLogin user = (UserLogin)Session[Common.CommonConstants.USER_SESSION]; var cart = (List <CartItem>)Session[Common.CommonConstants.CART_SESSION]; var itemList = new List <CartItem>(); if (cart != null) { itemList = (List <CartItem>)cart; } var coupon = (List <Coupon>)Session[Common.CommonConstants.COUPON_SESSION]; var couponList = new List <Coupon>(); if (cart != null) { couponList = (List <Coupon>)coupon; } var productDao = new ProductDao(); //check quantity+status của product foreach (var item in cart) { if (productDao.CheckProduct(item.Product.ID, item.Quantity) == false) { var alertMessage = "Số lượng sản phẩm [" + item.Product.Name + "] đã hết. Xin vui lòng chọn sản phẩm khác."; SetAlert(alertMessage, "error"); return(Redirect("/het-san-pham")); } } //getting the apiContext APIContext apiContext = helper.PaypalConfiguration.GetAPIContext(); try { //A resource representing a Payer that funds a payment Payment Method as paypal //Payer Id will be returned when payment proceeds or click to pay string payerId = Request.Params["PayerID"]; if (string.IsNullOrEmpty(payerId)) { //this section will be executed first because PayerID doesn't exist //it is returned by the create function call of the payment class // Creating a payment // baseURL is the url on which paypal sendsback the data. // So we have provided URL of this controller only string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Cart/PaymentWithPaypal?"; //here we are generating guid for storing the paymentID received in session //which will be used in the payment execution. //guid we are generating for storing the paymentID received in session //after calling the create function and it is used in the payment execution var guid = Convert.ToString((new Random()).Next(100000)); //CreatePayment function gives us the payment approval url //on which payer is redirected for paypal account payment var createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid); //get links returned from paypal in response to Create function call var links = createdPayment.links.GetEnumerator(); string paypalRedirectUrl = null; while (links.MoveNext()) { Links lnk = links.Current; if (lnk.rel.ToLower().Trim().Equals("approval_url")) { //saving the payapalredirect URL to which user will be redirected for payment paypalRedirectUrl = lnk.href; } } // saving the paymentID in the key guid Session.Add(guid, createdPayment.id); return(Redirect(paypalRedirectUrl)); } else { // This section is executed when we have received all the payments parameters // from the previous call to the function Create // Executing a payment var guid = Request.Params["guid"]; var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string); //If executed payment failed then we will show payment failure message to user if (executedPayment.state.ToLower() != "approved") { Session.Remove(guid); return(View("FailureView")); } //Tới đây coi như thành công //ghi order vào databasse var orderDetailDao = new Model.Dao.OrderDetailDao(); var orderCounponDao = new Model.Dao.OrderCouponDao(); var order = new Model.EF.Order(); order.CreatedDate = DateTime.Parse(executedPayment.create_time); if (user != null) { order.CustomerID = user.UserID; } order.ShipName = executedPayment.payer.payer_info.shipping_address.recipient_name; order.ShipMobile = executedPayment.payer.payer_info.shipping_address.phone; order.ShipAddress = executedPayment.payer.payer_info.shipping_address.line1 + ", " + executedPayment.payer.payer_info.shipping_address.city + ", " + executedPayment.payer.payer_info.shipping_address.state + ", " + executedPayment.payer.payer_info.shipping_address.country_code + "."; order.ShipEmail = executedPayment.payer.payer_info.email; order.Status = -1; //đang chờ shipper nhận var orderID = new OrderDao().Insert(order); decimal sumProduct = 0; foreach (var item in itemList) { //Xử lý orderDetail var orderDetail = new OrderDetail(); orderDetail.ProductID = item.Product.ID; orderDetail.OrderID = orderID; decimal?tempPrice = item.Product.PromotionPrice != null ? item.Product.PromotionPrice : item.Product.Price; orderDetail.Price = tempPrice; orderDetail.Quantity = item.Quantity; orderDetailDao.Insert(orderDetail); //Xử lý sản phẩm // cập nhật số lượng sản phẩm productDao.UpdateQuantity(item.Product.ID, item.Quantity); // sumProduct += orderDetail.Price.GetValueOrDefault(0) * orderDetail.Quantity.GetValueOrDefault(0); } //xử lý coupon + CouponUser var couponDao = new CouponDao(); var couponUserDao = new CouponUserDao(); if (couponList != null) { foreach (var item in couponList) { //xử lý coupon // giảm quantity của coupon đi 1 couponDao.UseCouponDiscountCode(item.Code); //Xử lý CouponUser var couponUser = new CouponUser(); couponUser.CouponID = item.ID; couponUser.UserID = user.UserID; couponUserDao.Insert(couponUser); //Xử lý orderCoupon var orderCoupon = new OrderCoupon(); orderCoupon.OrderID = orderID; orderCoupon.CouponID = item.ID; decimal tempAmount = 0; if (item.ByPercentage == true) { tempAmount = sumProduct * item.DiscountBy / 100; //discount theo % } else { tempAmount = item.DiscountBy; //discount cố định } orderCoupon.DiscountAmount = tempAmount; orderCounponDao.Insert(orderCoupon); } } //gán cart+coupon null Session[Common.CommonConstants.CART_SESSION] = null; Session[Common.CommonConstants.COUPON_SESSION] = null; } } catch (Exception ex) { Logger.Log("Error" + ex.Message); return(View("FailureView")); } //on successful payment, show success page to user. return(View("SuccessView")); }
public ActionResult SendOrder(string shipName, string mobile, string address, string email) { try { UserLogin user = (UserLogin)Session[Common.CommonConstants.USER_SESSION]; var cart = (List <CartItem>)Session[Common.CommonConstants.CART_SESSION]; var itemList = new List <CartItem>(); if (cart != null) { itemList = (List <CartItem>)cart; } var coupon = (List <Coupon>)Session[Common.CommonConstants.COUPON_SESSION]; var couponList = new List <Coupon>(); if (coupon != null) { couponList = (List <Coupon>)coupon; } var productDao = new ProductDao(); decimal originPrice = 0; foreach (var item in itemList) { //check quantity+status của product if (productDao.CheckProduct(item.Product.ID, item.Quantity) == false) { var alertMessage = "Số lượng sản phẩm [" + item.Product.Name + "] đã hết. Xin vui lòng chọn sản phẩm khác."; SetAlert(alertMessage, "error"); return(Redirect("/het-san-pham")); } if (item.Product.PromotionPrice != null) { originPrice += (item.Product.PromotionPrice.GetValueOrDefault(0) * item.Quantity); } else { originPrice += (item.Product.Price.GetValueOrDefault(0) * item.Quantity); } } decimal newPrice = originPrice; foreach (var item in couponList) { if (item.ByPercentage == true) { newPrice = (newPrice * (1 - item.DiscountBy / 100)); } else { newPrice = newPrice - item.DiscountBy; } } if (newPrice < 0) { newPrice = 0; } //Gửi Email //đọc file neworder.html //email mẫu string content = System.IO.File.ReadAllText(Server.MapPath("/assets/client/template/neworder.html")); //replace các key {{}} content = content.Replace("{{CustomerName}}", shipName); //tùy chọn: cần 2 phone+email hoặc ít nhất 1 int infoCount = (mobile != "" ? 1 : 0) + (email != "" ? 1 : 0); if (infoCount > 0) { content = content.Replace("{{Phone}}", mobile != "" ? mobile : "trống"); content = content.Replace("{{Email}}", email != "" ? email : "trống"); } else { return(Redirect("/loi-dat-hang")); } content = content.Replace("{{Address}}", address); decimal ship = 100000; // ship 100k content = content.Replace("{{Ship}}", ship.ToString("N0") + "đ"); if (newPrice == originPrice) //ko có coupon, ko có newPrice { content = content.Replace("{{OriginPrice}}", "Giá: " + originPrice.ToString("N0") + "đ"); content = content.Replace("{{NewPrice}}", ""); } else { content = content.Replace("{{OriginPrice}}", "Giá gốc: " + originPrice.ToString("N0") + "đ"); content = content.Replace("{{NewPrice}}", "Giá mới: " + newPrice.ToString("N0") + "đ"); } content = content.Replace("{{Total}}", (newPrice + ship).ToString("N0") + "đ"); //đọc tham số từ key trong Web.config của project OnlineShop var toEmail = ConfigurationManager.AppSettings["ToEmailAddress"].ToString(); //gửi đi 2 nơi new MailHelper().SendMail(toEmail, "Đơn hàng mới từ OnlineShop đến người cung cấp sản phẩm", content); new MailHelper().SendMail(email, "Đơn hàng mới từ OnlineShop đến người đặt đơn hàng", content); //Gửi thành công // bắt đầu xử lý database //ghi order vào databasse var orderDao = new OrderDao(); var order = new Model.EF.Order(); order.CreatedDate = DateTime.Now; if (user != null) { order.CustomerID = user.UserID; } order.ShipName = shipName; order.ShipMobile = mobile; order.ShipAddress = address; order.ShipEmail = email; order.Status = -1; //đang chờ shipper nhận var orderId = orderDao.Insert(order); //xử lý OrderDetail + Product var detailDao = new OrderDetailDao(); foreach (var item in itemList) { //Xử lý OrderDetail var orderDetail = new OrderDetail(); orderDetail.ProductID = item.Product.ID; orderDetail.OrderID = orderId; orderDetail.Price = item.Product.Price; orderDetail.Quantity = item.Quantity; detailDao.Insert(orderDetail); //Xử lý sản phẩm // cập nhật số lượng sản phẩm productDao.UpdateQuantity(item.Product.ID, item.Quantity); } //xử lý coupon + CouponUser var couponDao = new CouponDao(); var couponUserDao = new CouponUserDao(); foreach (var item in couponList) { //xử lý coupon couponDao.UseCouponDiscountCode(item.Code); //Xử lý CouponUser var couponUser = new CouponUser(); couponUser.CouponID = item.ID; couponUser.UserID = user.UserID; couponUserDao.Insert(couponUser); } //gán cart+coupon null Session[Common.CommonConstants.CART_SESSION] = null; Session[Common.CommonConstants.COUPON_SESSION] = null; } catch (Exception ex) { //ghi log Logger.Log("Error" + ex.Message); return(Redirect("/loi-dat-hang")); } return(Redirect("/hoan-thanh")); }
public ActionResult Payment(string shipName, string mobile, string address, string email) { var order = new Order(); order.CreatedDate = DateTime.Now; order.ShipAddress = address; order.ShipMobile = mobile; order.ShipName = shipName; order.ShipEmail = email; try { var id = new OrderDao().Insert(order); var cart = (List<CartItem>)Session[CartSession]; var detailDao = new OrderDetailDao(); decimal total = 0; foreach (var item in cart) { var orderDetail = new OrderDetail(); orderDetail.ProductID = item.Product.ID; orderDetail.OrderID = id; orderDetail.Price = item.Product.Price; orderDetail.Quantity = item.Quantity; detailDao.Insert(orderDetail); total += (item.Product.Price.GetValueOrDefault(0) * item.Quantity); } string content = System.IO.File.ReadAllText(Server.MapPath("~/Assets/client/template/newOrder.html")); content = content.Replace("{{CustomerName}}",shipName); content = content.Replace("{{Phone}}", mobile); content = content.Replace("{{Email}}", email); content = content.Replace("{{Address}}", address); content = content.Replace("{{Total}}", total.ToString("N0")); new MailHelper().SendEmail(email, "Đơn hàng mới từ OnlineShop",content); } catch (Exception ex) { //ghi log return Redirect("/loi-thanh-toan"); } return Redirect("/hoan-thanh"); }