public override bool Execute(OrderTaskContext context)
        {
            bool result = true;

            foreach (Orders.OrderTransaction p in context.MTApp.OrderServices.Transactions.FindForOrder(context.Order.bvin))
            {
                List <Orders.OrderTransaction> transactions = context.MTApp.OrderServices.Transactions.FindForOrder(context.Order.bvin);

                if (p.Action == MerchantTribe.Payment.ActionType.CreditCardInfo ||
                    p.Action == MerchantTribe.Payment.ActionType.CreditCardHold)
                {
                    // if we already have an auth or charge on the card, skip
                    if (p.HasSuccessfulLinkedAction(MerchantTribe.Payment.ActionType.CreditCardCharge, transactions) ||
                        p.HasSuccessfulLinkedAction(MerchantTribe.Payment.ActionType.CreditCardHold, transactions))
                    {
                        continue;
                    }

                    try
                    {
                        MerchantTribe.Payment.Transaction t = context.Order.GetEmptyTransaction();
                        t.Card   = p.CreditCard;
                        t.Amount = p.Amount;

                        if (p.Action == MerchantTribe.Payment.ActionType.CreditCardHold)
                        {
                            t.Action = MerchantTribe.Payment.ActionType.CreditCardCapture;
                        }
                        else
                        {
                            t.Action = MerchantTribe.Payment.ActionType.CreditCardCharge;
                        }

                        MerchantTribe.Payment.Method proc = context.MTApp.CurrentRequestContext.CurrentStore.Settings.PaymentCurrentCreditCardProcessor();
                        proc.ProcessTransaction(t);

                        Orders.OrderTransaction ot = new Orders.OrderTransaction(t);
                        ot.LinkedToTransaction = p.IdAsString;

                        context.MTApp.OrderServices.AddPaymentTransactionToOrder(context.Order, ot, context.MTApp);

                        if (t.Result.Succeeded == false)
                        {
                            result = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        context.Errors.Add(new WorkflowMessage("Exception During Complete Credit Card", ex.Message + ex.StackTrace, false));
                    }
                }

                Orders.OrderPaymentStatus previousPaymentStatus = context.Order.PaymentStatus;
                context.MTApp.OrderServices.EvaluatePaymentStatus(context.Order);
                context.Inputs.Add("bvsoftware", "PreviousPaymentStatus", previousPaymentStatus.ToString());
                BusinessRules.Workflow.RunByName(context, WorkflowNames.PaymentChanged);
            }

            return(result);
        }
        protected virtual void CreateAccount(OrderTaskContext context, CustomerAccount n)
        {
            try
            {
                if (context.HccApp.MembershipServices.CreateCustomer(n, n.Password))
                {
                    // Update Addresses for Customer
                    context.Order.BillingAddress.CopyTo(n.BillingAddress);
                    context.Order.ShippingAddress.CopyTo(n.ShippingAddress);
                    context.HccApp.MembershipServices.UpdateCustomer(n);

                    if (_isCreateGuestAccount)
                    {
                        context.Order.CustomProperties.Add("hcc", "allowpasswordreset", "1");
                    }

                    // Email Password to Customer
                    EmailPasswordToCustomer(context, n);
                }
            }
            catch (Exception ex)
            {
                EventLog.LogEvent(ex);
            }
        }
Exemple #3
0
        public override bool Execute(OrderTaskContext context)
        {
            if (context.Order.IsRecurring)
            {
                return(true);
            }

            if (context.PreviousPaymentStatus == OrderPaymentStatus.Paid &&
                context.Order.PaymentStatus != OrderPaymentStatus.Paid)
            {
                var statusCode  = OrderStatusCode.Received;
                var orderStatus = OrderStatusCode.FindByBvin(statusCode);
                if (orderStatus != null && orderStatus.Bvin != string.Empty)
                {
                    context.Order.StatusCode = orderStatus.Bvin;
                    context.Order.StatusName = orderStatus.StatusName;
                }
                else
                {
                    EventLog.LogEvent("Change Order Status When Payment Removed",
                                      "Could not find order status with id of " + statusCode, EventLogSeverity.Error);
                }
            }

            return(true);
        }
 public override bool Rollback(OrderTaskContext context)
 {
     EventLog.LogEvent("Order Workflow",
                       "Order number " + context.Order.OrderNumber + " was assigned but the order was not completed. The cart ID is " + context.Order.bvin,
                        EventLogSeverity.Information);            
     return true;
 }
Exemple #5
0
        public override bool Execute(OrderTaskContext context)
        {
            try
            {
                if (context.Order.ApplyVATRules && !context.Order.IsRecurring)
                {
                    var toEmail = context.HccApp.CurrentStore.Settings.MailServer.EmailForGeneral;

                    if (!string.IsNullOrEmpty(toEmail))
                    {
                        var storeSettingsProvider = Factory.CreateStoreSettingsProvider();
                        var defaultCulture        = storeSettingsProvider.GetDefaultLocale();
                        var hccRequestContext     = HccRequestContextUtils.GetContextWithCulture(context.RequestContext,
                                                                                                 defaultCulture);
                        var contentService = Factory.CreateService <ContentService>(hccRequestContext);

                        var t = contentService.GetHtmlTemplateOrDefault(HtmlTemplateType.FreeProductIsOutOfStock);
                        t = t.ReplaceTagsInTemplate(hccRequestContext, context.Order, context.Order.ItemsAsReplaceable());

                        var m = t.ConvertToMailMessage(toEmail);
                        MailServices.SendMail(m, hccRequestContext.CurrentStore);
                    }
                }
            }
            catch (Exception ex)
            {
                EventLog.LogEvent(ex);
            }

            return(true);
        }
Exemple #6
0
        private void ProcessOrder(CheckoutViewModel model)
        {
            HccApp.OrderServices.Orders.Update(model.CurrentOrder);

            // Save as Order
            var c = new OrderTaskContext
            {
                UserId = HccApp.CurrentCustomerId,
                Order  = model.CurrentOrder
            };

            if (Workflow.RunByName(c, WorkflowNames.ProcessNewOrder))
            {
                // Clear Cart ID because we're now an order
                SessionManager.SetCurrentCartId(HccApp.CurrentStore, string.Empty);

                // Process Payment
                if (Workflow.RunByName(c, WorkflowNames.ProcessNewOrderPayments))
                {
                    Workflow.RunByName(c, WorkflowNames.ProcessNewOrderAfterPayments);
                    var tempOrder = HccApp.OrderServices.Orders.FindForCurrentStore(model.CurrentOrder.bvin);
                    HccApp.CurrentRequestContext.IntegrationEvents.OrderReceived(tempOrder, HccApp);
                    SessionManager.AnalyticsOrderId = model.CurrentOrder.bvin;
                    Redirect(Url.RouteHccUrl(HccRoute.Checkout,
                                             new { action = "receipt", id = model.CurrentOrder.bvin }));
                }
            }
        }
        public override bool Execute(OrderTaskContext context)
        {
            if (context.UserId != string.Empty)
            {
                // see if the customer already exists
                var user = context.HccApp.MembershipServices.Customers.Find(context.UserId);

                // the user doesn't exist yet, so exit the workflow task
                if (user == null)
                {
                    return(true);
                }

                // copy the shipping address from the order to the user
                context.Order.ShippingAddress.CopyTo(user.ShippingAddress);

                // copy the billing address if it's different than shipping
                if (!context.Order.BillingAddress.IsEqualTo(context.Order.ShippingAddress))
                {
                    context.Order.BillingAddress.CopyTo(user.BillingAddress);
                }

                // save our changes
                context.HccApp.MembershipServices.UpdateCustomer(user);
            }

            return(true);
        }
        public override bool Execute(OrderTaskContext context)
        {
            int maxItems = context.MTApp.CurrentRequestContext.CurrentStore.Settings.MaxItemsPerOrder;

            if (maxItems <= 0)
            {
                maxItems = 99999;
            }
            decimal maxWeight = context.MTApp.CurrentRequestContext.CurrentStore.Settings.MaxWeightPerOrder;

            if (maxWeight <= 0)
            {
                maxWeight = 99999;
            }
            string maxMessage = context.MTApp.CurrentRequestContext.CurrentStore.Settings.MaxOrderMessage;

            int     totalItems  = context.Order.Items.Sum(y => y.Quantity);
            decimal totalWeight = context.Order.TotalWeightOfShippingItems();

            if ((totalItems > maxItems) || (totalWeight > maxWeight))
            {
                context.Errors.Add(new BusinessRules.WorkflowMessage("Order Too Large", maxMessage, true));
                return(false);
            }
            else
            {
                return(true);
            }
        }
        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);
        }
