Esempio n. 1
0
        /// <summary>
        /// Saves the campaign source reference.
        /// </summary>
        /// <param name="userId">The user identifier.</param>
        /// <param name="campaignSrcRef">The campaign source reference.</param>
        /// <returns></returns>
        public bool SaveCampaignSourceRef(int userId, CampaignSourceRef campaignSrcRef)
        {
            if (campaignSrcRef == null)
            {
                return(false);
            }

            campaignSrcRef.RSource = campaignSrcRef.RSource ?? "Direct";
            campaignSrcRef.RDate   = campaignSrcRef.RDate ?? DateTime.UtcNow;

            using (var sqlConnection = GetOpenedSqlConnection2()) {
                using (var sqlCommand = new SqlCommand("SaveCampaignSourceRef", sqlConnection.SqlConnection())) {
                    sqlCommand.CommandType = CommandType.StoredProcedure;
                    sqlCommand.Parameters.AddWithValue("CustomerID", userId);

                    var          dataTable           = ConvertToDataTable(campaignSrcRef, new string[] { "Id", "CustomerId" });
                    SqlParameter tableValueParameter = sqlCommand.Parameters.AddWithValue("@Tbl", dataTable);
                    tableValueParameter.SqlDbType = SqlDbType.Structured;

                    return(ExecuteNonQueryAndLog(sqlCommand));
                }
            }
        }
Esempio n. 2
0
        public void TestFullSignUp()
        {
            IContainer container = InitContainer(typeof(CustomerProcessor));

            var customerSignUp = container.GetInstance <CustomerProcessor>();


            string passwordString = GetRandomPassword();
            string emailAddress   = GetRandomEmailAddress();

            var loginInfo = new LoginInfo()
            {
                Password           = new Password(passwordString, passwordString),
                Email              = emailAddress,
                PasswordAnswer     = "bbbb",
                RemoteIp           = "111.111.111.111",
                PasswordQuestionId = 1
            };

            Customer customer = new Customer {
                Name             = emailAddress,
                Id               = GetRundomInteger(2000, int.MaxValue),
                Status           = CustomerStatus.Registered.ToString(),
                RefNumber        = GetRandomPassword(),
                WizardStep       = (int)WizardStepType.SignUp,
                CollectionStatus = (int)CollectionStatusNames.Enabled,
                IsTest           = true,
                IsOffline        = null,
                PromoCode        = "lalala",
                PersonalInfo     =
                {
                    MobilePhone         = "123456789",
                    MobilePhoneVerified = false,
                    FirstName           = GenerateName(),
                    Surname             = GenerateName(),
                    MaritalStatus       = EzBobModels.Enums.MaritalStatus.Married,
                    Gender      = Gender.M,
                    DateOfBirth = DateTime.Today
                },
                TrustPilotStatusID   = (int)TrustPilotStauses.Neither,
                GreetingMailSentDate = DateTime.UtcNow,
                Vip             = false,
                WhiteLabelId    = null,
                BrokerID        = null,
                GoogleCookie    = "kind of google cookie",
                ReferenceSource = "lalalalala",
                AlibabaId       = null,
                IsAlibaba       = false,
                OriginID        = 1
            };

            CampaignSourceRef campaignSourceRef = new CampaignSourceRef()
            {
                RSource = "Direct",
                RDate   = DateTime.UtcNow
            };

            decimal requestedLoan = 10000;
            //TODO: update test for customer address and customer phone (two last nulls)
            var infoAccumulator = customerSignUp.UpdateCustomer(customer, requestedLoan, customer.ReferenceSource, GenerateVisitTimesString(), campaignSourceRef, null, null);

            Assert.False(infoAccumulator.HasErrors, "expected no errors");


            CustomerQueries realCustomerQueries = new CustomerQueries("Server=localhost;Database=ezbob;User Id=ezbobuser;Password=ezbobuser;MultipleActiveResultSets=true");

            var customerQueriesMock = new Mock <ICustomerQueries>();
//            customerQueriesMock.SetupAllProperties();

            Func <string, string, int, string, string, SecurityUser> createUser = (s1, s2, i, s3, s4) => realCustomerQueries.CreateSecurityUser(s1, s2, i, s3, s4);

            customerQueriesMock.Setup(o => o.CreateSecurityUser(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int>(),
                                                                It.IsAny <string>(), It.IsAny <string>()))
            .Returns(createUser);

            customerQueriesMock.Setup(o => o.UpsertCustomer(It.IsAny <Customer>()))
            .Returns(() => null);

            container.Configure(r => r.ForSingletonOf <ICustomerQueries>()
                                .Use(() => customerQueriesMock.Object));

            container.EjectAllInstancesOf <CustomerProcessor>();

            customerSignUp = container.GetInstance <CustomerProcessor>();

            //TODO: update test for customer address and customer phone (two last nulls)
            infoAccumulator = customerSignUp.UpdateCustomer(customer, requestedLoan, customer.ReferenceSource, GenerateVisitTimesString(), campaignSourceRef, null, null);
            Assert.True(infoAccumulator.HasErrors, "expected to have errors");
        }
