Пример #1
0
 public ActionResult Create(BillType billtype)
 {
     try
     {
         using (var db = new SemplestModel.Semplest())
         {
             db.BillTypes.Add(billtype);
             db.SaveChanges();
         }
         return RedirectToAction("BillType");
     }
     catch
     {
         return View();
     }
 }
Пример #2
0
        public ActionResult ContactUs(SEMCustomerDetail model)
        {
            if (ModelState.IsValid && !(model.CallMe == false && model.EmailMe == false))
            {
                try
                {
                    model.CreatedDate = DateTime.Now;
                    using (var dbContext = new SemplestModel.Semplest())
                    {
                        string semEmail = dbContext.Configurations.Select(m => m.DefalutEmailContactMe).FirstOrDefault();

                        if (model.EmailMe == false)
                        {
                            model.email = "";
                        }
                        else if (model.CallMe == false)
                        {
                            model.Phone = "";
                        }
                        dbContext.SEMCustomerDetails.Add(model);
                        dbContext.SaveChanges();

                        // send email using smtp server
                        if (model.EmailMe == true)
                            SendMail(model, semEmail);
                    }
                }
                catch (Exception ex)
                {
                    string errMsg = "Error: " + ex.Message + "\r\n" + ex.StackTrace;
                    var errModel = new ErrorModel() { MsgToLog = errMsg, MsgToShow = "Error" };
                    return View("ErrorPage", errModel);
                }
                return RedirectToAction("ThankYou");
            }
            else
            {

                return View(model);
            }
        }
Пример #3
0
 public void SaveSiteLinks(CampaignSetupModel model, int customerFk, CampaignSetupModel oldModel)
 {
     bool shouldRefreshSiteLinks = false;
     using (var dbcontext = new SemplestModel.Semplest())
     {
         var queryProd = (from c in dbcontext.ProductGroups
                          where
                              c.CustomerFK == customerFk &&
                              c.ProductGroupName == model.ProductGroup.ProductGroupName
                          select c).Single();
         var promo = GetPromotionFromProductGroup(queryProd, model.ProductGroup.ProductPromotionName);
         List<GoogleSiteLink> sl =
                                   model.SiteLinks.Where(t => !t.Delete).Select(row => new GoogleSiteLink
                                   {
                                       LinkText = row.LinkText,
                                       LinkURL = row.LinkURL
                                   }).ToList();
         if (sl.Any())
         {
             GoogleViolation[] gv = ValidateSiteLinks(sl);
             if (gv.Length > 0)
                 throw new Exception(gv.First().shortFieldPath + ": " + gv.First().errorMessage);
         }
         shouldRefreshSiteLinks = AddSiteLinksToPromotion(promo, model, customerFk, ((IObjectContextAdapter)dbcontext).ObjectContext, oldModel);
         dbcontext.SaveChanges();
         _savedCampaign = true;
         try
         {
             var adEngines = new List<string>();
             if (promo.IsLaunched && shouldRefreshSiteLinks)
             {
                 adEngines.AddRange(
                     promo.PromotionAdEngineSelecteds.Select(pades => pades.AdvertisingEngine.AdvertisingEngine1));
                 var sw = new ServiceClientWrapper();
                 sw.scheduleRefreshSiteLinks(promo.PromotionPK, adEngines);
             }
         }
         catch (Exception ex)
         {
             SharedResources.Helpers.ExceptionHelper.LogException(ex);
         }
     }
 }
        public ActionResult Upload(HttpPostedFileBase uploadFile, CustomerImport imp, FormCollection fc)
        {
            string importstatus;
            importstatus  = "The import was the successful..";
            SemplestModel.Semplest dbcontext = new SemplestModel.Semplest();
            

            {

                StringBuilder strValidations = new StringBuilder(string.Empty);
                try
                {
                    if (uploadFile.ContentLength > 0)
                    {
                        string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
                        Path.GetFileName(uploadFile.FileName));
                        uploadFile.SaveAs(filePath);
                        FileHelperEngine engine = new FileHelperEngine(typeof(CustomerImportData));
                        engine.ErrorManager.ErrorMode = ErrorMode.SaveAndContinue;

                        CustomerImportData[] customersimported = (CustomerImportData[])engine.ReadFile(filePath);


                        if (engine.ErrorManager.HasErrors)
                            foreach (ErrorInfo err in engine.ErrorManager.Errors)
                            {
                                string s;
                                s = err.LineNumber + " / " + err.RecordString + " / " + err.ExceptionInfo.ToString();

                                //Console.WriteLine(err.LineNumber);    
                                //Console.WriteLine(err.RecordString);   
                                //Console.WriteLine(err.ExceptionInfo.ToString());
                            }

                        if (customersimported.Count() < 1) throw new Exception("No customers could be imported from csv file");
                        ///////////
                        ///////////


                        foreach (CustomerImportData cust in customersimported)
                        {

                            CustomerAccount m = new CustomerAccount();


                            #region
                            //cust.ContactCompanyName;
                            //cust.ContactEmail;
                            //cust.ContactFirstName;
                            //cust.ContactLastName;
                            //cust.ContactMiddleInitial;
                            //cust.ContactPhoneNumber;
                            //cust.ContactAddressLine1;
                            //cust.ContactAddressLine2;
                            //cust.ContactCity;
                            //cust.ContactState;
                            //cust.ContactStatus;
                            //cust.ContactZip;
                            //cust.FixedMonthlybudget;
                            //cust.InternalCustomerID;
                            ///////
                            //cust.LocalTargetAddress1;
                            //cust.LocalTargetAddress2;
                            //cust.LocalTargetAddress3;
                            //cust.LocalTargetProximity1;
                            //cust.LocalTargetProximity1;
                            //cust.LocalTargetProximity2;
                            //cust.LocalTargetProximity3;
                            //cust.ParentCompanyName;

                            //ca.Address1;
                            //ca.Address2;
                            //ca.City;
                            //ca.Customer;
                            //ca.Email;
                            //ca.FirstName;
                            //ca.MiddleInitial;
                            //ca.Phone;
                            //ca.State;
                            //ca.UserID;
                            //ca.UserPassword;
                            //ca.Zip;
                            //ca.isActive;
                            #endregion

                            /*
                        //cust.ContactStatus;
                        cust.FixedMonthlybudget;
                        //cust.InternalCustomerID;
                        /////
                        cust.LocalTargetAddress1;
                        cust.LocalTargetAddress2;
                        cust.LocalTargetAddress3;
                        cust.LocalTargetProximity1;
                        cust.LocalTargetProximity2;
                        cust.LocalTargetProximity3;
                        cust.ParentCompanyName;
                        /////
                        */

                            m.internalID = cust.InternalCustomerID;
                            m.Address1 = cust.ContactAddressLine1;
                            m.Address2 = cust.ContactAddressLine2;
                            m.City = cust.ContactCity;
                            m.Customer = cust.ContactCompanyName;
                            m.Email = cust.ContactEmail;
                            m.FirstName = cust.ContactFirstName;
                            m.MiddleInitial = cust.ContactMiddleInitial;
                            m.LastName = cust.ContactLastName;
                            m.Phone = cust.ContactPhoneNumber;
                            m.State = cust.ContactState;
                            m.UserID = cust.ContactEmail;
                            m.UserPassword = Semplest.SharedResources.Helpers.RandomPassword.Generate(8, 10);
                            m.Zip = cust.ContactZip;
                            m.isActive = true;


                            var emailtemplate = (from et in dbcontext.EmailTemplates
                                                 where et.EmailTemplatePK.Equals(13)
                                                 select et).FirstOrDefault();
                                                        
                            try
                            {
                                var existing = (from ex in dbcontext.Customers
                                                where ex.InternalCustomerId.Equals(cust.InternalCustomerID) && ex.Name.Equals(m.Customer)
                                                select ex).ToList();

                                if (existing.Count() > 0) throw new Exception();


                                ProductGroupCycleType pgct = dbcontext.ProductGroupCycleTypes.First(p => p.ProductGroupCycleType1 == "Product Group Cycle 30");

                                //Customer c = dbcontext.Customers.Add(new Customer { Name = m.Customer, BillTypeFK = imp.SelectedBillTypeID, ProductGroupCycleType = pgct, InternalCustomerId = cust.InternalCustomerID });
                                var c = new Customer { Name = m.Customer, BillTypeFK = imp.SelectedBillTypeID, ProductGroupCycleType = pgct, InternalCustomerId = cust.InternalCustomerID };
                                dbcontext.Customers.Add(c);
                                var u = new User
                                {
                                    Customer = c,
                                    Email = m.Email,
                                    FirstName = m.FirstName,
                                    LastName = m.LastName,
                                    MiddleInitial = m.MiddleInitial,
                                    IsActive = m.isActive
                                };
                                dbcontext.Users.Add(u);

                                var cr = new Credential { User = u, UsersFK = u.UserPK, Username = m.UserID, Password = m.UserPassword };
                                dbcontext.Credentials.Add(cr);


                                PhoneType pt = dbcontext.PhoneTypes.First(p => p.PhoneType1 == "Business"); // --- phone types --- !!!!
                                Phone ph = new Phone { Phone1 = m.Phone, PhoneType = pt };
                                dbcontext.Phones.Add(ph);
                                
                                var cpa = new CustomerPhoneAssociation { Customer = c, Phone = ph };
                                dbcontext.CustomerPhoneAssociations.Add(cpa);

                                StateCode sc = dbcontext.StateCodes.First(p => p.StateAbbr == m.State);
                                AddressType at = dbcontext.AddressTypes.First(p => p.AddressType1 == "H"); // --- address types --- !!!
                                var a = new Address { Address1 = m.Address1, Address2 = m.Address2, City = m.City, ZipCode = m.Zip, StateCode = sc };
                                dbcontext.Addresses.Add(a);
                                var caa = new CustomerAddressAssociation { Address = a, Customer = c, AddressType = at };
                                dbcontext.CustomerAddressAssociations.Add(caa);

                                var cn = new CustomerNote { Customer = c, Note = m.CustomerNote };
                                dbcontext.CustomerNotes.Add(cn);

                                var r = dbcontext.Roles.First(p => p.RolePK == imp.SelectedRoleID);
                                var ura = new UserRolesAssociation { Role = r, User = u };
                                dbcontext.UserRolesAssociations.Add(ura);

                                //default to the parent's rep and salesperson

                                var parentrepandsales = (from prs in dbcontext.EmployeeCustomerAssociations
                                                         where prs.CustomerFK.Equals(imp.ParentID)
                                                         select prs).ToList();
                                foreach (EmployeeCustomerAssociation eca in parentrepandsales)
                                {
                                    var addrepandsales = new EmployeeCustomerAssociation { Customer = c, EmployeeFK = eca.EmployeeFK };
                                    dbcontext.EmployeeCustomerAssociations.Add(addrepandsales);
                                }

                                //add child to parent in customerhierarchy
                                var ch = new CustomerHierarchy { CustomerFK = c.CustomerPK, CustomerParentFK = imp.ParentID };
                                dbcontext.CustomerHierarchies.Add(ch);
                                dbcontext.SaveChanges();

                                if (fc["sendcustomeremail"] != null)
                                {

                                    ///////////////////////////////////////////////////////////////
                                    //FOR SENDING OUT EMAILS to child customers
                                    /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// ///

                                    var parentdetails = from usr in dbcontext.Users
                                                        join cus in dbcontext.Customers on usr.CustomerFK equals cus.CustomerPK
                                                        where usr.CustomerFK == imp.ParentID
                                                        select new { usr.CustomerFK, usr.Email, cus.Name };

                                    //send mail //revisit
                                    string from = "*****@*****.**";
                                    string to = u.Email;
                                    string body = emailtemplate.EmailBody;
                                    string subject = emailtemplate.EmailSubject;
                                    body = body.Replace("[ChildCustomerFirstLast]", u.FirstName.ToString() + " " + u.LastName.ToString());
                                    body = body.Replace("[ParentCustomerName]", parentdetails.FirstOrDefault().Name.ToString());
                                    body = body.Replace("[FAQs]", "http://faq");
                                    body = body.Replace("[ChildCustomerUserID]", cr.Username.ToString());
                                    body = body.Replace("[ChildCustomerPassword]", cr.Password.ToString());
                                    body = body.Replace("[INSERT LINK]", "http://encrypto");

                                    //SendEmail
                                    bool sent = false;
                                    ServiceClientWrapper scw = new ServiceClientWrapper();
                                    sent = scw.SendEmail(subject, from, to, body);
                                }
                                                            
                            }
                            catch (Exception ex)
                            {
                                //Console.WriteLine(ex.TargetSite);
                                SemplestModel.Semplest _dbContext = new SemplestModel.Semplest();
                                SemplestModel.Error er = new SemplestModel.Error();
                                er.ErrorMessage = ex.Message+"  \r\n "+ex.InnerException  +"  \r\n "+ex.StackTrace +"  \r\n "+ex.Source+"  \r\n "+ex.TargetSite;
                                //filterContext.RequestContext.HttpContext.Session
                                //if (HttpContext.Current.Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID] == null)
                                //    er.UsersFK = 1;
                                //else
                                //    er.UsersFK = ((Credential)HttpContext.Current.Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]) == null ? 1 : ((Credential)HttpContext.Current.Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]).UsersFK;
                                er.CreatedDate = DateTime.Now;
                                _dbContext.Errors.Add(er);
                                _dbContext.SaveChanges();
                                
                                var scw = new ServiceClientWrapper();
                                scw.SendEmail("WebSite Error Message", "*****@*****.**", _dbContext.Configurations.First().OnErrorEmail, er.ErrorMessage);
                            }
                        }//endforeach

                    }
                    else throw new Exception();

                }
                catch (Exception ex)
                {
                    importstatus = "An error has occured. Please check the file for errors and try again..";
                    //Console.WriteLine(ex.TargetSite);
                    SemplestModel.Semplest _dbContext = new SemplestModel.Semplest();
                    SemplestModel.Error er = new SemplestModel.Error();
                    er.ErrorMessage = ex.Message + "  \r\n " + ex.InnerException + "  \r\n " + ex.StackTrace + "  \r\n " + ex.Source + "  \r\n " + ex.TargetSite;
                    //filterContext.RequestContext.HttpContext.Session
                    //if (HttpContext.Current.Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID] == null)
                    //    er.UsersFK = 1;
                    //else
                    //    er.UsersFK = ((Credential)HttpContext.Current.Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]) == null ? 1 : ((Credential)HttpContext.Current.Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]).UsersFK;
                    er.CreatedDate = DateTime.Now;
                    _dbContext.Errors.Add(er);
                    _dbContext.SaveChanges();
                    var scw = new ServiceClientWrapper();
                    scw.SendEmail("WebSite Error Message", "*****@*****.**", _dbContext.Configurations.First().OnErrorEmail, er.ErrorMessage);

                }


                /*
                 
                 *   public Boolean SendEmail(String subject, String from, String recipient, String msgTxt)
        {
            var jsonHash = new Dictionary<string, string>();
            jsonHash.Add("subject", subject);
            jsonHash.Add("from", from);
            jsonHash.Add("recipient", recipient);
            jsonHash.Add("msgTxt", msgTxt);
            string jsonstr = JsonConvert.SerializeObject(jsonHash);
            string returnData = runMethod(_baseURLTest, MAILSERVICEOFFERED, "SendEmail", jsonstr, timeoutMS);
            var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(returnData);
            string boolResult = dict.Values.First();
            return Convert.ToBoolean(boolResult);
        }
                 
                 */



                //scope.Complete();
            }

            //return View(m);

            ImportResultModel res = new ImportResultModel();
            res.Importresult = importstatus;
            return RedirectToAction("CustomerImportResult", "AccountService",   res );
        }