Exemple #10
0
        public override bool Execute(OrderTaskContext context)
        {
            var u = context.HccApp.MembershipServices.Customers.FindByEmail(context.Order.UserEmail).FirstOrDefault();

            if (u != null)
            {
                if (u.Bvin != string.Empty)
                {
                    context.UserId = u.Bvin;
                    return(true);
                }
            }

            var n = new CustomerAccount();

            n.Email = context.Order.UserEmail;
            var length = WebAppSettings.PasswordMinimumLength;

            if (length < 8)
            {
                length = 8;
            }
            var newPassword = PasswordGenerator.GeneratePassword(length);

            n.Password  = newPassword;
            n.FirstName = context.Order.ShippingAddress.FirstName;
            n.LastName  = context.Order.ShippingAddress.LastName;

            if (context.HccApp.MembershipServices.CreateCustomer(n, n.Password))
            {
                // Update Addresses for Customer
                context.Order.BillingAddress.CopyTo(n.BillingAddress);
                context.Order.ShippingAddress.CopyTo(n.ShippingAddress);
                context.HccApp.MembershipServices.UpdateCustomer(n);
                context.Order.CustomProperties.Add("hcc", "allowpasswordreset", "1");

                // Email Password to Customer
                var hccRequestContext = HccRequestContextUtils.GetContextWithCulture(context.RequestContext,
                                                                                     context.Order.UsedCulture);
                var contentService = Factory.CreateService <ContentService>(hccRequestContext);
                var t = contentService.GetHtmlTemplateOrDefault(HtmlTemplateType.ForgotPassword);
                if (t != null)
                {
                    var replacers = new List <IReplaceable>();
                    replacers.Add(n);
                    replacers.Add(new Replaceable("[[NewPassword]]", newPassword));
                    t = t.ReplaceTagsInTemplate(hccRequestContext, replacers);

                    var m = t.ConvertToMailMessage(n.Email);
                    if (!MailServices.SendMail(m, hccRequestContext.CurrentStore))
                    {
                        EventLog.LogEvent("Create Account During Checkout",
                                          "Failed to send email to new customer " + n.Email, EventLogSeverity.Warning);
                    }
                }
            }
            context.UserId = n.Bvin;

            return(true);
        }
 public override bool Rollback(OrderTaskContext context)
 {
     EventLog.LogEvent("Order Workflow",
                       "Order number " + context.Order.OrderNumber + " was assigned but the order was not completed. The cart ID is " + context.Order.bvin,
                       EventLogSeverity.Information);
     return(true);
 }
Exemple #12
0
        public override bool Execute(OrderTaskContext context)
        {
            bool allowed = false;

            if (context.MTApp.CurrentRequestContext != null)
            {
                allowed = context.MTApp.CurrentRequestContext.CurrentStore.Settings.AllowZeroDollarOrders;
            }
            if (!allowed)
            {
                if (context.Order.TotalOrderBeforeDiscounts - context.Order.TotalOrderDiscounts <= 0)
                {
                    WorkflowMessage errorMessage = new WorkflowMessage("Error", "Zero dollar orders are not allowed on this store.", true);
                    context.Errors.Add(errorMessage);
                    return(false);
                }
            }

            if (context.Order.Items.Count < 1)
            {
                WorkflowMessage error2 = new WorkflowMessage("Error", "The system was unable to process your order and may be busy. Please try again.", true);
                context.Errors.Add(error2);
                return(false);
            }
            return(true);
        }
Exemple #13
0
        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);
        }
Exemple #14
0
        public override bool Execute(OrderTaskContext context)
        {
            try
            {
                if (context.Order.ApplyVATRules && !context.Order.IsRecurring)
                {
                    var toEmail = context.Order.UserEmail;

                    if (!string.IsNullOrEmpty(toEmail))
                    {
                        var hccRequestContext = HccRequestContextUtils.GetContextWithCulture(context.RequestContext,
                                                                                             context.Order.UsedCulture);
                        var contentService = Factory.CreateService <ContentService>(hccRequestContext);
                        var t = contentService.GetHtmlTemplateOrDefault(HtmlTemplateType.VATInvoice);
                        t = t.ReplaceTagsInTemplate(hccRequestContext, context.Order, context.Order.ItemsAsReplaceable());

                        var m = t.ConvertToMailMessage(toEmail);
                        MailServices.SendMail(m, hccRequestContext.CurrentStore);
                    }
                }
            }
            catch (Exception ex)
            {
                EventLog.LogEvent(ex);
            }

            return(true);
        }
Exemple #15
0
		public override bool Execute(OrderTaskContext context)
		{

            Content.HtmlTemplate t = context.MTApp.ContentServices.GetHtmlTemplateOrDefault(Content.HtmlTemplateType.NewOrder);

            string EmailSelection = _ToEmail;
            string toEmail = context.Order.UserEmail;
		
			switch (EmailSelection) {
				case "Admin":
                    toEmail = context.MTApp.CurrentRequestContext.CurrentStore.Settings.MailServer.EmailForNewOrder;
                    break;			
				case "Custom":
                    toEmail = CustomEmail;
                    break;
			}

			try {
				if (toEmail.Trim().Length > 0) {
                    
                    t = t.ReplaceTagsInTemplate(context.MTApp,context.Order, context.Order.ItemsAsReplaceable());
					
					System.Net.Mail.MailMessage m = new System.Net.Mail.MailMessage();
					m = t.ConvertToMailMessage(toEmail);
					if (m != null) {
						Utilities.MailServices.SendMail(m, context.MTApp.CurrentStore);
					}
				}
			}
			catch (Exception ex) {
				EventLog.LogEvent(ex);
			}

			return true;
		}
        public override bool Execute(OrderTaskContext context)
        {
            if (context.Order != null)
            {
                string issued = context.Order.CustomProperties.GetProperty("bvsoftware", "rewardspointsissued");
                if (issued == "1") return true;

                // skip if there is no user account
                if (context.UserId == string.Empty) return true;

                bool hasPointsPayment = false;
                foreach (OrderTransaction t in context.MTApp.OrderServices.Transactions.FindForOrder(context.Order.bvin))
                {
                    if (t.Action == MerchantTribe.Payment.ActionType.RewardPointsInfo)
                    {
                        hasPointsPayment = true;
                        break;
                    }
                }

                // Don't issue points when paying with points
                if (hasPointsPayment) return true;

                CustomerPointsManager pointsManager = CustomerPointsManager.InstantiateForDatabase(context.MTApp.CurrentRequestContext.CurrentStore.Settings.RewardsPointsIssuedPerDollarSpent,
                                                                                context.MTApp.CurrentRequestContext.CurrentStore.Settings.RewardsPointsNeededPerDollarCredit,
                                                                                context.MTApp.CurrentRequestContext.CurrentStore.Id);
                int pointsToIssue = pointsManager.PointsToIssueForSpend(context.Order.TotalOrderAfterDiscounts);

                pointsManager.IssuePoints(context.Order.UserID, pointsToIssue);
                context.Order.CustomProperties.SetProperty("bvsoftware", "rewardspointsissued", "1");
                context.MTApp.OrderServices.Orders.Update(context.Order);
            }
            return true;
        }
Exemple #17
0
 public override bool Execute(OrderTaskContext context)
 {
     if (context.Inputs["PreviousShippingStatus"] != null)
     {
         var val    = 0;
         var parsed = int.TryParse(context.Inputs["PreviousShippingStatus"].Value, out val);
         if (parsed && val == (int)OrderShippingStatus.FullyShipped)
         {
             if (context.Order.ShippingStatus != OrderShippingStatus.NonShipping &&
                 context.Order.ShippingStatus != OrderShippingStatus.FullyShipped)
             {
                 var statusCode  = OrderStatusCode.Received;
                 var orderStatus = OrderStatusCode.FindByBvin(statusCode);
                 if (orderStatus != null && orderStatus.Bvin != string.Empty)
                 {
                     context.Order.StatusCode = orderStatus.Bvin;
                     context.Order.StatusName = orderStatus.StatusName;
                 }
                 else
                 {
                     EventLog.LogEvent("Change Order Status When Shipment Removed",
                                       "Could not find order status with id of " + statusCode, EventLogSeverity.Error);
                 }
             }
         }
     }
     return(true);
 }
