public bool Insert(OrderCoupon entity) { try { db.OrderCoupons.Add(entity); db.SaveChanges(); return(true); } catch { return(false); } }
public void FromDTO(OrderDTO dto) { if (dto == null) return; this.AffiliateID = dto.AffiliateID ?? string.Empty; this.BillingAddress.FromDto(dto.BillingAddress); this.bvin = dto.Bvin ?? string.Empty; this.Coupons.Clear(); if (dto.Coupons != null) { foreach (OrderCouponDTO c in dto.Coupons) { OrderCoupon cp = new OrderCoupon(); cp.FromDto(c); this.Coupons.Add(cp); } } this.CustomProperties.Clear(); if (dto.CustomProperties != null) { foreach (CustomPropertyDTO prop in dto.CustomProperties) { CustomProperty p = new CustomProperty(); p.FromDto(prop); this.CustomProperties.Add(p); } } this.FraudScore = dto.FraudScore; this.Id = dto.Id; this.Instructions = dto.Instructions ?? string.Empty; this.IsPlaced = dto.IsPlaced; this.Items.Clear(); if (dto.Items != null) { foreach (LineItemDTO li in dto.Items) { LineItem l = new LineItem(); l.FromDto(li); this.Items.Add(l); } } this.LastUpdatedUtc = dto.LastUpdatedUtc; this.Notes.Clear(); if (dto.Notes != null) { foreach (OrderNoteDTO n in dto.Notes) { OrderNote nn = new OrderNote(); nn.FromDto(n); this.Notes.Add(nn); } } this.OrderDiscountDetails.Clear(); if (dto.OrderDiscountDetails != null) { foreach (DiscountDetailDTO d in dto.OrderDiscountDetails) { Marketing.DiscountDetail m = new Marketing.DiscountDetail(); m.FromDto(d); this.OrderDiscountDetails.Add(m); } } this.OrderNumber = dto.OrderNumber ?? string.Empty; this.Packages.Clear(); if (dto.Packages != null) { foreach (OrderPackageDTO pak in dto.Packages) { OrderPackage pak2 = new OrderPackage(); pak2.FromDto(pak); this.Packages.Add(pak2); } } this.PaymentStatus = (OrderPaymentStatus)((int)dto.PaymentStatus); this.ShippingAddress.FromDto(dto.ShippingAddress); this.ShippingDiscountDetails.Clear(); if (dto.ShippingDiscountDetails != null) { foreach (DiscountDetailDTO sd in dto.ShippingDiscountDetails) { Marketing.DiscountDetail sdd = new Marketing.DiscountDetail(); sdd.FromDto(sd); this.ShippingDiscountDetails.Add(sdd); } } this.ShippingMethodDisplayName = dto.ShippingMethodDisplayName ?? string.Empty; this.ShippingMethodId = dto.ShippingMethodId ?? string.Empty; this.ShippingProviderId = dto.ShippingProviderId ?? string.Empty; this.ShippingProviderServiceCode = dto.ShippingProviderServiceCode ?? string.Empty; this.ShippingStatus = (OrderShippingStatus)((int)dto.ShippingStatus); this.StatusCode = dto.StatusCode ?? string.Empty; this.StatusName = dto.StatusName ?? string.Empty; this.StoreId = dto.StoreId; this.ThirdPartyOrderId = dto.ThirdPartyOrderId ?? string.Empty; this.TimeOfOrderUtc = dto.TimeOfOrderUtc; this.TotalHandling = dto.TotalHandling; this.TotalShippingBeforeDiscounts = dto.TotalShippingBeforeDiscounts; this.TotalTax = dto.TotalTax; this.TotalTax2 = dto.TotalTax2; this.UserEmail = dto.UserEmail ?? string.Empty; this.UserID = dto.UserID ?? string.Empty; }
/// <summary> /// Create a "PendingOffsite" Order by copying the CheckoutOrderInfo into an actual Order in the database. /// </summary> /// <param name="checkoutOrderInfo"></param> /// <returns></returns> public Order CreateOrder(CheckoutOrderInfo checkoutOrderInfo, OrderStatusName orderStatus) { using (esTransactionScope transaction = new esTransactionScope()) { Order pendingOrder = new Order(); if (checkoutOrderInfo.PaymentProvider != PaymentProviderName.CardCaptureOnly) { //--- check if we have an existing pending order for this Cart.... Order existingOrderByCartId = Order.GetOrderByCartId(checkoutOrderInfo.Cart.Id.Value); if (existingOrderByCartId != null) { //existingOrderByCartId.MarkAsDeleted(); existingOrderByCartId.OrderStatus = OrderStatusName.Failed; existingOrderByCartId.Save(); } } //pendingOrder.OrderStatus = OrderStatusName.PendingOffsite; pendingOrder.OrderStatus = orderStatus; pendingOrder.PaymentStatus = PaymentStatusName.Pending; //---- copy the Checkout Order Info into our Order database object pendingOrder.StoreId = storeContext.CurrentStore.Id.Value; pendingOrder.UserId = storeContext.UserId; pendingOrder.CreatedFromCartId = checkoutOrderInfo.Cart.Id; pendingOrder.CreatedByIP = HttpContext.Current.Request.UserHostAddress; pendingOrder.OrderNumber = ""; // we'll update it later pendingOrder.CustomerFirstName = checkoutOrderInfo.BillingAddress.FirstName; pendingOrder.CustomerLastName = checkoutOrderInfo.BillingAddress.LastName; pendingOrder.CustomerEmail = checkoutOrderInfo.BillingAddress.Email; pendingOrder.BillAddress1 = checkoutOrderInfo.BillingAddress.Address1; pendingOrder.BillAddress2 = !string.IsNullOrEmpty(checkoutOrderInfo.BillingAddress.Address2) ? checkoutOrderInfo.BillingAddress.Address2 : String.Empty; pendingOrder.BillCity = checkoutOrderInfo.BillingAddress.City; pendingOrder.BillRegion = checkoutOrderInfo.BillingAddress.Region; pendingOrder.BillPostalCode = checkoutOrderInfo.BillingAddress.PostalCode; pendingOrder.BillCountryCode = checkoutOrderInfo.BillingAddress.Country; pendingOrder.BillTelephone = checkoutOrderInfo.BillingAddress.Telephone; pendingOrder.ShipRecipientName = string.Format("{0} {1}", checkoutOrderInfo.ShippingAddress.FirstName, checkoutOrderInfo.ShippingAddress.LastName); pendingOrder.ShipRecipientBusinessName = checkoutOrderInfo.ShippingAddress.BusinessName ?? ""; pendingOrder.ShipAddress1 = checkoutOrderInfo.ShippingAddress.Address1; pendingOrder.ShipAddress2 = checkoutOrderInfo.ShippingAddress.Address2; pendingOrder.ShipCity = checkoutOrderInfo.ShippingAddress.City; pendingOrder.ShipRegion = checkoutOrderInfo.ShippingAddress.Region; pendingOrder.ShipPostalCode = checkoutOrderInfo.ShippingAddress.PostalCode; pendingOrder.ShipCountryCode = checkoutOrderInfo.ShippingAddress.Country; pendingOrder.ShipTelephone = checkoutOrderInfo.ShippingAddress.Telephone; //--- Shipping Provider Stuff pendingOrder.ShippingServiceProvider = checkoutOrderInfo.ShippingProvider.ToString(); pendingOrder.ShippingServiceOption = checkoutOrderInfo.ShippingRate.ServiceTypeDescription ?? ""; pendingOrder.ShippingServiceType = checkoutOrderInfo.ShippingRate.ServiceType ?? ""; pendingOrder.ShippingServicePrice = checkoutOrderInfo.ShippingRate.Rate; //--- Order Notes pendingOrder.OrderNotes = checkoutOrderInfo.OrderNotes ?? ""; //---- Cart Items List <vCartItemProductInfo> cartItems = checkoutOrderInfo.Cart.GetCartItemsWithProductInfo(); foreach (vCartItemProductInfo cartItem in cartItems) { Product product = cartItem.GetProduct(); OrderItem newItem = pendingOrder.OrderItemCollectionByOrderId.AddNew(); newItem.ProductId = product.Id; newItem.Name = product.Name; newItem.Sku = product.Sku; if (product.DeliveryMethodId == 2) { newItem.DigitalFilename = product.DigitalFilename; newItem.DigitalFileDisplayName = product.DigitalFileDisplayName; } newItem.ProductFieldData = cartItem.ProductFieldData; newItem.Quantity = cartItem.Quantity; newItem.WeightTotal = cartItem.GetWeightForQuantity(); newItem.PriceTotal = cartItem.GetPriceForQuantity(); } pendingOrder.SubTotal = checkoutOrderInfo.SubTotal; pendingOrder.ShippingAmount = checkoutOrderInfo.ShippingRate.Rate; pendingOrder.DiscountAmount = checkoutOrderInfo.DiscountAmount; pendingOrder.TaxAmount = checkoutOrderInfo.TaxAmount; pendingOrder.Total = checkoutOrderInfo.Total; //--- Coupons foreach (CheckoutCouponInfo checkoutCoupon in checkoutOrderInfo.GetAppliedCoupons()) { OrderCoupon orderCoupon = pendingOrder.OrderCouponCollectionByOrderId.AddNew(); orderCoupon.CouponCode = checkoutCoupon.CouponCode; orderCoupon.DiscountAmount = checkoutCoupon.DiscountAmount; } //--- Save limited Credit Card info to order pendingOrder.CreditCardType = checkoutOrderInfo.CreditCard.CardType.ToString(); // the full card number is not saved here for security pendingOrder.CreditCardNumberLast4 = checkoutOrderInfo.CreditCard.CardNumber.Right(4); pendingOrder.CreditCardExpiration = string.Format("{0} / {1}", checkoutOrderInfo.CreditCard.ExpireMonth2Digits, checkoutOrderInfo.CreditCard.ExpireYear); // Credit Card CVV not saved here for security pendingOrder.CreditCardNameOnCard = checkoutOrderInfo.CreditCard.NameOnCard; pendingOrder.Save(); // update the order number pendingOrder.OrderNumber = storeContext.CurrentStore.GetSetting(StoreSettingNames.OrderNumberPrefix) + pendingOrder.Id; pendingOrder.Save(); transaction.Complete(); int orderId = pendingOrder.Id.Value; pendingOrder.LoadByPrimaryKey(orderId); return(pendingOrder); } }
//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")); }