Пример #5
0
        public ActionResult LogIn(Semplest.SharedResources.Models.ProfileModel pm, string ReturnUrl, string isAdmin, FormCollection f)
        {
            if (ModelState.IsValid)
            {
                ModelState.Clear();
                Dictionary<string, int> loginHash = (Dictionary<string, int>)Session[Semplest.SharedResources.SEMplestConstants.SESSION_LOGINATTEMPTS];
                if (loginHash == null)
                {
                    loginHash = new Dictionary<string, int>();
                    loginHash.Add(pm.UserName, 1);
                }
                else if (loginHash.ContainsKey(pm.UserName))
                    loginHash[pm.UserName] += 1;
                else
                    loginHash.Add(pm.UserName, 1);

                Session[Semplest.SharedResources.SEMplestConstants.SESSION_LOGINATTEMPTS] = loginHash;
                bool isAdminLogin = isAdmin == null ? false : true;
                using (var dbContext = new SemplestModel.Semplest())
                {
                    Credential cred = null;
                    if (Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID] != null)
                    {
                        cred = (Credential)Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID];
                    }
                    else
                    {
                        IQueryable<Credential> creds = null;
                        if(pm.LoggedInSucceeded)
                            creds = dbContext.Credentials.Where(c => c.Username == pm.UserName);
                        else
                            creds = dbContext.Credentials.Where(c => c.Username == pm.UserName && c.Password == pm.Password1);

                        if (creds.Count() == 1)
                        {
                            if ((isAdminLogin && creds.First().IsAdmin()) || (!isAdminLogin && !creds.First().IsAdmin()))
                                cred = creds.First();
                        }

                    }
                    if (cred == null)
                    {
                        pm.LoggedInSucceeded = false;
                        if (loginHash[pm.UserName] > 3)
                        {
                            var userCreds = dbContext.Credentials.Where(c => c.Username == pm.UserName);
                            if (userCreds.Count() > 0 && userCreds.First().User.IsActive)
                            {
                                userCreds.First().User.IsActive = false;
                                dbContext.SaveChanges();
                            }
                            pm.LoginFailedMessage = "Sorry, your account is currently locked. To enable your account, please email [email protected] for assistance. Thank you!";
                        }
                        else
                            pm.LoginFailedMessage = "The user name or password entered is incorrect. Please try again.";
                    }
                    else if (!cred.User.IsActive)
                    {
                        pm.LoggedInSucceeded = false;
                        pm.LoginFailedMessage = "Sorry, your account is currently locked. To enable your account, please email [email protected] for assistance. Thank you!";
                    }
                    else
                    {
                        Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID] = cred;
                        if (cred.User.IsRegistered)
                        {
                            //if the user doesn't have a parent in the customerparentfk column then they are a parent else they are a child
                            //if (cred.User.CustomerFK == null || string.IsNullOrEmpty(cred.User.Customer.CustomerHierarchies.First().CustomerParentFK.ToString()))
                            //    return RedirectToAction("Index", "Home");
                            //else if (cred.User.IsRegistered)
                            //user is a regular core user
                            if (cred.User.CustomerFK == null)
                                return RedirectToAction("Index", "Home");
                            else
                                return RedirectToAction("Index2", "Home");
                        }
                        else if (pm.LoggedInSucceeded)
                        {
                            Credential saveCred = dbContext.Credentials.Where(x => x.Username == cred.Username && x.Password == cred.Password).First();
                            //authenticated properly and submitted secondary form SecurityAnswer/SecurityQuestion
                            saveCred.SecurityAnswer = pm.SecurityAnswer;
                            saveCred.SecurityQuestion = pm.SecurityQuestion;
                            saveCred.Password = pm.Password2;
                            saveCred.User.IsRegistered = true;
                            int i = dbContext.SaveChanges();
                            return RedirectToAction("Index", "Home");
                        }
                        else
                        {
                            //authenticated properly and HAS NOT submitted secondary form SecurityAnswer/SecurityQuestion to complete registration
                            pm.IsRegistered = false;
                            pm.LoggedInSucceeded = true;
                        }
                    }
                }
            }
            return View(pm);
        }