Exemple #18
0
        public override bool Execute(OrderTaskContext context)
        {
            var result = true;

            foreach (var orderItem in context.Order.Items)
            {
                var product = context.HccApp.CatalogServices.Products.FindWithCache(orderItem.ProductId);

                if (product != null)
                {
                    if (product.IsRecurring)
                    {
                        ProcessRecurringProduct(context, orderItem.Quantity, product);
                    }
                    else if (!product.IsBundle)
                    {
                        ProcessSingleProduct(context, orderItem.Quantity, product);
                    }
                    else
                    {
                        foreach (var bundledProduct in product.BundledProducts)
                        {
                            ProcessSingleProduct(context, bundledProduct.Quantity, bundledProduct.BundledProduct);
                        }
                    }
                }
                else
                {
                    result = false;
                }
            }

            return(result);
        }
Exemple #19
0
        private List <TransactionItem> GetLineItemsForTransaction(OrderTaskContext context, string orderNumber)
        {
            var repo  = new OrderRepository(context.HccApp.CurrentRequestContext);
            var order = repo.FindByOrderNumber(orderNumber);

            if (order != null && order.OrderNumber == orderNumber)
            {
                var items = new List <TransactionItem>();

                foreach (var item in order.Items)
                {
                    items.Add(new TransactionItem
                    {
                        Sku           = item.ProductSku,
                        LineTotal     = item.LineTotal,
                        Description   = item.ProductShortDescription,
                        IsNonShipping = item.IsNonShipping
                    });
                }

                return(items);
            }

            return(null);
        }
        private bool SendEmail(OrderTaskContext context, VendorManufacturer vendorOrManufacturer, Order order)
        {
            var storeSettingsProvider = Factory.CreateStoreSettingsProvider();
            var defaultCulture        = storeSettingsProvider.GetDefaultLocale();
            var hccRequestContext     = HccRequestContextUtils.GetContextWithCulture(context.RequestContext, defaultCulture);
            var contentService        = Factory.CreateService <ContentService>(hccRequestContext);

            var toEmail = vendorOrManufacturer.EmailAddress;

            HtmlTemplate t            = null;
            var          templateBvin = vendorOrManufacturer.DropShipEmailTemplateId;

            if (templateBvin != string.Empty)
            {
                long templateId = 0;
                long.TryParse(templateBvin, out templateId);
                t = contentService.HtmlTemplates.Find(templateId);
            }
            if (t == null)
            {
                t = contentService.GetHtmlTemplateOrDefault(HtmlTemplateType.DropShippingNotice);
            }

            if (!string.IsNullOrEmpty(toEmail))
            {
                var replacers = new List <IReplaceable>();
                replacers.Add(order);
                replacers.Add(vendorOrManufacturer);
                t = t.ReplaceTagsInTemplate(hccRequestContext, replacers, order.ItemsAsReplaceable());

                var m = t.ConvertToMailMessage(toEmail);
                return(MailServices.SendMail(m, hccRequestContext.CurrentStore));
            }
            return(false);
        }
        protected void EmailPasswordToCustomer(OrderTaskContext context, CustomerAccount n)
        {
            try
            {
                var hccRequestContext = HccRequestContextUtils.GetContextWithCulture(context.RequestContext,
                                                                                     context.Order.UsedCulture);
                var contentService = Factory.CreateService <ContentService>(hccRequestContext);
                var t = context.HccApp.ContentServices.GetHtmlTemplateOrDefault(HtmlTemplateType.ForgotPassword);

                if (t != null)
                {
                    var replacers = new List <IReplaceable>();
                    replacers.Add(n);
                    replacers.Add(new Replaceable("[[NewPassword]]", n.Password));
                    t = t.ReplaceTagsInTemplate(hccRequestContext, replacers);

                    var m = t.ConvertToMailMessage(n.Email);

                    if (!MailServices.SendMail(m, hccRequestContext.CurrentStore))
                    {
                        EventLog.LogEvent("Create Account During Checkout",
                                          "Failed to send email to new customer " + n.Email, EventLogSeverity.Warning);
                    }
                }
            }
            catch (Exception ex)
            {
                EventLog.LogEvent(ex);
            }
        }
        public override bool Execute(OrderTaskContext context)
        {
            var manufacturers = new Collection <string>();
            var vendors       = new Collection <string>();

            foreach (var item in context.Order.Items)
            {
                if (item.IsBundle)
                {
                    continue;
                }
                if (item.ShipFromMode == ShippingMode.ShipFromManufacturer)
                {
                    if (!string.IsNullOrEmpty(item.ShipFromNotificationId))
                    {
                        if (!manufacturers.Contains(item.ShipFromNotificationId))
                        {
                            manufacturers.Add(item.ShipFromNotificationId);
                        }
                    }
                    else
                    {
                        EventLog.LogEvent("RunAllDropShipWorkflows",
                                          "Item with sku " + item.ProductSku +
                                          " is marked as Ship From Manufacturer, but contains no Manufacturer Id",
                                          EventLogSeverity.Warning);
                    }
                }
                else if (item.ShipFromMode == ShippingMode.ShipFromVendor)
                {
                    if (!string.IsNullOrEmpty(item.ShipFromNotificationId))
                    {
                        if (!vendors.Contains(item.ShipFromNotificationId))
                        {
                            vendors.Add(item.ShipFromNotificationId);
                        }
                    }
                    else
                    {
                        EventLog.LogEvent("RunAllDropShipWorkflows",
                                          "Item with sku " + item.ProductSku +
                                          " is marked as Ship From Vendor, but contains no Vendor Id", EventLogSeverity.Warning);
                    }
                }
            }

            foreach (var item in manufacturers)
            {
                var manufacturer = context.HccApp.ContactServices.Manufacturers.Find(item);
                ProcessVendorManufacturer(context, manufacturer);
            }

            foreach (var item in vendors)
            {
                var vendor = context.HccApp.ContactServices.Vendors.Find(item);
                ProcessVendorManufacturer(context, vendor);
            }

            return(true);
        }
Exemple #23
0
        public bool OrdersShipPackage(OrderPackage package, Order order)
        {
            if (order == null)
            {
                throw new NullReferenceException("order");
            }

            if (package == null)
            {
                throw new NullReferenceException("package");
            }

            package.HasShipped = true;
            OrdersShipItems(package, order);

            var c = new OrderTaskContext(CurrentRequestContext);

            c.Order  = order;
            c.UserId = CurrentCustomerId;
            if (!Workflow.RunByName(c, WorkflowNames.PackageShipped))
            {
                EventLog.LogEvent("PackageShippedWorkflow", "Package Shipped Workflow Failed", EventLogSeverity.Debug);
                foreach (var item in c.Errors)
                {
                    EventLog.LogEvent("PackageShippedWorkflow", item.Description, EventLogSeverity.Debug);
                }
            }
            return(true);
        }
Exemple #24
0
        public override bool Execute(OrderTaskContext context)
        {
            foreach (var item in context.Order.Items)
            {
                if (item.IsGiftCard)
                {
                    var product = item.GetAssociatedProduct(context.HccApp);

                    // assign if issue to line item additional props
                    var gcsAlreadyIssued = item.CustomProperties.GetPropertyAsInt("hcc", "giftCardsIssued");
                    var gcsToIssue       = 0;
                    if (gcsAlreadyIssued < item.Quantity)
                    {
                        gcsToIssue = item.Quantity - gcsAlreadyIssued;
                    }

                    for (var i = 0; i < gcsToIssue; i++)
                    {
                        AddNewGiftCard(context, item);
                    }

                    item.CustomProperties.SetProperty("hcc", "giftCardsIssued", item.Quantity);
                }
            }

            return(true);
        }
