public override UpdateCartParameter MapParameter(CartModel cartModel, HttpRequestMessage request)
        {
            UpdateCartParameter updateCartParameter1 = new UpdateCartParameter();

            updateCartParameter1.CartId = cartModel.Id.ToCurrentOrGuid();
            updateCartParameter1.Status = cartModel.Status;
            ShipToModel shipTo = cartModel.ShipTo;

            updateCartParameter1.ShipToId  = shipTo != null ? new Guid?(shipTo.Id.ToGuid()) : new Guid?();
            updateCartParameter1.ShipViaId = cartModel.ShipVia?.Id;
            updateCartParameter1.Notes     = cartModel.Notes;
            updateCartParameter1.PoNumber  = cartModel.PoNumber;
            updateCartParameter1.TermsCode = cartModel.PaymentMethod?.Name;
            PaymentMethodDto paymentMethod = cartModel.PaymentMethod;

            updateCartParameter1.RequestedDeliveryDate = cartModel.RequestedDeliveryDate;
            UpdateCartParameter updateCartParameter2 = updateCartParameter1;

            if (cartModel.PaymentOptions != null && cartModel.PaymentOptions.IsPayPal)
            {
                updateCartParameter2.IsPayPal          = cartModel.PaymentOptions.IsPayPal;
                updateCartParameter2.PaypalRedirectUrl = cartModel.PaymentOptions.PayPalPaymentUrl;
                if (cartModel.Status == "Submitted")
                {
                    updateCartParameter2.PayPalPayerId = cartModel.PaymentOptions.PayPalPayerId;
                    updateCartParameter2.PayPalToken   = cartModel.PaymentOptions.PayPalToken;
                }
            }
            if (!cartModel.Status.EqualsIgnoreCase("Submitted") && !cartModel.Status.EqualsIgnoreCase("CreateSmartSupply") && !cartModel.Status.EqualsIgnoreCase("SaveNewCard") && !cartModel.Status.EqualsIgnoreCase("PayInvoice")) //BUSA-PIO
            {
                return(updateCartParameter2);
            }

            updateCartParameter2.PaymentMethod = cartModel.PaymentMethod;
            //if (cartModel.PaymentMethod.IsCreditCard)
            if (cartModel.PaymentOptions.PaymentMethods.Count > 0) /*BUSA-619 : Card Information popup becomes unresponsive on clicking save button.*/
            {
                updateCartParameter2.CreditCard = cartModel.PaymentOptions.CreditCard;
            }
            updateCartParameter2.StorePaymentProfile = cartModel.PaymentOptions.StorePaymentProfile;
            if (cartModel.PaymentMethod != null && cartModel.PaymentMethod.IsPaymentProfile)
            {
                updateCartParameter2.IsPaymentProfile = true;
                updateCartParameter2.PaymentProfileId = cartModel.PaymentMethod.Name;
            }
            //BUSA-1170 Added order level property for sample product
            if (cartModel.CartLines.Where(cl => cl.Properties.ContainsKey("isSampleCartLine") && cl.Properties.ContainsValue("true")).Count() > 0)
            {
                cartModel.Properties.Add("isSampleOrder", "true");
            }
            updateCartParameter2.Properties = cartModel.Properties; //
            return(updateCartParameter2);
        }
        public virtual void Execute(DataSet dataSet, CancellationToken cancellationToken)
        {
            CustomerOrder subscriptionOrder = null;

            try
            {
                // Fetching job parameters.
                var jobParameters = this.IntegrationJob.IntegrationJobParameters;
                if (jobParameters == null || jobParameters.Count <= 0)
                {
                    return;
                }

                var subscriptionOrderId = Guid.Empty;

                foreach (var jobParameter in jobParameters)
                {
                    // Check for null or empty for the job parameter value.
                    if (!string.IsNullOrEmpty(jobParameter.Value))
                    {
                        if (jobParameter.JobDefinitionStepParameter.Name.EqualsIgnoreCase("Ship Now"))
                        {
                            shipNow = bool.Parse(jobParameter.Value);
                        }
                        else if (jobParameter.JobDefinitionStepParameter.Name.EqualsIgnoreCase("SmartSupplyOrderId"))
                        {
                            subscriptionOrderId = Guid.Parse(jobParameter.Value);
                        }
                    }

                    // Assigning the job parameter value i.e Customer Order ID in order to pull the customer order.

                }

                // Pull the customer order based on the job parameter value.
                this.UnitOfWork.BeginTransaction();
                subscriptionOrder = this.UnitOfWork.GetRepository<CustomerOrder>().GetTable().FirstOrDefault(x => x.Id == subscriptionOrderId);

                if (subscriptionOrder == null)
                {
                    return;
                }

                // Validate subscription deactivation date before processing next order.
                var subscriptionBrasselerOrder = this.UnitOfWork.GetRepository<SubscriptionBrasseler>().GetTable().Where(x => x.CustomerOrderId == subscriptionOrder.Id).FirstOrDefault();

                if (subscriptionBrasselerOrder != null && subscriptionOrder.Status.EqualsIgnoreCase("SubscriptionOrder"))
                {
                    if (subscriptionBrasselerOrder.DeActivationDate != null)
                    {
                        if (subscriptionBrasselerOrder.DeActivationDate >= DateTimeOffset.Now.Date)
                        {
                            // Retrieve the subscription order to set the SiteContext object and frequency of the subscription order.

                            var userProfile = this.UnitOfWork.GetRepository<UserProfile>().GetTable().FirstOrDefault(x => x.Id == subscriptionOrder.InitiatedByUserProfileId);
                            var billTo = this.UnitOfWork.GetRepository<Customer>().GetTable().FirstOrDefault(x => x.Id == subscriptionOrder.CustomerId);
                            var shipTo = this.UnitOfWork.GetRepository<Customer>().GetTable().FirstOrDefault(x => x.Id == subscriptionOrder.ShipToId);
                            var website = this.UnitOfWork.GetRepository<Website>().GetTable().FirstOrDefault(x => x.Id == subscriptionOrder.WebsiteId);
                            var currency = this.UnitOfWork.GetRepository<Currency>().GetTable().FirstOrDefault(x => x.Id == subscriptionOrder.CurrencyId);

                            // Check for null before setting up the SiteContext object.
                            if (userProfile == null || billTo == null || shipTo == null)
                            {
                                return;
                            }

                            // Set the SiteContext object.
                            SiteContext.SetSiteContext(new SiteContextDto(SiteContext.Current) { UserProfileDto = new UserProfileDto(userProfile), BillTo = billTo, ShipTo = shipTo, WebsiteDto = new WebsiteDto(website), CurrencyDto = new CurrencyDto(currency) });
                            //create new Cart
                            var cart = CreateNewCart(this.UnitOfWork, subscriptionOrder);
                            //Insert in SubscriptionBrasseler
                            if (cart == null)
                            {
                                return;
                            }
                            cart.RecalculatePromotions = true;
                            cart.RecalculateTax = true;
                            this.pricingPipeline.GetCartPricing(new GetCartPricingParameter(cart)
                            {
                                CalculateShipping = true,
                                CalculateTaxes = true,
                                CalculateOrderTotal = true,
                                ForceRecalculation = true,

                            });
                            /*BUSA-755 Smart supply discount issue when user added product qualifies for VDG and smart supply feature*/
                            var newSubscriptionBrasseler = CreateSubscriptionBrasseler(subscriptionBrasselerOrder, cart);
                            if (newSubscriptionBrasseler == null)
                            {
                                return;
                            }
                            // Recalculate the cart to have customer order updated based on Promotion, Tax, Shipping and Handling.
                            //this.pricingPipeline.GetCartPricing(this.UnitOfWork, cart, (OrderLine)null, true);

                            // Build up the update cart paramter.
                            var updateCartParameter = new UpdateCartParameter();
                            updateCartParameter.CartId = cart.Id;

                            if (!string.IsNullOrEmpty(newSubscriptionBrasseler.PaymentMethod))
                            {
                                if (newSubscriptionBrasseler.PaymentMethod.EqualsIgnoreCase("CK"))
                                {
                                    updateCartParameter.IsPaymentProfile = false;
                                    updateCartParameter.TermsCode = "CK";
                                }
                                else
                                {
                                    Guid userPaymentprofileId = Guid.Parse(newSubscriptionBrasseler.PaymentMethod);
                                    var userPaymentprofile = this.UnitOfWork.GetRepository<UserPaymentProfile>().GetTable().Where(x => x.Id == userPaymentprofileId).FirstOrDefault();
                                    if (userPaymentprofile != null)
                                    {
                                        updateCartParameter.PaymentProfileId = userPaymentprofile.CardIdentifier;
                                        updateCartParameter.IsPaymentProfile = true;
                                        updateCartParameter.TermsCode = "CC";
                                    }
                                }
                            }
                            updateCartParameter.Status = "Submitted";
                            updateCartParameter.IsJobQuote = false;
                            updateCartParameter.IsPayPal = false;
                            updateCartParameter.ShipToId = cart.ShipToId;
                            updateCartParameter.ShipViaId = cart.ShipViaId;

                            IHandler<UpdateCartParameter, UpdateCartResult> handler = this.HandlerFactory.GetHandler<IHandler<UpdateCartParameter, UpdateCartResult>>();
                            IUnitOfWork unitOfWork = this.UnitOfWork;
                            var updateCartSubmitResult = handler.Execute(unitOfWork, updateCartParameter, updateCartResult);
                            newSubscriptionBrasseler.NextDelieveryDate = new DateTimeOffset(DateTimeProvider.Current.Now.AddDays(subscriptionBrasselerOrder.Frequency).DateTime, TimeSpan.Zero);
                            this.UnitOfWork.CommitTransaction();
                        }
                    }
                }
            }

            catch (Exception ex)
            {
                LogHelper.For(this).Error(ex);

                if (ex.Message == "Value cannot be null.\r\nParameter name: siteContext")
                {
                    JobLogger.Error("CC Declined");
                    //BUSA-1076 - start: Send Email Notification for SS Failure due to CC decline when triggered from admin console with CC added for sp and ism
                    if (!shipNow)
                    {
                        EmailList orCreateByName_USA = this.UnitOfWork.GetTypedRepository<IEmailListRepository>().GetOrCreateByName("SmartSupplyOrderFailureUSA", "SmartSupplyOrderFailure");
                        EmailList orCreateByName_CA = this.UnitOfWork.GetTypedRepository<IEmailListRepository>().GetOrCreateByName("SmartSupplyOrderFailureCA", "SmartSupplyOrderFailure");
                        EmailList orCreateByName_FR = this.UnitOfWork.GetTypedRepository<IEmailListRepository>().GetOrCreateByName("SmartSupplyOrderFailureFR", "SmartSupplyOrderFailure");
                        dynamic expandoObjects = new ExpandoObject();
                        SendEmailParameter sendEmailParameter = new SendEmailParameter();
                        EmailList emailList_USA = this.UnitOfWork.GetRepository<EmailList>().GetTable().Expand((EmailList x) => x.EmailTemplate).FirstOrDefault((EmailList x) => x.Id == orCreateByName_USA.Id);
                        EmailList emailList_CA = this.UnitOfWork.GetRepository<EmailList>().GetTable().Expand((EmailList x) => x.EmailTemplate).FirstOrDefault((EmailList x) => x.Id == orCreateByName_CA.Id);
                        EmailList emailList_FR = this.UnitOfWork.GetRepository<EmailList>().GetTable().Expand((EmailList x) => x.EmailTemplate).FirstOrDefault((EmailList x) => x.Id == orCreateByName_FR.Id);
                        expandoObjects.OrderNumber = subscriptionOrder.OrderNumber;
                        EmailList emailList = null;
                        expandoObjects.CustomerNumber = subscriptionOrder.CustomerNumber;
                        if (subscriptionOrder != null && !string.IsNullOrEmpty(subscriptionOrder.ShipTo.CustomerSequence))
                        {
                            expandoObjects.CustomerShipToNumber = subscriptionOrder.ShipTo.CustomerSequence;
                        }
                        else
                        {
                            expandoObjects.CustomerShipToNumber = string.Empty;
                        }

                        var languageid = this.UnitOfWork.GetRepository<CustomProperty>().GetTable().Where(x => x.ParentTable == "UserProfile" && x.Name == "userLanguage" && x.ParentId == updateCartResult.GetCartResult.Cart.InitiatedByUserProfileId).FirstOrDefault()?.Value;
                        var languageName = this.UnitOfWork.GetRepository<Language>().GetTable().Where(x => x.Id.ToString() == languageid).FirstOrDefault()?.LanguageCode;

                        string htmlTemplate = string.Empty;
                        if (updateCartResult.GetCartResult.Cart.OrderNumber.StartsWith("W") || languageName == "en-us")
                        {
                            htmlTemplate = GetHtmlTemplate(emailList_USA);
                            emailList = emailList_USA;

                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(languageid) && languageName=="fr-CA")
                            {
                                htmlTemplate = GetHtmlTemplate(emailList_FR);
                                emailList = emailList_FR;

                            }
                            else
                            {
                                htmlTemplate = GetHtmlTemplate(emailList_CA);
                                emailList = emailList_CA;
                            }

                        }
                        sendEmailParameter.Body = this.EmailService.Value.ParseTemplate(htmlTemplate, expandoObjects);
                        sendEmailParameter.Subject = emailList.Subject;
                        sendEmailParameter.ToAddresses.Add(updateCartResult.GetCartResult.Cart.CreatedBy);
                        var emailCCAddresses = this.UnitOfWork.GetRepository<Salesperson>().GetTable().Where(x => x.Id == updateCartResult.GetCartResult.Cart.SalespersonId).FirstOrDefault();
                        var customProperty = this.UnitOfWork.GetRepository<CustomProperty>().GetTable().Where(x => x.ParentId == updateCartResult.GetCartResult.Cart.ShipToId);

                        foreach (var iAmCodeEmail in customProperty)
                        {
                            if (iAmCodeEmail.Name == "IAMCodeEmail")
                            {
                                var insideRepEmail = iAmCodeEmail.Value;

                                if (!string.IsNullOrEmpty(insideRepEmail))
                                {
                                    sendEmailParameter.CCAddresses.Add(insideRepEmail);
                                }
                            }
                        }
                        if ((emailCCAddresses != null) && (!string.IsNullOrEmpty(emailCCAddresses.Email)))
                        {
                            sendEmailParameter.CCAddresses.Add(emailCCAddresses.Email);
                        }

                        string defaultEmailAddress = this.CustomSettings.DefaultEmailAddress;
                        sendEmailParameter.FromAddress = (emailList.FromAddress.IsBlank() ? defaultEmailAddress : emailList.FromAddress);
                        sendEmailParameter.ReplyToAddresses = new List<string>();
                        sendEmailParameter.ExtendedProperties = new NameValueCollection();
                        this.EmailService.Value.SendEmail(sendEmailParameter, this.UnitOfWork);

                    }
                    //BUSA-1076 - end:Send Email Notification for SS Failure due to CC decline when triggered from admin console with CC added  for sp and ism
                }

                throw;
            }
            finally
            {
                if (subscriptionOrder != null)
                {
                    var subscriptionBrasselerOrder = this.UnitOfWork.GetRepository<SubscriptionBrasseler>().GetTable().Where(x => x.CustomerOrderId == subscriptionOrder.Id).FirstOrDefault();
                    if (subscriptionBrasselerOrder.DeActivationDate != null)
                    {
                        if (subscriptionBrasselerOrder.DeActivationDate >= DateTimeOffset.Now.Date)
                        {
                            // Added ship now condition to not update the next delievery date if it is true. Order needs to be placed now. By default value is false.
                            if (subscriptionBrasselerOrder != null)
                            {
                                subscriptionBrasselerOrder.NextDelieveryDate = new DateTimeOffset(DateTimeProvider.Current.Now.AddDays(subscriptionBrasselerOrder.Frequency).DateTime, TimeSpan.Zero);
                            }
                            this.UnitOfWork.Save();
                        }
                    }
                }
            }
        }
        public override AddRmaResult Execute(IUnitOfWork unitOfWork, AddRmaParameter parameter, AddRmaResult result)
        {
            //Uncomment following lines to disable RMA for Canada.
            if (result.OrderHistory.CustomerNumber.ElementAt(0) != '1')
            {
                return(base.NextHandler.Execute(unitOfWork, parameter, result));
            }
            CustomerOrder customerOrder = new CustomerOrder();

            customerOrder = unitOfWork.GetRepository <CustomerOrder>().GetTable().Where(x => x.OrderNumber == result.OrderHistory.WebOrderNumber).FirstOrDefault();

            if (customerOrder == null)
            {
                CreateCustomerOrderRecord createCustomerOrder = new CreateCustomerOrderRecord(this.CartPipeline);
                CustomerOrder             cartObj             = createCustomerOrder.CreateNewCart(unitOfWork, result.OrderHistory, parameter, result);

                if (cartObj == null)
                {
                    return(this.CreateErrorServiceResult(result, SubCode.Forbidden, MessageProvider.Current.Cart_CartNotFound));
                }

                result.Properties.Add("ReturnNumber", cartObj.OrderNumber);
                if (cartObj.Notes != null)
                {
                    result.Properties.Add("InvoiceNumber", cartObj.Notes.Split('/')[0]);
                }

                cartObj.RecalculatePromotions = false;
                cartObj.RecalculateTax        = false;

                // Build up the update cart paramter.
                var updatecartObjParameter = new UpdateCartParameter();

                updatecartObjParameter.CartId     = cartObj.Id;
                updatecartObjParameter.Status     = "Return Requested";
                updatecartObjParameter.IsJobQuote = false;
                updatecartObjParameter.IsPayPal   = false;
                updatecartObjParameter.ShipToId   = cartObj.ShipToId;
                updatecartObjParameter.ShipViaId  = cartObj.ShipViaId;

                IHandler <UpdateCartParameter, UpdateCartResult> updateHandler = this.HandlerFactory.GetHandler <IHandler <UpdateCartParameter, UpdateCartResult> >();
                var updateCartObjSubmitResult = updateHandler.Execute(unitOfWork, updatecartObjParameter, updateCartResult);

                LogHelper.For(this).Info(string.Format("{0}: RMA UpdateCart Message: {1}", string.IsNullOrEmpty(result.OrderHistory.WebOrderNumber) ? result.OrderHistory.ErpOrderNumber : result.OrderHistory.WebOrderNumber, updateCartObjSubmitResult.Message));

                return(base.NextHandler.Execute(unitOfWork, parameter, result));
                //return this.CreateErrorServiceResult(result, SubCode.NotFound, MessageProvider.Current.Order_NotFound);
            }

            var userProfile = unitOfWork.GetRepository <UserProfile>().GetTable().FirstOrDefault(x => x.Id == customerOrder.InitiatedByUserProfileId);
            var billTo      = unitOfWork.GetRepository <Customer>().GetTable().FirstOrDefault(x => x.Id == customerOrder.CustomerId);
            var shipTo      = unitOfWork.GetRepository <Customer>().GetTable().FirstOrDefault(x => x.Id == customerOrder.ShipToId);
            var website     = unitOfWork.GetRepository <Website>().GetTable().FirstOrDefault(x => x.Id == customerOrder.WebsiteId);
            var currency    = unitOfWork.GetRepository <Currency>().GetTable().FirstOrDefault(x => x.Id == customerOrder.CurrencyId);

            // Check for null before setting up the SiteContext object.
            if (userProfile == null || billTo == null || shipTo == null)
            {
                return(this.CreateErrorServiceResult(result, SubCode.NotFound, MessageProvider.Current.Order_NotFound));
            }

            SiteContextDto siteContextDto = new SiteContextDto(SiteContext.Current);

            siteContextDto.UserProfileDto = new UserProfileDto(userProfile);
            siteContextDto.BillTo         = billTo;
            siteContextDto.ShipTo         = shipTo;
            siteContextDto.CurrencyDto    = new CurrencyDto(currency);

            //create new Cart
            CustomerOrder cart = CreateNewCart(unitOfWork, customerOrder, parameter, result);

            if (cart == null)
            {
                return(this.CreateErrorServiceResult(result, SubCode.Forbidden, MessageProvider.Current.Cart_CartNotFound));
            }

            cart.RecalculatePromotions = false;
            cart.RecalculateTax        = false;

            // Build up the update cart paramter.
            var updateCartParameter = new UpdateCartParameter();

            updateCartParameter.CartId     = cart.Id;
            updateCartParameter.Status     = "Return Requested";
            updateCartParameter.IsJobQuote = false;
            updateCartParameter.IsPayPal   = false;
            updateCartParameter.ShipToId   = cart.ShipToId;
            updateCartParameter.ShipViaId  = cart.ShipViaId;

            IHandler <UpdateCartParameter, UpdateCartResult> handler = this.HandlerFactory.GetHandler <IHandler <UpdateCartParameter, UpdateCartResult> >();
            var updateCartSubmitResult = handler.Execute(unitOfWork, updateCartParameter, updateCartResult);

            LogHelper.For(this).Info(string.Format("{0}: RMA UpdateCart Message: {1}", string.IsNullOrEmpty(result.OrderHistory.WebOrderNumber) ? result.OrderHistory.ErpOrderNumber : result.OrderHistory.WebOrderNumber, updateCartSubmitResult.Message));

            return(this.NextHandler.Execute(unitOfWork, parameter, result));
        }