Пример #6
0
 public ActionResult LaunchAdProduct(CampaignSetupModel model)
 {
     try
     {
         var dbContext = new SemplestModel.Semplest();
         var cr = new CreditCardRepository(dbContext);
         var sr = new StateRepository(dbContext);
         var pr = new PromotionRepository(dbContext);
         var bt = new BillTypeRepository(dbContext);
         var promo = pr.GetPromoitionFromCampaign(GetCustomerId(), model.ProductGroup.ProductGroupName,
                                                  model.ProductGroup.ProductPromotionName);
         var retVal = new ReturnState(false,false,"Not a credit card customer", null);
         if (model.BillType == bt.GetBillTypeCode("Credit Card"))
         {
             retVal = cr.ChargeCreditCard(new CustomerObject
                                                  {
                                                      Address1 = model.BillingLaunch.Address,
                                                      City = model.BillingLaunch.City,
                                                      Email = model.BillingLaunch.Email,
                                                      StateAbbr =
                                                          sr.GetStateNameFromCode(
                                                              int.Parse(model.BillingLaunch.StateCodeFK)),
                                                      ExpireDateMMYY =
                                                          model.BillingLaunch.ExpiryMonth +
                                                          model.BillingLaunch.ExpiryYear,
                                                      FirstName = model.BillingLaunch.FirstName,
                                                      LastName = model.BillingLaunch.LastName,
                                                      Phone = model.BillingLaunch.Phone,
                                                      ZipCode = model.BillingLaunch.Zip,
                                                      creditCardNumber = model.BillingLaunch.CardNumber
                                                  }, promo, model.BillType, model.ProductGroup.Budget);
         }
         try
         {
             if (!retVal.IsException && !retVal.IsValidationError)
             {
                 dbContext.SaveChanges();
                 var adEngines = new List<string>();
                 adEngines.AddRange(
                     promo.PromotionAdEngineSelecteds.Select(
                         pades => pades.AdvertisingEngine.AdvertisingEngine1));
                 var sw = new ServiceClientWrapper();
                 if (sw.ScheduleAddPromotionToAdEngine(GetCustomerId(), promo.ProductGroupFK,
                                                       promo.PromotionPK, adEngines.ToArray()))
                 {
                     pr.SetPromotionToLaunched(promo.PromotionPK);
                     dbContext.SaveChanges();
                 }
                 return Json(retVal.ReturnMessage);
             }
         }
         catch (Exception ex)
         {
             ExceptionHelper.LogException(ex);
             return Json(retVal.ReturnMessage);
         }
         if (!retVal.IsException && retVal.IsValidationError)
             return Json("Validation Error<~> " + retVal.ReturnMessage);
     }
     catch (Exception ex)
     {
         ExceptionHelper.LogException(ex);
     }
     return Json(ConfigurationManager.AppSettings["TechnicalDifficulties"]);
 }
        public ActionResult Add(CustomerAccountWithEmployeeModel m, string command, FormCollection fc )
        {
            
            if (command.ToLower() == "cancel") return RedirectToAction("Index");


            SemplestModel.Semplest dbcontext = new SemplestModel.Semplest();

            


            //check if userid has been taken by other users

            var userIDSs = from c in dbcontext.Credentials
                        where c.Username.Equals(m.CustomerAccount.UserID) 
                        select c;
            if (userIDSs.Count() > 0)
                      ModelState.AddModelError("CustomerAccount.UserID", "This UserID is already taken!!");

               
                  if (!ModelState.IsValid)
                  {
                      //repopulate 
                   #region needs to repopulate lists to get the same view again

                      var roles = (from r in dbcontext.Roles select r).ToList().OrderBy(r => r.RoleName);

                      m.Roles = roles.Select(r => new SelectListItem
                      {
                          Value = r.RolePK.ToString(),
                          Text = r.RoleName.ToString()
                      });




                      //repopualte

                      var allreps = from e in dbcontext.Employees
                                    //join eca in dbcontext.EmployeeCustomerAssociations on e.EmployeePK equals eca.EmployeeFK
                                    join et in dbcontext.EmployeeTypes on e.EmployeeTypeFK equals et.EmployeeTypeID
                                    join u in dbcontext.Users on e.UsersFK equals u.UserPK
                                    where (et.EmployeeType1 == "Rep" && u.IsActive.Equals(true))
                                    select new EmployeeCustomerAssociaitionModel
                                    {
                                        //AccountNumber = eca.CustomerFK,
                                        employeePK = e.EmployeePK,
                                        EmployeeType = et.EmployeeType1,
                                        EmployeeUserPK = u.UserPK,
                                        FirstName = u.FirstName,
                                        MiddleInitial = u.MiddleInitial,
                                        LastName = u.LastName
                                    };



                      /////////////////////////////////////////////////////////////////////////////////
                      //for sales dropdown
                      /////////////////////////////////////////////////////////////////////////////////
                      var allsalespersons = from e in dbcontext.Employees
                                            //join eca in dbcontext.EmployeeCustomerAssociations on e.EmployeePK equals eca.EmployeeFK
                                            join et in dbcontext.EmployeeTypes on e.EmployeeTypeFK equals et.EmployeeTypeID
                                            join u in dbcontext.Users on e.UsersFK equals u.UserPK
                                            where (et.EmployeeType1 == "Sales" && u.IsActive.Equals(true))
                                            select new EmployeeCustomerAssociaitionModel
                                            {
                                                //AccountNumber = eca.CustomerFK,
                                                employeePK = e.EmployeePK,
                                                EmployeeType = et.EmployeeType1,
                                                EmployeeUserPK = u.UserPK,
                                                FirstName = u.FirstName,
                                                MiddleInitial = u.MiddleInitial,
                                                LastName = u.LastName
                                            };


                      var allparents =
              from c in dbcontext.Customers
              join chi in dbcontext.CustomerHierarchies.Where(p => p.CustomerParentFK == null) on c.CustomerPK equals chi.CustomerFK
              select c;

                      List<SelectListItem> sli = new List<SelectListItem>();


                      sli.Add(new SelectListItem { Value = (-1).ToString(), Text = "«« Parent »»" });
                      sli.Add(new SelectListItem { Value = (0).ToString(), Text = "«« Single User   »»" });

                      //x.SelectedParentID = -1;

                      m.Parents = allparents.ToList().Select(r => new SelectListItem
                      {
                          Value = r.CustomerPK.ToString(),
                          Text = r.Name.ToString()
                      }).Union(sli);



                      /////////////////////////////////////////////////////////////////////////////////
                      //for billtype dropdown
                      /////////////////////////////////////////////////////////////////////////////////
                      var allbilltypes = (from a in dbcontext.BillTypes select a).ToList();

                      
                      m.BillTypes = allbilltypes.Select(r => new SelectListItem
                      {
                          Value = r.BillTypePK.ToString(),
                          Text = r.BillType1.ToString()
                      });




                      //for state dropdown
                      /////////////////////////////////////////////////////////////////////////////////
                      var allstates = (from sc in dbcontext.StateCodes select sc).ToList();
                      
                      m.States = allstates.Select(r => new SelectListItem
                      {
                          Value = r.StateAbbrPK.ToString(),
                          Text = r.StateAbbr.ToString()
                      });


                      List<SelectListItem> slina = new List<SelectListItem>();
                      slina.Add(new SelectListItem { Value = (-1).ToString(), Text = "«« Not Assigned »»" });



                      List<EmployeeCustomerAssociaitionModel> ll1 = allreps.OrderBy(r => r.LastName).ThenBy(r => r.FirstName).ToList(); ;
                      List<SelectListItem> sl1 = new List<SelectListItem>();
                      foreach (EmployeeCustomerAssociaitionModel s in ll1)
                      {
                          SelectListItem mylistitem = new SelectListItem();
                          mylistitem.Text = s.FirstName + " " + s.LastName;
                          mylistitem.Value = s.employeePK.ToString();
                          sl1.Add(mylistitem);
                      }
                      m.Reps = sl1.Union(slina);


                      List<EmployeeCustomerAssociaitionModel> ll2 = allsalespersons.OrderBy(r => r.LastName).ThenBy(r => r.FirstName).ToList();
                      List<SelectListItem> sl2 = new List<SelectListItem>();
                      foreach (EmployeeCustomerAssociaitionModel s in ll2)
                      {
                          SelectListItem mylistitem = new SelectListItem();
                          mylistitem.Text = s.FirstName + " " + s.LastName;
                          mylistitem.Value = s.employeePK.ToString();
                          sl2.Add(mylistitem);
                      }
                      m.SalesPersons = sl2.Union(slina);
                      return View(m);     
   #endregion
                  }

             

            try
            {
                


                //BillType bt = dbcontext.BillTypes.First(p => p.BillType1 == "Flat Fee"); // --- feees --- !!!
                //revisit 
                ProductGroupCycleType pgct = dbcontext.ProductGroupCycleTypes.First(p => p.ProductGroupCycleType1 == "Product Group Cycle 30");

                var c = new Customer
                            { 
                                Name = m.CustomerAccount.Customer,
                                BillTypeFK = m.SelectedBillTypeID,
                                ProductGroupCycleType = pgct,
                                 PercentOfMedia=m.CustomerAccount.PercentMedia,
                                 ServiceFee= m.CustomerAccount.ServiceFee,
                                  InternalCustomerId= m.CustomerAccount.internalID,
                                PromotionFeeAmount = m.CustomerAccount.PromotionFeeAmount,
                                CreditLimit=m.CustomerAccount.CreditLimit,
                                PromotionFeeOverride=m.CustomerAccount.PromotionFeeOverride 
                            };

                dbcontext.Customers.Add(c);

                var u = new User
                            {
                                Customer = c,
                                Email = m.CustomerAccount.Email,
                                FirstName = m.CustomerAccount.FirstName,
                                LastName = m.CustomerAccount.LastName,
                                MiddleInitial = m.CustomerAccount.MiddleInitial,
                                IsActive = m.CustomerAccount.isActive
                            };
                dbcontext.Users.Add(u);

                var r = dbcontext.Roles.First(p => p.RolePK == m.SelectedRoleID);
                var ura = new UserRolesAssociation { Role = r, User = u };
                dbcontext.UserRolesAssociations.Add(ura);


                //
                var cr = new Credential
                             { 
                                 User = u,
                                 UsersFK = u.UserPK,
                                 Username = m.CustomerAccount.UserID,
                                 Password = m.CustomerAccount.UserPassword
                             };
                dbcontext.Credentials.Add(cr);


                PhoneType pt = dbcontext.PhoneTypes.First(p => p.PhoneType1 == "Business"); // --- phone types --- !!!!
                var ph = new Phone {Phone1 = m.CustomerAccount.Phone, PhoneType = pt};
                dbcontext.Phones.Add(ph);

                var cpa = new CustomerPhoneAssociation {Customer = c, Phone = ph};
                dbcontext.CustomerPhoneAssociations.Add(cpa);

                var sc = dbcontext.StateCodes.First(p => p.StateAbbrPK == m.SelectedStateID);
                var at = dbcontext.AddressTypes.First(p => p.AddressType1 == "H"); // --- address types --- !!!

                var a = new Address
                            {
                                Address1 = m.CustomerAccount.Address1,
                                Address2 = m.CustomerAccount.Address2,
                                City = m.CustomerAccount.City,
                                ZipCode = m.CustomerAccount.Zip,
                                StateCode = sc
                            };
                dbcontext.Addresses.Add(a);

                var caa = new CustomerAddressAssociation {Address = a, Customer = c, AddressType = at};
                dbcontext.CustomerAddressAssociations.Add(caa);

                var cn = new CustomerNote {Customer = c, Note = m.CustomerAccount.CustomerNote};
                dbcontext.CustomerNotes.Add(cn);

                
                //don't add if not assigned
                if (m.SelectedRepID != -1)
                {
                    var addrep = new EmployeeCustomerAssociation { Customer = c, EmployeeFK = m.SelectedRepID };
                    dbcontext.EmployeeCustomerAssociations.Add(addrep);
                }
                
                //don't add if not assigned
                if (m.SelectedSalesPersonID != -1)
                {
                    var addsales = new EmployeeCustomerAssociation { Customer = c, EmployeeFK = m.SelectedSalesPersonID };
                    dbcontext.EmployeeCustomerAssociations.Add(addsales);
                }

                CustomerHierarchy ch = null;
                if (m.SelectedParentID == -1) //set parent
                {
                    ch = new CustomerHierarchy {CustomerFK = c.CustomerPK, CustomerParentFK = null};
                    dbcontext.CustomerHierarchies.Add(ch);
                }
                else if (m.SelectedParentID == 0) //set self -- single user
                {
                    ch = new CustomerHierarchy {CustomerFK = c.CustomerPK, CustomerParentFK = c.CustomerPK};
                    dbcontext.CustomerHierarchies.Add(ch);
                }
                else //assign a parent
                {
                    ch = new CustomerHierarchy {CustomerFK = c.CustomerPK, CustomerParentFK = m.SelectedParentID};
                    dbcontext.CustomerHierarchies.Add(ch);
                }
                dbcontext.SaveChanges();

                /////////////////////////////////////////////////////////////////////////////
                ///// sending of emails
                AesEncyrption ae = AesEncyrption.getInstance();
                string encryptedToken = ae.GenerateToken(ch.CustomerParentFK.Value.ToString(), DateTime.Now.ToString(), cr.Username, cr.Password);
                string emailUrl = System.Configuration.ConfigurationManager.AppSettings["VerificationUrl"].ToString() + encryptedToken;
                if (fc["sendcustomeremail"] != null)
                {
                    string from, to, body, subject;

                    //send email to child customers
                    //if  child customer
                    if (m.SelectedParentID >0)
                    {
                        var emailtemplate = (
                                            from et in dbcontext.EmailTemplates
                                            join ey in dbcontext.EmailTypes on et.EmailTypeFK equals ey.EmailTypePK
                                            where ey.EmailType1.Equals("WelcomeEmailChild")
                                            select et).FirstOrDefault();

                        var parentdetails = from usr in dbcontext.Users
                                            join cus in dbcontext.Customers on usr.CustomerFK equals cus.CustomerPK
                                            where usr.CustomerFK == m.SelectedParentID
                                            select new { usr.CustomerFK, usr.Email, cus.Name };

                        //send mail //revisit
                        from = "*****@*****.**";
                        to = u.Email;
                        body = emailtemplate.EmailBody;
                        //parent name in subject line
                        subject = parentdetails.FirstOrDefault().Name + " " +emailtemplate.EmailSubject;
                        body = body.Replace("[ChildCustomerFirstLast]", u.FirstName.ToString() + " " + u.LastName.ToString());
                        body = body.Replace("[ParentCustomerName]", parentdetails.FirstOrDefault().Name.ToString());
                        body = body.Replace("[FAQs]", "http://faq");
                        body = body.Replace("[ChildCustomerUserID]", cr.Username.ToString());
                        body = body.Replace("[ChildCustomerPassword]", cr.Password.ToString());
                        body = body.Replace("[INSERT LINK]", emailUrl);
                        bool sent = false;
                        ServiceClientWrapper scw = new ServiceClientWrapper();
                        sent = scw.SendEmail(subject, from, to, body);
                    }


                    if (m.SelectedParentID == -1) ///set parent
                    {
                        var emailtemplate = (
                                            from et in dbcontext.EmailTemplates
                                            join ey in dbcontext.EmailTypes on et.EmailTypeFK equals ey.EmailTypePK
                                            where ey.EmailType1.Equals("WelcomeEmailParent")
                                            select et).FirstOrDefault();

                        
                        //send mail //revisit
                        from = "*****@*****.**";
                        to = u.Email;
                        body = emailtemplate.EmailBody;
                        subject = emailtemplate.EmailSubject;
                        

                        
                        body = body.Replace("[ParentCustomerName]", c.Name.FirstOrDefault().ToString());
                        body = body.Replace("[ParentCustomerUserID]", cr.Username.ToString());
                        body = body.Replace("[ParentCustomerPassword]", cr.Password.ToString());
                        body = body.Replace("[INSERT LINK]", emailUrl);
                        body = body.Replace("[DefaultEmailContactUS]", dbcontext.Configurations.First().DefaultEmailContactUs.ToString());
                        bool sent = false;
                        ServiceClientWrapper scw = new ServiceClientWrapper();
                        sent = scw.SendEmail(subject, from, to, body);
                    }



                    
                    if (m.SelectedParentID ==0) // non child parent customer - self
                    {

                        var emailtemplate = (
                                                from et in dbcontext.EmailTemplates
                                                join ey in dbcontext.EmailTypes on et.EmailTypeFK equals ey.EmailTypePK
                                                where ey.EmailType1.Equals("WelcomeEmailNonParentUser")
                                                select et).FirstOrDefault();

                        //send mail //revisit
                        from = "*****@*****.**";
                        to = u.Email;
                        body = emailtemplate.EmailBody;
                        subject = emailtemplate.EmailSubject;
                        body = body.Replace("[NonParentCustomer]", u.FirstName.ToString() + " " + u.LastName.ToString());
                        body = body.Replace("[NonParentCustomerUserID]", cr.Username.ToString());
                        body = body.Replace("[NonParentCustomerPassword]", cr.Password.ToString());
                        body = body.Replace("[INSERT LINK]", emailUrl);
                        bool sent = false;
                        ServiceClientWrapper scw = new ServiceClientWrapper();
                        sent = scw.SendEmail(subject, from, to, body);
                    }
                    //SendEmail


                }

            }
            catch (Exception ex)
            {
                Semplest.SharedResources.Helpers.ExceptionHelper.LogException(ex);
            }


            return RedirectToAction("Index");
        }
Пример #8
0
        public ActionResult MyProfile(ChildModel m, string command)
        {
            
            if (command.ToLower() == "cancel") return RedirectToAction("Index2", "Home");
            //if (command.ToLower() == "delete")



            SemplestModel.Semplest dbcontext = new SemplestModel.Semplest();




            //check if userid has been taken by other users

            var userIDSs = from c in dbcontext.Credentials
                           where c.Username.Equals(m.UserID) && !c.UsersFK.Equals(m.UserPK)
                           select c;
            if (userIDSs.Count() > 0)
                ModelState.AddModelError("UserID", "This UserID is already taken!!");



            if (!ModelState.IsValid)
            {
                

                var allstates = (from sc in dbcontext.StateCodes select sc).ToList();

                m.States = allstates.Select(r => new SelectListItem
                {
                    Value = r.StateAbbrPK.ToString(),
                    Text = r.StateAbbr.ToString()
                });

                return View(m);
            }


            var user = dbcontext.Users.ToList().Find(p => p.UserPK == m.UserPK);
            user.FirstName = m.FirstName;
            user.LastName = m.LastName;
            user.MiddleInitial = m.MiddleInitial;
            user.Email = m.Email;
            user.EditedDate = DateTime.Now;
            //UpdateModel(user);

            var customer = dbcontext.Customers.ToList().Find(p => p.CustomerPK == m.AccountNumber);
            var customeraddressassociation = dbcontext.CustomerAddressAssociations.ToList().Find(p => p.CustomerFK == customer.CustomerPK);
            var address = dbcontext.Addresses.ToList().Find(p => p.AddressPK == customeraddressassociation.AddressFK);

            customer.Name = m.Customer;
            customer.InternalCustomerId = m.internalID;
            UpdateModel(customer);

            address.Address1 = m.Address1;
            address.Address2 = m.Address2;
            address.City = m.City;
            address.ZipCode = m.Zip;
            address.EditedDate = DateTime.Now;
            address.StateAbbrFK = m.SelectedStateID;
            UpdateModel(address);

            var customerphoneassociation = dbcontext.CustomerPhoneAssociations.ToList().Find(p => p.CustomerFK == m.AccountNumber);
            var phone = dbcontext.Phones.ToList().Find(p => p.PhonePK == customerphoneassociation.PhoneFK);
            phone.Phone1 = m.Phone;

            UpdateModel(phone);

            var credentials = dbcontext.Credentials.ToList().Find(p => p.UsersFK == m.UserPK);
            credentials.Username = m.UserID;
            credentials.Password = m.UserPassword;
            credentials.SecurityQuestion = m.SecurityQuestion;
            credentials.SecurityAnswer = m.SecurityAnswer;

            UpdateModel(credentials);
            dbcontext.SaveChanges();

            return RedirectToAction("Index2","Home");
            //return View("index");
            //return View(m);
        }