Exemple #25
0
        public override bool Execute(OrderTaskContext context)
        {
            var order = context.Order;

            if (order != null)
            {
                var hccApp = context.HccApp;
                var store  = hccApp.CurrentStore;

                if (order.CustomProperties.HccRewardsPointsIssued ||
                    !store.Settings.RewardsPointsEnabled ||
                    string.IsNullOrEmpty(context.UserId)) // skip if there is no user account
                {
                    return(true);
                }

                var pointsAmount = GetPointsAmount(order, hccApp);
                var orderTotal   = GetOrderTotal(order, store);

                if (orderTotal > pointsAmount)
                {
                    var pointsManager = new CustomerPointsManager(hccApp.CurrentRequestContext);

                    var pointsToIssue = pointsManager.PointsToIssueForSpend(orderTotal - pointsAmount);
                    pointsManager.IssuePoints(order.UserID, pointsToIssue);

                    order.CustomProperties.HccRewardsPointsIssued = true;
                    hccApp.OrderServices.Orders.Update(order);
                }
            }

            return(true);
        }
        private void ProcessPaymentErrorOrder(CheckoutViewModel model)
        {
            // Save as Order
            var c = new OrderTaskContext
            {
                UserId = HccApp.CurrentCustomerId,
                Order  = model.CurrentOrder
            };

            c.Inputs.SetProperty("hcc", "CardSecurityCode", model.PaymentViewModel.DataCreditCard.SecurityCode);

            if (Workflow.RunByName(c, WorkflowNames.ProcessNewOrderPayments))
            {
                // Clear Pending Cart ID because payment is good
                SessionManager.SetCurrentPaymentPendingCartId(HccApp.CurrentStore, string.Empty);

                // Process Post Payment Stuff
                Workflow.RunByName(c, WorkflowNames.ProcessNewOrderAfterPayments);
                var tempOrder = HccApp.OrderServices.Orders.FindForCurrentStore(model.CurrentOrder.bvin);
                HccApp.CurrentRequestContext.IntegrationEvents.OrderReceived(tempOrder, HccApp);
                SessionManager.AnalyticsOrderId = model.CurrentOrder.bvin;
                Response.Redirect(Url.RouteHccUrl(HccRoute.Checkout,
                                                  new { action = "receipt", id = model.CurrentOrder.bvin }));
            }
        }
        private void PopulateFraudData(Security.FraudCheckData d, OrderTaskContext context)
        {
            if (context.MTApp.CurrentRequestContext.RoutingContext.HttpContext != null)
            {
                if (context.MTApp.CurrentRequestContext.RoutingContext.HttpContext.Request.UserHostAddress != null)
                {
                    d.IpAddress = context.MTApp.CurrentRequestContext.RoutingContext.HttpContext.Request.UserHostAddress;
                }
            }

            if (context.Order.UserEmail != string.Empty)
            {
                d.EmailAddress = context.Order.UserEmail;
                string[] parts = d.EmailAddress.Split('@');
                if (parts.Length > 1)
                {
                    d.DomainName = parts[1];
                }
            }

            d.PhoneNumber = context.Order.BillingAddress.Phone;

            foreach (Orders.OrderTransaction p in context.MTApp.OrderServices.Transactions.FindForOrder(context.Order.bvin))
            {
                if (p.Action == MerchantTribe.Payment.ActionType.CreditCardInfo)
                {
                    d.CreditCard = p.CreditCard.CardNumber;
                    break;
                }
            }
        }
        protected override void CreateAccount(OrderTaskContext context, CustomerAccount n)
        {
            try
            {
                if (context.HccApp.MembershipServices.CreateCustomer(n, n.Password))
                {
                    if (string.IsNullOrEmpty(context.HccApp.CurrentCustomerId))
                    {
                        LoginNewUser(context, n);
                    }

                    // Update Addresses for Customer
                    context.Order.BillingAddress.CopyTo(n.BillingAddress);
                    context.Order.ShippingAddress.CopyTo(n.ShippingAddress);
                    context.HccApp.MembershipServices.UpdateCustomer(n);

                    if (_isCreateGuestAccount)
                    {
                        context.Order.CustomProperties.Add("hcc", "allowpasswordreset", "1");

                        AssignToGuestRole(n);
                    }

                    // Email Password to Customer
                    EmailPasswordToCustomer(context, n);
                }
            }
            catch (Exception ex)
            {
                LogError(ex);
                EventLog.LogEvent(ex);
            }
        }
		private void PopulateFraudData(Security.FraudCheckData d, OrderTaskContext context)
		{            
			if (context.MTApp.CurrentRequestContext.RoutingContext.HttpContext != null) {
				if (context.MTApp.CurrentRequestContext.RoutingContext.HttpContext.Request.UserHostAddress != null) {
					d.IpAddress = context.MTApp.CurrentRequestContext.RoutingContext.HttpContext.Request.UserHostAddress;
				}
			}
			
            if (context.Order.UserEmail != string.Empty) {
				d.EmailAddress = context.Order.UserEmail;
				string[] parts = d.EmailAddress.Split('@');
				if (parts.Length > 1) {
					d.DomainName = parts[1];
				}
			}
			
            d.PhoneNumber = context.Order.BillingAddress.Phone;

            foreach (Orders.OrderTransaction p in context.MTApp.OrderServices.Transactions.FindForOrder(context.Order.bvin))
            {
                if (p.Action == MerchantTribe.Payment.ActionType.CreditCardInfo)
                {
					d.CreditCard = p.CreditCard.CardNumber;
                    break; 
				}				
			}
		}
        public override bool Execute(OrderTaskContext context)
        {
            var result = true;

            if (context.Order.IsRecurring)
            {
                _app        = context.HccApp;
                _payManager = new OrderPaymentManager(context.Order, _app);
                var infoList     = _payManager.RecurringSubscriptionInfoListAll();
                var transactions = _app.OrderServices.Transactions.FindForOrder(context.Order.bvin);

                foreach (var info in infoList)
                {
                    info.CreditCard.SecurityCode = context.Inputs.GetProperty("hcc", "CardSecurityCode");

                    foreach (var li in context.Order.Items)
                    {
                        if (HasSuccessfulLinkedAction(transactions, info, li.Id))
                        {
                            var note = new OrderNote("Skipping creation of subscription. Transaction " + info.Id);
                            context.Order.Notes.Add(note);
                        }
                        else
                        {
                            result &= ProcessTransaction(context, info, li);
                        }
                    }
                }
            }

            return(result);
        }
 public override bool Execute(OrderTaskContext context)
 {
     if (context.Inputs["PreviousPaymentStatus"] != null)
     {
         int val = 0;
         if (int.TryParse(context.Inputs["PreviousPaymentStatus"].Value, out val))
         {
             if ((val == (int)Orders.OrderPaymentStatus.Paid) && (context.Order.PaymentStatus != Orders.OrderPaymentStatus.Paid))
             {
                 string statusCode = Orders.OrderStatusCode.Received;
                 Orders.OrderStatusCode orderStatus = Orders.OrderStatusCode.FindByBvin(statusCode);
                 if (orderStatus != null && orderStatus.Bvin != string.Empty)
                 {
                     context.Order.StatusCode = orderStatus.Bvin;
                     context.Order.StatusName = orderStatus.StatusName;
                 }
                 else
                 {
                     EventLog.LogEvent("Change Order Status When Payment Removed", "Could not find order status with id of " + statusCode, EventLogSeverity.Error);
                 }
             }
         }
     }
     return(true);
 }
        public void ForwardToCheckout(CartViewModel model)
        {
            if (Request["paypalexpress"] != null && Request["paypalexpress"] == "true")
            {
                ForwardToPayPalExpress(model);
            }

            OrderTaskContext c = new OrderTaskContext(MTApp);

            c.UserId = SessionManager.GetCurrentUserId(MTApp.CurrentStore);
            c.Order  = model.CurrentOrder;
            if (Workflow.RunByName(c, WorkflowNames.CheckoutSelected))
            {
                Response.Redirect(MTApp.StoreUrl(true, false) + "checkout");
            }
            else
            {
                bool customerMessageFound = false;
                foreach (WorkflowMessage msg in c.Errors)
                {
                    EventLog.LogEvent(msg.Name, msg.Description, EventLogSeverity.Error);
                    if (msg.CustomerVisible)
                    {
                        customerMessageFound = true;
                        this.FlashFailure(msg.Description);
                    }
                }
                if (!customerMessageFound)
                {
                    EventLog.LogEvent("Checkout Selected Workflow", "Checkout failed but no errors were recorded.", EventLogSeverity.Error);
                    this.FlashFailure("Checkout Failed. If problem continues, please contact customer support.");
                }
            }
        }
		public override bool Execute(OrderTaskContext context)
		{
			for (int i = 0; i <= 5; i++) {
				WorkflowMessage errorMessage = new WorkflowMessage("Error", "This error is error number " + i.ToString(), true);
				context.Errors.Add(errorMessage);
			}
			return false;
		}
 public override bool Execute(OrderTaskContext context)
 {
     Orders.OrderNote note = new Orders.OrderNote();
     note.IsPublic = false;
     note.Note = this.Note;            
     context.Order.Notes.Add(note);            
     return true;
 }
