/// <summary> /// Gets a value indicating whether customers can complete a payment after order is placed but not completed (for redirection payment methods) /// </summary> /// <param name="order">Order</param> /// <returns>Result</returns> public virtual bool CanRePostProcessPayment(Order order) { if (order == null) throw new ArgumentNullException("order"); if (!_paymentSettings.AllowRePostingPayments) return false; var paymentMethod = LoadPaymentMethodBySystemName(order.PaymentMethodSystemName); if (paymentMethod == null) return false; //Payment method couldn't be loaded (for example, was uninstalled) if (paymentMethod.PaymentMethodType != PaymentMethodType.Redirection) return false; //this option is available only for redirection payment methods if (order.Deleted) return false; //do not allow for deleted orders if (order.OrderStatus == OrderStatus.Cancelled) return false; //do not allow for cancelled orders if (order.PaymentStatus != PaymentStatus.Pending) return false; //payment status should be Pending return paymentMethod.CanRePostProcessPayment(order); }
//Reques A Credit Order Study public virtual IActionResult RequestCredit(int orderId) { var or = new Nop.Core.Domain.Orders.Order(); or.BillingAddress = _workContext.CurrentCustomer.BillingAddress; or.Customer = _workContext.CurrentCustomer; foreach (var item in Items) { var prod = _productService.GetProductById(item.ProductId); or.OrderItems.Add(new OrderItem() { ProductId = item.ProductId, Product = prod, UnitPriceInclTax = decimal.Parse(item.UnitPrice), Quantity = item.Quantity, AttributeDescription = item.ProductName }); } _orderService.InsertOrder(or); foreach (var it in _workContext.CurrentCustomer.ShoppingCartItems) { _shoppingCartService.DeleteShoppingCartItem(it.Id); } return(RedirectToRoute("Home")); }
/// <summary> /// Add reward points history record /// </summary> /// <param name="customer">Customer</param> /// <param name="points">Number of points to add</param> /// <param name="storeId">Store identifier</param> /// <param name="message">Message</param> /// <param name="usedWithOrder">the order for which points were redeemed as a payment</param> /// <param name="usedAmount">Used amount</param> public virtual void AddRewardPointsHistoryEntry(Customer customer, int points, int storeId, string message = "", Order usedWithOrder = null, decimal usedAmount = 0M) { if (customer == null) throw new ArgumentNullException("customer"); if (storeId <= 0) throw new ArgumentException("Store ID should be valid"); var rph = new RewardPointsHistory { Customer = customer, StoreId = storeId, UsedWithOrder = usedWithOrder, Points = points, PointsBalance = GetRewardPointsBalance(customer.Id, storeId) + points, UsedAmount = usedAmount, Message = message, CreatedOnUtc = DateTime.UtcNow }; _rphRepository.Insert(rph); //event notification _eventPublisher.EntityInserted(rph); }
/// <summary> /// Deletes an order /// </summary> /// <param name="order">The order</param> public virtual void DeleteOrder(Order order) { if (order == null) throw new ArgumentNullException("order"); order.Deleted = true; UpdateOrder(order); }
public bool CanRePostProcessPayment(Order order) { if (order == null) { throw new ArgumentNullException("order"); } return false; }
public void setCustomValue(string key, object value, Nop.Core.Domain.Orders.Order order) { Dictionary <string, object> customValues = PaymentExtensions.DeserializeCustomValues(order); customValues[key] = value; ProcessPaymentRequest request = new ProcessPaymentRequest(); request.CustomValues = customValues; order.CustomValuesXml = request.SerializeCustomValues(); }
public bool CanRePostProcessPayment(Order order) { if (order == null) throw new ArgumentNullException("order"); //удостоверимся, что прошло не меньше минуты после перехода к оплате if ((DateTime.UtcNow - order.CreatedOnUtc).TotalMinutes < 1) return false; return true; }
protected virtual bool HasAccessToOrder(Nop.Core.Domain.Orders.Order order) { if (order == null) throw new ArgumentNullException("order"); if (_workContext.CurrentVendor == null) //not a vendor; has access return true; var vendorId = _workContext.CurrentVendor.Id; var hasVendorProducts = order.OrderItems.Any(orderItem => orderItem.Product.VendorId == vendorId); return hasVendorProducts; }
public override void AddOrderTokens(IList <Token> tokens, Nop.Core.Domain.Orders.Order order, int languageId, int vendorId = 0) { var miscPlugins = _pluginFinder.GetPlugins <MyOrderServicePlugin>(storeId: order.StoreId).ToList(); if (miscPlugins.Count > 0) { //string orderID = BuildOrderID(order, languageId); NopResourceDisplayNameAttribute orderNumberKeyGBS = new NopResourceDisplayNameAttribute("Account.CustomerOrders.OrderNumber"); tokens.Add(new Token("Order.GBSOrderID", order.DeserializeCustomValues()[orderNumberKeyGBS.DisplayName].ToString(), true)); base.AddOrderTokens(tokens, order, languageId); } }
public void Can_save_and_load_customer_with_affiliate() { var order = new Order { OrderGuid = Guid.NewGuid(), Customer = GetTestCustomer(), Affiliate = GetTestAffiliate(), BillingAddress = GetTestBillingAddress(), CreatedOnUtc = new DateTime(2010, 01, 01) }; var fromDb = SaveAndLoadEntity(order); fromDb.ShouldNotBeNull(); fromDb.Affiliate.ShouldNotBeNull(); fromDb.Affiliate.Active.ShouldEqual(true); }
public static void AddRewardPointsHistoryEntry(this Customer customer, int points, string message = "", Order usedWithOrder = null, decimal usedAmount = 0M) { int newPointsBalance = customer.GetRewardPointsBalance() + points; var rewardPointsHistory = new RewardPointsHistory() { Customer = customer, UsedWithOrder = usedWithOrder, Points = points, PointsBalance = newPointsBalance, UsedAmount = usedAmount, Message = message, CreatedOnUtc = DateTime.UtcNow }; customer.RewardPointsHistory.Add(rewardPointsHistory); }
public static VendorReviewModel ToModel(this VendorReview Review, Order Order, Product Product) { var model = new VendorReviewModel() { CreatedOnUTC = Review.CreatedOnUTC, CustomerId = Review.CustomerId, HelpfulnessNoTotal = Review.HelpfulnessNoTotal, HelpfulnessYesTotal = Review.HelpfulnessYesTotal, Id = Review.Id, IsApproved = Review.IsApproved, ProductId = Review.ProductId, Rating = Review.Rating, ReviewText = Review.ReviewText, Title = Review.Title, VendorId = Review.VendorId, OrderId = Review.OrderId, ProductName = Product.Name, CertifiedBuyerReview = Review.CertifiedBuyerReview, DisplayCertifiedBadge = Review.DisplayCertifiedBadge }; return model; }
/// <summary> /// Gets a value indicating whether order can be marked as voided /// </summary> /// <param name="order">Order</param> /// <returns>A value indicating whether order can be marked as voided</returns> public virtual bool CanVoidOffline(Order order) { if (order == null) throw new ArgumentNullException("order"); if (order.OrderTotal == decimal.Zero) return false; //uncomment the lines below in order to allow this operation for cancelled orders //if (order.OrderStatus == OrderStatus.Cancelled) // return false; if (order.PaymentStatus == PaymentStatus.Authorized) return true; return false; }
/// <summary> /// Gets a value indicating whether refund from admin panel is allowed /// </summary> /// <param name="order">Order</param> /// <returns>A value indicating whether refund from admin panel is allowed</returns> public virtual bool CanRefund(Order order) { if (order == null) throw new ArgumentNullException("order"); if (order.OrderTotal == decimal.Zero) return false; //uncomment the lines below in order to allow this operation for cancelled orders //if (order.OrderStatus == OrderStatus.Cancelled) // return false; if (order.PaymentStatus == PaymentStatus.Paid && _paymentService.SupportRefund(order.PaymentMethodSystemName)) return true; return false; }
/// <summary> /// Gets a value indicating whether order can be marked as partially refunded /// </summary> /// <param name="order">Order</param> /// <param name="amountToRefund">Amount to refund</param> /// <returns>A value indicating whether order can be marked as partially refunded</returns> public virtual bool CanPartiallyRefundOffline(Order order, decimal amountToRefund) { if (order == null) throw new ArgumentNullException("order"); if (order.OrderTotal == decimal.Zero) return false; //uncomment the lines below in order to allow this operation for cancelled orders //if (order.OrderStatus == OrderStatus.Cancelled) // return false; decimal canBeRefunded = order.OrderTotal - order.RefundedAmount; if (canBeRefunded <= decimal.Zero) return false; if (amountToRefund > canBeRefunded) return false; if (order.PaymentStatus == PaymentStatus.Paid || order.PaymentStatus == PaymentStatus.PartiallyRefunded) return true; return false; }
/// <summary> /// Gets a value indicating whether order can be marked as paid /// </summary> /// <param name="order">Order</param> /// <returns>A value indicating whether order can be marked as paid</returns> public virtual bool CanMarkOrderAsPaid(Order order) { if (order == null) throw new ArgumentNullException("order"); if (order.OrderStatus == OrderStatus.Cancelled) return false; if (order.PaymentStatus == PaymentStatus.Paid || order.PaymentStatus == PaymentStatus.Refunded || order.PaymentStatus == PaymentStatus.Voided) return false; return true; }
/// <summary> /// Gets a value indicating whether order can be marked as authorized /// </summary> /// <param name="order">Order</param> /// <returns>A value indicating whether order can be marked as authorized</returns> public virtual bool CanMarkOrderAsAuthorized(Order order) { if (order == null) throw new ArgumentNullException("order"); if (order.OrderStatus == OrderStatus.Cancelled) return false; if (order.PaymentStatus == PaymentStatus.Pending) return true; return false; }
protected virtual void PrepareOrderDetailsModel(OrderModel model, Nop.Core.Domain.Orders.Order order) { if (order == null) throw new ArgumentNullException("order"); if (model == null) throw new ArgumentNullException("model"); model.Id = order.Id; model.OrderStatus = order.OrderStatus.GetLocalizedEnum(_localizationService, _workContext); model.OrderStatusId = order.OrderStatusId; model.OrderGuid = order.OrderGuid; model.CustomOrderNumber = order.CustomOrderNumber; var store = _storeService.GetStoreById(order.StoreId); model.StoreName = store != null ? store.Name : "Unknown"; model.CustomerId = order.CustomerId; var customer = order.Customer; model.CustomerInfo = customer.IsRegistered() ? customer.Email : _localizationService.GetResource("Admin.Customers.Guest"); model.CustomerIp = order.CustomerIp; model.VatNumber = order.VatNumber; model.CreatedOn = _dateTimeHelper.ConvertToUserTime(order.CreatedOnUtc, DateTimeKind.Utc); model.AllowCustomersToSelectTaxDisplayType = _taxSettings.AllowCustomersToSelectTaxDisplayType; model.TaxDisplayType = _taxSettings.TaxDisplayType; var affiliate = _affiliateService.GetAffiliateById(order.AffiliateId); if (affiliate != null) { model.AffiliateId = affiliate.Id; model.AffiliateName = affiliate.GetFullName(); } //a vendor should have access only to his products model.IsLoggedInAsVendor = _workContext.CurrentVendor != null; //custom values model.CustomValues = order.DeserializeCustomValues(); #region Order totals var primaryStoreCurrency = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId); if (primaryStoreCurrency == null) throw new Exception("Cannot load primary store currency"); //subtotal model.OrderSubtotalInclTax = _priceFormatter.FormatPrice(order.OrderSubtotalInclTax, true, primaryStoreCurrency, _workContext.WorkingLanguage, true); model.OrderSubtotalExclTax = _priceFormatter.FormatPrice(order.OrderSubtotalExclTax, true, primaryStoreCurrency, _workContext.WorkingLanguage, false); model.OrderSubtotalInclTaxValue = order.OrderSubtotalInclTax; model.OrderSubtotalExclTaxValue = order.OrderSubtotalExclTax; //discount (applied to order subtotal) string orderSubtotalDiscountInclTaxStr = _priceFormatter.FormatPrice(order.OrderSubTotalDiscountInclTax, true, primaryStoreCurrency, _workContext.WorkingLanguage, true); string orderSubtotalDiscountExclTaxStr = _priceFormatter.FormatPrice(order.OrderSubTotalDiscountExclTax, true, primaryStoreCurrency, _workContext.WorkingLanguage, false); if (order.OrderSubTotalDiscountInclTax > decimal.Zero) model.OrderSubTotalDiscountInclTax = orderSubtotalDiscountInclTaxStr; if (order.OrderSubTotalDiscountExclTax > decimal.Zero) model.OrderSubTotalDiscountExclTax = orderSubtotalDiscountExclTaxStr; model.OrderSubTotalDiscountInclTaxValue = order.OrderSubTotalDiscountInclTax; model.OrderSubTotalDiscountExclTaxValue = order.OrderSubTotalDiscountExclTax; //shipping model.OrderShippingInclTax = _priceFormatter.FormatShippingPrice(order.OrderShippingInclTax, true, primaryStoreCurrency, _workContext.WorkingLanguage, true); model.OrderShippingExclTax = _priceFormatter.FormatShippingPrice(order.OrderShippingExclTax, true, primaryStoreCurrency, _workContext.WorkingLanguage, false); model.OrderShippingInclTaxValue = order.OrderShippingInclTax; model.OrderShippingExclTaxValue = order.OrderShippingExclTax; //payment method additional fee if (order.PaymentMethodAdditionalFeeInclTax > decimal.Zero) { model.PaymentMethodAdditionalFeeInclTax = _priceFormatter.FormatPaymentMethodAdditionalFee(order.PaymentMethodAdditionalFeeInclTax, true, primaryStoreCurrency, _workContext.WorkingLanguage, true); model.PaymentMethodAdditionalFeeExclTax = _priceFormatter.FormatPaymentMethodAdditionalFee(order.PaymentMethodAdditionalFeeExclTax, true, primaryStoreCurrency, _workContext.WorkingLanguage, false); } model.PaymentMethodAdditionalFeeInclTaxValue = order.PaymentMethodAdditionalFeeInclTax; model.PaymentMethodAdditionalFeeExclTaxValue = order.PaymentMethodAdditionalFeeExclTax; //tax model.Tax = _priceFormatter.FormatPrice(order.OrderTax, true, false); SortedDictionary<decimal, decimal> taxRates = order.TaxRatesDictionary; bool displayTaxRates = _taxSettings.DisplayTaxRates && taxRates.Any(); bool displayTax = !displayTaxRates; foreach (var tr in order.TaxRatesDictionary) { model.TaxRates.Add(new OrderModel.TaxRate { Rate = _priceFormatter.FormatTaxRate(tr.Key), Value = _priceFormatter.FormatPrice(tr.Value, true, false), }); } model.DisplayTaxRates = displayTaxRates; model.DisplayTax = displayTax; model.TaxValue = order.OrderTax; model.TaxRatesValue = order.TaxRates; //discount if (order.OrderDiscount > 0) model.OrderTotalDiscount = _priceFormatter.FormatPrice(-order.OrderDiscount, true, false); model.OrderTotalDiscountValue = order.OrderDiscount; //gift cards foreach (var gcuh in order.GiftCardUsageHistory) { model.GiftCards.Add(new OrderModel.GiftCard { CouponCode = gcuh.GiftCard.GiftCardCouponCode, Amount = _priceFormatter.FormatPrice(-gcuh.UsedValue, true, false), }); } //reward points if (order.RedeemedRewardPointsEntry != null) { model.RedeemedRewardPoints = -order.RedeemedRewardPointsEntry.Points; model.RedeemedRewardPointsAmount = _priceFormatter.FormatPrice(-order.RedeemedRewardPointsEntry.UsedAmount, true, false); } //total model.OrderTotal = _priceFormatter.FormatPrice(order.OrderTotal, true, false); model.OrderTotalValue = order.OrderTotal; //refunded amount if (order.RefundedAmount > decimal.Zero) model.RefundedAmount = _priceFormatter.FormatPrice(order.RefundedAmount, true, false); //used discounts var duh = _discountService.GetAllDiscountUsageHistory(orderId: order.Id); foreach (var d in duh) { model.UsedDiscounts.Add(new OrderModel.UsedDiscountModel { DiscountId = d.DiscountId, DiscountName = d.Discount.Name }); } //profit (hide for vendors) if (_workContext.CurrentVendor == null) { var profit = _orderReportService.ProfitReport(orderId: order.Id); model.Profit = _priceFormatter.FormatPrice(profit, true, false); } #endregion #region Payment info //payment method info var pm = _paymentService.LoadPaymentMethodBySystemName(order.PaymentMethodSystemName); model.PaymentMethod = pm != null ? pm.PluginDescriptor.FriendlyName : order.PaymentMethodSystemName; model.PaymentStatus = order.PaymentStatus.GetLocalizedEnum(_localizationService, _workContext); #endregion #region Billing & shipping info model.BillingAddress = order.BillingAddress.ToModel(); model.BillingAddress.FormattedCustomAddressAttributes = _addressAttributeFormatter.FormatAttributes(order.BillingAddress.CustomAttributes); model.BillingAddress.FirstNameEnabled = true; model.BillingAddress.FirstNameRequired = true; model.BillingAddress.LastNameEnabled = true; model.BillingAddress.LastNameRequired = true; model.BillingAddress.EmailEnabled = true; model.BillingAddress.EmailRequired = true; model.BillingAddress.CompanyEnabled = _addressSettings.CompanyEnabled; model.BillingAddress.CompanyRequired = _addressSettings.CompanyRequired; model.BillingAddress.CountryEnabled = _addressSettings.CountryEnabled; model.BillingAddress.CountryRequired = _addressSettings.CountryEnabled; //country is required when enabled model.BillingAddress.StateProvinceEnabled = _addressSettings.StateProvinceEnabled; model.BillingAddress.CityEnabled = _addressSettings.CityEnabled; model.BillingAddress.CityRequired = _addressSettings.CityRequired; model.BillingAddress.StreetAddressEnabled = _addressSettings.StreetAddressEnabled; model.BillingAddress.StreetAddressRequired = _addressSettings.StreetAddressRequired; model.BillingAddress.StreetAddress2Enabled = _addressSettings.StreetAddress2Enabled; model.BillingAddress.StreetAddress2Required = _addressSettings.StreetAddress2Required; model.BillingAddress.ZipPostalCodeEnabled = _addressSettings.ZipPostalCodeEnabled; model.BillingAddress.ZipPostalCodeRequired = _addressSettings.ZipPostalCodeRequired; model.BillingAddress.PhoneEnabled = _addressSettings.PhoneEnabled; model.BillingAddress.PhoneRequired = _addressSettings.PhoneRequired; model.BillingAddress.FaxEnabled = _addressSettings.FaxEnabled; model.BillingAddress.FaxRequired = _addressSettings.FaxRequired; model.ShippingStatus = order.ShippingStatus.GetLocalizedEnum(_localizationService, _workContext); ; if (order.ShippingStatus != ShippingStatus.ShippingNotRequired) { model.IsShippable = true; model.PickUpInStore = order.PickUpInStore; if (!order.PickUpInStore) { model.ShippingAddress = order.ShippingAddress.ToModel(); model.ShippingAddress.FormattedCustomAddressAttributes = _addressAttributeFormatter.FormatAttributes(order.ShippingAddress.CustomAttributes); model.ShippingAddress.FirstNameEnabled = true; model.ShippingAddress.FirstNameRequired = true; model.ShippingAddress.LastNameEnabled = true; model.ShippingAddress.LastNameRequired = true; model.ShippingAddress.EmailEnabled = true; model.ShippingAddress.EmailRequired = true; model.ShippingAddress.CompanyEnabled = _addressSettings.CompanyEnabled; model.ShippingAddress.CompanyRequired = _addressSettings.CompanyRequired; model.ShippingAddress.CountryEnabled = _addressSettings.CountryEnabled; model.ShippingAddress.CountryRequired = _addressSettings.CountryEnabled; //country is required when enabled model.ShippingAddress.StateProvinceEnabled = _addressSettings.StateProvinceEnabled; model.ShippingAddress.CityEnabled = _addressSettings.CityEnabled; model.ShippingAddress.CityRequired = _addressSettings.CityRequired; model.ShippingAddress.StreetAddressEnabled = _addressSettings.StreetAddressEnabled; model.ShippingAddress.StreetAddressRequired = _addressSettings.StreetAddressRequired; model.ShippingAddress.StreetAddress2Enabled = _addressSettings.StreetAddress2Enabled; model.ShippingAddress.StreetAddress2Required = _addressSettings.StreetAddress2Required; model.ShippingAddress.ZipPostalCodeEnabled = _addressSettings.ZipPostalCodeEnabled; model.ShippingAddress.ZipPostalCodeRequired = _addressSettings.ZipPostalCodeRequired; model.ShippingAddress.PhoneEnabled = _addressSettings.PhoneEnabled; model.ShippingAddress.PhoneRequired = _addressSettings.PhoneRequired; model.ShippingAddress.FaxEnabled = _addressSettings.FaxEnabled; model.ShippingAddress.FaxRequired = _addressSettings.FaxRequired; model.ShippingAddressGoogleMapsUrl = string.Format("http://maps.google.com/maps?f=q&hl=en&ie=UTF8&oe=UTF8&geocode=&q={0}", Server.UrlEncode(order.ShippingAddress.Address1 + " " + order.ShippingAddress.ZipPostalCode + " " + order.ShippingAddress.City + " " + (order.ShippingAddress.Country != null ? order.ShippingAddress.Country.Name : ""))); } else { if (order.PickupAddress != null) { model.PickupAddress = order.PickupAddress.ToModel(); model.PickupAddressGoogleMapsUrl = string.Format("http://maps.google.com/maps?f=q&hl=en&ie=UTF8&oe=UTF8&geocode=&q={0}", Server.UrlEncode(string.Format("{0} {1} {2} {3}", order.PickupAddress.Address1, order.PickupAddress.ZipPostalCode, order.PickupAddress.City, order.PickupAddress.Country != null ? order.PickupAddress.Country.Name : string.Empty))); } } model.ShippingMethod = order.ShippingMethod; } #endregion #region Products model.CheckoutAttributeInfo = order.CheckoutAttributeDescription; bool hasDownloadableItems = false; var products = order.OrderItems; //a vendor should have access only to his products if (_workContext.CurrentVendor != null) { products = products .Where(orderItem => orderItem.Product.VendorId == _workContext.CurrentVendor.Id) .ToList(); } foreach (var orderItem in products) { if (orderItem.Product.IsDownload) hasDownloadableItems = true; var orderItemModel = new OrderModel.OrderItemModel { Id = orderItem.Id, ProductId = orderItem.ProductId, ProductName = orderItem.Product.Name, Sku = orderItem.Product.FormatSku(orderItem.AttributesXml, _productAttributeParser), Quantity = orderItem.Quantity, IsDownload = orderItem.Product.IsDownload, DownloadCount = orderItem.DownloadCount, DownloadActivationType = orderItem.Product.DownloadActivationType, IsDownloadActivated = orderItem.IsDownloadActivated }; //vendor var vendor = _vendorService.GetVendorById(orderItem.Product.VendorId); orderItemModel.VendorName = vendor != null ? vendor.Name : ""; //unit price orderItemModel.UnitPriceInclTaxValue = orderItem.UnitPriceInclTax; orderItemModel.UnitPriceExclTaxValue = orderItem.UnitPriceExclTax; orderItemModel.UnitPriceInclTax = _priceFormatter.FormatPrice(orderItem.UnitPriceInclTax, true, primaryStoreCurrency, _workContext.WorkingLanguage, true, true); orderItemModel.UnitPriceExclTax = _priceFormatter.FormatPrice(orderItem.UnitPriceExclTax, true, primaryStoreCurrency, _workContext.WorkingLanguage, false, true); //discounts orderItemModel.DiscountInclTaxValue = orderItem.DiscountAmountInclTax; orderItemModel.DiscountExclTaxValue = orderItem.DiscountAmountExclTax; orderItemModel.DiscountInclTax = _priceFormatter.FormatPrice(orderItem.DiscountAmountInclTax, true, primaryStoreCurrency, _workContext.WorkingLanguage, true, true); orderItemModel.DiscountExclTax = _priceFormatter.FormatPrice(orderItem.DiscountAmountExclTax, true, primaryStoreCurrency, _workContext.WorkingLanguage, false, true); //subtotal orderItemModel.SubTotalInclTaxValue = orderItem.PriceInclTax; orderItemModel.SubTotalExclTaxValue = orderItem.PriceExclTax; orderItemModel.SubTotalInclTax = _priceFormatter.FormatPrice(orderItem.PriceInclTax, true, primaryStoreCurrency, _workContext.WorkingLanguage, true, true); orderItemModel.SubTotalExclTax = _priceFormatter.FormatPrice(orderItem.PriceExclTax, true, primaryStoreCurrency, _workContext.WorkingLanguage, false, true); orderItemModel.AttributeInfo = orderItem.AttributeDescription; if (orderItem.Product.IsRecurring) orderItemModel.RecurringInfo = string.Format(_localizationService.GetResource("Admin.Orders.Products.RecurringPeriod"), orderItem.Product.RecurringCycleLength, orderItem.Product.RecurringCyclePeriod.GetLocalizedEnum(_localizationService, _workContext)); //rental info if (orderItem.Product.IsRental) { var rentalStartDate = orderItem.RentalStartDateUtc.HasValue ? orderItem.Product.FormatRentalDate(orderItem.RentalStartDateUtc.Value) : ""; var rentalEndDate = orderItem.RentalEndDateUtc.HasValue ? orderItem.Product.FormatRentalDate(orderItem.RentalEndDateUtc.Value) : ""; orderItemModel.RentalInfo = string.Format(_localizationService.GetResource("Order.Rental.FormattedDate"), rentalStartDate, rentalEndDate); } model.Items.Add(orderItemModel); } model.HasDownloadableProducts = hasDownloadableItems; #endregion }
/// <summary> /// Gets a value indicating whether customers can complete a payment after order is placed but not completed (for redirection payment methods) /// </summary> /// <param name="order">Order</param> /// <returns>Result</returns> public bool CanRePostProcessPayment(Order order) { if (order == null) throw new ArgumentNullException("order"); //let's ensure that at least 5 seconds passed after order is placed //P.S. there's no any particular reason for that. we just do it if ((DateTime.UtcNow - order.CreatedOnUtc).TotalSeconds < 5) return false; return true; }
public bool CanRePostProcessPayment(Nop.Core.Domain.Orders.Order order) => false;
/// <summary> /// Partially refunds an order (from admin panel) /// </summary> /// <param name="order">Order</param> /// <param name="amountToRefund">Amount to refund</param> /// <returns>A list of errors; empty list if no errors</returns> public virtual IList<string> PartiallyRefund(Order order, decimal amountToRefund) { if (order == null) throw new ArgumentNullException("order"); if (!CanPartiallyRefund(order, amountToRefund)) throw new NopException("Cannot do partial refund for order."); var request = new RefundPaymentRequest(); RefundPaymentResult result = null; try { request.Order = order; request.AmountToRefund = amountToRefund; request.IsPartialRefund = true; result = _paymentService.Refund(request); if (result.Success) { //total amount refunded decimal totalAmountRefunded = order.RefundedAmount + amountToRefund; //update order info order.RefundedAmount = totalAmountRefunded; order.PaymentStatus = result.NewPaymentStatus; _orderService.UpdateOrder(order); //add a note order.OrderNotes.Add(new OrderNote { Note = string.Format("Order has been partially refunded. Amount = {0}", _priceFormatter.FormatPrice(amountToRefund, true, false)), DisplayToCustomer = false, CreatedOnUtc = DateTime.UtcNow }); _orderService.UpdateOrder(order); //check order status CheckOrderStatus(order); //raise event _eventPublisher.Publish(new OrderRefundedEvent(order, amountToRefund)); } } catch (Exception exc) { if (result == null) result = new RefundPaymentResult(); result.AddError(string.Format("Error: {0}. Full exception: {1}", exc.Message, exc.ToString())); } //process errors string error = ""; for (int i = 0; i < result.Errors.Count; i++) { error += string.Format("Error {0}: {1}", i, result.Errors[i]); if (i != result.Errors.Count - 1) error += ". "; } if (!String.IsNullOrEmpty(error)) { //add a note order.OrderNotes.Add(new OrderNote { Note = string.Format("Unable to partially refund order. {0}", error), DisplayToCustomer = false, CreatedOnUtc = DateTime.UtcNow }); _orderService.UpdateOrder(order); //log it string logError = string.Format("Error refunding order #{0}. Error: {1}", order.Id, error); _logger.InsertLog(LogLevel.Error, logError, logError); } return result.Errors; }
/// <summary> /// Marks order as authorized /// </summary> /// <param name="order">Order</param> public virtual void MarkAsAuthorized(Order order) { if (order == null) throw new ArgumentNullException("order"); order.PaymentStatusId = (int)PaymentStatus.Authorized; _orderService.UpdateOrder(order); //add a note order.OrderNotes.Add(new OrderNote { Note = "Order has been marked as authorized", DisplayToCustomer = false, CreatedOnUtc = DateTime.UtcNow }); _orderService.UpdateOrder(order); //check order status CheckOrderStatus(order); }
/// <summary> /// Deletes an order /// </summary> /// <param name="order">The order</param> public virtual void DeleteOrder(Order order) { if (order == null) throw new ArgumentNullException("order"); //check whether the order wasn't cancelled before //if it already was cancelled, then there's no need to make the following adjustments //(such as reward points, inventory, recurring payments) //they already was done when cancelling the order if (order.OrderStatus != OrderStatus.Cancelled) { //reward points ReduceRewardPoints(order); //cancel recurring payments var recurringPayments = _orderService.SearchRecurringPayments(0, 0, order.Id, null, 0, int.MaxValue); foreach (var rp in recurringPayments) { var errors = CancelRecurringPayment(rp); //use "errors" variable? } //Adjust inventory for already shipped shipments //only products with "use mutliple warehouses" foreach (var shipment in order.Shipments) { foreach (var shipmentItem in shipment.ShipmentItems) { var orderItem = _orderService.GetOrderItemById(shipmentItem.OrderItemId); if (orderItem == null) continue; _productService.ReverseBookedInventory(orderItem.Product, shipmentItem); } } //Adjust inventory foreach (var orderItem in order.OrderItems) { _productService.AdjustInventory(orderItem.Product, orderItem.Quantity, orderItem.AttributesXml); } } //add a note order.OrderNotes.Add(new OrderNote { Note = "Order has been deleted", DisplayToCustomer = false, CreatedOnUtc = DateTime.UtcNow }); _orderService.UpdateOrder(order); //now delete an order _orderService.DeleteOrder(order); }
/// <summary> /// Capture an order (from admin panel) /// </summary> /// <param name="order">Order</param> /// <returns>A list of errors; empty list if no errors</returns> public virtual IList<string> Capture(Order order) { if (order == null) throw new ArgumentNullException("order"); if (!CanCapture(order)) throw new NopException("Cannot do capture for order."); var request = new CapturePaymentRequest(); CapturePaymentResult result = null; try { //old info from placing order request.Order = order; result = _paymentService.Capture(request); if (result.Success) { var paidDate = order.PaidDateUtc; if (result.NewPaymentStatus == PaymentStatus.Paid) paidDate = DateTime.UtcNow; order.CaptureTransactionId = result.CaptureTransactionId; order.CaptureTransactionResult = result.CaptureTransactionResult; order.PaymentStatus = result.NewPaymentStatus; order.PaidDateUtc = paidDate; _orderService.UpdateOrder(order); //add a note order.OrderNotes.Add(new OrderNote { Note = "Order has been captured", DisplayToCustomer = false, CreatedOnUtc = DateTime.UtcNow }); _orderService.UpdateOrder(order); CheckOrderStatus(order); if (order.PaymentStatus == PaymentStatus.Paid) { ProcessOrderPaid(order); } } } catch (Exception exc) { if (result == null) result = new CapturePaymentResult(); result.AddError(string.Format("Error: {0}. Full exception: {1}", exc.Message, exc.ToString())); } //process errors string error = ""; for (int i = 0; i < result.Errors.Count; i++) { error += string.Format("Error {0}: {1}", i, result.Errors[i]); if (i != result.Errors.Count - 1) error += ". "; } if (!String.IsNullOrEmpty(error)) { //add a note order.OrderNotes.Add(new OrderNote { Note = string.Format("Unable to capture order. {0}", error), DisplayToCustomer = false, CreatedOnUtc = DateTime.UtcNow }); _orderService.UpdateOrder(order); //log it string logError = string.Format("Error capturing order #{0}. Error: {1}", order.Id, error); _logger.InsertLog(LogLevel.Error, logError, logError); } return result.Errors; }
public OrderDetailsModel PrepareOrderDetailsModelLegacy(Nop.Core.Domain.Orders.Order order) { var model = new OrderDetailsModel(); return(model); }
/// <summary> /// Checks order status /// </summary> /// <param name="order">Order</param> /// <returns>Validated order</returns> public virtual void CheckOrderStatus(Order order) { if (order == null) throw new ArgumentNullException("order"); if (order.PaymentStatus == PaymentStatus.Paid && !order.PaidDateUtc.HasValue) { //ensure that paid date is set order.PaidDateUtc = DateTime.UtcNow; _orderService.UpdateOrder(order); } if (order.OrderStatus == OrderStatus.Pending) { if (order.PaymentStatus == PaymentStatus.Authorized || order.PaymentStatus == PaymentStatus.Paid) { SetOrderStatus(order, OrderStatus.Processing, false); } } if (order.OrderStatus == OrderStatus.Pending) { if (order.ShippingStatus == ShippingStatus.PartiallyShipped || order.ShippingStatus == ShippingStatus.Shipped || order.ShippingStatus == ShippingStatus.Delivered) { SetOrderStatus(order, OrderStatus.Processing, false); } } if (order.OrderStatus != OrderStatus.Cancelled && order.OrderStatus != OrderStatus.Complete) { if (order.PaymentStatus == PaymentStatus.Paid) { if (order.ShippingStatus == ShippingStatus.ShippingNotRequired || order.ShippingStatus == ShippingStatus.Delivered) { SetOrderStatus(order, OrderStatus.Complete, true); } } } }
private void SyncKlarnaAndNopOrder(KlarnaCheckoutEntity klarnaRequest, Customer customer, out Order nopOrder, out KlarnaCheckoutOrder klarnaCheckoutOrder) { nopOrder = _orderService.GetOrderByGuid(klarnaRequest.OrderGuid); var resourceUri = new Uri(klarnaRequest.KlarnaResourceUri); var apiOrder = _klarnaCheckoutPaymentService.Fetch(resourceUri); klarnaCheckoutOrder = KlarnaCheckoutOrder.FromApiOrder(apiOrder); // Create the order if it doesn't exist in nop. According to the Klarna Checkout // developer guidelines, one should only create the order if the status is // 'checkout_complete'. // https://developers.klarna.com/en/klarna-checkout/acknowledge-an-order if (nopOrder == null && klarnaCheckoutOrder.Status == KlarnaCheckoutOrder.StatusCheckoutComplete) { if (klarnaCheckoutOrder.Status == KlarnaCheckoutOrder.StatusCheckoutComplete) { klarnaRequest.Status = KlarnaCheckoutStatus.Complete; _repository.Update(klarnaRequest); } _klarnaCheckoutPaymentService.SyncBillingAndShippingAddress(customer, klarnaCheckoutOrder); nopOrder = CreateOrderAndSyncWithKlarna(klarnaRequest, customer, klarnaCheckoutOrder, resourceUri); } }
/// <summary> /// Check whether return request is allowed /// </summary> /// <param name="order">Order</param> /// <returns>Result</returns> public virtual bool IsReturnRequestAllowed(Order order) { if (!_orderSettings.ReturnRequestsEnabled) return false; if (order == null || order.Deleted) return false; if (order.OrderStatus != OrderStatus.Complete) return false; bool numberOfDaysReturnRequestAvailableValid = false; if (_orderSettings.NumberOfDaysReturnRequestAvailable == 0) { numberOfDaysReturnRequestAvailableValid = true; } else { var daysPassed = (DateTime.UtcNow - order.CreatedOnUtc).TotalDays; numberOfDaysReturnRequestAvailableValid = (daysPassed - _orderSettings.NumberOfDaysReturnRequestAvailable) < 0; } return numberOfDaysReturnRequestAvailableValid; }
/// <summary> /// Sends an order placed notification to a store owner /// </summary> /// <param name="order">Order instance</param> /// <param name="languageId">Message language identifier</param> /// <returns>Queued email identifier</returns> public virtual int SendOrderPlacedStoreOwnerNotification(Order order, int languageId) { if (order == null) throw new ArgumentNullException("order"); languageId = EnsureLanguageIsActive(languageId); var messageTemplate = GetLocalizedActiveMessageTemplate("OrderPlaced.StoreOwnerNotification", languageId); if (messageTemplate == null) return 0; var orderTokens = GenerateTokens(order, languageId); //event notification _eventPublisher.MessageTokensAdded(messageTemplate, orderTokens); var emailAccount = GetEmailAccountOfMessageTemplate(messageTemplate, languageId); var toEmail = emailAccount.Email; var toName = emailAccount.DisplayName; return SendNotification(messageTemplate, emailAccount, languageId, orderTokens, toEmail, toName); }
/// <summary> /// Marks order as paid /// </summary> /// <param name="order">Order</param> public virtual void MarkOrderAsPaid(Order order) { if (order == null) throw new ArgumentNullException("order"); if (!CanMarkOrderAsPaid(order)) throw new NopException("You can't mark this order as paid"); order.PaymentStatusId = (int)PaymentStatus.Paid; order.PaidDateUtc = DateTime.UtcNow; _orderService.UpdateOrder(order); //add a note order.OrderNotes.Add(new OrderNote { Note = "Order has been marked as paid", DisplayToCustomer = false, CreatedOnUtc = DateTime.UtcNow }); _orderService.UpdateOrder(order); CheckOrderStatus(order); if (order.PaymentStatus == PaymentStatus.Paid) { ProcessOrderPaid(order); } }
/// <summary> /// Updates the order /// </summary> /// <param name="order">The order</param> public virtual void UpdateOrder(Order order) { if (order == null) throw new ArgumentNullException("order"); _orderRepository.Update(order); //event notification _eventPublisher.EntityUpdated(order); }
/// <summary> /// Sends an order placed notification to a customer /// </summary> /// <param name="order">Order instance</param> /// <param name="languageId">Message language identifier</param> /// <returns>Queued email identifier</returns> public virtual int SendOrderPlacedCustomerNotification(Order order, int languageId) { if (order == null) throw new ArgumentNullException("order"); languageId = EnsureLanguageIsActive(languageId); var messageTemplate = GetLocalizedActiveMessageTemplate("OrderPlaced.CustomerNotification", languageId); if (messageTemplate == null) return 0; var orderTokens = GenerateTokens(order, languageId); //event notification _eventPublisher.MessageTokensAdded(messageTemplate, orderTokens); var emailAccount = GetEmailAccountOfMessageTemplate(messageTemplate, languageId); var toEmail = order.BillingAddress.Email; var toName = string.Format("{0} {1}", order.BillingAddress.FirstName, order.BillingAddress.LastName); return SendNotification(messageTemplate, emailAccount, languageId, orderTokens, toEmail, toName); }
//public static DBManager manager = new DBManager(_gbsOrderSettings.HOMConnectionString); public object getCustomValue(string key, Nop.Core.Domain.Orders.Order order) { Dictionary <string, object> customValues = PaymentExtensions.DeserializeCustomValues(order); return(customValues[key]); }
private IList<Token> GenerateTokens(Order order, int languageId) { var tokens = new List<Token>(); _messageTokenProvider.AddStoreTokens(tokens); _messageTokenProvider.AddOrderTokens(tokens, order, languageId); _messageTokenProvider.AddCustomerTokens(tokens, order.Customer); return tokens; }
/// <summary> /// Gets a value indicating whether capture from admin panel is allowed /// </summary> /// <param name="order">Order</param> /// <returns>A value indicating whether capture from admin panel is allowed</returns> public virtual bool CanCapture(Order order) { if (order == null) throw new ArgumentNullException("order"); if (order.OrderStatus == OrderStatus.Cancelled || order.OrderStatus == OrderStatus.Pending) return false; if (order.PaymentStatus == PaymentStatus.Authorized && _paymentService.SupportCapture(order.PaymentMethodSystemName)) return true; return false; }
protected SubmitReturnRequestModel PrepareReturnRequestModel(SubmitReturnRequestModel model, Order order) { if (order == null) throw new ArgumentNullException("order"); if (model == null) throw new ArgumentNullException("model"); model.OrderId = order.Id; //return reasons if (_orderSettings.ReturnRequestReasons != null) foreach (var rrr in _orderSettings.ReturnRequestReasons) { model.AvailableReturnReasons.Add(new SelectListItem() { Text = rrr, Value = rrr }); } //return actions if (_orderSettings.ReturnRequestActions != null) foreach (var rra in _orderSettings.ReturnRequestActions) { model.AvailableReturnActions.Add(new SelectListItem() { Text = rra, Value = rra }); } //products var orderProductVariants = _orderService.GetAllOrderProductVariants(order.Id, null, null, null, null, null, null); foreach (var opv in orderProductVariants) { var opvModel = new SubmitReturnRequestModel.OrderProductVariantModel() { Id = opv.Id, ProductId = opv.ProductVariant.ProductId, ProductSeName = opv.ProductVariant.Product.GetSeName(), AttributeInfo = opv.AttributeDescription, Quantity = opv.Quantity }; //product name if (!String.IsNullOrEmpty(opv.ProductVariant.GetLocalized(x => x.Name))) opvModel.ProductName = string.Format("{0} ({1})", opv.ProductVariant.Product.GetLocalized(x => x.Name), opv.ProductVariant.GetLocalized(x => x.Name)); else opvModel.ProductName = opv.ProductVariant.Product.GetLocalized(x => x.Name); model.Items.Add(opvModel); //unit price switch (order.CustomerTaxDisplayType) { case TaxDisplayType.ExcludingTax: { var opvUnitPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(opv.UnitPriceExclTax, order.CurrencyRate); opvModel.UnitPrice = _priceFormatter.FormatPrice(opvUnitPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, false); } break; case TaxDisplayType.IncludingTax: { var opvUnitPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(opv.UnitPriceInclTax, order.CurrencyRate); opvModel.UnitPrice = _priceFormatter.FormatPrice(opvUnitPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, _workContext.WorkingLanguage, true); } break; } } return model; }
/// <summary> /// Sets an order status /// </summary> /// <param name="order">Order</param> /// <param name="os">New order status</param> /// <param name="notifyCustomer">True to notify customer</param> protected virtual void SetOrderStatus(Order order, OrderStatus os, bool notifyCustomer) { if (order == null) throw new ArgumentNullException("order"); OrderStatus prevOrderStatus = order.OrderStatus; if (prevOrderStatus == os) return; //set and save new order status order.OrderStatusId = (int)os; _orderService.UpdateOrder(order); //order notes, notifications order.OrderNotes.Add(new OrderNote { Note = string.Format("Order status has been changed to {0}", os.ToString()), DisplayToCustomer = false, CreatedOnUtc = DateTime.UtcNow }); _orderService.UpdateOrder(order); if (prevOrderStatus != OrderStatus.Complete && os == OrderStatus.Complete && notifyCustomer) { //notification var orderCompletedAttachmentFilePath = _orderSettings.AttachPdfInvoiceToOrderCompletedEmail ? _pdfService.PrintOrderToPdf(order, 0) : null; var orderCompletedAttachmentFileName = _orderSettings.AttachPdfInvoiceToOrderCompletedEmail ? "order.pdf" : null; int orderCompletedCustomerNotificationQueuedEmailId = _workflowMessageService .SendOrderCompletedCustomerNotification(order, order.CustomerLanguageId, orderCompletedAttachmentFilePath, orderCompletedAttachmentFileName); if (orderCompletedCustomerNotificationQueuedEmailId > 0) { order.OrderNotes.Add(new OrderNote { Note = string.Format("\"Order completed\" email (to customer) has been queued. Queued email identifier: {0}.", orderCompletedCustomerNotificationQueuedEmailId), DisplayToCustomer = false, CreatedOnUtc = DateTime.UtcNow }); _orderService.UpdateOrder(order); } } if (prevOrderStatus != OrderStatus.Cancelled && os == OrderStatus.Cancelled && notifyCustomer) { //notification int orderCancelledCustomerNotificationQueuedEmailId = _workflowMessageService.SendOrderCancelledCustomerNotification(order, order.CustomerLanguageId); if (orderCancelledCustomerNotificationQueuedEmailId > 0) { order.OrderNotes.Add(new OrderNote { Note = string.Format("\"Order cancelled\" email (to customer) has been queued. Queued email identifier: {0}.", orderCancelledCustomerNotificationQueuedEmailId), DisplayToCustomer = false, CreatedOnUtc = DateTime.UtcNow }); _orderService.UpdateOrder(order); } } //reward points if (_rewardPointsSettings.PointsForPurchases_Awarded == order.OrderStatus) { AwardRewardPoints(order); } if (_rewardPointsSettings.PointsForPurchases_Canceled == order.OrderStatus) { ReduceRewardPoints(order); } //gift cards activation if (_orderSettings.GiftCards_Activated_OrderStatusId > 0 && _orderSettings.GiftCards_Activated_OrderStatusId == (int)order.OrderStatus) { SetActivatedValueForPurchasedGiftCards(order, true); } //gift cards deactivation if (_orderSettings.GiftCards_Deactivated_OrderStatusId > 0 && _orderSettings.GiftCards_Deactivated_OrderStatusId == (int)order.OrderStatus) { SetActivatedValueForPurchasedGiftCards(order, false); } }
/// <summary> /// Gets a value indicating whether customers can complete a payment after order is placed but not completed (for redirection payment methods) /// </summary> /// <param name="order">Order</param> /// <returns>Result</returns> public bool CanRePostProcessPayment(Order order) { if (order == null) throw new ArgumentNullException("order"); //it's not a redirection payment method. So we always return false return false; }
/// <summary> /// Cancels order /// </summary> /// <param name="order">Order</param> /// <param name="notifyCustomer">True to notify customer</param> public virtual void CancelOrder(Order order, bool notifyCustomer) { if (order == null) throw new ArgumentNullException("order"); if (!CanCancelOrder(order)) throw new NopException("Cannot do cancel for order."); //Cancel order SetOrderStatus(order, OrderStatus.Cancelled, notifyCustomer); //add a note order.OrderNotes.Add(new OrderNote { Note = "Order has been cancelled", DisplayToCustomer = false, CreatedOnUtc = DateTime.UtcNow }); _orderService.UpdateOrder(order); //cancel recurring payments var recurringPayments = _orderService.SearchRecurringPayments(0, 0, order.Id, null, 0, int.MaxValue); foreach (var rp in recurringPayments) { var errors = CancelRecurringPayment(rp); //use "errors" variable? } //Adjust inventory for already shipped shipments //only products with "use mutliple warehouses" foreach (var shipment in order.Shipments) { foreach (var shipmentItem in shipment.ShipmentItems) { var orderItem = _orderService.GetOrderItemById(shipmentItem.OrderItemId); if (orderItem == null) continue; _productService.ReverseBookedInventory(orderItem.Product, shipmentItem); } } //Adjust inventory foreach (var orderItem in order.OrderItems) { _productService.AdjustInventory(orderItem.Product, orderItem.Quantity, orderItem.AttributesXml); } _eventPublisher.Publish(new OrderCancelledEvent(order)); }