Пример #9
0
        public ActionResult AddProductGroupName(FormCollection fc)
        {
            try
            {
                string productgroupname = fc["newproductgroupname"].ToString().Trim();
                Credential c = ((Credential)(Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]));
                if (productgroupname == null || productgroupname == "") throw new Exception("Blank");
                SemplestModel.Semplest dbContext = new SemplestModel.Semplest();
                var productgroupexists = from pg in dbContext.ProductGroups
                                         where pg.CustomerFK.Equals(c.User.CustomerFK.Value) && pg.ProductGroupName.Equals(productgroupname)
                                         select pg;

                if (productgroupexists.Count() > 0) throw new Exception("Duplicate");

                dbContext.ProductGroups.Add(new ProductGroup { CustomerFK = c.User.CustomerFK.Value, ProductGroupName = productgroupname, StartDate = DateTime.Now, IsActive = true });
                dbContext.SaveChanges();

            }
            catch (Exception ex)
            {

            }

            return RedirectToAction("Index2");
        }
        public ActionResult Delete(CustomerAccountWithEmployeeModel m, string command)
        {
            SemplestModel.Semplest dbcontext = new SemplestModel.Semplest();
            //Semplest context = new SemplestModel.Semplest();


            if (command.ToLower() == "cancel") return RedirectToAction("Index");
            if (command.ToLower() == "delete")
            {

                try
                {

                    var user = dbcontext.Users.ToList().Find(p => p.UserPK == m.CustomerAccount.UserPK);


                    var customer = dbcontext.Customers.ToList().Find(p => p.CustomerPK == m.CustomerAccount.AccountNumber);
                    var customeraddressassociation = dbcontext.CustomerAddressAssociations.ToList().Find(p => p.CustomerFK.Equals(m.CustomerAccount.AccountNumber));
                    var address = dbcontext.Addresses.ToList().Find(p => p.AddressPK.Equals(customeraddressassociation.AddressFK));
                    var customernotes = dbcontext.CustomerNotes.ToList().Find(p => p.CustomerFK.Equals(m.CustomerAccount.AccountNumber));

                    var employeecustomerassociation = dbcontext.EmployeeCustomerAssociations.ToList();
                    //var employeecustomerassociation = dbcontext.EmployeeCustomerAssociations.ToList().Find(p => p.CustomerFK.Equals(m.CustomerAccount.AccountNumber));
                    //var employeecustomerassociation = from x in dbcontext.EmployeeCustomerAssociations 
                    //                                where x.CustomerFK.Equals(m.CustomerAccount.AccountNumber)


                    var customerstyle = dbcontext.CustomerStyles.ToList().Find(p => p.CustomerFK.Equals(m.CustomerAccount.AccountNumber));
                    var customerphoneassociation = dbcontext.CustomerPhoneAssociations.ToList().Find(p => p.CustomerFK.Equals(m.CustomerAccount.AccountNumber));
                    var phone = dbcontext.Phones.ToList().Find(p => p.PhonePK.Equals(customerphoneassociation.PhoneFK));
                    var credentials = dbcontext.Credentials.ToList().Find(p => p.UsersFK.Equals(m.CustomerAccount.UserPK));
                    var userrolesassociation = dbcontext.UserRolesAssociations.ToList().Find(p => p.UsersFK.Equals(m.CustomerAccount.UserPK));
                    var customerhierarchy = dbcontext.CustomerHierarchies.ToList().Find(p => p.CustomerFK.Equals(m.CustomerAccount.AccountNumber));


                    var productgroup = dbcontext.ProductGroups.ToList().Find(p => p.CustomerFK.Equals(customer.CustomerPK));
                    if (productgroup != null) throw new Exception("Could not delete customer");


                    //UPDATE: no need to check for promotion, won't be deleting any customer that has a productgroup assigned!!!
                    //var promotion = dbcontext.Promotions.ToList().Find(p => p.ProductGroupFK.Equals(productgroup.ProductGroupPK));
                    //if (promotion != null) throw new Exception("Could not delete customer");


                    //Message = "The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not sup...
                    //dbcontext.Customers.Remove(customer);
                    //dbcontext.Users.Remove(user);
                    //dbcontext.EmployeeCustomerAssociations.Remove(employeecustomerassociation);
                    //if (customerstyle!=null)
                    //    dbcontext.CustomerStyles.Remove(customerstyle);
                    //dbcontext.CustomerPhoneAssociations.Remove(customerphoneassociation);
                    //dbcontext.Phones.Remove(phone);
                    //dbcontext.Credentials.Remove(credentials);
                    //if(userrolesassociation!=null)
                    //    dbcontext.UserRolesAssociations.Remove(userrolesassociation);

                    //workaround for deletion:


                    var caa = customeraddressassociation;
                    var a = address;
                    var cn = customernotes;

                    dbcontext.CustomerAddressAssociations.Remove(caa);
                    dbcontext.Addresses.Remove(a);
                    dbcontext.CustomerNotes.Remove(cn);


                    //EmployeeCustomerAssociation eca = employeecustomerassociation;
                    //dbcontext.EmployeeCustomerAssociations.Remove(eca);

                    foreach (EmployeeCustomerAssociation c1 in employeecustomerassociation)
                    {
                        if (c1.CustomerFK.Equals(m.CustomerAccount.AccountNumber))
                        {
                            dbcontext.EmployeeCustomerAssociations.Remove(c1);
                        }
                    }


                    var c = customer;
                    dbcontext.Customers.Remove(c);

                    var cr = credentials;
                    dbcontext.Credentials.Remove(cr);

                    var u = user;
                    dbcontext.Users.Remove(u);

                    var cpa = customerphoneassociation;
                    dbcontext.CustomerPhoneAssociations.Remove(cpa);

                    var ph = phone;
                    dbcontext.Phones.Remove(ph);


                    if (customerstyle != null)
                    {
                        var cs = customerstyle;
                        dbcontext.CustomerStyles.Remove(cs);
                    }

                    if (userrolesassociation != null)
                    {
                        var ura = userrolesassociation;
                        dbcontext.UserRolesAssociations.Remove(ura);
                    }

                    var ch = customerhierarchy;
                    dbcontext.CustomerHierarchies.Remove(ch);

                    dbcontext.SaveChanges();

                    TempData["message"] = "Customer Account #" + m.CustomerAccount.AccountNumber + " (" + m.CustomerAccount.Customer + ") has been successfully deleted.";
                }

                catch (Exception ex)
                {
                    TempData["message"] = "Customer Account #" + m.CustomerAccount.AccountNumber + " (" + m.CustomerAccount.Customer + ") could NOT be deleted.";
                }



            }
            //return View();
            return RedirectToAction("Index");
        }
Пример #11
0
        public ActionResult Add(EmployeeSetupWithRolesModel m, string command)
        {

            if (command.ToLower() == "cancel") return RedirectToAction("Index");

            SemplestModel.Semplest dbcontext = new SemplestModel.Semplest();


            //check if userid has been taken by other users

                  var userIDSs = from c in dbcontext.Credentials
                        where c.Username.Equals(m.EmployeeSetup.UserID) //&& !c.UsersFK.Equals(m.EmployeeSetup.UserPK)
                        select c;
                  if (userIDSs.Count() > 0)
                      ModelState.AddModelError("EmployeeSetup.UserID", "This UserID is already taken!!");


                  if (!ModelState.IsValid)
                  {
                      //repopulate 


                      var roles = (from r in dbcontext.Roles select r).ToList().OrderBy(r => r.RoleName);
                      
                      m.Roles = roles.Select(r => new SelectListItem
                      {
                          Value = r.RolePK.ToString(),
                          Text = r.RoleName.ToString()
                      });



                      /////////////////////////////////////////////////////////////////////////////////
                      //for Reportingto dropdown
                      /////////////////////////////////////////////////////////////////////////////////
                      var reportingto = (
                          from e in dbcontext.Employees
                          join u in dbcontext.Users on e.UsersFK equals u.UserPK
                          where u.IsActive.Equals(true)
                          select new ReportingToModel
                          {
                              EmployeePK = e.EmployeePK,
                              FirstName = u.FirstName,
                              LastName = u.LastName
                          }
                          ).ToList().OrderBy(r => r.LastName).ThenBy(r => r.FirstName);
                      



                      //to add exception to dropdownlist - it can be optional, in this case the employee reporting to may be optional
                      List<SelectListItem> sli = new List<SelectListItem>();
                      sli.Add(new SelectListItem { Value = (-1).ToString(), Text = "«« Not Assigned »»" });


                      m.ReportingTo = reportingto.Select(r => new SelectListItem
                      {
                          Value = r.EmployeePK.ToString(),
                          Text = r.FirstName.ToString() + " " + r.LastName.ToString()
                      }).Union(sli);



                      /////////////////////////////////////////////////////////////////////////////////
                      // for employeetype dropdown
                      /////////////////////////////////////////////////////////////////////////////////
                      var employeetypes = (from r in dbcontext.EmployeeTypes select r).ToList();
                      m.EmployeeTypes = employeetypes.Select(r => new SelectListItem
                      {
                          Value = r.EmployeeTypeID.ToString(),
                          Text = r.EmployeeType1.ToString()
                      });


                      return View(m);
                  }


            try
            {

                var u = new User
                            {
                                Customer = null,
                                Email = m.EmployeeSetup.Email,
                                FirstName = m.EmployeeSetup.FirstName,
                                MiddleInitial = m.EmployeeSetup.MiddleInitial,
                                LastName = m.EmployeeSetup.LastName,
                                CustomerFK = null,
                                IsActive = m.EmployeeSetup.isActive,
                                IsRegistered = true //only for admin, force registered=true (Andre)

                            };
                dbcontext.Users.Add(u);
                

                var r= dbcontext.Roles.First(p => p.RolePK   == m.SelectedRoleID );
                var ura = new UserRolesAssociation {Role = r, User = u};
                dbcontext.UserRolesAssociations.Add(ura);

                var et = dbcontext.EmployeeTypes.First(p => p.EmployeeTypeID == m.SelectedEmployeeTypeID);
                var e = new Employee {EmployeeType = et, User = u, HireDate = m.EmployeeSetup.HireDate};
                dbcontext.Employees.Add(e);
                //Credential c = dbcontext.Credentials.Add(new Credential { User = u, Username = m.EmployeeSetup.Email, Password = "******" });

                var cr = new Credential
                             {
                                 User = u,
                                 UsersFK = u.UserPK,
                                 Username = m.EmployeeSetup.UserID,
                                 Password = m.EmployeeSetup.UserPassword
                             };
                dbcontext.Credentials.Add(cr); 


                //BillType bt = dbcontext.BillTypes.First(p => p.BillType1 == "Flat Fee"); // --- feees --- !!!

                //ProductGroupCycleType pgct = dbcontext.ProductGroupCycleTypes.First(p => p.ProductGroupCycleType1 == "Product Group Cycle 30");

                //Customer c = dbcontext.Customers.Add(new Customer { Name = m.CustomerAccount.Customer, BillType = bt, ProductGroupCycleType = pgct });
                //User u = dbcontext.Users.Add(new User
                //{
                //    Customer = c,
                //    Email = m.CustomerAccount.Email,
                //    FirstName = m.CustomerAccount.FirstName,
                //    LastName = m.CustomerAccount.LastName
                //});

                //Credential cr = dbcontext.Credentials.Add(new Credential { User = u, UsersFK = u.UserPK, Username = m.CustomerAccount.Email, Password = "******" }); //-- default password --- !!

                //PhoneType pt = dbcontext.PhoneTypes.First(p => p.PhoneType1 == "Business"); // --- phone types --- !!!!
                //Phone ph = dbcontext.Phones.Add(new Phone { Phone1 = m.CustomerAccount.Phone, PhoneType = pt });
                //CustomerPhoneAssociation cpa = dbcontext.CustomerPhoneAssociations.Add(new CustomerPhoneAssociation { Customer = c, Phone = ph });

                //StateCode sc = dbcontext.StateCodes.First(p => p.StateAbbrPK == m.SelectedStateID);
                //AddressType at = dbcontext.AddressTypes.First(p => p.AddressType1 == "H"); // --- address types --- !!!
                //Address a = dbcontext.Addresses.Add(new Address { Address1 = m.CustomerAccount.Address1, Address2 = m.CustomerAccount.Address2, City = m.CustomerAccount.City, ZipCode = m.CustomerAccount.Zip, StateCode = sc });
                //CustomerAddressAssociation caa = dbcontext.CustomerAddressAssociations.Add(new CustomerAddressAssociation { Address = a, Customer = c, AddressType = at });


                dbcontext.SaveChanges();

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.TargetSite);
            }


            return RedirectToAction("Index");
        }
Пример #12
0
        public ActionResult Remove(EmployeeSetupWithRolesModel m, string command)
        {
            var dbcontext = new SemplestModel.Semplest();

            if (command.ToLower() == "cancel") return RedirectToAction("Index");
            if (command.ToLower() == "delete") {

                try
                { 

                var user = dbcontext.Users.ToList().Find(p => p.UserPK == m.EmployeeSetup.UserPK);
                
                //need to add effective date to db ---><><>

                var employee = dbcontext.Employees.ToList().Find(p => p.UsersFK == m.EmployeeSetup.UserPK);
                
                var userrolesassociation = dbcontext.UserRolesAssociations.ToList().Find(p => p.UsersFK == m.EmployeeSetup.UserPK);

                var credential = dbcontext.Credentials.ToList().Find(p => p.UsersFK == m.EmployeeSetup.UserPK);


                var employeecustomerassociation = dbcontext.EmployeeCustomerAssociations.ToList().Find(p => p.EmployeeFK.Equals(m.EmployeeSetup.UserPK));

                if (employeecustomerassociation != null) throw new Exception("Could not delete employee");

                dbcontext.Users.Remove(user);
                dbcontext.Employees.Remove(employee);
                dbcontext.UserRolesAssociations.Remove(userrolesassociation);
                dbcontext.Credentials.Remove(credential);

                dbcontext.SaveChanges();
                TempData["message"] = "Employee " + m.EmployeeSetup.FirstName + " " + m.EmployeeSetup.LastName + " has been successfully deleted.";
                }
                
                catch(Exception ex)
                {
                    TempData["message"] = "Employee " + m.EmployeeSetup.FirstName + " " + m.EmployeeSetup.LastName + " could NOT be deleted."; 
                }



            }
            //return View();
            return RedirectToAction("Index");
        }