Exemple #35
0
 public override bool Execute(OrderTaskContext context)
 {
     if (context.Order.ShippingStatus == OrderShippingStatus.FullyShipped)
     {
         return(Workflow.RunByName(context, WorkflowNames.ShippingComplete));
     }
     return(true);
 }
 public override bool Execute(OrderTaskContext context)
 {
     Orders.OrderNote note = new Orders.OrderNote();
     note.IsPublic = false;
     note.Note     = this.Note;
     context.Order.Notes.Add(note);
     return(true);
 }
		public override bool Execute(OrderTaskContext context)
		{
			bool result = true;

			foreach (Orders.OrderTransaction p in context.MTApp.OrderServices.Transactions.FindForOrder(context.Order.bvin)) {

                List<Orders.OrderTransaction> transactions = context.MTApp.OrderServices.Transactions.FindForOrder(context.Order.bvin);

                if (p.Action == MerchantTribe.Payment.ActionType.CreditCardInfo ||
                    p.Action == MerchantTribe.Payment.ActionType.CreditCardHold)
                {
                    // if we already have an auth or charge on the card, skip
                    if (p.HasSuccessfulLinkedAction(MerchantTribe.Payment.ActionType.CreditCardCharge, transactions) ||
                        p.HasSuccessfulLinkedAction(MerchantTribe.Payment.ActionType.CreditCardHold, transactions))
                    {
                        continue;
                    }

                    try
                    {
                        MerchantTribe.Payment.Transaction t = context.Order.GetEmptyTransaction();
                        t.Card = p.CreditCard;
                        t.Amount = p.Amount;

                        if (p.Action == MerchantTribe.Payment.ActionType.CreditCardHold)
                        {
                            t.Action = MerchantTribe.Payment.ActionType.CreditCardCapture;
                        }
                        else
                        {
                            t.Action = MerchantTribe.Payment.ActionType.CreditCardCharge;
                        }

                        MerchantTribe.Payment.Method proc = context.MTApp.CurrentRequestContext.CurrentStore.Settings.PaymentCurrentCreditCardProcessor();
                        proc.ProcessTransaction(t);

                        Orders.OrderTransaction ot = new Orders.OrderTransaction(t);
                        ot.LinkedToTransaction = p.IdAsString;

                        context.MTApp.OrderServices.AddPaymentTransactionToOrder(context.Order, ot, context.MTApp);

                        if (t.Result.Succeeded == false) result = false;

                    }
                    catch (Exception ex)
                    {
                        context.Errors.Add(new WorkflowMessage("Exception During Complete Credit Card", ex.Message + ex.StackTrace, false));
                    }
                }

                Orders.OrderPaymentStatus previousPaymentStatus = context.Order.PaymentStatus;
                context.MTApp.OrderServices.EvaluatePaymentStatus(context.Order);
                context.Inputs.Add("bvsoftware", "PreviousPaymentStatus", previousPaymentStatus.ToString());
                BusinessRules.Workflow.RunByName(context, WorkflowNames.PaymentChanged);
			}

			return result;
		}
		public override bool Execute(OrderTaskContext context)
		{
			if (context.Order.ShippingStatus == Orders.OrderShippingStatus.FullyShipped) {
				return BusinessRules.Workflow.RunByName(context, WorkflowNames.ShippingComplete);
			}
			else {
				return true;
			}
		}
		public override bool Execute(OrderTaskContext context)
		{
			if (context.Order.TotalOrderBeforeDiscounts < context.MTApp.CurrentRequestContext.CurrentStore.Settings.MinumumOrderAmount) {
                context.Errors.Add(new BusinessRules.WorkflowMessage("Minimum Order Amount", context.MTApp.CurrentRequestContext.CurrentStore.Settings.MinumumOrderAmount.ToString("c"), true));
				return false;
			}
			else {
				return true;
			}
		}
		public override bool Execute(OrderTaskContext context)
		{
			if ((context.Order.ShippingStatus == Orders.OrderShippingStatus.FullyShipped) && (context.Order.PaymentStatus == Orders.OrderPaymentStatus.Paid)) {
				Orders.OrderStatusCode orderStatus = Orders.OrderStatusCode.FindByBvin(OrderStatusCode.Completed);
				if (orderStatus != null) {
					context.Order.StatusCode = orderStatus.Bvin;
					context.Order.StatusName = orderStatus.StatusName;
				}
			}
			return true;
		}
		public override bool Rollback(OrderTaskContext context)
		{
            // No Rollback for this. Never unplace an order

            //context.MTApp.OrdersUnreserveInventoryForAllItems(context.Order);
            //context.Order.IsPlaced = false;
            //context.Order.StatusCode = string.Empty;
            //context.Order.StatusName = "Shopping Cart";
            //context.MTApp.OrderServices.Orders.Update(context.Order);
			return true;
		}
        public override bool Execute(OrderTaskContext context)
        {
            CustomerAccount u = context.MTApp.MembershipServices.Customers.FindByEmail(context.Order.UserEmail);
            if (u != null)
            {
                if (u.Bvin != string.Empty)
                {
                    return true;
                }
            }

            CustomerAccount n = new CustomerAccount();
            n.Email = context.Order.UserEmail;
            int length = WebAppSettings.PasswordMinimumLength;
            if (length < 8) length = 8;
            string newPassword = MerchantTribe.Web.PasswordGenerator.GeneratePassword(length);
            n.Password = newPassword;
            n.FirstName = context.Order.ShippingAddress.FirstName;
            n.LastName = context.Order.ShippingAddress.LastName;

            if (context.MTApp.MembershipServices.CreateCustomer(n, n.Password))
            {
                // Update Addresses for Customer
                context.Order.BillingAddress.CopyTo(n.BillingAddress);
                context.Order.ShippingAddress.CopyTo(n.ShippingAddress);
                context.MTApp.MembershipServices.UpdateCustomer(n);
                context.Order.CustomProperties.Add("bvsoftware", "allowpasswordreset", "1");

                // Email Password to Customer
                HtmlTemplate t = context.MTApp.ContentServices.GetHtmlTemplateOrDefault(HtmlTemplateType.ForgotPassword);
                if (t != null)
                {
                    System.Net.Mail.MailMessage m;

                    List<IReplaceable> replacers = new List<IReplaceable>();
                    replacers.Add(n);
                    replacers.Add(new Replaceable("[[NewPassword]]", newPassword));
                    t = t.ReplaceTagsInTemplate(context.MTApp, replacers);

                    m = t.ConvertToMailMessage(n.Email);

                    if (MailServices.SendMail(m) == false)
                    {
                        EventLog.LogEvent("Create Account During Checkout", "Failed to send email to new customer " + n.Email, EventLogSeverity.Warning);
                    }
                }
            }
            context.UserId = n.Bvin;

            return true;
        }
        public override bool Execute(OrderTaskContext context)
        {
            // Assign Order Number
            if (context.Order.OrderNumber == string.Empty)
            {
                context.Order.OrderNumber = context.MTApp.OrderServices.GenerateNewOrderNumber(context.MTApp.CurrentRequestContext.CurrentStore.Id).ToString();

                Orders.OrderNote note = new Orders.OrderNote();
                note.IsPublic = false;
                note.Note = "This order was assigned number " + context.Order.OrderNumber;
                context.Order.Notes.Add(note);                
            }
            return true;
        }
		public override bool Execute(OrderTaskContext context)
		{
			if (context.UserId != string.Empty) {
				Membership.CustomerAccount user = context.MTApp.MembershipServices.Customers.Find(context.UserId);
                if (user == null) return true;

                context.Order.ShippingAddress.CopyTo(user.ShippingAddress);
                if (!context.Order.BillingAddress.IsEqualTo(context.Order.ShippingAddress))
                {
                    context.Order.BillingAddress.CopyTo(user.BillingAddress);
                }
				context.MTApp.MembershipServices.UpdateCustomer(user);
			}
			return true;
		}
		public override bool Execute(OrderTaskContext context)
		{
			try {
				if (context.UserId.Trim() == string.Empty) {
                    if (context.MTApp.CurrentRequestContext.RoutingContext.HttpContext != null)
                    {
                        context.MTApp.CurrentRequestContext.RoutingContext.HttpContext.Response.Redirect("~/login.aspx?ReturnTo=Checkout");
					}
				}
			}
			catch (Exception ex){
                EventLog.LogEvent(ex);
			}
			return true;
		}
        public override bool Execute(OrderTaskContext context)
        {
            bool result = true;
            if (context.MTApp.OrderServices.PaymentSummary(context.Order).AmountDue > 0)
            {
                CustomerPointsManager pointsManager = CustomerPointsManager.InstantiateForDatabase(context.MTApp.CurrentRequestContext.CurrentStore.Settings.RewardsPointsIssuedPerDollarSpent,
                                                                                context.MTApp.CurrentRequestContext.CurrentStore.Settings.RewardsPointsNeededPerDollarCredit,
                                                                                context.MTApp.CurrentRequestContext.CurrentStore.Id);
                Orders.OrderPaymentManager payManager = new Orders.OrderPaymentManager(context.Order,
                                                                                       context.MTApp);

                foreach (Orders.OrderTransaction p in context.MTApp.OrderServices.Transactions.FindForOrder(context.Order.bvin))
                {
                    List<Orders.OrderTransaction> transactions = context.MTApp.OrderServices.Transactions.FindForOrder(context.Order.bvin);

                    if (p.Action == MerchantTribe.Payment.ActionType.RewardPointsInfo)
                    {
                        // if we already have an auth or charge on the card, skip
                        if (p.HasSuccessfulLinkedAction(MerchantTribe.Payment.ActionType.RewardPointsDecrease, transactions) ||
                            p.HasSuccessfulLinkedAction(MerchantTribe.Payment.ActionType.RewardPointsHold, transactions))
                        {
                            continue;
                        }

                        try
                        {
                            payManager.RewardsPointsHold(p, p.Amount);                                                     
                        }
                        catch (Exception ex)
                        {
                            context.Errors.Add(new WorkflowMessage("Exception During Receive Credit Card", ex.Message + ex.StackTrace, false));
                        }

                    }
                }

                // Evaluate Payment Status After Receiving Payments
                Orders.OrderPaymentStatus previousPaymentStatus = context.Order.PaymentStatus;
                context.MTApp.OrderServices.EvaluatePaymentStatus(context.Order);
                context.Inputs.Add("bvsoftware", "PreviousPaymentStatus", previousPaymentStatus.ToString());
                BusinessRules.Workflow.RunByName(context, WorkflowNames.PaymentChanged);
            }
            
            return result;
        }
		public override bool Execute(OrderTaskContext context)
		{
			if (context.Inputs["PreviousPaymentStatus"] != null) {
				int val = 0;
				if (int.TryParse(context.Inputs["PreviousPaymentStatus"].Value,out val)) {
					if ((val == (int)Orders.OrderPaymentStatus.Paid) && (context.Order.PaymentStatus != Orders.OrderPaymentStatus.Paid)) {
						string statusCode =  Orders.OrderStatusCode.Received;						
						Orders.OrderStatusCode orderStatus = Orders.OrderStatusCode.FindByBvin(statusCode);
						if (orderStatus != null && orderStatus.Bvin != string.Empty) {
							context.Order.StatusCode = orderStatus.Bvin;
							context.Order.StatusName = orderStatus.StatusName;
						}
						else {
							EventLog.LogEvent("Change Order Status When Payment Removed", "Could not find order status with id of " + statusCode, EventLogSeverity.Error);
						}
					}
				}
			}
			return true;
		}
		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.", Content.SiteTerms.GetTerm(Content.SiteTermIds.OrderAlreadyPlaced), true));
                return false;
            }

       

			context.Order.IsPlaced = true;
			context.Order.TimeOfOrderUtc = DateTime.UtcNow;            
			//if (!WebAppSettings.DisableInventory) {				
					List<string> errors = new List<string>();
					if (!context.MTApp.OrdersReserveInventoryForAllItems(context.Order,errors)) {
						foreach (string item in errors) {
							context.Errors.Add(new WorkflowMessage("Stock Too Low", item, true));
						}
						return false;
					}				
			//}

                    if (context.MTApp.CurrentRequestContext.RoutingContext.HttpContext != null)
                    {
				Orders.OrderNote note = new Orders.OrderNote();
                note.IsPublic = false;
                note.Note = "Customer IP: " + context.MTApp.CurrentRequestContext.RoutingContext.HttpContext.Request.UserHostAddress;
                note.Note += "<br> Customer Host: " + context.MTApp.CurrentRequestContext.RoutingContext.HttpContext.Request.UserHostName;
                note.Note += "<br> Browser: " + context.MTApp.CurrentRequestContext.RoutingContext.HttpContext.Request.UserAgent;
				context.Order.Notes.Add(note);
			}

			Orders.OrderStatusCode c = Orders.OrderStatusCode.FindByBvin(Orders.OrderStatusCode.Received);
			if (c != null) {
				context.Order.StatusName = c.StatusName;
				context.Order.StatusCode = c.Bvin;
                context.Order.AffiliateID = context.MTApp.ContactServices.GetValidAffiliateId(context.MTApp).ToString();
			}
			return true;
		}
        public override bool Execute(OrderTaskContext context)
        {
            int      maxItems  = context.MTApp.CurrentRequestContext.CurrentStore.Settings.MaxItemsPerOrder;
            if (maxItems <= 0) maxItems = 99999;
            decimal maxWeight = context.MTApp.CurrentRequestContext.CurrentStore.Settings.MaxWeightPerOrder;
            if (maxWeight <= 0) maxWeight = 99999;
            string maxMessage = context.MTApp.CurrentRequestContext.CurrentStore.Settings.MaxOrderMessage;

            int totalItems = context.Order.Items.Sum(y => y.Quantity);
            decimal totalWeight = context.Order.TotalWeightOfShippingItems();

            if ((totalItems > maxItems) || (totalWeight > maxWeight))
            {
                context.Errors.Add(new BusinessRules.WorkflowMessage("Order Too Large", maxMessage, true));
                return false;
            }
            else
            {
                return true;
            }
        }
		public override bool Execute(OrderTaskContext context)
		{
			if (context.Order != null) {
				foreach (Orders.LineItem item in context.Order.Items) {
                    //if ((item.AssociatedProduct.IsGiftCertificate)) {
                    //    Collection<Catalog.GiftCertificate> gcsAlreadyIssued = Catalog.GiftCertificate.FindByLineItem(item.Bvin);
                    //    int gcsToIssue = 0;
                    //    if (gcsAlreadyIssued.Count < item.Quantity) {
                    //        gcsToIssue = (int)item.Quantity - gcsAlreadyIssued.Count;
                    //    }
                    //    for (int i = 0; i <= ((int)gcsToIssue - 1); i++) {
                    //        Catalog.GiftCertificate gc = new Catalog.GiftCertificate();
                    //        gc.AssociatedProductId = item.ProductId;
                    //        gc.OriginalAmount = item.AdjustedPrice;
                    //        gc.LineItemId = item.Bvin;
                    //        if (!Catalog.GiftCertificate.Insert(gc)) {
                    //            WorkflowMessage message = new WorkflowMessage("Gift Certificate Insert Failed", "Gift Certificate for line item " + item.Bvin + " in order " + context.Order.OrderNumber + " failed.", false);
                    //            context.Errors.Add(message);
                    //        }
                    //        else {
                    //            if (context.Order.UserEmail != string.Empty) {
                    //                Content.EmailTemplate template = Content.EmailTemplate.FindByBvin("34f5dffd-03ab-4bc9-b305-cd15020045ca");
                    //                System.Net.Mail.MailMessage m = new System.Net.Mail.MailMessage();
                    //                if (gc != null) {
                    //                    m = template.ConvertToMailMessage(template.From, gc, context.Order.UserEmail);
                    //                }

                    //                if (m != null) {
                    //                    Utilities.MailServices.SendMail(m);
                    //                }
                    //            }
                    //        }
                    //    }
                    //}
				}
			}
			return true;
		}
		public override bool Execute(OrderTaskContext context)
		{
            bool allowed = false;
            if (context.MTApp.CurrentRequestContext != null)
            {
                allowed = context.MTApp.CurrentRequestContext.CurrentStore.Settings.AllowZeroDollarOrders;
            }
			if (!allowed) {
				if (context.Order.TotalOrderBeforeDiscounts - context.Order.TotalOrderDiscounts <= 0) {
					WorkflowMessage errorMessage = new WorkflowMessage("Error", "Zero dollar orders are not allowed on this store.", true);
					context.Errors.Add(errorMessage);
					return false;
				}
			}

            if (context.Order.Items.Count < 1)
            {
                WorkflowMessage error2 = new WorkflowMessage("Error", "The system was unable to process your order and may be busy. Please try again.", true);
                context.Errors.Add(error2);
                return false;
            }
			return true;
		}
		public override bool Execute(OrderTaskContext context)
		{
			bool result = true;

			if (context.Order != null) {
				Security.FraudCheckData d = new Security.FraudCheckData();
				PopulateFraudData(d, context);

                FraudScorer scorer = new FraudScorer(context.MTApp.CurrentRequestContext);

                context.Order.FraudScore = scorer.ScoreData(d);

				if (context.Order.FraudScore >= 5) {					
					Orders.OrderStatusCode s = Orders.OrderStatusCode.FindByBvin(Orders.OrderStatusCode.OnHold);
					context.Order.StatusCode = s.Bvin;
					context.Order.StatusName = s.StatusName;
                    context.MTApp.OrderServices.Orders.Update(context.Order);
				}

                if (d.Messages.Count > 0)
                {
                    Orders.OrderNote n = new Orders.OrderNote();
                    n.IsPublic = false;
                    n.Note = "Fraud Check Failed";
                    foreach (string m in d.Messages)
                    {
                        n.Note += " | " + m;
                    }                    
                    context.Order.Notes.Add(n);                    
                }

                context.MTApp.OrderServices.Orders.Update(context.Order);

			}

			return result;
		}
 public override bool Rollback(OrderTaskContext context)
 {
     return true;
 }
		public override bool Rollback(OrderTaskContext context)
		{
			context.Order.StatusCode = OrderStatusCode.Received;
			return true;
		}
		public override bool Rollback(OrderTaskContext context)
		{
			context.Order.UserID = string.Empty;
			return true;
		}
		public override bool Execute(OrderTaskContext context)
		{
			context.Order.UserID = context.UserId;
			return true;
		}
		public override bool Execute(OrderTaskContext context)
		{
			if (context.Inputs["Mode"] != null) {
				if (context.Inputs["Mode"].Value == "PaypalExpress") {
                    if (context.MTApp.CurrentRequestContext.RoutingContext.HttpContext != null)
                    {
						PayPalAPI ppAPI = Utilities.PaypalExpressUtilities.GetPaypalAPI(context.MTApp.CurrentStore);
						try {

                            string cartReturnUrl = string.Empty;
                            string cartCancelUrl = string.Empty;
                            if (context.MTApp.CurrentRequestContext != null)
                            {
                                cartReturnUrl = context.MTApp.CurrentRequestContext.CurrentStore.RootUrlSecure() + "paypalexpresscheckout";
                                cartCancelUrl = context.MTApp.CurrentRequestContext.CurrentStore.RootUrlSecure() + "checkout";
                            }

                            EventLog.LogEvent("PayPal Express Checkout", "CartCancelUrl=" + cartCancelUrl, EventLogSeverity.Information);
                            EventLog.LogEvent("PayPal Express Checkout", "CartReturnUrl=" + cartReturnUrl, EventLogSeverity.Information);

							SetExpressCheckoutResponseType expressResponse;
							PaymentActionCodeType mode = PaymentActionCodeType.Authorization;

                            if (context.MTApp.CurrentRequestContext.CurrentStore.Settings.PayPal.ExpressAuthorizeOnly)
                            {
								mode = PaymentActionCodeType.Order;
							}
							else {
								mode = PaymentActionCodeType.Sale;
							}

                            // Accelerated boarding
                            if (context.MTApp.CurrentRequestContext.CurrentStore.Settings.PayPal.UserName.Trim().Length < 1) mode = PaymentActionCodeType.Sale;


							bool addressSupplied = false;
							if (context.Inputs["AddressSupplied"] != null) {
								if (context.Inputs["AddressSupplied"].Value == "1") {
									addressSupplied = true;
									context.Order.CustomProperties.Add("bvsoftware", "PaypalAddressOverride", "1");
								}
							}

							string amountToPayPal = context.Order.TotalOrderBeforeDiscounts.ToString("N", System.Globalization.CultureInfo.CreateSpecificCulture("en-US"));

							if (addressSupplied) {
								Contacts.Address address = context.Order.ShippingAddress;

								MerchantTribe.Web.Geography.Country country = MerchantTribe.Web.Geography.Country.FindByBvin(address.CountryBvin);
								if (country != null) {
                                    expressResponse = ppAPI.SetExpressCheckout(
                                        amountToPayPal, 
                                        cartReturnUrl, 
                                        cartCancelUrl, 
                                        mode,
                                        PayPalAPI.GetCurrencyCodeType(context.MTApp.CurrentRequestContext.CurrentStore.Settings.PayPal.Currency), 
                                        address.FirstName + " " + address.LastName, 
                                        country.IsoCode, 
                                        address.Line1, 
                                        address.Line2, 
                                        address.City,
									    address.RegionBvin, 
                                        address.PostalCode, 
                                        address.Phone, 
                                        context.Order.OrderNumber + System.Guid.NewGuid().ToString());
                                    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 {
                                expressResponse = ppAPI.SetExpressCheckout(amountToPayPal, 
                                                                        cartReturnUrl, 
                                                                        cartCancelUrl, 
                                                                        mode,
                                                                        PayPalAPI.GetCurrencyCodeType(context.MTApp.CurrentRequestContext.CurrentStore.Settings.PayPal.Currency), 
                                                                        context.Order.OrderNumber + System.Guid.NewGuid().ToString());
                                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.MTApp.OrderServices.Orders.Update(context.Order))
                                {
                                    if (string.Compare(context.MTApp.CurrentRequestContext.CurrentStore.Settings.PayPal.Mode, "Live", true) == 0)
                                    {
										context.MTApp.CurrentRequestContext.RoutingContext.HttpContext.Response.Redirect("https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + expressResponse.Token, true);
									}
									else {
                                        context.MTApp.CurrentRequestContext.RoutingContext.HttpContext.Response.Redirect("https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + 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", Content.SiteTerms.GetTerm(Content.SiteTermIds.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", Content.SiteTerms.GetTerm(Content.SiteTermIds.PaypalCheckoutCustomerError), true));
							return false;
						}
						finally {
							ppAPI = null;
						}
					}
				}
				else {
					return true;
				}
			}
			else {
				return true;
			}

            return false;
		}
		public override bool Execute(OrderTaskContext context)
		{
			bool result = true;

            if (context.MTApp.OrderServices.PaymentSummary(context.Order).AmountDue > 0)
            {

                foreach (OrderTransaction p in context.MTApp.OrderServices.Transactions.FindForOrder(context.Order.bvin))
                {
                    List<OrderTransaction> transactions = context.MTApp.OrderServices.Transactions.FindForOrder(context.Order.bvin);

                    if (p.Action == MerchantTribe.Payment.ActionType.PayPalExpressCheckoutInfo)
                    {
                        // if we already have an auth or charge on the card, skip
                        if (p.HasSuccessfulLinkedAction(MerchantTribe.Payment.ActionType.PayPalHold, transactions) ||
                            p.HasSuccessfulLinkedAction(MerchantTribe.Payment.ActionType.PayPalCharge, transactions))
                        {
                            continue;
                        }

                        try
                        {
                            Orders.OrderPaymentManager payManager = new OrderPaymentManager(context.Order,
                                                                                            context.MTApp);

                            bool transactionSuccess = false;

                            if (context.MTApp.CurrentRequestContext.CurrentStore.Settings.PayPal.ExpressAuthorizeOnly)
                            {
                                transactionSuccess = payManager.PayPalExpressHold(p, context.MTApp.OrderServices.PaymentSummary(context.Order).AmountDue);
                            }
                            else
                            {
                                transactionSuccess = payManager.PayPalExpressCharge(p, context.MTApp.OrderServices.PaymentSummary(context.Order).AmountDue);
                            }

                            if (transactionSuccess == false) result = false;
                        }
                        catch (Exception ex)
                        {
                            context.Errors.Add(new WorkflowMessage("Exception During Receive Paypal Express Payments", ex.Message + ex.StackTrace, false));
                        }
                        finally
                        {
                            Orders.OrderPaymentStatus previousPaymentStatus = context.Order.PaymentStatus;
                            context.MTApp.OrderServices.EvaluatePaymentStatus(context.Order);
                            context.Inputs.Add("bvsoftware", "PreviousPaymentStatus", previousPaymentStatus.ToString());
                            BusinessRules.Workflow.RunByName(context, WorkflowNames.PaymentChanged);
                        }
                    }
                }                                                               
			}

			if (result == false) {

				// Add Error
                bool throwErrors = true;
				//throwErrors = this.SettingsManager.GetBooleanSetting("ThrowErrors");
				if (throwErrors == true) {
					if (result == false) {
                        string errorString = string.Empty; // this.SettingsManager.GetSetting("CustomerErrorMessage");
						if (errorString == string.Empty) {
							errorString = "An error occured while attempting to process your Paypal Express payment. Please check your payment information and try again";
						}
						context.Errors.Add(new WorkflowMessage("Receive Card Failed", errorString, true));
					}
				}
				else {
					// Hide Error
					result = true;
				}

				// Failure Status Code
				bool SetStatus = false;
                SetStatus = true; // this.SettingsManager.GetBooleanSetting("SetStatusOnFail");
				if (SetStatus == true) {
					string failCode = Orders.OrderStatusCode.OnHold;					
					Orders.OrderStatusCode c = Orders.OrderStatusCode.FindByBvin(failCode);
					if (c != null) {
						context.Order.StatusCode = c.Bvin;
						context.Order.StatusName = c.StatusName;
					}
				}

			}
			return result;
		}
		public override bool Execute(OrderTaskContext context)
		{
			Collection<string> manufacturers = new Collection<string>();
			Collection<string> vendors = new Collection<string>();
			foreach (Orders.LineItem item in context.Order.Items) {

					
						if (item.ShipFromMode == Shipping.ShippingMode.ShipFromManufacturer) {
							if (item.ShipFromNotificationId != string.Empty) {
								if (!manufacturers.Contains(item.ShipFromNotificationId)) {
									manufacturers.Add(item.ShipFromNotificationId);
								}
							}
							else {
								EventLog.LogEvent("RunAllDropShipWorkflows.bv", "Item with sku " + item.ProductSku + " is marked as Ship From Manufacturer, but contains no Manufacturer Id", EventLogSeverity.Warning);
							}
						}
						else if (item.ShipFromMode == Shipping.ShippingMode.ShipFromVendor) {
							if (item.ShipFromNotificationId != string.Empty) {
								if (!vendors.Contains(item.ShipFromNotificationId)) {
									vendors.Add(item.ShipFromNotificationId);
								}
							}
							else {
								EventLog.LogEvent("RunAllDropShipWorkflows.bv", "Item with sku " + item.ProductSku + " is marked as Ship From Vendor, but contains no Vendor Id", EventLogSeverity.Warning);
							}
						}
					
								
			}
			
			foreach (string item in manufacturers) {
                Contacts.VendorManufacturer mfg = context.MTApp.ContactServices.Manufacturers.Find(item);
				if (mfg != null) {
					if (mfg.Bvin != string.Empty) {
						bool success = false;
                        //if (WebAppSettings.SendDropShipNotificationsThroughWebService) {
                        //    itemsNeedToBeDropShipped = true;
                        //    success = true;
                        //}
                        //else {
                        if (!SendEmail(context.MTApp, mfg, context.Order))
                        {
								Orders.OrderNote n = new Orders.OrderNote();
                                n.IsPublic = false;
								n.Note = "Drop shipper notices for " + mfg.DisplayName + " were not able to send correctly.";
								context.Order.Notes.Add(n);
                                context.MTApp.OrderServices.Orders.Upsert(context.Order);
							}
							else {
								success = true;
							}
						//}

						if (success) {
							Orders.OrderNote n = new Orders.OrderNote();
                            n.IsPublic = false;
							n.Note = "Drop shipper notices for " + mfg.DisplayName + " were sent successfully.";
							context.Order.Notes.Add(n);
                            context.MTApp.OrderServices.Orders.Upsert(context.Order);
						}
					}
				}
			}

			foreach (string item in vendors) {
                Contacts.VendorManufacturer vendor = context.MTApp.ContactServices.Vendors.Find(item);
				if (vendor != null) {
					if (vendor.Bvin != string.Empty) {
						bool success = false;
                        //if (WebAppSettings.SendDropShipNotificationsThroughWebService) {
                        //    itemsNeedToBeDropShipped = true;
                        //    success = true;
                        //}
                        //else {
                        if (!SendEmail(context.MTApp, vendor, context.Order))
                        {
								Orders.OrderNote n = new Orders.OrderNote();
								n.IsPublic = false;
								n.Note = "Drop shipper notices for " + vendor.DisplayName + " were not able to send correctly.";
								context.Order.Notes.Add(n);
                                context.MTApp.OrderServices.Orders.Upsert(context.Order);
							}
							else {
								success = true;
							}
						//}

						if (success) {
							Orders.OrderNote n = new Orders.OrderNote();
							n.IsPublic = false;
							n.Note = "Drop shipper notices for " + vendor.DisplayName + " were sent successfully.";
							context.Order.Notes.Add(n);
                            context.MTApp.OrderServices.Orders.Upsert(context.Order);
						}
					}
				}
			}

            //if (itemsNeedToBeDropShipped) {
            //    return LogDropShipNotification(context.Order);
            //}
			return true;
		}
		public override bool Execute(OrderTaskContext context)
		{
			bool result = true;
            if (context.MTApp.OrderServices.PaymentSummary(context.Order).AmountDue > 0)
            {

                foreach (Orders.OrderTransaction p in context.MTApp.OrderServices.Transactions.FindForOrder(context.Order.bvin))
                {
                    List<Orders.OrderTransaction> transactions = context.MTApp.OrderServices.Transactions.FindForOrder(context.Order.bvin);

                    if (p.Action == MerchantTribe.Payment.ActionType.CreditCardInfo)
                    {
                        // if we already have an auth or charge on the card, skip
                        if (p.HasSuccessfulLinkedAction(MerchantTribe.Payment.ActionType.CreditCardCharge, transactions) ||
                            p.HasSuccessfulLinkedAction(MerchantTribe.Payment.ActionType.CreditCardHold, transactions))
                        {
                            Orders.OrderNote note = new Orders.OrderNote();
                            note.IsPublic = false;
                            note.Note = "Skipping receive for credit card info because auth or charge already exists. Transaction " + p.Id;
                            context.Order.Notes.Add(note);
                            continue;
                        }

                        try
                        {
                            MerchantTribe.Payment.Transaction t = context.Order.GetEmptyTransaction();
                            t.Card = p.CreditCard;
                            t.Amount = p.Amount;

                            if (context.MTApp.CurrentRequestContext.CurrentStore.Settings.PaymentCreditCardAuthorizeOnly == true)
                            {
                                t.Action = MerchantTribe.Payment.ActionType.CreditCardHold;
                            }
                            else
                            {
                                t.Action = MerchantTribe.Payment.ActionType.CreditCardCharge;
                            }

                            MerchantTribe.Payment.Method proc = context.MTApp.CurrentRequestContext.CurrentStore.Settings.PaymentCurrentCreditCardProcessor();
                            proc.ProcessTransaction(t);

                            Orders.OrderTransaction ot = new Orders.OrderTransaction(t);
                            ot.LinkedToTransaction = p.IdAsString;
                            context.MTApp.OrderServices.AddPaymentTransactionToOrder(context.Order, ot, context.MTApp);

                            if (t.Result.Succeeded == false) result = false;

                        }
                        catch (Exception ex)
                        {
                            context.Errors.Add(new WorkflowMessage("Exception During Receive Credit Card", ex.Message + ex.StackTrace, false));
                            Orders.OrderNote note = new Orders.OrderNote();
                            note.IsPublic = false;
                            note.Note = "EXCEPTION: " + ex.Message + " | " + ex.StackTrace;
                            context.Order.Notes.Add(note);
                        }

                    }
                }

                // Evaluate Payment Status After Receiving Payments
                Orders.OrderPaymentStatus previousPaymentStatus = context.Order.PaymentStatus;
                context.MTApp.OrderServices.EvaluatePaymentStatus(context.Order);
                context.Inputs.Add("bvsoftware", "PreviousPaymentStatus", previousPaymentStatus.ToString());
                BusinessRules.Workflow.RunByName(context, WorkflowNames.PaymentChanged);
            }
            else
            {
                Orders.OrderNote note = new Orders.OrderNote();
                note.IsPublic = false;
                note.Note = "Amount due was less than zero. Skipping receive credit cards";
                context.Order.Notes.Add(note);             
            }

            

			if (result == false) {

				// Add Error
				bool throwErrors = false;
                throwErrors = context.MTApp.CurrentRequestContext.CurrentStore.Settings.RejectFailedCreditCardOrdersAutomatically;
				if (throwErrors == true) {
					if (result == false) {
                        string errorString = string.Empty; // this.SettingsManager.GetSetting("CustomerErrorMessage");
						if (errorString == string.Empty) {
							errorString = "An error occured while attempting to process your credit card. Please check your payment information and try again";
						}
						context.Errors.Add(new WorkflowMessage("Receive Card Failed", errorString, true));
					}
				}
				else {
					// Hide Error
					result = true;
				}

				// Failure Status Code
				bool SetStatus = false;
                SetStatus = true; // this.SettingsManager.GetBooleanSetting("SetStatusOnFail");
				if (SetStatus == true) {
					string failCode = Orders.OrderStatusCode.OnHold;
					Orders.OrderStatusCode c = Orders.OrderStatusCode.FindByBvin(failCode);
					if (c != null) {
						context.Order.StatusCode = c.Bvin;
						context.Order.StatusName = c.StatusName;
					}
				}

			}
			return result;
		}