Esempio n. 3
0
        /// <summary>
        /// Updates customer.
        /// </summary>
        /// <param name="customer">The customer.</param>
        /// <param name="requestedAmount">The requested amount.</param>
        /// <param name="sourceRefList">The source reference list.</param>
        /// <param name="visitTimeList">The visit time list.</param>
        /// <param name="campaignSrcRef">The campaign source reference.</param>
        /// <param name="addresses">The addresses.</param>
        /// <param name="phoneNumbers">The phone numbers.</param>
        /// <returns></returns>
        public InfoAccumulator UpdateCustomer(Customer customer, decimal requestedAmount, string sourceRefList, string visitTimeList,
                                              CampaignSourceRef campaignSrcRef, IEnumerable <CustomerAddress> addresses, IEnumerable <CustomerPhone> phoneNumbers)
        {
            InfoAccumulator info = new InfoAccumulator();

            using (var unitOfWork = new UnitOfWork()) {
                DateTime now = DateTime.UtcNow;

                int customerId = (int)CustomerQueries.UpsertCustomer(customer);
                if (customerId < 1)
                {
                    info.AddError("could not save customer");
                    return(info);
                }

                bool isSuccess = true;

                if (requestedAmount > 0)
                {
                    CustomerRequestedLoan requestedLoan = new CustomerRequestedLoan {
                        CustomerId = customerId,
                        Amount     = requestedAmount,
                        Created    = DateTime.UtcNow
                    };

                    int id = (int)LoanQueries.UpsertCustomerRequestedLoan(requestedLoan);
                    if (id < 1)
                    {
                        info.AddError("could not save requested loan");
                        return(info);
                    }
                }


//                var session = new CustomerSession() {
//                    CustomerId = customer.Id,
//                    StartSession = now,
//                    Ip = customer.LoginInfo != null ? customer.LoginInfo.RemoteIp ?? "unknown" : "unknown",//TODO: review
//                    IsPasswdOk = true,
//                    ErrorMessage = "Registration" //TODO: do something with this
//                };
//
//                isSuccess = CustomerQueries.SaveCustomerSession(session) ?? true;
//                if (!isSuccess) {
//                    info.AddError("could not save customer session");
//                    return info;
//                }

                if (sourceRefList != null && visitTimeList != null)
                {
                    isSuccess = CustomerQueries.SaveSourceRefHistory(customer.Id, sourceRefList, visitTimeList) ?? true;
                    if (!isSuccess)
                    {
                        info.AddError("could not save customer ref history");
                    }
                }

                if (campaignSrcRef != null)
                {
                    isSuccess = CustomerQueries.SaveCampaignSourceRef(customer.Id, campaignSrcRef);
                    if (!isSuccess)
                    {
                        info.AddError("could not save campaign source ref for customer: " + customer.Id);
                        return(info);
                    }
                }

                if (customer.AlibabaId != null && customer.IsAlibaba)
                {
                    AlibabaBuyer alibabaBuyer = new AlibabaBuyer {
                        AliId      = Convert.ToInt64(customer.AlibabaId),
                        CustomerId = customer.Id
                    };

                    isSuccess = AlibabaQueries.CreateAlibabaBuyer(alibabaBuyer) ?? true;
                    if (!isSuccess)
                    {
                        info.AddError("could not create alibaba buyer");
                    }
                }

                if (customer.CustomerAddress != null)
                {
                    customer.CustomerAddress.CustomerId = customer.Id;
                    isSuccess = CustomerQueries.UpsertCustomerAddress(customer.CustomerAddress) ?? true;
                    if (!isSuccess)
                    {
                        info.AddError("could not save customer address");
                    }
                }

                if (CollectionUtils.IsNotEmpty(addresses))
                {
                    foreach (CustomerAddress customerAddress in addresses)
                    {
                        bool?res = CustomerQueries.UpsertCustomerAddress(customerAddress);
                        if (res == null || res.Value == false)
                        {
                            info.AddError("could not save customer address");
                            return(info);
                        }
                    }
                }

                if (CollectionUtils.IsNotEmpty(phoneNumbers))
                {
                    foreach (CustomerPhone phone in phoneNumbers)
                    {
                        bool saveCustomerPhone = CustomerQueries.SaveCustomerPhone(phone);
                        if (!saveCustomerPhone)
                        {
                            info.AddError("could not save customer phone");
                            return(info);
                        }
                    }
                }

                unitOfWork.Commit();
                return(info);
            }
        }