Пример #13
0
        public ActionResult Edit(EmployeeSetupWithRolesModel m, string command)
        {
            if (command.ToLower() == "cancel") return RedirectToAction("Index");

            if (command.ToLower() == "delete") return RedirectToAction("delete", new { id = m.EmployeeSetup.EmployeePK });

            //for cancel redirect to index

            //for delete
            //@Html.RouteLink("Remove Employee", new { Controller = "EmployeeSetup", action = "Remove", id = Model.EmployeeSetup.EmployeePK })

            SemplestModel.Semplest dbcontext = new SemplestModel.Semplest();


            //check if userid has been taken by other users

                  var userIDSs = from c in dbcontext.Credentials
                        where c.Username.Equals(m.EmployeeSetup.UserID) && !c.UsersFK.Equals(m.EmployeeSetup.UserPK)
                        select c;
                  if (userIDSs.Count() > 0)
                      ModelState.AddModelError("EmployeeSetup.UserID", "This UserID is already taken!!");


                  if (!ModelState.IsValid)
                  {
                      //repopulate 

                      /////////////////////////////////////////////////////////////////////////////////
                      //for roles dropdown
                      /////////////////////////////////////////////////////////////////////////////////
                      var roles = (from r in dbcontext.Roles select r).ToList().OrderBy(r => r.RoleName);

                      m.Roles = roles.Select(r => new SelectListItem
                      {
                          Value = r.RolePK.ToString(),
                          Text = r.RoleName.ToString()
                      });


                      /////////////////////////////////////////////////////////////////////////////////
                      //for Reportingto dropdown
                      /////////////////////////////////////////////////////////////////////////////////
                      var reportingto = (
                          from e in dbcontext.Employees
                          join u in dbcontext.Users on e.UsersFK equals u.UserPK
                          where u.IsActive.Equals(true)
                          select new ReportingToModel
                          {
                              EmployeePK = e.EmployeePK,
                              FirstName = u.FirstName,
                              LastName = u.LastName
                          }
                          ).ToList().OrderBy(r => r.LastName).ThenBy(r => r.FirstName);



                      //to add exception to dropdownlist - it can be optional, in this case the employee reporting to may be optional
                      List<SelectListItem> sli = new List<SelectListItem>();
                      sli.Add(new SelectListItem { Value = (-1).ToString(), Text = "Not Assigned" });


                      m.ReportingTo = reportingto.Select(r => new SelectListItem
                      {
                          Value = r.EmployeePK.ToString(),
                          Text = r.FirstName.ToString() + " " + r.LastName.ToString()
                      }).Union(sli);

                      /////////////////////////////////////////////////////////////////////////////////
                      // for employeetype dropdown
                      /////////////////////////////////////////////////////////////////////////////////
                      var employeetypes = (from r in dbcontext.EmployeeTypes select r).ToList();

                      m.EmployeeTypes = employeetypes.Select(r => new SelectListItem
                      {
                          Value = r.EmployeeTypeID.ToString(),
                          Text = r.EmployeeType1.ToString()
                      });

                      return View(m);
                  }
            
            var user = dbcontext.Users.ToList().Find(p => p.UserPK == m.EmployeeSetup.UserPK);
            user.FirstName = m.EmployeeSetup.FirstName;
            user.MiddleInitial = m.EmployeeSetup.MiddleInitial;
            user.LastName = m.EmployeeSetup.LastName;
            user.Email = m.EmployeeSetup.Email;
            user.EditedDate = DateTime.Now;
            user.IsActive = m.EmployeeSetup.isActive;
            UpdateModel(user);
            //need to add effective date to db ---><><>

            var employee = dbcontext.Employees.ToList().Find(p => p.UsersFK == m.EmployeeSetup.UserPK);
            employee.EmployeeTypeFK = m.SelectedEmployeeTypeID;
            employee.ReportingTo = m.SelectedReportingToID == -1 ?  default(int?) : m.SelectedReportingToID;
            employee.HireDate = m.EmployeeSetup.HireDate;
            UpdateModel(employee);

            var userrolesassociation = dbcontext.UserRolesAssociations.ToList().Find(p => p.UsersFK == m.EmployeeSetup.UserPK);
            userrolesassociation.RolesFK = m.SelectedRoleID;
            UpdateModel(userrolesassociation);

            var credentials = dbcontext.Credentials.ToList().Find(p => p.UsersFK == m.EmployeeSetup.UserPK);
            credentials.Username = m.EmployeeSetup.UserID;
            credentials.Password = m.EmployeeSetup.UserPassword;

            UpdateModel(credentials);

            dbcontext.SaveChanges();


            ////repopulate states ddl
            //var states = (from sc in dbcontext.StateCodes select sc).ToList();
            //m.States = states.Select(r => new SelectListItem
            //{
            //    Value = r.StateAbbrPK.ToString(),
            //    Text = r.StateAbbr.ToString()
            //});


            ////repopulate reps ddl
            //var allreps = from e in dbcontext.Employees
            //              join eca in dbcontext.EmployeeCustomerAssociations on e.EmployeePK equals eca.EmployeeFK
            //              join et in dbcontext.EmployeeTypes on e.EmployeeTypeFK equals et.EmployeeTypeID
            //              join u in dbcontext.Users on e.UsersFK equals u.UserPK
            //              where (et.EmployeeType1 == "Rep")
            //              select new EmployeeCustomerAssociaitionModel
            //              {
            //                  AccountNumber = eca.CustomerFK,
            //                  employeePK = e.EmployeePK,
            //                  EmployeeType = et.EmployeeType1,
            //                  EmployeeUserPK = u.UserPK,
            //                  FirstName = u.FirstName,
            //                  LastName = u.LastName
            //              };
            //List<EmployeeCustomerAssociaitionModel> ll1 = allreps.ToList();
            //List<SelectListItem> sl1 = new List<SelectListItem>();
            //foreach (EmployeeCustomerAssociaitionModel s in ll1)
            //{
            //    SelectListItem mylistitem = new SelectListItem();
            //    mylistitem.Text = s.FirstName + " " + s.LastName;
            //    mylistitem.Value = s.EmployeeUserPK.ToString();
            //    sl1.Add(mylistitem);
            //}
            //m.Reps = sl1;

            ////repopulate salepersons ddl
            ////for reps dropdown
            //var allsalespersons = from e in dbcontext.Employees
            //                      join eca in dbcontext.EmployeeCustomerAssociations on e.EmployeePK equals eca.EmployeeFK
            //                      join et in dbcontext.EmployeeTypes on e.EmployeeTypeFK equals et.EmployeeTypeID
            //                      join u in dbcontext.Users on e.UsersFK equals u.UserPK
            //                      where (et.EmployeeType1 == "Sales")
            //                      select new EmployeeCustomerAssociaitionModel
            //                      {
            //                          AccountNumber = eca.CustomerFK,
            //                          employeePK = e.EmployeePK,
            //                          EmployeeType = et.EmployeeType1,
            //                          EmployeeUserPK = u.UserPK,
            //                          FirstName = u.FirstName,
            //                          LastName = u.LastName
            //                      };
            //List<EmployeeCustomerAssociaitionModel> ll2 = allsalespersons.ToList();
            //List<SelectListItem> sl2 = new List<SelectListItem>();
            //foreach (EmployeeCustomerAssociaitionModel s in ll2)
            //{
            //    SelectListItem mylistitem = new SelectListItem();
            //    mylistitem.Text = s.FirstName + " " + s.LastName;
            //    mylistitem.Value = s.EmployeeUserPK.ToString();
            //    sl2.Add(mylistitem);
            //}
            //m.SalesPersons = sl2;

            //return View("index");

            return RedirectToAction("Index"); 

        }
Пример #14
0
 public void SetKeywordsDeleted(List<int> keywordIds, int promoId)
 {
     using (var dbcontext = new SemplestModel.Semplest())
     {
         foreach (int keywordId in keywordIds)
             dbcontext.PromotionKeywordAssociations.Where(key => key.KeywordFK == keywordId).First(key => key.PromotionFK == promoId).IsDeleted = true;
         dbcontext.SaveChanges();
     }
 }
Пример #15
0
        public void SaveProductGroupAndCampaign(int userid, CampaignSetupModel model)
        {
            using (var dbcontext = new SemplestModel.Semplest())
            {
                // get the customerfk from userid
                var queryCustFk = from c in dbcontext.Users where c.UserPK == userid select c.CustomerFK;
                var i = queryCustFk.FirstOrDefault();
                if (i != null)
                {
                    var custfk = (int)i;

                    // check if the ProductGroupName already exists
                    var queryProdGrp = from c in dbcontext.ProductGroups
                                       where c.CustomerFK == custfk && c.ProductGroupName == model.ProductGroup.ProductGroupName
                                       select c;
                    if (queryProdGrp.Any())
                    {
                        // product grp already exists so update the product group 
                        var updateProdGrp = queryProdGrp.FirstOrDefault();
                        if (updateProdGrp != null)
                        {
                            updateProdGrp.ProductGroupName = model.ProductGroup.ProductGroupName;
                            updateProdGrp.StartDate = Convert.ToDateTime(model.ProductGroup.StartDate, new CultureInfo("en-Us"));
                            updateProdGrp.EndDate = String.IsNullOrEmpty(model.ProductGroup.EndDate) ? (DateTime?)null : Convert.ToDateTime(model.ProductGroup.EndDate);

                            // get promotion and update it
                            var updatePromotion = GetPromotionFromProductGroup(updateProdGrp, model.ProductGroup.ProductPromotionName);
                            // if this is null means promotion name changed so create a new promotion
                            if (updatePromotion == null)
                            {
                                // create new promotion
                                updatePromotion = CreatePromotionFromModel(model, dbcontext.Configurations.First().CustomerDefaultPerCampaignFlatFeeAmount);
                                updatePromotion.ProductGroupFK = updateProdGrp.ProductGroupPK;

                                // add geotargeting to promotion
                                AddGeoTargetingToPromotion(updatePromotion, model, custfk);
                                // promotion ads
                                AddPromotionAdsToPromotion(updatePromotion, model, custfk);

                                dbcontext.Promotions.Add(updatePromotion);
                            }
                            else
                            {
                                // update promotion
                                UpdatePromotionFromModel(updatePromotion, model, dbcontext, custfk);
                            }
                        }

                        dbcontext.SaveChanges();

                        // we need to set this because the _dbcontext is  and campaign is updated so reflect changes we need to create new context
                        _savedCampaign = true;
                    }
                    else
                    {
                        // create product group
                        var prodgroup = new ProductGroup
                        {
                            ProductGroupName = model.ProductGroup.ProductGroupName,
                            IsActive = true,
                            CustomerFK = custfk,
                            StartDate = Convert.ToDateTime(model.ProductGroup.StartDate, new CultureInfo("en-Us")),
                            EndDate = String.IsNullOrEmpty(model.ProductGroup.EndDate) ? (DateTime?)null : Convert.ToDateTime(model.ProductGroup.EndDate)
                        };

                        // create promotion
                        var promo = CreatePromotionFromModel(model, dbcontext.Configurations.First().CustomerDefaultPerCampaignFlatFeeAmount);

                        // add advertising engines that are selected
                        SavePromotionAdEngineSelected(promo, model, dbcontext);

                        // add geotargeting to promotion
                        AddGeoTargetingToPromotion(promo, model, custfk);

                        // save site links
                        AddSiteLinksToPromotion(promo, model, custfk);

                        // promotion ads
                        AddPromotionAdsToPromotion(promo, model, custfk);

                        // add product group
                        dbcontext.ProductGroups.Add(prodgroup);
                        // add promotion
                        dbcontext.Promotions.Add(promo);
                        dbcontext.SaveChanges();

                        // save negative keywords
                        SaveNegativeKeywords(promo, model, dbcontext);

                        // we need to set this because the _dbcontext is  and campaign is updated so reflect changes we need to create new context
                        _savedCampaign = true;
                    }
                }
            }
        }
        public ActionResult EnableUser(int id)
        {
            SemplestModel.Semplest dbContext = new SemplestModel.Semplest();

            dbContext.Customers.Where(key => key.CustomerPK==id).First().Users.First().IsActive= true;
            dbContext.SaveChanges();
            Dictionary<string, object> d = new Dictionary<string, object>();
            d.Add("id", id);
            return RedirectToAction("Index", new System.Web.Routing.RouteValueDictionary(d));
        }
Пример #17
0
 public ActionResult RemovePromotion(int promotionId)
 {
     try
     {
         ServiceClientWrapper sw = new ServiceClientWrapper();
         SemplestModel.Semplest dbContext = new SemplestModel.Semplest();
         int customerId = ((Credential)Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]).User.CustomerFK.Value;
         dbContext.Promotions.First(x => x.PromotionPK == promotionId).IsDeleted = sw.schedulePromotion(promotionId, dbContext.Promotions.First(x => x.PromotionPK == promotionId).PromotionAdEngineSelecteds.Select(pades => pades.AdvertisingEngine.AdvertisingEngine1).ToArray(), SEMplestConstants.SchedulePromotionType.Delete);
         dbContext.SaveChanges();
     }
     catch (Exception ex) { Semplest.SharedResources.Helpers.ExceptionHelper.LogException(ex); }
     return RedirectToAction("Index2");
 }
        public ActionResult RestartPromotions(int id)
        {
            SemplestModel.Semplest dbContext = new SemplestModel.Semplest();
            ServiceClientWrapper sw = new ServiceClientWrapper();
            foreach (ProductGroup pg in dbContext.Customers.Where(key => key.CustomerPK == id).First().ProductGroups)
            {
                foreach (Promotion p in pg.Promotions)
                {
                    if (p.IsLaunched && p.IsPaused && (!p.IsCompleted))
                    {
                        List<string> adEngines = new List<string>();
                        foreach (PromotionAdEngineSelected pades in p.PromotionAdEngineSelecteds)
                            adEngines.Add(pades.AdvertisingEngine.AdvertisingEngine1);
                        p.IsPaused = !sw.schedulePromotion(id, p.PromotionPK, adEngines.ToArray(), true);
                    }
                }
            }

            dbContext.SaveChanges();
            Dictionary<string, object> d = new Dictionary<string, object>();
            d.Add("id", id);
            return RedirectToAction("Index", new System.Web.Routing.RouteValueDictionary(d));
        }
