public override bool ProcessCheckout(OrderTaskContext context) { if (context.HccApp.CurrentRequestContext.RoutingContext.HttpContext != null) { try { var settings = new MyPaymentMethodSettings(); var methodSettings = context.HccApp.CurrentStore.Settings.MethodSettingsGet(PaymentMethodId); settings.Merge(methodSettings); // Here you can do custom processing of your payment. // It can be direct post to payment service or redirection to hosted payment page // In either case you have to end up on HccUrlBuilder.RouteHccUrl(HccRoute.ThirdPartyPayment) page // So either you have to do such redirect here on your own // or make sure that third party hosted pay page will make it in case of successfull or failed payment HttpContextBase httpContext = new HccHttpContextWrapper(HttpContext.Current); httpContext.Response.Redirect(HccUrlBuilder.RouteHccUrl(HccRoute.ThirdPartyPayment)); } catch (Exception ex) { EventLog.LogEvent("My Custom Checkout", "Exception occurred during call to Moneris: " + ex, EventLogSeverity.Error); context.Errors.Add(new WorkflowMessage("My Custom Checkout Error", GlobalLocalization.GetString("MonerisCheckoutError"), true)); return(false); } } return(false); }
private void CannotAddProductsNotification(PromotionContext context, List <LineItem> productIds) { var flag = context.Order.CustomProperties .FirstOrDefault(s => s.DeveloperId == HCC_KEY && s.Key == "sendflag"); if (flag == null || flag.Value != ONE) { var itemF = new CustomProperty(HCC_KEY, "sendflag", "1"); context.Order.CustomProperties.Add(itemF); foreach (var product in productIds) { var note = new OrderNote(); note.IsPublic = false; note.Note = string.Format(GlobalLocalization.GetString("SkippingReceiveFreeProduct"), product.ProductName, product.ProductSku); context.Order.Notes.Add(note); } // sent mail to the store var epio = new EmailProductIsOut(); epio.Execute(context.HccApp, context.Order); } }
private void LoadShippingMethods(Order o) { var rates = new SortableCollection <ShippingRateDisplay>(); if (!o.HasShippingItems) { var r = new ShippingRateDisplay { DisplayName = GlobalLocalization.GetString("NoShippingRequired"), ProviderId = string.Empty, ProviderServiceCode = string.Empty, Rate = 0, ShippingMethodId = "NOSHIPPING" }; rates.Add(r); } else { // Shipping Methods rates = HccApp.OrderServices.FindAvailableShippingRates(o); if (rates.Count < 1) { var result = new ShippingRateDisplay(); result.DisplayName = GlobalLocalization.GetString("ToBeDetermined"); result.ShippingMethodId = "TOBEDETERMINED"; result.Rate = 0; rates.Add(result); } } litShippingMethods.Text = HtmlRendering.ShippingRatesToRadioButtons(rates, 300, o.ShippingMethodUniqueKey); }
/// <summary> /// Provides a listing of the tokens that the customer information can be replaced with in email templates /// </summary> /// <param name="context">An instance of the Hotcakes Request context object</param> /// <returns>List of name/value pairs of the tokens and replacement content</returns> public List <HtmlTemplateTag> GetReplaceableTags(HccRequestContext context) { var result = new List <HtmlTemplateTag>(); result.Add(new HtmlTemplateTag("[[User.Bvin]]", Bvin)); // TODO: make this obsolete result.Add(new HtmlTemplateTag("[[User.Notes]]", Notes)); result.Add(new HtmlTemplateTag("[[User.Comment]]", GlobalLocalization.GetString("UserCommentObsolete"), true)); result.Add(new HtmlTemplateTag("[[User.CreationDate]]", DateHelper.ConvertUtcToStoreTime(context.CurrentStore, CreationDateUtc).ToString())); result.Add(new HtmlTemplateTag("[[User.Email]]", Email)); result.Add(new HtmlTemplateTag("[[User.UserName]]", Username)); result.Add(new HtmlTemplateTag("[[User.FirstName]]", FirstName)); result.Add(new HtmlTemplateTag("[[User.LastLoginDate]]", DateHelper.ConvertUtcToStoreTime(context.CurrentStore, LastLoginDateUtc).ToString())); result.Add(new HtmlTemplateTag("[[User.LastName]]", LastName)); result.Add(new HtmlTemplateTag("[[User.LastUpdated]]", DateHelper.ConvertUtcToStoreTime(context.CurrentStore, LastUpdatedUtc).ToString())); result.Add(new HtmlTemplateTag("[[User.Locked]]", Locked.ToString())); result.Add(new HtmlTemplateTag("[[User.LockedUntil]]", DateHelper.ConvertUtcToStoreTime(context.CurrentStore, LockedUntilUtc).ToString())); result.Add(new HtmlTemplateTag("[[User.Password]]", Password)); return(result); }
public override bool Execute(OrderTaskContext context) { var maxItems = context.HccApp.CurrentRequestContext.CurrentStore.Settings.MaxItemsPerOrder; if (maxItems <= 0) { maxItems = 99999; } var maxWeight = context.HccApp.CurrentRequestContext.CurrentStore.Settings.MaxWeightPerOrder; if (maxWeight <= 0) { maxWeight = 99999; } var totalItems = context.Order.Items.Sum(y => y.Quantity); var totalWeight = context.Order.TotalWeightOfShippingItems(); if (totalItems > maxItems || totalWeight > maxWeight) { var maxMessage = GlobalLocalization.GetString("MaxOrderMessage"); context.Errors.Add(new WorkflowMessage("Order Too Large", maxMessage, true)); return(false); } return(true); }
/// <summary> /// Generate the different type of price information for the product /// </summary> /// <param name="price"> /// User specific price information based on the chosen option for the product on the product detail /// page /// </param> public ProductPrices(UserSpecificPrice price) { if (price.ListPriceGreaterThanCurrentPrice) { ListPrice = new PriceData { Label = GlobalLocalization.GetString("ListPrice"), Text = price.ListPrice.ToString("C"), RawValue = price.ListPrice.ToString("F") }; } SitePrice = new PriceData { Label = GlobalLocalization.GetString("SitePrice"), Text = price.DisplayPrice(true, false), RawValue = price.DisplayPrice(true, false) }; if (price.BasePrice < price.ListPrice && price.OverrideText.Trim().Length < 1) { YouSave = new PriceData { Label = GlobalLocalization.GetString("YouSave"), Text = string.Format("{0} - {1}{2}", price.Savings.ToString("c"), price.SavingsPercent, Thread.CurrentThread.CurrentUICulture.NumberFormat.PercentSymbol), RawValue = price.SavingsPercent.ToString("N") }; } }
public override bool Execute(OrderTaskContext context) { if (context.Order.IsPlaced) { return(true); } if (context.Order.Items.Count == 0) { context.Errors.Add(new WorkflowMessage("Order already placed.", GlobalLocalization.GetString("OrderAlreadyPlaced"), true)); return(false); } context.Order.IsPlaced = true; context.Order.TimeOfOrderUtc = DateTime.UtcNow; var errors = new List <string>(); if (!context.HccApp.OrdersReserveInventoryForAllItems(context.Order, errors)) { foreach (var item in errors) { context.Errors.Add(new WorkflowMessage("Stock Too Low", item, true)); } return(false); } if (context.HccApp.CurrentRequestContext.RoutingContext.HttpContext != null) { var request = context.HccApp.CurrentRequestContext.RoutingContext.HttpContext.Request; var note = new OrderNote(); note.IsPublic = false; note.Note = "Customer IP: " + request.UserHostAddress; note.Note += "<br> Customer Host: " + request.UserHostName; note.Note += "<br> Browser: " + request.UserAgent; context.Order.Notes.Add(note); context.Order.UserDeviceType = DetermineDeviceType(request); } var c = OrderStatusCode.FindByBvin(OrderStatusCode.Received); if (c != null) { var affiliateId = context.HccApp.ContactServices.GetCurrentAffiliateId(); context.Order.StatusName = c.StatusName; context.Order.StatusCode = c.Bvin; context.Order.AffiliateID = affiliateId; if (affiliateId.HasValue) { context.HccApp.ContactServices.UpdateProfileAffiliateId(affiliateId.Value); } } return(true); }
public ActionResult Index() { var model = new ProductListViewModel { Title = GlobalLocalization.GetString("RecentlyViewedItems"), Items = LoadItems() }; return(View(model)); }
public void LoadTrail(string categoryId) { TrailPlaceholder.Controls.Clear(); var trail = Category.BuildTrailToRoot(categoryId, HccApp.CatalogServices.Categories); if (DisplayLinks) { var m = new HyperLink(); m.CssClass = "root"; m.ToolTip = GlobalLocalization.GetString("Home"); m.Text = GlobalLocalization.GetString("Home"); m.NavigateUrl = ResolveUrl("~/"); m.EnableViewState = false; TrailPlaceholder.Controls.Add(m); } else { TrailPlaceholder.Controls.Add(new LiteralControl("<span class=\"current\">Home</span>")); } TrailPlaceholder.Controls.Add(new LiteralControl("<span class=\"spacer\">" + _Spacer + "</span>")); if (trail != null) { // Walk list backwards for (var i = trail.Count - 1; i >= 0; i += -1) { if (i != trail.Count - 1) { TrailPlaceholder.Controls.Add(new LiteralControl("<span class=\"spacer\">" + _Spacer + "</span>")); } if (i != 0) { if (DisplayLinks) { AddCategoryLink(trail[i]); } else { AddCategoryName(trail[i]); } } else { AddCategoryName(trail[i]); } } } }
public SystemOperationResult ValidateUser(string email, string password) { var result = new SystemOperationResult(); var u = Customers.FindByEmail(email).FirstOrDefault(); if (u != null) { if (DoPasswordsMatchForCustomer(password, u)) { CustomerCheckLock(u); if (u.Locked == false) { // Reset Failed Login Count if (u.FailedLoginCount > 0) { u.FailedLoginCount = 0; UpdateCustomer(u); } result.Success = true; } else { result.Success = false; result.Message = GlobalLocalization.GetString("AccountLocked"); } } else { result.Message = GlobalLocalization.GetString("LoginIncorrect"); u.FailedLoginCount += 1; UpdateCustomer(u); CustomerCheckLock(u); } } else { result.Message = GlobalLocalization.GetString("LoginIncorrect"); } if (result.Success == false) { EventLog.LogEvent("Membership", "Login Failed for User: " + email, EventLogSeverity.Information); } return(result); }
private void FillShippingMethods() { // Shipping Methods ShippingRatesList.Items.Clear(); if (!CurrentOrder.HasShippingItems) { ShippingRatesList.Items.Add(new ListItem(GlobalLocalization.GetString("NoShippingRequired"), "NOSHIPPING")); } else { var rates = HccApp.OrderServices.FindAvailableShippingRates(CurrentOrder); ShippingRatesList.DataTextField = "RateAndNameForDisplay"; ShippingRatesList.DataValueField = "UniqueKey"; ShippingRatesList.DataSource = rates; ShippingRatesList.DataBind(); } }
private ShippingRateDisplay FindSelectedRate(string uniqueKey, Order o) { ShippingRateDisplay result = null; if (!o.HasShippingItems) { result = new ShippingRateDisplay { DisplayName = GlobalLocalization.GetString("NoShippingRequired"), ProviderId = string.Empty, ProviderServiceCode = string.Empty, Rate = 0m, ShippingMethodId = "NOSHIPPING" }; } else { result = HccApp.OrderServices.FindShippingRateByUniqueKey(uniqueKey, o); } return(result); }
public override bool ProcessCheckout(OrderTaskContext context) { if (context.HccApp.CurrentRequestContext.RoutingContext.HttpContext != null) { try { PayPalAPI ppAPI = Utilities.PaypalExpressUtilities.GetPaypalAPI(context.HccApp.CurrentStore); string cartReturnUrl = HccUrlBuilder.RouteHccUrl(HccRoute.ThirdPartyPayment, null, Uri.UriSchemeHttps); string cartCancelUrl = HccUrlBuilder.RouteHccUrl(HccRoute.Checkout, null, Uri.UriSchemeHttps); EventLog.LogEvent("PayPal Express Checkout", "CartCancelUrl=" + cartCancelUrl, EventLogSeverity.Information); EventLog.LogEvent("PayPal Express Checkout", "CartReturnUrl=" + cartReturnUrl, EventLogSeverity.Information); PaymentActionCodeType mode = PaymentActionCodeType.Authorization; if (!context.HccApp.CurrentStore.Settings.PayPal.ExpressAuthorizeOnly) { mode = PaymentActionCodeType.Sale; } // Accelerated boarding if (string.IsNullOrWhiteSpace(context.HccApp.CurrentStore.Settings.PayPal.UserName)) { mode = PaymentActionCodeType.Sale; } var solutionType = context.HccApp.CurrentStore.Settings.PayPal.RequirePayPalAccount ? SolutionTypeType.Mark : SolutionTypeType.Sole; bool isNonShipping = !context.Order.HasShippingItems; bool addressSupplied = false; if (context.Inputs["ViaCheckout"] != null && context.Inputs["ViaCheckout"].Value == "1") { addressSupplied = true; context.Order.CustomProperties.Add("hcc", "ViaCheckout", "1"); } PaymentDetailsItemType[] itemsDetails = GetOrderItemsDetails(context); SetExpressCheckoutResponseType expressResponse; if (addressSupplied) { Contacts.Address address = context.Order.ShippingAddress; // in some cases, this logic will be hit with non-shipping orders, causing an exception if (address == null || string.IsNullOrEmpty(address.Bvin)) { // this is a workaround for that use case address = context.Order.BillingAddress; } if (address.CountryData != null) { var itemsTotalWithoutTax = context.Order.TotalOrderAfterDiscounts; if (context.HccApp.CurrentStore.Settings.ApplyVATRules) { itemsTotalWithoutTax -= context.Order.ItemsTax; } string itemsTotal = itemsTotalWithoutTax.ToString("N", CultureInfo.InvariantCulture); string taxTotal = context.Order.TotalTax.ToString("N", CultureInfo.InvariantCulture); var shippingTotalWithoutTax = context.Order.TotalShippingAfterDiscounts; if (context.HccApp.CurrentStore.Settings.ApplyVATRules) { shippingTotalWithoutTax -= context.Order.ShippingTax; } string shippingTotal = shippingTotalWithoutTax.ToString("N", CultureInfo.InvariantCulture); string orderTotal = context.Order.TotalGrand.ToString("N", CultureInfo.InvariantCulture); expressResponse = ppAPI.SetExpressCheckout( itemsDetails, itemsTotal, taxTotal, shippingTotal, orderTotal, cartReturnUrl, cartCancelUrl, mode, PayPalAPI.GetCurrencyCodeType(context.HccApp.CurrentStore.Settings.PayPal.Currency), solutionType, address.FirstName + " " + address.LastName, address.CountryData.IsoCode, address.Line1, address.Line2, address.City, address.RegionBvin, address.PostalCode, address.Phone, context.Order.OrderNumber + Guid.NewGuid().ToString(), isNonShipping); if (expressResponse == null) { EventLog.LogEvent("PayPal Express Checkout", "Express Response Was Null!", EventLogSeverity.Error); } } else { EventLog.LogEvent("StartPaypalExpressCheckout", "Country with bvin " + address.CountryBvin + " was not found.", EventLogSeverity.Error); return(false); } } else { decimal includedTax = 0; if (context.HccApp.CurrentStore.Settings.ApplyVATRules) { includedTax = context.Order.ItemsTax; } string taxTotal = includedTax.ToString("N", CultureInfo.InvariantCulture); var itemsTotalWithoutTax = context.Order.TotalOrderAfterDiscounts; if (context.HccApp.CurrentStore.Settings.ApplyVATRules) { itemsTotalWithoutTax -= context.Order.ItemsTax; } string itemsTotal = itemsTotalWithoutTax.ToString("N", CultureInfo.InvariantCulture); string orderTotal = context.Order.TotalOrderAfterDiscounts.ToString("N", CultureInfo.InvariantCulture); expressResponse = ppAPI.SetExpressCheckout(itemsDetails, itemsTotal, taxTotal, orderTotal, cartReturnUrl, cartCancelUrl, mode, PayPalAPI.GetCurrencyCodeType(context.HccApp.CurrentStore.Settings.PayPal.Currency), solutionType, context.Order.OrderNumber + Guid.NewGuid().ToString(), isNonShipping); if (expressResponse == null) { EventLog.LogEvent("PayPal Express Checkout", "Express Response2 Was Null!", EventLogSeverity.Error); } } if (expressResponse.Ack == AckCodeType.Success || expressResponse.Ack == AckCodeType.SuccessWithWarning) { context.Order.ThirdPartyOrderId = expressResponse.Token; // Recording of this info is handled on the paypal express // checkout page instead of here. //Orders.OrderPaymentManager payManager = new Orders.OrderPaymentManager(context.Order); //payManager.PayPalExpressAddInfo(context.Order.TotalGrand, expressResponse.Token); EventLog.LogEvent("PayPal Express Checkout", "Response SUCCESS", EventLogSeverity.Information); Orders.OrderNote note = new Orders.OrderNote(); note.IsPublic = false; note.Note = "Paypal Order Accepted With Paypal Order Number: " + expressResponse.Token; context.Order.Notes.Add(note); if (context.HccApp.OrderServices.Orders.Update(context.Order)) { string urlTemplate; if (string.Compare(context.HccApp.CurrentStore.Settings.PayPal.Mode, "Live", true) == 0) { urlTemplate = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token={0}"; } else { urlTemplate = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token={0}"; } HttpContextBase httpContext = new HccHttpContextWrapper(HttpContext.Current); httpContext.Response.Redirect(string.Format(urlTemplate, expressResponse.Token), true); } return(true); } else { foreach (ErrorType ppError in expressResponse.Errors) { context.Errors.Add(new WorkflowMessage(ppError.ErrorCode, ppError.ShortMessage, true)); //create a note to save the paypal error info onto the order Orders.OrderNote note = new Orders.OrderNote(); note.IsPublic = false; note.Note = "Paypal error number: " + ppError.ErrorCode + " Paypal Error: '" + ppError.ShortMessage + "' Message: '" + ppError.LongMessage; context.Order.Notes.Add(note); EventLog.LogEvent("Paypal error number: " + ppError.ErrorCode, "Paypal Error: '" + ppError.ShortMessage + "' Message: '" + ppError.LongMessage + "' " + " Values passed to SetExpressCheckout: Total=" + string.Format("{0:c}", context.Order.TotalOrderBeforeDiscounts) + " Cart Return Url: " + cartReturnUrl + " Cart Cancel Url: " + cartCancelUrl, EventLogSeverity.Error); } context.Errors.Add(new WorkflowMessage("Paypal checkout error", GlobalLocalization.GetString("PaypalCheckoutCustomerError"), true)); return(false); } } catch (Exception ex) { EventLog.LogEvent("Paypal Express Checkout", "Exception occurred during call to Paypal: " + ex.ToString(), EventLogSeverity.Error); context.Errors.Add(new WorkflowMessage("Paypal checkout error", GlobalLocalization.GetString("PaypalCheckoutCustomerError"), true)); return(false); } } return(false); }
public override bool ProcessCheckout(OrderTaskContext context) { if (context.HccApp.CurrentRequestContext.RoutingContext.HttpContext != null) { try { var settings = new MonerisSettings(); var methodSettings = context.HccApp.CurrentStore.Settings.MethodSettingsGet(PaymentMethodId); settings.Merge(methodSettings); var order = context.Order; var amount = order.TotalGrandAfterStoreCredits(context.HccApp.OrderServices); var parameters = new NameValueCollection(); parameters.Add("ps_store_id", settings.HostedPayPageId); parameters.Add("hpp_key", settings.HostedPayPageToken); parameters.Add("hpp_preload", ""); parameters.Add("charge_total", amount.ToString("F2", CultureInfo.InvariantCulture)); parameters.Add("lang", CultureInfo.CurrentCulture.Name); parameters.Add("hst", order.TotalTax.ToString("F2", CultureInfo.InvariantCulture)); parameters.Add("shipping_cost", order.TotalShippingAfterDiscounts.ToString("F2", CultureInfo.InvariantCulture)); parameters.Add("email", Text.TrimToLength(order.UserEmail, 50)); parameters.Add("note", string.Format(CultureInfo.InvariantCulture, "Order discounts: {0:F2}", order.TotalOrderDiscounts)); parameters.Add("ship_first_name", Text.TrimToLength(order.ShippingAddress.FirstName, 30)); parameters.Add("ship_last_name", Text.TrimToLength(order.ShippingAddress.LastName, 30)); parameters.Add("ship_company_name", Text.TrimToLength(order.ShippingAddress.Company, 30)); parameters.Add("ship_address_one", Text.TrimToLength(string.Join(", ", order.ShippingAddress.Line2, order.ShippingAddress.Line1), 30)); parameters.Add("ship_city", Text.TrimToLength(order.ShippingAddress.City, 30)); if (order.ShippingAddress.RegionData != null) { parameters.Add("ship_state_or_province", Text.TrimToLength(order.ShippingAddress.RegionData.DisplayName, 30)); } parameters.Add("ship_postal_code", Text.TrimToLength(order.ShippingAddress.PostalCode, 30)); parameters.Add("ship_country", Text.TrimToLength(order.ShippingAddress.CountryData.DisplayName, 30)); parameters.Add("ship_phone", Text.TrimToLength(order.ShippingAddress.Phone, 30)); parameters.Add("bill_first_name", Text.TrimToLength(order.BillingAddress.FirstName, 30)); parameters.Add("bill_last_name", Text.TrimToLength(order.BillingAddress.LastName, 30)); parameters.Add("bill_company_name", Text.TrimToLength(order.BillingAddress.Company, 30)); parameters.Add("bill_address_one", string.Join(", ", order.BillingAddress.Line2, order.BillingAddress.Line1)); parameters.Add("bill_city", Text.TrimToLength(order.BillingAddress.City, 30)); if (order.BillingAddress.RegionData != null) { parameters.Add("bill_state_or_province", Text.TrimToLength(order.BillingAddress.RegionData.DisplayName, 30)); } parameters.Add("bill_postal_code", Text.TrimToLength(order.BillingAddress.PostalCode, 30)); parameters.Add("bill_country", Text.TrimToLength(order.BillingAddress.CountryData.DisplayName, 30)); parameters.Add("bill_phone", Text.TrimToLength(order.BillingAddress.Phone, 30)); for (var i = 0; i < order.Items.Count; i++) { var item = order.Items[i]; parameters.Add("id" + (i + 1), item.ProductSku); parameters.Add("description" + (i + 1), item.ProductName); parameters.Add("quantity" + (i + 1), item.Quantity.ToString()); parameters.Add("price" + (i + 1), item.AdjustedPricePerItem.ToString("F2", CultureInfo.InvariantCulture)); parameters.Add("subtotal" + (i + 1), item.LineTotal.ToString("F2", CultureInfo.InvariantCulture)); } MonerisHPPDPResponse monerisResponse; var url = settings.DeveloperMode ? DevelopmentUrl : ProductionUrl; using (var client = new WebClient()) { if (settings.DebugMode) { EventLog.LogEvent("Moneris Checkout", Url.BuldQueryString(parameters), EventLogSeverity.Debug); } var responseBytes = client.UploadValues(url, "POST", parameters); var responseBody = Encoding.UTF8.GetString(responseBytes); if (settings.DebugMode) { EventLog.LogEvent("Moneris Checkout", responseBody, EventLogSeverity.Debug); } using (var configFile = new StringReader(responseBody)) { var serializer = new XmlSerializer(typeof(MonerisHPPDPResponse)); monerisResponse = (MonerisHPPDPResponse)serializer.Deserialize(configFile); } } var urlTemplate = "{0}?hpp_id={1}&ticket={2}&hpp_preload"; HttpContextBase httpContext = new HccHttpContextWrapper(HttpContext.Current); httpContext.Response.Redirect( string.Format(urlTemplate, url, monerisResponse.HostedPayPageId, monerisResponse.Ticket), true); } catch (Exception ex) { EventLog.LogEvent("Moneris Checkout", "Exception occurred during call to Moneris: " + ex, EventLogSeverity.Error); context.Errors.Add(new WorkflowMessage("Moneris Checkout Error", GlobalLocalization.GetString("MonerisCheckoutError"), true)); return(false); } } return(false); }
private SortableCollection <ShippingRateDisplay> FindAvailableShippingRatesInternal(Order order, string shippingMethodIdFilter = null) { if (order == null) { return(new SortableCollection <ShippingRateDisplay>()); } var result = new SortableCollection <ShippingRateDisplay>(); // Get all the methods that apply to this shipping address and store var zones = ShippingZones.FindAllZonesForAddress(order.ShippingAddress, order.StoreId); var methods = ShippingMethods.FindForZones(zones); if (!string.IsNullOrEmpty(shippingMethodIdFilter)) { methods = methods.Where(m => m.Bvin == shippingMethodIdFilter).ToList(); } // Get Rates for each Method if (!order.IsOrderFreeShipping()) { var tasks = new List <Task <Collection <ShippingRateDisplay> > >(); foreach (var method in methods) { var task = Task.Factory.StartNew(hccContext => { HccRequestContext.Current = hccContext as HccRequestContext; return(method.GetRates(order, Context.CurrentStore)); }, HccRequestContext.Current); tasks.Add(task); } Task.WaitAll(tasks.ToArray()); foreach (var task in tasks) { var tempRates = task.Result; if (tempRates != null) { for (var i = 0; i <= tempRates.Count - 1; i++) { var fRate = tempRates[i].GetCopy(); result.Add(fRate); } } } } // Update results with extra ship fees and handling foreach (ShippingRateDisplay displayRate in result) { // Tally up extra ship fees var totalExtraFees = 0m; foreach (var li in order.Items) { if (li.ExtraShipCharge > 0 && !li.MarkedForFreeShipping(displayRate.ShippingMethodId) && li.ShippingCharge == ShippingChargeType.ChargeShippingAndHandling || li.ShippingCharge == ShippingChargeType.ChargeShipping) { totalExtraFees += li.ExtraShipCharge * li.Quantity; } } displayRate.Rate += totalExtraFees + order.TotalHandling; } // Apply promotions to rates here var membershipServices = Factory.CreateService <MembershipServices>(); CustomerAccount currentUser = null; if (order.UserID != string.Empty) { currentUser = membershipServices.Customers.Find(order.UserID); } var marketingServices = Factory.CreateService <MarketingService>(); var offers = marketingServices.Promotions.FindAllPotentiallyActive(DateTime.UtcNow, PromotionType.OfferForShipping); foreach (ShippingRateDisplay displayRate in result) { foreach (var offer in offers) { if (offer.DoNotCombine && order.HasAnyNonSaleDiscounts) { continue; } var newRate = offer.ApplyToShippingRate(Context, order, currentUser, displayRate.ShippingMethodId, displayRate.Rate); if (newRate < displayRate.Rate) { var discount = -1 * (newRate - displayRate.Rate); displayRate.PotentialDiscount = discount; } } } //Changes to have free shipping available for single item in cart by promotion set for "Order Items" - 9May2016-Tushar var offersForLineItems = marketingServices.Promotions.FindAllPotentiallyActive(DateTime.UtcNow, PromotionType.OfferForLineItems); foreach (ShippingRateDisplay displayRate in result) { foreach (var offer in offersForLineItems) { var context = new PromotionContext(Context, PromotionType.OfferForLineItems, offer.Id) { Order = order, CurrentCustomer = currentUser, CustomerDescription = offer.CustomerDescription, CurrentShippingMethodId = displayRate.ShippingMethodId, AdjustedShippingRate = displayRate.Rate, OtherOffersApplied = order.HasAnyNonSaleDiscounts }; var isQualified = offer.ApplyForFreeShipping(context); if (order.Items.Count == 1 || order.IsOrderHasAllItemsQualifiedFreeShipping()) { var isFreeShippingAction = offer.Actions.Where( p => p.TypeId.ToString() == LineItemFreeShipping.TypeIdString && p.Settings.ContainsKey("methodids") && p.Settings["methodids"].ToUpperInvariant() .Contains(displayRate.ShippingMethodId.ToUpperInvariant())).ToList(); if (isFreeShippingAction.Count > 0 && isQualified) { displayRate.PotentialDiscount = displayRate.Rate; } } } } //End changes to have free shipping available for single item in cart by promotion set for "Order Items" - 9May2016-Tushar FilterRatesByShippingMethods(result, order); // Sort Rates result.Sort("Rate", SortDirection.Ascending); if (result.Count < 1) { if (order.IsOrderFreeShipping()) { var rateName = order.TotalHandling > 0 ? GlobalLocalization.GetString("Handling") : GlobalLocalization.GetString("FreeShipping"); result.Add(new ShippingRateDisplay(rateName, "", "", order.TotalHandling, ShippingMethod.MethodFreeShipping)); } else { result.Add(new ShippingRateDisplay(GlobalLocalization.GetString("ToBeDetermined"), string.Empty, string.Empty, 0m, ShippingMethod.MethodToBeDetermined)); } } return(result); }
private void ApplyVolumeDiscounts(Order order) { // Count up how many of each item in order var quantityMap = new Dictionary <string, int>(); foreach (var item in order.Items) { if (!item.IsUserSuppliedPrice && !item.IsGiftCard) { if (quantityMap.ContainsKey(item.ProductId)) { quantityMap[item.ProductId] += item.Quantity; } else { quantityMap.Add(item.ProductId, item.Quantity); } } } // Check for discounts on each item foreach (var productId in quantityMap.Keys) { var volumeDiscounts = _app.CatalogServices.VolumeDiscounts.FindByProductId(productId); if (volumeDiscounts.Count == 0) { continue; } // Locate the correct discount in the chart of discounts var quantity = quantityMap[productId]; var volumeDiscountToApply = volumeDiscounts.LastOrDefault(vd => quantity >= vd.Qty); if (volumeDiscountToApply == null) { continue; } // Now we have to go through the entire order and discount all items // Traversal through all items is requred because few line items of same product may be present in the cart foreach (var item in order.Items) { if (item.ProductId == productId) { var p = _app.CatalogServices.Products.FindWithCache(item.ProductId); if (p != null) { var adjustedPricePerItem = item.BasePricePerItem + item.TotalDiscounts() / item.Quantity; var alreadyDiscounted = p.SitePrice > adjustedPricePerItem; var volumeDiscountGlobalText = GlobalLocalization.GetString(VOLUME_DISCOUNT_LOCALIZATION_KEY); if (string.IsNullOrEmpty(volumeDiscountGlobalText)) { volumeDiscountGlobalText = VOLUME_DISCOUNT_GLOBAL_TEXT; } if (!alreadyDiscounted || !item.DiscountDetails.Any()) { // item isn't discounted yet so apply the exact price the merchant set var toDiscount = -1 * (adjustedPricePerItem - volumeDiscountToApply.Amount); toDiscount = toDiscount * item.Quantity; item.DiscountDetails.Add(new DiscountDetail { Amount = toDiscount, Description = volumeDiscountGlobalText, DiscountType = PromotionType.VolumeDiscount }); } else { // item is already discounted (probably by user group) so figure out // the percentage of volume discount instead var originalPriceChange = p.SitePrice - volumeDiscountToApply.Amount; var percentChange = originalPriceChange / p.SitePrice; var newDiscount = -1 * percentChange * adjustedPricePerItem; newDiscount = newDiscount * item.Quantity; item.DiscountDetails.Add(new DiscountDetail { Amount = newDiscount, Description = percentChange.ToString(PERCENT_CHANGED_FORMAT) + volumeDiscountGlobalText, DiscountType = PromotionType.VolumeDiscount }); } } } } } }
public SystemOperationResult CheckForStockOnItems(LineItem item) { // Build a list of product quantities to check var products = new Dictionary <string, ProductIdCombo>(); var product = item.GetAssociatedProduct(this); if (product == null || product.Status == ProductStatus.Disabled) { var productNotAvailable = GlobalLocalization.GetFormattedString("ProductNotAvailable", product.ProductName); return(new SystemOperationResult(false, productNotAvailable)); } if (!product.IsBundle) { var combo = new ProductIdCombo { ProductId = item.ProductId, VariantId = item.VariantId, ProductName = item.ProductName, Quantity = item.Quantity, Product = product }; if (products.ContainsKey(combo.Key())) { products[combo.Key()].Quantity += combo.Quantity; } else { products.Add(combo.Key(), combo); } } else { foreach (var bundledProductAdv in product.BundledProducts) { var bundledProduct = bundledProductAdv.BundledProduct; if (bundledProduct == null) { continue; } var optionSelection = item.SelectionData.GetSelections(bundledProductAdv.Id); var variant = bundledProduct.Variants.FindBySelectionData(optionSelection, bundledProduct.Options); var variantId = variant != null ? variant.Bvin : string.Empty; var combo = new ProductIdCombo { ProductId = bundledProduct.Bvin, VariantId = variantId, ProductName = bundledProduct.ProductName, Quantity = bundledProductAdv.Quantity, Product = bundledProduct }; if (products.ContainsKey(combo.Key())) { products[combo.Key()].Quantity += combo.Quantity; } else { products.Add(combo.Key(), combo); } } } // Now check each quantity for the order foreach (var key in products.Keys) { var checkcombo = products[key]; var prod = checkcombo.Product; var data = CatalogServices.SimpleProductInventoryCheck(prod, checkcombo.VariantId, checkcombo.Quantity); if (!data.IsAvailableForSale) { if (data.Qty == 0) { var cartOutOfStock = GlobalLocalization.GetFormattedString("CartOutOfStock", prod.ProductName); return(new SystemOperationResult(false, cartOutOfStock)); } var message = GlobalLocalization.GetFormattedString("CartNotEnoughQuantity", prod.ProductName, data.Qty); return(new SystemOperationResult(false, message)); } } return(new SystemOperationResult(true, string.Empty)); }
public override bool ProcessCheckout(OrderTaskContext context) { if (context.HccApp.CurrentRequestContext.RoutingContext.HttpContext != null) { try { var settings = new OgoneSettings(); var methodSettings = context.HccApp.CurrentStore.Settings.MethodSettingsGet(PaymentMethodId); settings.Merge(methodSettings); var order = context.Order; var decimalAmount = order.TotalGrandAfterStoreCredits(context.HccApp.OrderServices); var intAmount = (int)(decimalAmount * 100); var parameters = new NameValueCollection(); parameters.Add("PSPID", settings.PaymentServiceProviderId); // We can't use order.bvin here because Ogone won't allow us try to pay failed order again parameters.Add("ORDERID", "order" + DateTime.UtcNow.Ticks); parameters.Add("AMOUNT", intAmount.ToString()); var regionInfo = new RegionInfo(context.HccApp.CurrentStore.Settings.CurrencyCultureCode); parameters.Add("CURRENCY", regionInfo.ISOCurrencySymbol); var language = CultureInfo.CurrentCulture.Name.Replace("-", "_"); parameters.Add("LANGUAGE", language); parameters.Add("EMAIL", order.UserEmail); var address = order.BillingAddress; parameters.Add("CN", string.Join(" ", address.FirstName, address.LastName)); parameters.Add("OWNERADDRESS", string.Join(", ", address.Line2, address.Line1)); parameters.Add("OWNERZIP", address.PostalCode); parameters.Add("OWNERTOWN", address.City); parameters.Add("OWNERCTY", address.CountryDisplayName); parameters.Add("OWNERTELNO", address.Phone); parameters.Add("OPERATION", "SAL"); if (!string.IsNullOrWhiteSpace(settings.TemplatePage)) { parameters.Add("TP", settings.TemplatePage); } var returnUrl = HccUrlBuilder.RouteHccUrl(HccRoute.ThirdPartyPayment); var cancelUrl = HccUrlBuilder.RouteHccUrl(HccRoute.Checkout); parameters.Add("ACCEPTURL", returnUrl); parameters.Add("DECLINEURL", returnUrl); parameters.Add("EXCEPTIONURL", returnUrl); parameters.Add("CANCELURL", cancelUrl); var shaSign = OgoneUtils.CalculateShaHash(parameters, settings.HashAlgorithm, settings.ShaInPassPhrase); parameters.Add("SHASIGN", shaSign); HttpContextBase httpContext = new HccHttpContextWrapper(HttpContext.Current); var url = settings.DeveloperMode ? DevelopmentUTF8Url : ProductionUTF8Url; var urlParams = Url.BuldQueryString(parameters); if (settings.DebugMode) { EventLog.LogEvent("Ogone Checkout", urlParams, EventLogSeverity.Debug); } var urlTemplate = "{0}?{1}"; httpContext.Response.Redirect(string.Format(urlTemplate, url, urlParams), true); } catch (Exception ex) { EventLog.LogEvent("Ogone Checkout", "Exception occurred during call to Ogone: " + ex, EventLogSeverity.Error); context.Errors.Add(new WorkflowMessage("Ogone Checkout Error", GlobalLocalization.GetString("OgoneCheckoutError"), true)); return(false); } } return(false); }