Esempio n. 4
0
        public JsonResult SignUp(
            User model,
            string FirstName,
            string Surname,
            string signupPass1,
            string signupPass2,
            string securityQuestion,
            string mobilePhone,
            string mobileCode,
            string isInCaptchaMode,
            int whiteLabelId
            )
        {
            string    id          = Guid.NewGuid().ToString("N");
            const int idChunkSize = 4;

            string uniqueID = string.Join("-",
                                          Enumerable.Range(0, id.Length / idChunkSize).Select(i => id.Substring(i * idChunkSize, idChunkSize))
                                          );

            log.Debug("Sign up client attempt id: '{0}'...", uniqueID);

            this.cookiesToRemoveOnSignup.Clear();

            if (!ModelState.IsValid)
            {
                return(GetModelStateErrors(ModelState));
            }

            if (model.SecurityAnswer.Length > 199)
            {
                throw new Exception(DbStrings.MaximumAnswerLengthExceeded);
            }

            CustomerOrigin uiOrigin = UiCustomerOrigin.Get();

            string alibabaID = GetAndRemoveCookie("alibaba_id");

            if (uiOrigin.IsAlibaba() && string.IsNullOrWhiteSpace(alibabaID))
            {
                return(Json(new {
                    success = false,
                    errorMessage = "No Alibaba customer id provided.",
                }, JsonRequestBehavior.AllowGet));
            }             // if

            var blm = new WizardBrokerLeadModel(Session);

            CampaignSourceRef campaignSourceRef = null;

            if (!blm.BrokerFillsForCustomer)
            {
                campaignSourceRef = new CampaignSourceRef {
                    FContent = GetAndRemoveCookie("fcontent"),
                    FMedium  = GetAndRemoveCookie("fmedium"),
                    FName    = GetAndRemoveCookie("fname"),
                    FSource  = GetAndRemoveCookie("fsource"),
                    FTerm    = GetAndRemoveCookie("fterm"),
                    FUrl     = GetAndRemoveCookie("furl"),
                    FDate    = ToDate(GetAndRemoveCookie("fdate")),
                    RContent = GetAndRemoveCookie("rcontent"),
                    RMedium  = GetAndRemoveCookie("rmedium"),
                    RName    = GetAndRemoveCookie("rname"),
                    RSource  = GetAndRemoveCookie("rsource"),
                    RTerm    = GetAndRemoveCookie("rterm"),
                    RUrl     = GetAndRemoveCookie("rurl"),
                    RDate    = ToDate(GetAndRemoveCookie("rdate")),
                };
            }             // if

            string visitTimes = GetAndRemoveCookie("sourceref_time");

            var signupModel = new SignupCustomerMultiOriginModel {
                UserName               = model.EMail,
                Origin                 = uiOrigin.GetOrigin(),
                RawPassword            = new DasKennwort(signupPass1),
                RawPasswordAgain       = new DasKennwort(signupPass2),
                PasswordQuestion       = Convert.ToInt32(securityQuestion),
                PasswordAnswer         = model.SecurityAnswer,
                RemoteIp               = RemoteIp(),
                FirstName              = FirstName,
                LastName               = Surname,
                CaptchaMode            = isInCaptchaMode == "True",
                MobilePhone            = mobilePhone,
                MobileVerificationCode = mobileCode,
                BrokerFillsForCustomer = blm.BrokerFillsForCustomer,
                WhiteLabelID           = whiteLabelId,
                IsTest                 = (Request.Cookies["istest"] != null) ? true : (bool?)null,
                CampaignSourceRef      = campaignSourceRef,
                GoogleCookie           = blm.BrokerFillsForCustomer ? string.Empty : GetAndRemoveCookie("__utmz"),
                ReferenceSource        = blm.BrokerFillsForCustomer ? "Broker" : GetAndRemoveCookie("sourceref"),
                AlibabaID              = blm.BrokerFillsForCustomer ? null : GetAndRemoveCookie("alibaba_id"),
                ABTesting              = GetAndRemoveCookie("ezbobab"),
                VisitTimes             = visitTimes,
                FirstVisitTime         = HttpUtility.UrlDecode(visitTimes),
                RequestedLoanAmount    = GetAndRemoveCookie("loan_amount"),
                RequestedLoanTerm      = GetAndRemoveCookie("loan_period"),
                BrokerLeadID           = blm.LeadID,
                BrokerLeadEmail        = blm.LeadEmail,
                BrokerLeadFirstName    = blm.FirstName,
            };

            log.Debug(
                "Sign up client attempt id: '{0}', model is {1}.",
                uniqueID,
                signupModel.ToLogStr()
                );

            try {
                log.Debug("Sign up client attempt id: '{0}', requesting backend sign up.", uniqueID);

                UserLoginActionResult signupResult = this.serviceClient.Instance.SignupCustomerMultiOrigin(signupModel);

                log.Debug("Sign up client attempt id: '{0}', backend sign up complete.", uniqueID);

                MembershipCreateStatus status = (MembershipCreateStatus)Enum.Parse(
                    typeof(MembershipCreateStatus),
                    signupResult.Status
                    );

                log.Debug("Sign up client attempt id: '{0}', status is {1}.", uniqueID, status);

                if (status == MembershipCreateStatus.DuplicateEmail)
                {
                    return(Json(
                               new {
                        success = false,
                        errorMessage = signupResult.ErrorMessage,
                    },
                               JsonRequestBehavior.AllowGet
                               ));
                }                 // if

                if ((status != MembershipCreateStatus.Success) || !string.IsNullOrWhiteSpace(signupResult.ErrorMessage))
                {
                    throw new Exception(string.IsNullOrWhiteSpace(signupResult.ErrorMessage)
                                                ? string.Format("Failed to sign up (error code is '{0}').", uniqueID)
                                                : signupResult.ErrorMessage
                                        );
                }                 // if

                ObjectFactory.GetInstance <IEzbobWorkplaceContext>().SessionId =
                    signupResult.SessionID.ToString(CultureInfo.InvariantCulture);

                Session["UserSessionId"] = signupResult.SessionID;

                this.context.SetSessionOrigin(uiOrigin.GetOrigin());
                FormsAuthentication.SetAuthCookie(model.EMail, false);
                HttpContext.User = new GenericPrincipal(new GenericIdentity(model.EMail), new[] { "Customer" });

                RemoveCookiesOnSignup();

                log.Debug("Sign up client attempt id: '{0}', sign up complete.", uniqueID);

                return(Json(
                           new {
                    success = true,
                    antiforgery_token = AntiForgery.GetHtml().ToString(),
                    refNumber = signupResult.RefNumber,
                },
                           JsonRequestBehavior.AllowGet
                           ));
            } catch (Exception e) {
                log.Alert(e, "Failed to sign up, client attempt id: {0}.", uniqueID);

                return(Json(
                           new {
                    success = false,
                    errorMessage = string.Format(
                        "Failed to sign up, please call support (error code is '{0}').",
                        uniqueID
                        ),
                },
                           JsonRequestBehavior.AllowGet
                           ));
            }     // try
        }         // SignUp