Пример #19
0
 public ActionResult EndPromotion(int promotionIdE)
 {
     try
     {
         ServiceClientWrapper sw = new ServiceClientWrapper();
         SemplestModel.Semplest dbContext = new SemplestModel.Semplest();
         List<string> adEngines = new List<string>();
         Promotion p = dbContext.Promotions.Where(x => x.PromotionPK == promotionIdE).First();
         int customerId = ((Credential)Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]).User.CustomerFK.Value;
         foreach (PromotionAdEngineSelected pades in p.PromotionAdEngineSelecteds)
             adEngines.Add(pades.AdvertisingEngine.AdvertisingEngine1);
         p.IsCompleted = sw.schedulePromotion(promotionIdE, adEngines.ToArray(), SEMplestConstants.SchedulePromotionType.End);
         dbContext.SaveChanges();
     }
     catch (Exception ex) { Semplest.SharedResources.Helpers.ExceptionHelper.LogException(ex); }
     return RedirectToAction("Index2");
 }
        public ActionResult Edit(CustomerAccountWithEmployeeModel m, string command)
        {
            //for cancel just redirect to main page
            if (command.ToLower() == "cancel") return RedirectToAction("Index");
            
            if (command.ToLower() == "delete") return RedirectToAction("Remove", new {id=m.CustomerAccount.AccountNumber});

            SemplestModel.Semplest dbcontext = new SemplestModel.Semplest();

            
            //check if userid has been taken by other users

                  var userIDSs = from c in dbcontext.Credentials
                        where c.Username.Equals(m.CustomerAccount.UserID) && !c.UsersFK.Equals(m.CustomerAccount.UserPK)
                        select c;

                  if (userIDSs.Count() > 0)
                      ModelState.AddModelError("CustomerAccount.UserID", "This UserID is already taken!!");


            if (!ModelState.IsValid)
            {
                #region needs to repopulate lists to get the same view again

                //repopulate 

                /////////////////////////////////////////////////////////////////////////////////
                //for reps dropdown
                /////////////////////////////////////////////////////////////////////////////////
                var allreps = from e in dbcontext.Employees
                              //join eca in dbcontext.EmployeeCustomerAssociations on e.EmployeePK equals eca.EmployeeFK
                              join et in dbcontext.EmployeeTypes on e.EmployeeTypeFK equals et.EmployeeTypeID
                              join u in dbcontext.Users on e.UsersFK equals u.UserPK
                              where (et.EmployeeType1 == "Rep" && u.IsActive.Equals(true))
                              select new EmployeeCustomerAssociaitionModel
                              {
                                  //AccountNumber = eca.CustomerFK,
                                  employeePK = e.EmployeePK,
                                  EmployeeType = et.EmployeeType1,
                                  EmployeeUserPK = u.UserPK,
                                  FirstName = u.FirstName,
                                  LastName = u.LastName,
                                  MiddleInitial = u.MiddleInitial
                              };

                //repopulate 

                /////////////////////////////////////////////////////////////////////////////////
                //for roles dropdown
                /////////////////////////////////////////////////////////////////////////////////
                var roles = (from r in dbcontext.Roles select r).ToList().OrderBy(r => r.RoleName);

                m.Roles = roles.Select(r => new SelectListItem
                {
                    Value = r.RolePK.ToString(),
                    Text = r.RoleName.ToString()
                });



                /////////////////////////////////////////////////////////////////////////////////
                //for sales dropdown
                /////////////////////////////////////////////////////////////////////////////////
                var allsalespersons = from e in dbcontext.Employees
                                      //join eca in dbcontext.EmployeeCustomerAssociations on e.EmployeePK equals eca.EmployeeFK
                                      join et in dbcontext.EmployeeTypes on e.EmployeeTypeFK equals et.EmployeeTypeID
                                      join u in dbcontext.Users on e.UsersFK equals u.UserPK
                                      where (et.EmployeeType1 == "Sales" && u.IsActive.Equals(true))
                                      select new EmployeeCustomerAssociaitionModel
                                      {
                                          //AccountNumber = eca.CustomerFK,
                                          employeePK = e.EmployeePK,
                                          EmployeeType = et.EmployeeType1,
                                          EmployeeUserPK = u.UserPK,
                                          FirstName = u.FirstName,
                                          LastName = u.LastName,
                                          MiddleInitial = u.MiddleInitial
                                      };

                var allstates = (from sc in dbcontext.StateCodes select sc).ToList();

                m.States = allstates.Select(r => new SelectListItem
                {
                    Value = r.StateAbbrPK.ToString(),
                    Text = r.StateAbbr.ToString()
                });


                List<SelectListItem> slina = new List<SelectListItem>();
                slina.Add(new SelectListItem { Value = (-1).ToString(), Text = "«« Not Assigned »»" });



                List<EmployeeCustomerAssociaitionModel> ll1 = allreps.OrderBy(r => r.LastName).ThenBy(r => r.FirstName).ToList();
                List<SelectListItem> sl1 = new List<SelectListItem>();
                foreach (EmployeeCustomerAssociaitionModel s in ll1)
                {
                    SelectListItem mylistitem = new SelectListItem();
                    mylistitem.Text = s.FirstName + " " + s.LastName;
                    mylistitem.Value = s.employeePK.ToString();
                    sl1.Add(mylistitem);
                }


                m.Reps= sl1.Union(slina);

                



                List<EmployeeCustomerAssociaitionModel> ll2 = allsalespersons.OrderBy(r => r.LastName).ThenBy(r => r.FirstName).ToList();
                List<SelectListItem> sl2 = new List<SelectListItem>();
                foreach (EmployeeCustomerAssociaitionModel s in ll2)
                {
                    SelectListItem mylistitem = new SelectListItem();
                    mylistitem.Text = s.FirstName + " " + s.LastName;
                    mylistitem.Value = s.employeePK.ToString();
                    sl2.Add(mylistitem);
                }
                m.SalesPersons = sl2.Union(slina);




              var allparents =
              from c in dbcontext.Customers
              join chi in dbcontext.CustomerHierarchies.Where(p=>p.CustomerParentFK == null) on c.CustomerPK equals chi.CustomerFK
              select c;




                List<SelectListItem> sli = new List<SelectListItem>();
                sli.Add(new SelectListItem { Value = (-1).ToString(), Text = "«« Parent »»" });
                sli.Add(new SelectListItem { Value = (0).ToString(), Text = "«« Single User »»" });
                m.Parents = allparents.ToList().Select(r => new SelectListItem
                {
                    Value = r.CustomerPK.ToString(),
                    Text = r.Name.ToString()
                }).Union(sli);



                var allbilltypes =
                    from bt in dbcontext.BillTypes
                    select bt;
				



                m.BillTypes = allbilltypes.ToList().Select(r => new SelectListItem
                {
                    Value = r.BillTypePK.ToString(),
                    Text = r.BillType1.ToString()
                });

                #endregion
                return View(m);
            }


            var user = dbcontext.Users.ToList().Find(p => p.UserPK == m.CustomerAccount.UserPK);
            user.FirstName = m.CustomerAccount.FirstName;
            user.LastName = m.CustomerAccount.LastName;
            user.MiddleInitial = m.CustomerAccount.MiddleInitial;
            user.Email = m.CustomerAccount.Email;
            user.EditedDate = DateTime.Now;
            user.IsActive = m.CustomerAccount.isActive;
            UpdateModel(user);


            var userrolesassociation = dbcontext.UserRolesAssociations.ToList().Find(p => p.UsersFK == m.CustomerAccount.UserPK);
            userrolesassociation.RolesFK = m.SelectedRoleID;
            UpdateModel(userrolesassociation);


            var customer = dbcontext.Customers.ToList().Find(p => p.CustomerPK == m.CustomerAccount.AccountNumber);
            var customeraddressassociation = dbcontext.CustomerAddressAssociations.ToList().Find(p => p.CustomerFK == customer.CustomerPK);
            var address = dbcontext.Addresses.ToList().Find(p => p.AddressPK == customeraddressassociation.AddressFK);


            customer.Name = m.CustomerAccount.Customer;
            customer.BillTypeFK = m.SelectedBillTypeID;
            customer.PercentOfMedia = m.CustomerAccount.PercentMedia;
            customer.InternalCustomerId = m.CustomerAccount.internalID;
            customer.ServiceFee = m.CustomerAccount.ServiceFee;
            customer.PromotionFeeAmount = m.CustomerAccount.PromotionFeeAmount;
            customer.PromotionFeeOverride = m.CustomerAccount.PromotionFeeOverride;
            customer.CreditLimit = m.CustomerAccount.CreditLimit;



            address.Address1 = m.CustomerAccount.Address1;
            address.Address2 = m.CustomerAccount.Address2;
            address.City = m.CustomerAccount.City;
            address.ZipCode = m.CustomerAccount.Zip;
            address.EditedDate = DateTime.Now;
            address.StateAbbrFK = m.SelectedStateID;

            var customerphoneassociation = dbcontext.CustomerPhoneAssociations.ToList().Find(p => p.CustomerFK == m.CustomerAccount.AccountNumber);
            var phone = dbcontext.Phones.ToList().Find(p => p.PhonePK == customerphoneassociation.PhoneFK);

            phone.Phone1 = m.CustomerAccount.Phone;


            var rep = from c in dbcontext.Customers
                      join eca in dbcontext.EmployeeCustomerAssociations on c.CustomerPK equals eca.CustomerFK
                      join e in dbcontext.Employees on eca.EmployeeFK equals e.EmployeePK
                      join et in dbcontext.EmployeeTypes on e.EmployeeTypeFK equals et.EmployeeTypeID
                      where (c.CustomerPK == m.CustomerAccount.AccountNumber && et.EmployeeType1.ToLower() == "rep")
                      select new ECAModel
                      {
                          CustomerPK = c.CustomerPK,
                          EmployeePK = e.EmployeePK
                      };

            var sales = from c in dbcontext.Customers
                        join eca in dbcontext.EmployeeCustomerAssociations on c.CustomerPK equals eca.CustomerFK
                        join e in dbcontext.Employees on eca.EmployeeFK equals e.EmployeePK
                        join et in dbcontext.EmployeeTypes on e.EmployeeTypeFK equals et.EmployeeTypeID
                        where (c.CustomerPK == m.CustomerAccount.AccountNumber && et.EmployeeType1.ToLower() == "sales")
                        select new ECAModel
                        {
                            CustomerPK = c.CustomerPK,
                            EmployeePK = e.EmployeePK
                        };

            //rep.ToList().First().EmployeePK = m.SelectedRepID;
            //sales.ToList().First().EmployeePK = m.SelectedSalesPersonID;
            var credentials = dbcontext.Credentials.ToList().Find(p => p.UsersFK == m.CustomerAccount.UserPK);
            credentials.Username = m.CustomerAccount.UserID;
            credentials.Password = m.CustomerAccount.UserPassword;

            var employeesales = dbcontext.EmployeeCustomerAssociations.ToList().Find(p => p.CustomerFK == m.CustomerAccount.AccountNumber && p.EmployeeFK == (sales.ToList().FirstOrDefault()==null?-1: sales.ToList().FirstOrDefault().EmployeePK) );
            if (employeesales == null && m.SelectedSalesPersonID !=-1)
            {
                //add one
                var addemployeesales=new EmployeeCustomerAssociation {  CustomerFK=m.CustomerAccount.AccountNumber  , EmployeeFK = m.SelectedSalesPersonID  };
                dbcontext.EmployeeCustomerAssociations.Add(addemployeesales);
            }
            else if (employeesales != null && m.SelectedSalesPersonID == -1)
            { 
                //remove
                dbcontext.EmployeeCustomerAssociations.Remove(employeesales);
            }
            else if (employeesales != null  && m.SelectedSalesPersonID != -1)
            {
                employeesales.EmployeeFK = m.SelectedSalesPersonID;
                UpdateModel(employeesales);
            }
            
            var employeerep = dbcontext.EmployeeCustomerAssociations.ToList().Find(p => p.CustomerFK == m.CustomerAccount.AccountNumber && p.EmployeeFK == (rep.ToList().FirstOrDefault()==null?-1: rep.ToList().FirstOrDefault().EmployeePK) );
            if (employeerep == null && m.SelectedRepID !=-1)
            {
                //add one
                var addemployeerep =new EmployeeCustomerAssociation {  CustomerFK=m.CustomerAccount.AccountNumber  , EmployeeFK = m.SelectedRepID };
                dbcontext.EmployeeCustomerAssociations.Add(addemployeerep);

            }
            else if (employeerep != null && m.SelectedRepID == -1)
                {
                    //remove
                    dbcontext.EmployeeCustomerAssociations.Remove(employeerep);
                }
        else if (employeerep != null  && m.SelectedRepID  != -1)
                {
                    employeerep.EmployeeFK = m.SelectedRepID;
                    UpdateModel(employeerep);
                }


            

            //var employeecustomerassociation = dbcontext.EmployeeCustomerAssociations.ToList().Find(p => p.CustomerFK  == customer.CustomerPK && p.EmployeeFK==1);

            //employeecustomerassociation.
            //employeecustomerassociation.EmployeeCustomerAssociationPK

            UpdateModel(address);
            var customernote = dbcontext.CustomerNotes.ToList().FirstOrDefault(p => p.CustomerFK == m.CustomerAccount.AccountNumber);
            customernote.Note = m.CustomerAccount.CustomerNote;
            UpdateModel(customernote);


            var parents = dbcontext.CustomerHierarchies.FirstOrDefault(p => p.CustomerFK == m.CustomerAccount.AccountNumber);
            //var parents = dbcontext.CustomerHierarchies.FirstOrDefault();

            if (m.SelectedParentID == 0) //self -- single user
            {
                parents.CustomerParentFK = parents.CustomerFK;
            }
            else if (m.SelectedParentID == -1) //parent
            {
                parents.CustomerParentFK = null;
            }
            else
            {
                parents.CustomerParentFK = m.SelectedParentID;
            }

            dbcontext.SaveChanges();

            return RedirectToAction("Index");
            //return View("index");
            //return View(m);
        }
Пример #21
0
        public List<CampaignSetupModel.KeywordsModel> SaveNegativeKeywords(CampaignSetupModel model, int customerFk)
        {
            if (model.AdModelProp.NegativeKeywords.Any())
            {
                GoogleViolation[] gv = ValidateGoogleNegativeKeywords(model.AdModelProp.NegativeKeywords);
                if (gv.Length > 0)
                    throw new Exception(gv.First().shortFieldPath + ": " + gv.First().errorMessage);
            }
            using (var dbcontext = new SemplestModel.Semplest())
            {
                var promo = GetPromoitionFromCampaign(dbcontext, customerFk, model);
                if (!promo.IsLaunched)
                { RefreshKeywords(model, promo); }
                else
                {
                    var addKiops = new List<KeywordIdRemoveOppositePair>();
                    var addNewKiops = new List<string>();
                    var addDeletedKiops = new List<int>();
                    var qpka = promo.PromotionKeywordAssociations.ToList();
                    //check negative keywords that have been added to the gui
                    if (model.AdModelProp.NegativeKeywords != null)
                    {
                        foreach (string negativeKeyword in model.AdModelProp.NegativeKeywords)
                        {
                            var kiop = new KeywordIdRemoveOppositePair();
                            var pka = qpka.SingleOrDefault(key => key.Keyword.Keyword1 == negativeKeyword);
                            if (pka != null)
                            {
                                //means if the keyword existied and was positive it needs to be removed and added as a negative. 
                                //if the keyword is already negative then do nothing because we've already added it
                                kiop.keywordId = pka.KeywordFK;
                                if (!pka.IsNegative)
                                {
                                    kiop.removeOpposite = true;
                                    addKiops.Add(kiop);
                                }
                            }
                            else
                            {
                                var kw = dbcontext.Keywords.SingleOrDefault(key => key.Keyword1 == negativeKeyword);
                                if (kw != null)
                                {
                                    kiop.keywordId = kw.KeywordPK;
                                    kiop.removeOpposite = false;
                                    addKiops.Add(kiop);
                                }
                                else//this keyword doesn't exist in the database so when we call the stored proc get the id so it can be sent to the api
                                    addNewKiops.Add(negativeKeyword);
                            }
                        }
                    }

                    //check for negative keywords that have been removed from the gui
                    foreach (PromotionKeywordAssociation k in qpka.Where(key => key.IsNegative == true).ToList())
                    {
                        if (!model.AdModelProp.NegativeKeywords.Contains(k.Keyword.Keyword1))
                            addDeletedKiops.Add(k.Keyword.KeywordPK);
                    }

                    List<int> deletedKeywords = new List<int>();
                    var op = new System.Data.Objects.ObjectParameter("NegativeKeywordID", typeof(int));
                    var op2 = new System.Data.Objects.ObjectParameter("Exists", typeof(int));
                    foreach (string kw in model.AdModelProp.NegativeKeywords)
                    {
                        //keywords that need to be deleted
                        var snr = dbcontext.SetNegativeKeyword(kw, promo.PromotionPK, op, op2).ToList();
                        if (snr.Any())
                        {
                            deletedKeywords.AddRange(snr.Select(ids => ids.KeywordPK));
                        }

                        if (!string.IsNullOrEmpty(op.Value.ToString()))
                        {
                            var kop = new KeywordIdRemoveOppositePair { keywordId = int.Parse(op.Value.ToString()), removeOpposite = bool.Parse(op2.Value.ToString()) };
                            addKiops.Add(kop);
                        }
                    }
                    foreach (int dk in addDeletedKiops)
                        promo.PromotionKeywordAssociations.Single(kw => kw.KeywordFK == dk).IsDeleted=true;
                    dbcontext.SaveChanges();
                    _savedCampaign = true;
                    var sw = new ServiceClientWrapper();
                    var adEngines = new List<string>();
                    adEngines.AddRange(
                        promo.PromotionAdEngineSelecteds.Select(pades => pades.AdvertisingEngine.AdvertisingEngine1));
                    if (addDeletedKiops.Any())
                        sw.DeleteNegativeKeywords(promo.PromotionPK, addDeletedKiops, adEngines);
                    if (addKiops.Any())
                        sw.AddNegativeKeywords(promo.PromotionPK, addKiops, adEngines);
                    if (deletedKeywords.Any())
                        sw.DeleteKeywords(promo.PromotionPK, deletedKeywords, adEngines);
                }
                model.AllKeywords.Clear();
                model.AllKeywords.AddRange(
                    promo.PromotionKeywordAssociations.Where(key => !key.IsDeleted && !key.IsNegative).Select(
                        key =>
                        new CampaignSetupModel.KeywordsModel { Name = key.Keyword.Keyword1, Id = key.Keyword.KeywordPK }));
            }
            return model.AllKeywords;
        }
Пример #22
0
        public ActionResult LaunchAdProduct(CampaignSetupModel model)
        {
            ServiceClientWrapper sw = new ServiceClientWrapper();
            List<string> adEngines = new List<string>();
            if (ModelState.IsValid)
            {
                model = (CampaignSetupModel)Session["CampaignSetupModel"];
                //SemplestDataService ds = new SemplestDataService();
                //ds.SaveAd(model);
            }
            var dbContext = new SemplestModel.Semplest();
            //ProductGroup pg = dbContext.ProductGroups.Where(x => x.ProductGroupName == model.ProductGroup.ProductGroupName).First();
            //Promotion pm = dbContext.ProductGroups.Where(x => x.ProductGroupName==model.ProductGroup.ProductGroupName).First().Promotions.Where(p => p.PromotionName == model.ProductGroup.ProductPromotionName).First();
            var userid = ((Credential)(Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID])).UsersFK;
            int customerFk = ((Credential)(Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID])).User.CustomerFK.Value;
            var pm =
                dbContext.Users.First(x => x.UserPK == userid).Customer.ProductGroups.First(
                    x => x.ProductGroupName == model.ProductGroup.ProductGroupName).Promotions.First(
                    p => p.PromotionName == model.ProductGroup.ProductPromotionName);
            foreach (PromotionAdEngineSelected pades in pm.PromotionAdEngineSelecteds)
                adEngines.Add(pades.AdvertisingEngine.AdvertisingEngine1);
            try
            {
                pm.IsLaunched = sw.scheduleAddPromotionToAdEngine(customerFk, pm.ProductGroupFK, pm.PromotionPK, adEngines.ToArray()); ;
            }
            catch (Exception ex)
            {
                var logEnty = new LogEntry { ActivityId = Guid.NewGuid(), Message = ex.Message };
                Logger.Write(logEnty);
                pm.IsLaunched = true;
            }
            dbContext.SaveChanges();
            //return PartialView("KeyWords", model);

            //return View();
            //return Json("Congratulations, Your Product has Launched!!!");
            // now we are showing the image with wait window so we don't to show this in message box
            return Json("");
            //return Json("LaunchAdProduct");

        }
Пример #23
0
 public void SaveProductPromotion(int customerFk, CampaignSetupModel model, CampaignSetupModel oldModel)
 {
     using (var dbcontext = new SemplestModel.Semplest())
     {
         var queryProdGrp = from c in dbcontext.ProductGroups
                            where
                                c.CustomerFK == customerFk &&
                                c.ProductGroupName == model.ProductGroup.ProductGroupName
                            select c;
         if (!queryProdGrp.Any())
         {
             //create new productgroup and promotion
             var prodgroup = new ProductGroup
             {
                 ProductGroupName = model.ProductGroup.ProductGroupName,
                 IsActive = true,
                 CustomerFK = customerFk,
                 StartDate =
                     Convert.ToDateTime(model.ProductGroup.StartDate,
                                        new CultureInfo("en-Us")),
                 EndDate =
                     String.IsNullOrEmpty(model.ProductGroup.EndDate)
                         ? (DateTime?)null
                         : Convert.ToDateTime(model.ProductGroup.EndDate)
             };
             var promo = CreatePromotionFromModel(model,
                                                     dbcontext.Configurations.First().
                                                         CustomerDefaultPerCampaignFlatFeeAmount);
             dbcontext.ProductGroups.Add(prodgroup);
             dbcontext.Promotions.Add(promo);
             SavePromotionAdEngineSelected(promo,model, dbcontext);
             dbcontext.SaveChanges();
             _savedCampaign = true;
         }
         else
         {//productgroupexists
             var updateProdGrp = queryProdGrp.Single();
             var updatePromotion = GetPromotionFromProductGroup(updateProdGrp,
                                                                model.ProductGroup.ProductPromotionName);
             // if this is null means promotion name changed so create a new promotion
             if (updatePromotion == null)
             {
                 // create new promotion
                 updatePromotion = CreatePromotionFromModel(model,
                                                            dbcontext.Configurations.First().
                                                                CustomerDefaultPerCampaignFlatFeeAmount);
                 updatePromotion.ProductGroupFK = updateProdGrp.ProductGroupPK;
                 dbcontext.Promotions.Add(updatePromotion);
                 SavePromotionAdEngineSelected(updatePromotion, model, dbcontext);
             }
             else
             {
                 // update promotion
                 UpdatePromotionFromModel(updatePromotion, model, dbcontext.Configurations.First().CustomerDefaultPerCampaignFlatFeeAmount);
                 if (updatePromotion.IsLaunched)
                 {
                     var sw = new ServiceClientWrapper();
                     var adEngines = new List<string>();
                     adEngines.AddRange(
                         updatePromotion.PromotionAdEngineSelecteds.Select(
                             pades => pades.AdvertisingEngine.AdvertisingEngine1));
                     if (model.ProductGroup.Budget != oldModel.ProductGroup.Budget)
                         sw.scheduleUpdateBudget(updatePromotion.PromotionPK, model.ProductGroup.Budget,
                                                 adEngines);
                     if (Convert.ToDateTime(model.ProductGroup.StartDate) != Convert.ToDateTime(oldModel.ProductGroup.StartDate))
                         sw.scheduleChangePromotionStartDate(updatePromotion.PromotionPK,
                                                             updatePromotion.PromotionStartDate, adEngines);
                 }
                 SavePromotionAdEngineSelected(updatePromotion, model, dbcontext);
             }
         }
         dbcontext.SaveChanges();
         // we need to set this because the _dbcontext is  and campaign is updated so reflect changes we need to create new context
         _savedCampaign = true;
     }
 }
Пример #24
0
        public string SavePromotionDetails(SmartWordSetupModel model, SmartWordSetupModel oldModel, int customerFk)
        {
            var rString = new System.Text.StringBuilder();
            using (var dbcontext = new SemplestModel.Semplest())
            {
                var queryProdGrp = (from c in dbcontext.ProductGroups
                                    where
                                        c.CustomerFK == customerFk &&
                                        c.ProductGroupName == model.ProductGroup.ProductGroupName
                                    select c).SingleOrDefault();
                Promotion promo;
                if (queryProdGrp == null)
                {
                    //create new productgroup and promotion
                    var prodgroup = new ProductGroup
                                        {
                                            ProductGroupName = model.ProductGroup.ProductGroupName,
                                            IsActive = true,
                                            CustomerFK = customerFk,
                                            StartDate =
                                                Convert.ToDateTime(model.ProductGroup.StartDate,
                                                                   new CultureInfo("en-Us")),
                                            EndDate =
                                                String.IsNullOrEmpty(model.ProductGroup.EndDate)
                                                    ? (DateTime?) null
                                                    : Convert.ToDateTime(model.ProductGroup.EndDate)
                                        };

                    if (model.LandingUrl != null)
                        model.LandingUrl = model.LandingUrl.Trim();
                    promo = CreatePromotionFromModel(model);
                    dbcontext.ProductGroups.Add(prodgroup);
                    dbcontext.Promotions.Add(promo);
                    dbcontext.SaveChanges();
                }
                else
                {
                    var updateProdGrp = queryProdGrp;
                    promo = GetPromotionFromProductGroup(updateProdGrp,
                                                         model.ProductGroup.ProductPromotionName);
                    // if this is null means promotion name changed so create a new promotion
                    if (promo == null)
                    {
                        // create new promotion
                        promo = CreatePromotionFromModel(model);
                        promo.ProductGroupFK = updateProdGrp.ProductGroupPK;
                        dbcontext.Promotions.Add(promo);
                    }
                    else
                    {
                        promo.LandingPageURL = model.LandingUrl.Trim();
                        promo.PromotionName = model.ProductGroup.ProductPromotionName;
                        promo.PromotionDescription = model.ProductGroup.Words;
                    }
                }


                GeoTargetTableType gt;
                int addressCode = -1;
                var st = dbcontext.AddressTypes.SingleOrDefault(pt => pt.AddressType1 == model.PromotionAddressType);
                if (st != null)
                    addressCode = st.AddressTypePK;
                AddGeoTargetingToPromotion(promo, model, oldModel, out gt);
      

                var parameter = new SqlParameter("PromotionPK", promo.PromotionPK) {SqlDbType = SqlDbType.Int};
                var parameter2 = new SqlParameter("LandingUrl", model.LandingUrl.Trim())
                                     {SqlDbType = SqlDbType.NVarChar};
                var parameter3 = new SqlParameter("DisplayUrl", string.Empty) {SqlDbType = SqlDbType.NVarChar};
                var parameter4 = new SqlParameter("AddressTypeFK", addressCode) {SqlDbType = SqlDbType.Int};
                var parameter5 = new SqlParameter("GeoTVP", gt)
                                     {SqlDbType = SqlDbType.Structured, TypeName = "GeoTargetTableType"};
                var parameter6 = new SqlParameter("AdTVP", null)
                                     {SqlDbType = SqlDbType.Structured, TypeName = "PromoAdTableType"};
                var parameters = new object[] {parameter, parameter2, parameter3, parameter4, parameter5, parameter6};
                var results =
                    ((IObjectContextAdapter) dbcontext).ObjectContext.ExecuteStoreQuery<RVal>(
                        "exec UpdateGeoTargetingPromoAds @PromotionPK, @LandingUrl, @DisplayUrl, @AddressTypeFK, @GeoTVP, @AdTVP",
                        parameters);
                foreach (var r in results)
                {
                    rString.Append(r.UID);
                    rString.Append("=");
                    rString.Append(r.PKEY);
                    rString.Append(",");
                }















                dbcontext.SaveChanges();
            }
            return string.IsNullOrEmpty(rString.ToString())
                       ? String.Empty
                       : rString.ToString().Substring(0, rString.ToString().Length - 1);
        }
Пример #25
0
 public void AddRightToDatabase(string label, string controllerName, string vAction)
 {
     return;
     bool found = false;
     string myController = ControllerContext.RouteData.Values["Controller"].ToString();
     if (controllerName != "Roles")
     {
         string controllerActionName = controllerName + "." + vAction;
         if (controllerName != myController && !string.IsNullOrEmpty(label))
         {
             using (var dbContext = new SemplestModel.Semplest())
             {
                 foreach (Right r in dbContext.Rights)
                 {
                     if (label == r.Label && controllerActionName == r.Controller)
                     {
                         found = true;
                         break;
                     }
                 }
                 try
                 {
                     if (!found)
                     {
                         dbContext.Rights.Add(new Right { Controller = controllerActionName, Label = label });
                         dbContext.SaveChanges();
                     }
                 }
                 catch (Exception ex)
                 {
                     Console.WriteLine(ex.ToString());
                 }
             }
         }
     }
 }
Пример #26
0
 public void SetKeywordsDeleted(List<int> keywordIds, int promoId)
 {
     using (var dbcontext = new SemplestModel.Semplest())
     {
         foreach (int keywordId in keywordIds)
             dbcontext.PromotionKeywordAssociations.Where(key => key.KeywordFK == keywordId).First(
                 key => key.PromotionFK == promoId).IsDeleted = true;
         dbcontext.SaveChanges();
         _savedCampaign = true;
         var adEngines = new List<string>();
         var promo = dbcontext.Promotions.Single(row => row.PromotionPK == promoId);
         if (promo.IsLaunched)
         {
             var sw = new ServiceClientWrapper();
             adEngines.AddRange(
                     promo.PromotionAdEngineSelecteds.Select(pades => pades.AdvertisingEngine.AdvertisingEngine1));
             sw.DeleteKeywords(promoId, keywordIds, adEngines);
         }
     }
 }
Пример #27
0
        public void AddCustomer(CustomerAccountWithEmployeeModel m)
        {
            try
            {
                SemplestModel.Semplest dbcontext = new SemplestModel.Semplest();
                //BillType bt = dbcontext.BillTypes.First(p => p.BillType1 == "Flat Fee"); // --- feees --- !!!
                //revisit 
                ProductGroupCycleType pgct = dbcontext.ProductGroupCycleTypes.First(p => p.ProductGroupCycleType1 == "Product Group Cycle 30");

                var c = new Customer
                            { 
                                Name = m.CustomerAccount.Customer,
                                BillTypeFK = m.SelectedBillTypeID,
                                ProductGroupCycleType = pgct,
                                 PercentOfMedia=m.CustomerAccount.PercentMedia,
                                 ServiceFee= m.CustomerAccount.ServiceFee,
                                  InternalCustomerId= m.CustomerAccount.internalID,
                                PromotionFeeAmount = m.CustomerAccount.PromotionFeeAmount,
                                CreditLimit=m.CustomerAccount.CreditLimit,
                                PromotionFeeOverride=m.CustomerAccount.PromotionFeeOverride,
                                CreatedDate = DateTime.Now,
                                AllowAutobid = m.CustomerAccount.AllowAutoBid
                            };

                dbcontext.Customers.Add(c);
                var ur = new UserRepository(dbcontext);
                var u = new User
                            {
                                Customer = c,
                                Email = m.CustomerAccount.Email,
                                FirstName = m.CustomerAccount.FirstName,
                                LastName = m.CustomerAccount.LastName,
                                MiddleInitial = m.CustomerAccount.MiddleInitial,
                                IsActive = m.CustomerAccount.isActive,
                                CreatedDate = DateTime.Now,
                                UserTypeFK = m.SelectedUserTypeID
                            };
                dbcontext.Users.Add(u);

                var r = dbcontext.Roles.First(p => p.RolePK == m.SelectedRoleID);
                var ura = new UserRolesAssociation { Role = r, User = u };
                dbcontext.UserRolesAssociations.Add(ura);
                AesEncyrption ae = AesEncyrption.getInstance();
                var encryptedPassword = ae.EncryptString(m.CustomerAccount.UserPassword);
                var cr = new Credential
                             { 
                                 User = u,
                                 UsersFK = u.UserPK,
                                 Username = m.CustomerAccount.UserID,
                                 Password = encryptedPassword
                             };
                dbcontext.Credentials.Add(cr);
                PhoneType pt = dbcontext.PhoneTypes.First(p => p.PhoneType1 == "Business"); // --- phone types --- !!!!
                var ph = new Phone {Phone1 = m.CustomerAccount.Phone, PhoneType = pt};
                dbcontext.Phones.Add(ph);
                var cpa = new CustomerPhoneAssociation {Customer = c, Phone = ph};
                dbcontext.CustomerPhoneAssociations.Add(cpa);
                var sc = dbcontext.StateCodes.First(p => p.StateAbbrPK == m.SelectedStateID);
                var at = dbcontext.AddressTypes.First(p => p.AddressType1 == "H"); // --- address types --- !!!
                var a = new Address
                            {
                                Address1 = m.CustomerAccount.Address1,
                                Address2 = m.CustomerAccount.Address2,
                                City = m.CustomerAccount.City,
                                ZipCode = m.CustomerAccount.Zip,
                                StateCode = sc
                            };
                dbcontext.Addresses.Add(a);
                var caa = new CustomerAddressAssociation {Address = a, Customer = c, AddressType = at};
                dbcontext.CustomerAddressAssociations.Add(caa);
                var cn = new CustomerNote {Customer = c, Note = m.CustomerAccount.CustomerNote};
                dbcontext.CustomerNotes.Add(cn);
                //don't add if not assigned
                if (m.SelectedRepID != -1)
                {
                    var addrep = new EmployeeCustomerAssociation { Customer = c, EmployeeFK = m.SelectedRepID };
                    dbcontext.EmployeeCustomerAssociations.Add(addrep);
                }
                //don't add if not assigned
                if (m.SelectedSalesPersonID != -1)
                {
                    var addsales = new EmployeeCustomerAssociation { Customer = c, EmployeeFK = m.SelectedSalesPersonID };
                    dbcontext.EmployeeCustomerAssociations.Add(addsales);
                }
                CustomerHierarchy ch = null;
                if (m.SelectedParentID == -1) //set parent
                {
                    ch = new CustomerHierarchy {CustomerFK = c.CustomerPK, CustomerParentFK = null};
                    dbcontext.CustomerHierarchies.Add(ch);
                }
                else if (m.SelectedParentID == 0) //set self -- single user
                {
                    ch = new CustomerHierarchy {CustomerFK = c.CustomerPK, CustomerParentFK = c.CustomerPK};
                    dbcontext.CustomerHierarchies.Add(ch);
                }
                else //assign a parent
                {
                    ch = new CustomerHierarchy {CustomerFK = c.CustomerPK, CustomerParentFK = m.SelectedParentID};
                    dbcontext.CustomerHierarchies.Add(ch);
                }
                dbcontext.SaveChanges();

                SendAccountActivationEmail(u.UserPK);

            }
            catch (Exception ex)
            {
                Semplest.SharedResources.Helpers.ExceptionHelper.LogException(ex);
            }
        }
Пример #28
0
 public void SaveSelectedCategories(int promotionId, IEnumerable<string> selectedCategories)
 {
     using (var dbcontext = new SemplestModel.Semplest())
     {
         var query = dbcontext.KeywordCategories.Where(c => c.PromotionFK == promotionId);
         if (!query.Any())
         {
             foreach (
                 var keyCategory in
                     selectedCategories.Select(
                         category => new KeywordCategory {PromotionFK = promotionId, KeywordCategory1 = category})
                 )
             {
                 dbcontext.KeywordCategories.Add(keyCategory);
             }
             dbcontext.SaveChanges();
         }
         else // categories exists so update them
         {
             // delete them first
             foreach (KeywordCategory kc in query)
             {
                 dbcontext.KeywordCategories.Remove(kc);
             }
             dbcontext.SaveChanges();
             // add them
             foreach (
                 var keyCategory in
                     selectedCategories.Select(
                         category => new KeywordCategory {PromotionFK = promotionId, KeywordCategory1 = category})
                 )
             {
                 dbcontext.KeywordCategories.Add(keyCategory);
             }
             dbcontext.SaveChanges();
         }
     }
 }
Пример #29
0
        public void SaveGeoTargetingAds(int customerFK, CampaignSetupModel model, CampaignSetupModel oldModel)
        {
            using (var dbcontext = new SemplestModel.Semplest())
            {
                var queryProd = (from c in dbcontext.ProductGroups
                                 where
                                     c.CustomerFK == customerFK &&
                                     c.ProductGroupName == model.ProductGroup.ProductGroupName
                                 select c).Single();
                var promo = GetPromotionFromProductGroup(queryProd, model.ProductGroup.ProductPromotionName);

                List<PromotionAd> addAds;
                List<int> updateAds;
                List<int> deleteAds;
                GoogleViolation[] gv;
                var shouldscheduleAds = AddPromotionAdsToPromotion(promo, model, customerFK, oldModel,
                                                   out addAds, out updateAds, out deleteAds);
                if (shouldscheduleAds)
                {
                    List<GoogleAddAdRequest> verifyAds =
                      model.AdModelProp.Ads.Where(t => !t.Delete).Select(pad => new GoogleAddAdRequest
                      {
                          promotionAdID = promo.PromotionPK,
                          headline = pad.AdTitle,
                          description1 =
                              pad.AdTextLine1,
                          description2 =
                              pad.AdTextLine2
                      }).ToList();
                    gv = ValidateAds(model.AdModelProp.LandingUrl,
                                                                           model.AdModelProp.DisplayUrl, verifyAds);
                    if (gv.Length > 0)
                        throw new Exception(gv.First().shortFieldPath + ": " + gv.First().errorMessage);
                }
                var shouldUpdateGeoTargeting = AddGeoTargetingToPromotion(promo, model, customerFK, oldModel,
           ((IObjectContextAdapter)dbcontext).ObjectContext);
                if (shouldUpdateGeoTargeting)
                {
                    var gtos = SerializeToGeoTargetObjectArray(model);
                    if (gtos.Any())
                    {
                        gv = ValidateGeotargeting(gtos);
                        if (gv.Length > 0)
                            throw new Exception(gv.First().shortFieldPath + ": " + gv.First().errorMessage);
                        var op = new System.Data.Objects.ObjectParameter("totalSize", typeof(int));
                        string valueDelimiter = ",";
                        string listDelimiter = ";";
                        dbcontext.GetMSNGeoLocation(null, SerializeToCommaDlimitedString(model.AdModelProp.Addresses, valueDelimiter, listDelimiter), valueDelimiter, listDelimiter, op);
                        if ((int)op.Value > 250)
                            throw new Exception("geotarget limit");
                    }
                }
                promo.LandingPageURL = model.AdModelProp.LandingUrl.Trim();
                promo.DisplayURL = model.AdModelProp.DisplayUrl.Trim();
                dbcontext.SaveChanges();
                _savedCampaign = true;

                if (promo.IsLaunched)
                {
                    var sw = new ServiceClientWrapper();
                    var adEngines = new List<string>();
                    adEngines.AddRange(
                            promo.PromotionAdEngineSelecteds.Select(
                                pades => pades.AdvertisingEngine.AdvertisingEngine1));
                    if (shouldscheduleAds)
                    {
                        if (addAds.Any())
                        {
                            var addAdsIds =
                                addAds.Select(
                                    promoAd =>
                                    dbcontext.PromotionAds.Single(
                                        row =>
                                        row.AdTextLine1 == promoAd.AdTextLine1 && row.AdTextLine2 == promoAd.AdTextLine2 &&
                                        row.AdTitle == promoAd.AdTitle && row.PromotionFK == promo.PromotionPK).
                                        PromotionAdsPK).ToList();
                            sw.scheduleAds(promo.PromotionPK, addAdsIds, adEngines,
                                           SEMplestConstants.PromotionAdAction.Add);
                        }
                        if (updateAds.Any())
                            sw.scheduleAds(promo.PromotionPK, updateAds, adEngines,
                                           SEMplestConstants.PromotionAdAction.Update);
                        if (deleteAds.Any())
                            sw.scheduleAds(promo.PromotionPK, deleteAds, adEngines,
                                           SEMplestConstants.PromotionAdAction.Delete);
                    }
                    if (shouldUpdateGeoTargeting)
                        sw.scheduleUpdateGeoTargeting(promo.PromotionPK, adEngines);
                }
            }
        }