Пример #1
0
        public void CanDeleteLabel()
        {
            var labelRepository  = new LocalRepository <Label>();
            var clientRepository = new LocalRepository <Client>();
            var controller       = new LabelController(labelRepository, clientRepository);

            labelRepository.Add(new Label()
            {
                Id = 1, Name = "Label 1"
            });
            labelRepository.Add(new Label()
            {
                Id = 2, Name = "Label 2"
            });
            labelRepository.Add(new Label()
            {
                Id = 3, Name = "Label 3"
            });

            Assert.AreEqual(3, labelRepository.All().Count());

            controller.Delete(2);

            Assert.AreEqual(2, labelRepository.All().Count());
            Assert.IsTrue(labelRepository.All().Any(l => l.Id == 1 && l.Name == "Label 1"));
            Assert.IsTrue(labelRepository.All().Any(l => l.Id == 3 && l.Name == "Label 3"));
        }
        public void CanEditValueAndCommentOfABudget()
        {
            IRepository <Client> clientRepository = new LocalRepository <Client>();
            IRepository <Budget> budgetRepository = new LocalRepository <Budget>();
            var userManager = new Mock <IIdentityMembershipProvider>();

            Budget budget1 = new Budget();

            budget1.Id       = 1;
            budget1.Value    = 1000;
            budget1.Month    = new DateTime(2014, 1, 1);
            budget1.ClientId = 1;

            budgetRepository.Add(budget1);

            Assert.AreEqual(1, budgetRepository.All().Count());
            var controller = new BudgetController(clientRepository, budgetRepository, userManager.Object);

            var createBudgetPostMessage = new EditBudgetViewModel
            {
                id       = 1,
                clientId = 1,
                month    = "2014-01-01",
                value    = 3000,
                comment  = "New Comment"
            };

            controller.Edit(createBudgetPostMessage);
            Assert.AreEqual(1, budgetRepository.All().Count());
            Assert.AreEqual(3000, budgetRepository.All().First().Value);
            Assert.AreEqual("New Comment", budgetRepository.All().First().Comment);
        }
        public void MandrillContentWebhookHasEmailInRepository()
        {
            var leadRepository = new LocalRepository <Contact>();
            var emailLead      = ModelHelper.EmailLead;

            leadRepository.Add(emailLead);
            var serverTime        = new Mock <IServerTime>();
            var clientRepository  = new Mock <IRepository <Client> >();
            var contactService    = new Mock <IContactService>();
            var xDataProvider     = new Mock <IExternalDataProvider>();
            var contactAutoRating = new Mock <IContactAutoRating>();


            serverTime.Setup(st => st.RequestStarted).Returns(new DateTime(2013, 01, 01, 9, 0, 0));

            var emailController = new WebhookController(leadRepository, clientRepository.Object, contactService.Object, serverTime.Object, xDataProvider.Object, contactAutoRating.Object);

            emailController.MandrillContentWebhook(new MadrillContentPost {
                id = "1", html = "<p>New Sample Text</p>", text = "New Sample Text", to = "*****@*****.**"
            });
            Assert.AreEqual(1, leadRepository.All().Count());
            Assert.AreEqual("New Sample Text", leadRepository.All().First().Property.First(lp => lp.Type == "Text").Value);
            Assert.AreEqual("<p>New Sample Text</p>", leadRepository.All().First().Property.First(lp => lp.Type == "Html").Value);
            contactAutoRating.Verify(ar => ar.SetAutoRating(It.Is <Contact>(c => c.Id == emailLead.Id)), Times.Once());

            contactService.Verify(cs => cs.NotifyClientsForNewContactWithEmail(It.IsAny <int>()), Times.Never);
            contactService.Verify(cs => cs.NotifyClientsForNewContactWithPhoneNotification(It.IsAny <int>()), Times.Never);
            contactService.Verify(cs => cs.NotifyClientsForNewContactWithSmsNotification(It.IsAny <int>()), Times.Never);
        }
Пример #4
0
        public void RemoveExpiredTokens()
        {
            var tokenRepository = new LocalRepository <Token>();
            var userRepository  = new Mock <IRepository <InsideUser> >();
            var provider        = new AccessTokenProvider(tokenRepository, userRepository.Object);
            var expiredToken    = new Token()
            {
                Id             = 1,
                UserId         = "NewGuidString",
                AccessToken    = "Some Random Generated String 1",
                ExpirationDate = DateTime.Today.AddDays(-1)
            };
            var validToken = new Token()
            {
                Id             = 2,
                UserId         = "NewGuidString2",
                AccessToken    = "Some Random Generated String 2",
                ExpirationDate = DateTime.Today.AddDays(1)
            };

            tokenRepository.Add(expiredToken);
            tokenRepository.Add(validToken);

            provider.RemoveExpired();

            Assert.AreEqual(1, tokenRepository.All().Count());
            Assert.AreEqual(validToken.ExpirationDate, tokenRepository.All().Single().ExpirationDate);
        }
        public void CanDeleteABudget()
        {
            IRepository <Client> clientRepository = new LocalRepository <Client>();
            IRepository <Budget> budgetRepository = new LocalRepository <Budget>();
            var userManager = new Mock <IIdentityMembershipProvider>();

            Budget budget1 = new Budget();

            budget1.Id       = 1;
            budget1.Value    = 1000;
            budget1.Month    = new DateTime(2014, 1, 1);
            budget1.ClientId = 1;

            Budget budget2 = new Budget();

            budget2.Id       = 2;
            budget2.Value    = 2000;
            budget2.Month    = new DateTime(2014, 2, 1);
            budget2.ClientId = 2;

            budgetRepository.Add(budget1);
            budgetRepository.Add(budget2);

            Assert.AreEqual(2, budgetRepository.All().Count());

            var controller = new BudgetController(clientRepository, budgetRepository, userManager.Object);

            controller.Delete(1);

            Assert.AreEqual(1, budgetRepository.All().Count());
        }
Пример #6
0
        public void CanCreateLabel()
        {
            var labelRepository  = new LocalRepository <Label>();
            var clientRepository = new LocalRepository <Client>();
            var controller       = new LabelController(labelRepository, clientRepository);

            Assert.AreEqual(0, labelRepository.All().Count());

            controller.Create("New Label");

            Assert.AreEqual(1, labelRepository.All().Count());
            Assert.IsTrue(labelRepository.All().Any(l => l.Name == "New Label"));
        }
Пример #7
0
        public void ExistingDateForSeoDataInDbNotCreateNewDataThrowException()
        {
            var downloadManager = new Mock <IDownloadManager>();
            var seoDataMapper   = new Mock <ISeoDataImportMapper>();
            var serpRepository  = new LocalRepository <SerpRanking>();

            var serpRankingInDb = new SerpRanking
            {
                Date    = DateTime.Now,
                Keyword = "Keyword",
                Url     = "url.se"
            };

            serpRepository.Add(serpRankingInDb);

            var seoPosion = "[{\"pr\":\"3\",\"url\":\"url.se\",\"kw\":\"key word\",\"region\":\"google.se\",\"language\":\"sv\",\"start\":\"0\"}]";

            downloadManager.Setup(dm => dm.FetchUrl(It.IsAny <string>())).Returns(seoPosion);

            var taskMessage = "";

            var task = new SeoDataImporter(downloadManager.Object, serpRepository, seoDataMapper.Object);

            task.PerformTask(new InsideModel.Models.Task()
            {
                Message = taskMessage
            });

            seoDataMapper.Verify(di => di.Map(It.IsAny <SearchEngineRank>(), It.IsAny <SerpRanking>()), Times.Never);
            Assert.AreEqual(1, serpRepository.All().Count());
        }
Пример #8
0
        public void EditPostSavesDataForOkDataWithEmptyMembershipProviderId()
        {
            var adminRepository            = new LocalRepository <InsideUser>();
            var userManager                = new Mock <IIdentityMembershipProvider>();
            var accountManagerInRepository = ModelHelper.TestAccountManager;

            accountManagerInRepository.Id           = null;
            accountManagerInRepository.PasswordHash = "HashedOldPassword";
            adminRepository.Add(accountManagerInRepository);

            var controller = new AccountManagerController(adminRepository, userManager.Object);

            var accountManager1 = new AccountManagerViewModel()
            {
                Name     = accountManagerInRepository.Name,
                Id       = accountManagerInRepository.Id,
                Password = "******",
                Email    = "*****@*****.**"
            };


            userManager.Setup(u => u.GetUsers()).Returns(adminRepository.All);
            userManager.Setup(u => u.FindById(accountManagerInRepository.Id)).Returns(accountManagerInRepository);
            userManager.Setup(u => u.UpdatePassword(accountManagerInRepository.Id, "Test Edited")).Returns(true).Verifiable();
            userManager.Setup(u => u.Create(accountManagerInRepository, "Test Edited")).Returns(true).Verifiable();

            var result = controller.Edit(accountManager1) as ViewResult;

            /* userManager.Verify(u => u.RemovePassword(accountManagerInRepository.Id), Times.Once);*/
            userManager.Verify(u => u.UpdatePassword(accountManagerInRepository.Id, "Test Edited"), Times.Never);
            userManager.Verify(u => u.Create(It.IsAny <InsideUser>(), "Test Edited"), Times.Once);
            Assert.AreEqual("*****@*****.**", adminRepository.All().First().Email);
        }
        public void CanHandleNewBudgets()
        {
            IRepository <Client> clientRepository = new LocalRepository <Client>();
            IRepository <Budget> budgetRepository = new LocalRepository <Budget>();
            var userManager = new Mock <IIdentityMembershipProvider>();

            Budget budget1 = new Budget
            {
                Id        = 1,
                ClientId  = 1,
                IsHandled = false
            };

            Budget budget2 = new Budget
            {
                Id        = 2,
                ClientId  = 1,
                IsHandled = false
            };

            budgetRepository.Add(budget1);
            budgetRepository.Add(budget2);

            Assert.AreEqual(2, budgetRepository.All().Count());

            var controller = new BudgetController(clientRepository, budgetRepository, userManager.Object);

            var result = controller.Handle(1);

            Assert.AreEqual(true, budgetRepository.Where(b => b.Id == budget1.Id).Single().IsHandled);
            Assert.AreEqual(false, budgetRepository.Where(b => b.Id == budget2.Id).Single().IsHandled);
        }
Пример #10
0
        public void CanCheckIfTaskInRepository()
        {
            var taskRepository = new LocalRepository <InsideModel.Models.Task>();
            var taskManager    = new Task.TaskCreator.TaskManager(taskRepository);

            var now            = new DateTime(2013, 01, 01, 08, 0, 0);
            var lowerBoundDate = now.Date;
            var upperBoundDate = lowerBoundDate.AddDays(1);

            var taskMessage = "{\"ClientId\":1,\"StartDate\":\"2013-12-30T00:00:00\",\"EndDate\":\"2014-01-02T00:00:00\"}";

            var result = taskManager.HasTaskInRepository(taskMessage, TaskType.AddProductAnalyticData, lowerBoundDate, upperBoundDate);

            Assert.IsFalse(result);

            taskRepository.Add(new InsideModel.Models.Task()
            {
                EarliestExecution = now.AddHours(2),
                Message           = taskMessage,
                Type = TaskType.AddProductAnalyticData
            });

            Assert.AreEqual(1, taskRepository.All().Count());
            var result2 = taskManager.HasTaskInRepository(taskMessage, TaskType.AddProductAnalyticData, lowerBoundDate, upperBoundDate);



            Assert.IsTrue(result2);
        }
        public void TaskInRepositoryDoesntCreatTaskForImportSeoData()
        {
            var clientRepository = new Mock <IRepository <Client> >();
            var taskQueueStorage = new Mock <ITaskQueueStorage>();
            var taskRepository   = new LocalRepository <InsideModel.Models.Task>();
            var serverTime       = new Mock <IServerTime>();
            var taskManager      = new Mock <ITaskManager>();

            var controller = new TaskController(
                clientRepository.Object,
                taskQueueStorage.Object,
                taskRepository,
                serverTime.Object,
                taskManager.Object);

            var taskExecutionDate = new DateTime(2014, 01, 01);

            serverTime.Setup(st => st.RequestStarted).Returns(taskExecutionDate);

            taskManager.Setup(
                tm =>
                tm.HasTaskInRepository(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <DateTime>(),
                                       It.IsAny <DateTime>())).Returns(true);

            var taskType3 = "ImportSeoData";
            var reult     = controller.Create(taskType3) as HttpStatusCodeResult;

            Assert.AreEqual(400, reult.StatusCode);
            Assert.AreEqual("Task Already in Database", reult.StatusDescription);
            Assert.AreEqual(0, taskRepository.All().Count());
            taskQueueStorage.Verify(ts => ts.Add(It.IsAny <InsideModel.Models.Task>()), Times.Never);
        }
        public void CreateMakesNewChatAndIgnoresNullProperties()
        {
            var clientRepository  = RepositoryHelper.RepositoryLocalWithOneClient;
            var chatRepository    = new LocalRepository <Contact>();
            var client            = clientRepository.All().First();
            var contactService    = new Mock <IContactService>();
            var restClient        = new Mock <IRestClient>();
            var userManager       = new Mock <IIdentityMembershipProvider>();
            var contactAutoRating = new Mock <IContactAutoRating>();

            var chat = new ChatViewModel
            {
                ClientId    = client.Id,
                ClientName  = client.Name,
                Date        = new DateTime(2013, 1, 02),
                Description = "this is the description",
                LiveChatId  = "LC123456",
                Email       = "",
                Phone       = "08654321"
            };

            var controller = new ChatController(
                chatRepository,
                clientRepository,
                contactService.Object,
                new ServerTime(),
                restClient.Object, userManager.Object, contactAutoRating.Object);
            var result = controller.Create(chat) as ViewResult;

            Assert.AreEqual(1, chatRepository.All().Count());
            Assert.AreEqual("this is the description", chatRepository.Where(c => c.Id == chat.Id).First().Property.Single(lp => lp.Type == "Description").Value);
            Assert.AreEqual("08654321", chatRepository.Where(c => c.Id == chat.Id).First().Property.Single(lp => lp.Type == "Phone").Value);
            Assert.AreEqual("LC123456", chatRepository.Where(c => c.Id == chat.Id).First().Property.Single(lp => lp.Type == "LiveChatId").Value);
            Assert.IsFalse(chatRepository.Where(c => c.Id == chat.Id).First().Property.Any(lp => lp.Type == "Email"));
        }
        public void CreateWithInvalidModelStateNotChangeRepository()
        {
            var clientRepository  = RepositoryHelper.RepositoryLocalWithOneClient;
            var chatRepository    = new LocalRepository <Contact>();
            var client            = clientRepository.All().First();
            var contactService    = new Mock <IContactService>();
            var restClient        = new Mock <IRestClient>();
            var userManager       = new Mock <IIdentityMembershipProvider>();
            var contactAutoRating = new Mock <IContactAutoRating>();

            var chat = new ChatViewModel
            {
                ClientId    = client.Id,
                ClientName  = client.Name,
                Date        = new DateTime(2013 - 1 - 02),
                Description = "this is the description"
            };

            var controller = new ChatController(
                chatRepository,
                clientRepository,
                contactService.Object,
                new ServerTime(),
                restClient.Object, userManager.Object, contactAutoRating.Object);

            controller.ModelState.AddModelError("error", "SomeError");
            var result = controller.Create(chat) as ViewResult;

            Assert.AreEqual(0, chatRepository.All().Count());
        }
        public void EditPostSavesData()
        {
            var clientRepository = RepositoryHelper.RepositoryLocalWithOneClient;
            var client           = clientRepository.All().First();

            var userRepository = new LocalRepository <InsideUser>();

            userRepository.Add(ModelHelper.TestUser1AllDataNoReferences);
            var user = userRepository.All().First();

            user.PasswordHash = "HashedOldPassword";
            var userManager = new Mock <IIdentityMembershipProvider>();

            userManager.Setup(u => u.FindById(user.Id)).Returns(user);
            userManager.Setup(u => u.UpdatePassword(user.Id, "Password1!")).Returns(true).Verifiable();
            var controller = new UserController(clientRepository, userRepository, userManager.Object);

            ModelHelper.SetCurrentUserToRole("consultant", controller);

            var userPostData = new UserViewModel();

            userPostData.Name       = "new";
            userPostData.Password   = "******";
            userPostData.ClientId   = client.Id;
            userPostData.Id         = user.Id;
            userPostData.ClientName = client.Name;

            var result = controller.Edit(userPostData) as ViewResult;

            /*userManager.Verify(u => u.RemovePassword(user.Id), Times.Once);*/
            userManager.Verify(u => u.UpdatePassword(user.Id, "Password1!"), Times.Once);
        }
        public void EditForIdReturnViewWithModel()
        {
            var clientRepository = RepositoryHelper.RepositoryLocalWithOneClient;
            var client           = clientRepository.All().First();

            var userRepository = new LocalRepository <InsideUser>();

            userRepository.Add(ModelHelper.TestUser1AllDataNoReferences);
            var user = userRepository.All().First();

            user.UserName = "******";
            user.Client   = client;
            var userManager = new Mock <IIdentityMembershipProvider>();

            userManager.Setup(u => u.FindById(user.Id)).Returns(user);
            var claim = new Claim("test", "AnyId");

            userManager.Setup(um => um.GetRoles(It.IsAny <string>())).Returns(new List <string> {
                "mockRole"
            });

            var controller = new UserController(clientRepository, userRepository, userManager.Object);

            ModelHelper.SetCurrentUserToRole("consultant", controller);
            ModelHelper.SetClaimAsCurrentUserForController(claim, controller);

            var result = controller.Edit(user.Id) as ViewResult;

            var resultmodel = result.Model as UserEditViewModel;

            Assert.AreEqual(user.ClientId, resultmodel.User.ClientId);
        }
Пример #16
0
        public void ContactInDbDoesNotCreateDuplicate()
        {
            var contactRepository = new LocalRepository <Contact>();
            var serverTime        = new Mock <IServerTime>();
            var contactAutoRating = new Mock <IContactAutoRating>();

            var controller = new TrackController(
                contactRepository,
                serverTime.Object,
                contactAutoRating.Object);
            var now = new DateTime(2014, 01, 01);

            serverTime.Setup(st => st.Now).Returns(now);
            var request = new Mock <HttpRequestBase>();

            var contact = new Contact
            {
                LeadType = "Email",
                ClientId = 1,
                Date     = now,
            };

            contact.Property.Add(new ContactProperty
            {
                Type  = "FormData",
                Value = "{\"firstName\":\"javad\",\"Telefon\":\"0123456\",\"e-post\":\"[email protected]\",\"description\":\"information\"}"
            });

            contact.Property.Add(new ContactProperty
            {
                Type  = "FormPostId",
                Value = "1-123456-0987"
            });
            contactRepository.Add(contact);

            var requestParams = new NameValueCollection
            {
                { "id", "1-123456-0987" },
                { "data", "{\"firstName\":\"javad\",\"Telefon\":\"0123456\",\"e-post\":\"[email protected]\",\"description\":\"information\"}" }
            };

            request.Setup(r => r.Params).Returns(requestParams);

            var server = new Mock <HttpServerUtilityBase>();

            server.Setup(su => su.MapPath("/Content/collect.gif")).Returns("~/Content/collect.gif");
            var context = new Mock <HttpContextBase>();

            context.SetupGet(x => x.Request).Returns(request.Object);
            context.SetupGet(x => x.Server).Returns(server.Object);

            controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);


            var result = controller.Index();


            Assert.AreEqual(1, contactRepository.All().Count());
        }
Пример #17
0
        public void CanAddSeoDataForDatesBetweenExistingDatesInRepository()
        {
            var downloadManager = new Mock <IDownloadManager>();
            var seoDataMapper   = new SeoDataImportMapper();
            var serpRepository  = new LocalRepository <SerpRanking>();

            var serpRankingInDb = new SerpRanking
            {
                Date    = DateTime.Now.AddDays(-1),
                Keyword = "Keyword",
                Url     = "url.com"
            };

            var serpRankingInDb2 = new SerpRanking
            {
                Date    = DateTime.Now.AddDays(1),
                Keyword = "Keyword",
                Url     = "url.com"
            };

            serpRepository.Add(serpRankingInDb);
            serpRepository.Add(serpRankingInDb2);

            var seoPosion = "[{\"pr\":\"0\",\"url\":\"url.se\",\"kw\":\"key word\",\"region\":\"google.se\",\"language\":\"sv\",\"start\":\"0\"}]";

            downloadManager.Setup(dm => dm.FetchUrl(It.IsAny <string>())).Returns(seoPosion);

            var taskMessage = "";

            var task = new SeoDataImporter(downloadManager.Object, serpRepository, seoDataMapper);

            task.PerformTask(new InsideModel.Models.Task()
            {
                Message = taskMessage
            });

            Assert.AreEqual(3, serpRepository.All().Count());

            var importedSerpRankings = serpRepository.All().Last();

            Assert.AreEqual("url.se", importedSerpRankings.Url);
            Assert.AreEqual("key word", importedSerpRankings.Keyword);
            Assert.AreEqual(0, importedSerpRankings.PageRank);
        }
        public void CallTrackingMetricWebhookCreatesLeadWithValidData()
        {
            var serverTime = new Mock <IServerTime>();

            serverTime.Setup(st => st.RequestStarted).Returns(new DateTime(2013, 01, 01, 8, 20, 0));
            var xDataProvider     = new Mock <IExternalDataProvider>();
            var contactAutoRating = new Mock <IContactAutoRating>();

            var request = new Mock <HttpRequestBase>();

            string sampleJsonData =
                "{\"id\":3158334,\"account_id\":9724,\"name\":\"Restricted\",\"search\":null,\"referrer\":null,\"location\":null,\"source\":\"Website\",\"source_id\":14932,\"tgid\":28622,\"likelihood\":null,\"duration\":107,\"talk_time\":101,\"ring_time\":6,\"parent_id\":null,\"email\":null,\"street\":null,\"city\":\"\",\"state\":\"Stockholm\",\"country\":\"SE\",\"postal_code\":\"\",\"called_at\":\"2013-10-01 10:17 AM +02:00\",\"tracking_number_id\":28938,\"tracking_number\":\"+46844680390\",\"tracking_label\":null,\"business_number\":\"+4687541040\",\"business_label\":\"Winassist Växel\",\"receiving_number_id\":14464,\"dial_status\":\"completed\",\"billed_amount\":1080.0,\"billed_at\":\"2013-10-01T08:19:09\",\"caller_number_split\":[\"46\",\"8\",\"890443\"],\"excluded\":false,\"tracking_number_format\":\"+46-8-44680390\",\"business_number_format\":\"+46-8-7541040\",\"caller_number_format\":\"(+46) 889-0443\",\"alternative_number\":\"+468890443\",\"caller_number_complete\":\"+468890443\",\"caller_number\":\"+468890443\",\"visitor\":false,\"audio\":\"https://ct4.s3.amazonaws.com/accounts/AC31fe87364641848e5d08c041cac16c84/recordings/REef08b869be099e8c7aeb0d85b04a99d2\",\"tag_list\":[],\"notes\":null,\"latitude\":59.3323,\"longitude\":18.0629,\"extended_lookup_on\":false}";

            var serializeObject =
                new MemoryStream(
                    Encoding.UTF8.GetBytes(
                        sampleJsonData));

            request.SetupGet(x => x.InputStream).Returns(serializeObject);

            var context = new Mock <HttpContextBase>();

            context.SetupGet(x => x.Request).Returns(request.Object);

            var leadsRepository = new LocalRepository <Contact>();

            var clientRepository = new LocalRepository <Client>();
            var client           = ModelHelper.TestClient1AllDataNoReferences;

            client.CallTrackingMetricId = 9724;
            clientRepository.Add(client);

            var contactService = new Mock <IContactService>();

            var returnContact = new Contact()
            {
                Id   = 1,
                Date = new DateTime(2013, 01, 01, 08, 17, 0)
            };

            xDataProvider.Setup(x => x.MapPhoneDataToContact(It.Is <CallTrackingMetricsWebhookData>(ctm => ctm.id == 3158334)))
            .Returns(returnContact);

            var controller = new WebhookController(leadsRepository, clientRepository, contactService.Object, serverTime.Object, xDataProvider.Object, contactAutoRating.Object);

            controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
            controller.CallTrackingMetricWebhook();

            Assert.AreEqual(1, leadsRepository.All().Count());

            contactAutoRating.Verify(ar => ar.SetAutoRating(It.Is <Contact>(c => c.Id == returnContact.Id)), Times.Once());

            contactService.Verify(cs => cs.NotifyClientsForNewContactWithEmail(It.IsAny <int>()), Times.Once());
            contactService.Verify(cs => cs.NotifyClientsForNewContactWithPhoneNotification(It.IsAny <int>()), Times.Once());
            contactService.Verify(cs => cs.NotifyClientsForNewContactWithSmsNotification(It.IsAny <int>()), Times.Once());
        }
        public void InActiveClientOrClientWithNoAnalyticIdDontCreateTask()
        {
            var clientRepository = new LocalRepository <Client>();
            var taskQueueStorage = new Mock <ITaskQueueStorage>();
            var taskRepository   = new LocalRepository <InsideModel.Models.Task>();
            var serverTime       = new Mock <IServerTime>();
            var taskManager      = new Mock <ITaskManager>();

            var task = new ImportCustomEventsTaskCreator(
                serverTime.Object,
                taskManager.Object,
                taskRepository,
                clientRepository,
                taskQueueStorage.Object);

            var clientLable = new Label()
            {
                Id = 1, Name = "Custom Event"
            };
            var inActiveClient = new Client()
            {
                Id = 1, Labels = new Collection <Label>()
                {
                    clientLable
                }, AnalyticsTableId = "someId"
            };
            var noAnalyticIdclient = new Client()
            {
                Id = 2, Labels = new Collection <Label>()
                {
                    clientLable
                }, IsActive = true
            };
            var clientWithoutLabel = new Client()
            {
                Id = 3
            };

            clientRepository.Add(inActiveClient);
            clientRepository.Add(noAnalyticIdclient);
            clientRepository.Add(clientWithoutLabel);

            var taskExecutionDate = new DateTime(2014, 01, 01);

            serverTime.Setup(st => st.RequestStarted).Returns(taskExecutionDate);

            task.PerformTask(new InsideModel.Models.Task()
            {
                Message = ""
            });

            Assert.AreEqual(0, taskRepository.All().Count());
            taskQueueStorage.Verify(ts => ts.Add(It.IsAny <InsideModel.Models.Task>()), Times.Never);
        }
Пример #20
0
        public void EditGetReturnsErrorIfIdIsNull()
        {
            var adminRepository = new LocalRepository <InsideUser>();
            var userManager     = new Mock <IIdentityMembershipProvider>();

            adminRepository.Add(ModelHelper.TestAccountManager);
            var accountManagerInRepository = adminRepository.All().First();
            var controller = new AccountManagerController(adminRepository, userManager.Object);
            var result     = controller.Edit((string)null) as HttpStatusCodeResult;

            Assert.AreEqual(400, result.StatusCode);
        }
Пример #21
0
        public void DontNotifyClientsWithEmailForExistingTaskInStorage()
        {
            var leadRepository    = new Mock <IRepository <Contact> >();
            var taskQueueStorage  = new Mock <ITaskQueueStorage>();
            var taskRepository    = new LocalRepository <Task>();
            var serverTime        = new Mock <IServerTime>();
            var taskExecutionDate = new DateTime(2014, 01, 01);

            var contactToQueueAsTask = new Contact()
            {
                Id = 1
            };

            var taskInRepository = new Task()
            {
                Id                = 1,
                Message           = "{\"ContactId\":1}",
                EarliestExecution = taskExecutionDate,
                Type              = "CreateTaskForUsersToSendNewContactEmailNotification"
            };

            taskRepository.Add(taskInRepository);


            serverTime.Setup(st => st.RequestStarted).Returns(taskExecutionDate);

            var contactService = new ContactService.ContactService(leadRepository.Object,
                                                                   taskQueueStorage.Object,
                                                                   taskRepository,
                                                                   serverTime.Object);

            contactService.NotifyClientsForNewContactWithEmail(contactToQueueAsTask.Id);

            Assert.AreEqual(1, taskRepository.All().Count());
            Assert.AreEqual("{\"ContactId\":1}", taskRepository.All().First().Message);
            Assert.AreEqual("2014-01-01", taskRepository.All().First().EarliestExecution.ToString("yyy-MM-dd"));
            Assert.AreEqual("CreateTaskForUsersToSendNewContactEmailNotification", taskRepository.All().First().Type);

            taskQueueStorage.Verify(ts => ts.Add(It.IsAny <Task>()), Times.Never);
        }
        public void CanCreateABudgetAndDoesNotCreateOverlapping()
        {
            IRepository <Client> clientRepository = new LocalRepository <Client>();
            IRepository <Budget> budgetRepository = new LocalRepository <Budget>();
            var userManager = new Mock <IIdentityMembershipProvider>();

            Budget budget1 = new Budget();

            budget1.Id       = 1;
            budget1.Value    = 1000;
            budget1.Month    = new DateTime(2014, 1, 1);
            budget1.ClientId = 1;

            Budget budget2 = new Budget();

            budget2.Id       = 2;
            budget2.Value    = 2000;
            budget2.Month    = new DateTime(2014, 2, 1);
            budget2.ClientId = 2;

            budgetRepository.Add(budget1);
            budgetRepository.Add(budget2);

            Assert.AreEqual(2, budgetRepository.All().Count());

            var controller = new BudgetController(clientRepository, budgetRepository, userManager.Object);

            EditBudgetViewModel createBudgetPostMessage = new EditBudgetViewModel();

            createBudgetPostMessage.clientId = 1;
            createBudgetPostMessage.month    = "2014-03";
            createBudgetPostMessage.value    = 3000;

            controller.Create(createBudgetPostMessage);
            Assert.AreEqual(3, budgetRepository.All().Count());

            controller.Create(createBudgetPostMessage);
            Assert.AreEqual(3, budgetRepository.All().Count());
        }
        public void CanGetRefreshToken()
        {
            var restClient = new Mock <IRestClient>();
            var externalTokenRepository = new LocalRepository <ExternalToken>();
            var serverTime    = new Mock <IServerTime>();
            var jsonConverter = new Mock <IJsonConverter>();

            var api = new GoogleAuthentication(restClient.Object,
                                               externalTokenRepository,
                                               serverTime.Object,
                                               jsonConverter.Object);

            var now = new DateTime(2014, 12, 17, 10, 0, 0);

            serverTime.Setup(st => st.RequestStarted).Returns(now);

            var restResponse = new RestResponse();

            restResponse.Content = "{\"access_token\" : \"AccessToken\", \"token_type\" : \"Bearer\", \"expires_in\" : 3600, \"refresh_token\" : \"RefreshToken\"}";
            restClient.Setup(rc => rc.Execute(It.IsAny <RestRequest>()))
            .Returns(restResponse);

            var googleApiTokenResponse = new GoogleApiTokenResponse
            {
                access_token  = "AccessToken",
                expires_in    = 3600,
                token_type    = "Bearer",
                refresh_token = "RefreshToken",
            };

            jsonConverter.Setup(
                jc =>
                jc.Deserilize <GoogleApiTokenResponse>(
                    "{\"access_token\" : \"AccessToken\", \"token_type\" : \"Bearer\", \"expires_in\" : 3600, \"refresh_token\" : \"RefreshToken\"}"))
            .Returns(googleApiTokenResponse);

            var token = api.GetRefreshToken("code", "redirectUrl");

            Assert.AreEqual(2, externalTokenRepository.All().Count());

            Assert.AreEqual("RefreshToken", token.AccessToken);
            Assert.AreEqual("Google_Refresh_Token", token.Type);
            Assert.AreEqual(2114, token.ExpirationDate.Year);

            var hasValidTokenInDb = externalTokenRepository.Any(t => t.Type == "Google_Access_Token" && t.ExpirationDate > now);

            Assert.AreEqual(true, hasValidTokenInDb);
            Assert.AreEqual("AccessToken", externalTokenRepository.Single(t => t.Type == "Google_Access_Token" && t.ExpirationDate > now).AccessToken);
            Assert.AreEqual("Google_Access_Token", externalTokenRepository.Single(t => t.Type == "Google_Access_Token" && t.ExpirationDate > now).Type);
            Assert.AreEqual(11, externalTokenRepository.Single(t => t.Type == "Google_Access_Token" && t.ExpirationDate > now).ExpirationDate.Hour);
        }
        public void NoEntriesNoInsertionInDataBase()
        {
            var clientRepositoryMoq   = new LocalRepository <Client>();
            var contactRepositoryMoq  = new Mock <IRepository <Contact> >();
            var contactProductService = new Mock <IProductService>();
            var contactAutoRating     = new Mock <IContactAutoRating>();
            var gaService             = new Mock <IGoogleAnalyticsApi>();

            var client = new Client()
            {
                Id = 1, IsActive = true, AnalyticsTableId = "ga:123456"
            };

            clientRepositoryMoq.Add(client);

            var startDate = new DateTime(2014, 01, 01);
            var endDate   = new DateTime(2014, 01, 03);

            var analyticQuery = new AnalyticQuery();

            analyticQuery.Dimenssions.AddMany("ga:eventAction", "ga:eventLabel", "ga:keyword", "ga:sourceMedium", "ga:dateHour", "ga:minute", "ga:campaign");
            analyticQuery.TabelId   = clientRepositoryMoq.All().First().AnalyticsTableId;
            analyticQuery.StartDate = startDate;
            analyticQuery.EndDate   = endDate;
            analyticQuery.Metrics.AddMany("ga:uniqueEvents", "ga:eventValue");
            analyticQuery.Filters.Add("ga:eventCategory==Helloy Event");

            gaService.Setup(
                ga =>
                ga.Get <EventAnalyticData>(It.Is <AnalyticQuery>(
                                               aq =>
                                               !aq.Dimenssions.Except(analyticQuery.Dimenssions).Any() &&
                                               !aq.Metrics.Except(analyticQuery.Metrics).Any() &&
                                               !aq.Filters.Except(analyticQuery.Filters).Any() &&
                                               aq.StartDate == analyticQuery.StartDate &&
                                               aq.EndDate == analyticQuery.EndDate &&
                                               aq.TabelId == analyticQuery.TabelId))).Returns((IEnumerable <EventAnalyticData>)null);

            var customEventsExtractor = new CustomEventsExtractor(
                clientRepositoryMoq,
                contactRepositoryMoq.Object,
                new ServerTime(),
                contactProductService.Object,
                contactAutoRating.Object,
                gaService.Object);


            customEventsExtractor.ImportEvents(client.Id, startDate, endDate);
            contactRepositoryMoq.Verify(l => l.SaveChanges(), Times.Never);
            contactRepositoryMoq.Verify(l => l.Add(It.IsAny <Contact>()), Times.Never);
        }
        public void CanSetTagsForContactForClientDuplicateIgnored()
        {
            var tagRepository     = new LocalRepository <Tag>();
            var userManager       = new Mock <IIdentityMembershipProvider>();
            var contactRepository = new LocalRepository <Contact>();

            var tag1 = new Tag
            {
                Id       = 1,
                Name     = "Tag1",
                ClientId = 1
            };

            tagRepository.Add(tag1);

            var tagToSet = new Tag
            {
                Id       = 2,
                Name     = "Tag2",
                ClientId = 1
            };

            tagRepository.Add(tagToSet);

            var contact = new Contact
            {
                Id       = 1,
                ClientId = 1
            };

            contact.Tags.Add(tag1);

            contactRepository.Add(contact);

            var controller = new TagController(userManager.Object, tagRepository, contactRepository);

            var result = controller.SetTag(contact.ClientId, contact.Id, tagToSet.Id);

            Assert.AreEqual(2, tagRepository.All().Count());

            Assert.AreEqual(2, contactRepository.Single(c => c.Id == 1).Tags.Count());
            Assert.AreEqual("Tag1", contactRepository.Single(c => c.Id == 1).Tags.Single(t => t.Id == 1).Name);
            Assert.AreEqual("Tag2", contactRepository.Single(c => c.Id == 1).Tags.Single(t => t.Id == 2).Name);

            var result2 = controller.SetTag(contact.ClientId, contact.Id, tagToSet.Id);

            Assert.AreEqual(2, contactRepository.Single(c => c.Id == 1).Tags.Count());
            Assert.AreEqual("Tag1", contactRepository.Single(c => c.Id == 1).Tags.Single(t => t.Id == 1).Name);
            Assert.AreEqual("Tag2", contactRepository.Single(c => c.Id == 1).Tags.Single(t => t.Id == 2).Name);
        }
Пример #26
0
        public void CanCreateContactForOkData()
        {
            var contactRepository = new LocalRepository <Contact>();
            var serverTime        = new Mock <IServerTime>();
            var contactAutoRating = new Mock <IContactAutoRating>();

            var controller = new TrackController(
                contactRepository,
                serverTime.Object,
                contactAutoRating.Object);
            var now = new DateTime(2014, 01, 01);

            serverTime.Setup(st => st.Now).Returns(now);
            var request = new Mock <HttpRequestBase>();

            var requestParams = new NameValueCollection
            {
                { "id", "1-123456-0987" },
                { "data", "{\"firstName\":\"javad\",\"Telefon\":\"0123456\",\"e-post\":\"[email protected]\",\"description\":\"information\"}" }
            };

            request.Setup(r => r.Params).Returns(requestParams);

            var server = new Mock <HttpServerUtilityBase>();

            server.Setup(su => su.MapPath("/Content/collect.gif")).Returns("~/Content/collect.gif");
            var context = new Mock <HttpContextBase>();

            context.SetupGet(x => x.Request).Returns(request.Object);
            context.SetupGet(x => x.Server).Returns(server.Object);

            controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);


            var result = controller.Index();


            Assert.AreEqual(1, contactRepository.All().Count());
            Assert.AreEqual(now, contactRepository.All().First().Date);
            Assert.AreEqual("Email", contactRepository.All().First().LeadType);
            Assert.AreEqual(1, contactRepository.All().First().ClientId);
            Assert.AreEqual("{\"firstName\":\"javad\",\"Telefon\":\"0123456\",\"e-post\":\"[email protected]\",\"description\":\"information\"}",
                            contactRepository.All().First().Property.Single(p => p.Type == "FormData").Value);
            Assert.AreEqual("1-123456-0987", contactRepository.All().First().Property.Single(p => p.Type == "FormPostId").Value);
            Assert.AreEqual("0123456", contactRepository.All().First().Property.Single(p => p.Type == "FromPhone").Value);
            Assert.AreEqual("[email protected]", contactRepository.All().First().Property.Single(p => p.Type == "FromEmail").Value);
        }
        public void MultiMandrilleventsWithSameIdIsNotDuplicatedInRepository()
        {
            var leadRepository    = new LocalRepository <Contact>();
            var xDataProvider     = new Mock <IExternalDataProvider>();
            var contactAutoRating = new Mock <IContactAutoRating>();
            var mandrill_event    =
                "[{\"event\":\"send\",\"msg\":{\"ts\":1365109999,\"subject\":\"This an example webhook message\",\"email\":\"[email protected]\"," +
                "\"sender\":\"[email protected]\",\"tags\":[\"webhook-example\"],\"opens\":[],\"clicks\":[],\"state\":\"sent\",\"metadata\":{\"user_id\":111}," +
                "\"_id\":\"1\",\"_version\":\"exampleaaaaaaaaaaaaaaa1\"},\"_id\":\"1\",\"ts\":1385020180}," +

                "{\"event\":\"send\",\"msg\":{\"ts\":1365109999,\"subject\":\"This an example webhook message\",\"email\":\"[email protected]\"," +
                "\"sender\":\"[email protected]\",\"tags\":[\"webhook-example\"],\"opens\":[],\"clicks\":[],\"state\":\"sent\",\"metadata\":{\"user_id\":111}," +
                "\"_id\":\"1\",\"_version\":\"exampleaaaaaaaaaaaaaaa1\"},\"_id\":\"1\",\"ts\":1385020180}," +

                "{\"event\":\"send\",\"msg\":{\"ts\":1365109999,\"subject\":\"This an example webhook message2\",\"email\":\"[email protected]\"," +
                "\"sender\":\"[email protected]\",\"tags\":[\"webhook-example\"],\"opens\":[],\"clicks\":[],\"state\":\"sent\",\"metadata\":{\"user_id\":222}," +
                "\"_id\":\"2\",\"_version\":\"exampleaaaaaaaaaaaaaaa2\"},\"_id\":\"2\",\"ts\":1385020180}]";

            var clientRepository = new LocalRepository <Client>();
            var client           = ModelHelper.TestClient1AllDataNoReferences;

            client.EmailAddress = "*****@*****.**";
            clientRepository.Add(client);

            var client2 = ModelHelper.TestClient1AllDataNoReferences;

            client2.EmailAddress = "*****@*****.**";
            client2.Id           = 2;
            clientRepository.Add(client2);

            var serverTime = new Mock <IServerTime>();

            serverTime.Setup(st => st.RequestStarted).Returns(new DateTime(2013, 11, 21, 8, 50, 0)); //2013-11-21 08:49:40 on email date

            var contactService = new Mock <IContactService>();

            var emailController = new WebhookController(leadRepository, clientRepository, contactService.Object, serverTime.Object, xDataProvider.Object, contactAutoRating.Object);
            var result          = emailController.ManrillWebhook(mandrill_event);

            Assert.AreEqual(2, leadRepository.All().Count());

            Assert.AreEqual("This an example webhook message", leadRepository.Where(l => l.Property.Any(lp => lp.Type == "MandrillId" && lp.Value == "1")).First().Property.First(lp => lp.Type == "Subject").Value);
            Assert.AreEqual("This an example webhook message2", leadRepository.Where(l => l.Property.Any(lp => lp.Type == "MandrillId" && lp.Value == "2")).First().Property.First(lp => lp.Type == "Subject").Value);
            contactAutoRating.Verify(ar => ar.SetAutoRating(It.IsAny <Contact>()), Times.Exactly(3));

            contactService.Verify(cs => cs.NotifyClientsForNewContactWithEmail(It.IsAny <int>()), Times.Exactly(2));
            contactService.Verify(cs => cs.NotifyClientsForNewContactWithPhoneNotification(It.IsAny <int>()), Times.Exactly(2));
            contactService.Verify(cs => cs.NotifyClientsForNewContactWithSmsNotification(It.IsAny <int>()), Times.Exactly(2));
        }
        public void EditGetReturnsCorrectData()
        {
            IRepository <Client> clientRepository = new LocalRepository <Client>();
            IRepository <Budget> budgetRepository = new LocalRepository <Budget>();
            var userManager = new Mock <IIdentityMembershipProvider>();

            Budget budget1 = new Budget();

            budget1.Id       = 1;
            budget1.Value    = 1000;
            budget1.Month    = new DateTime(2014, 1, 1);
            budget1.ClientId = 1;
            budget1.Comment  = "Comment";
            budget1.Client   = new Client {
                Name = "Client Name"
            };

            budgetRepository.Add(budget1);

            Assert.AreEqual(1, budgetRepository.All().Count());

            userManager.Setup(um => um.GetRoles(It.IsAny <string>())).Returns(new List <string> {
                "mockRole"
            });
            var controller = new BudgetController(clientRepository, budgetRepository, userManager.Object);
            var claim      = new Claim("test", "AnyId");

            ModelHelper.SetClaimAsCurrentUserForController(claim, controller);

            var expectedEditBudgetInRepository = new CreateEditClientBudgetViewModel
            {
                BudgetId   = 1,
                ClientId   = 1,
                Month      = "2014-01",
                Value      = 1000,
                Comment    = "Comment",
                ClientName = "Client Name"
            };

            var result      = controller.Edit(1) as ViewResult;
            var resultModel = result.Model as CreateEditClientBudgetViewModel;

            Assert.AreEqual(expectedEditBudgetInRepository.BudgetId, resultModel.BudgetId);
            Assert.AreEqual(expectedEditBudgetInRepository.ClientId, resultModel.ClientId);
            Assert.AreEqual(expectedEditBudgetInRepository.Month, resultModel.Month);
            Assert.AreEqual(expectedEditBudgetInRepository.Value, resultModel.Value);
            Assert.AreEqual(expectedEditBudgetInRepository.Comment, resultModel.Comment);
            Assert.AreEqual(expectedEditBudgetInRepository.ClientName, resultModel.ClientName);
        }
        public void DontCreateUserEmailTaskForNoUsers()
        {
            var generationDate    = new DateTime(2013, 1, 17);
            var contactRepository = new LocalRepository <Contact>();

            var taskCreator = new Mock <ITaskManager>();
            var client      = ModelHelper.TestClient1AllDataNoReferences;

            client.Labels         = new Collection <Label>();
            client.InsideUserSets = new List <InsideUser>();
            var lableForClient = new Label()
            {
                Id   = 1,
                Name = "Helloypaket"
            };
            var contactForUser = new Contact()
            {
                Id = 1
            };

            client.Labels.Add(lableForClient);
            contactForUser.Client = client;

            contactRepository.Add(contactForUser);

            var serverTime            = new Mock <IServerTime>();
            var taskRepository        = new LocalRepository <InsideModel.Models.Task>();
            var taskQueueStorage      = new Mock <ITaskQueueStorage>();
            var newContactEmailSender = new NotificationEmailSender(
                contactRepository,
                taskCreator.Object,
                serverTime.Object, taskRepository,
                taskQueueStorage.Object);

            var taskMessage = JsonConvert.SerializeObject(new NotificationTaskMessage()
            {
                ContactId = contactForUser.Id
            });

            newContactEmailSender.PerformTask(new InsideModel.Models.Task()
            {
                Message = taskMessage, EarliestExecution = generationDate
            });

            Assert.AreEqual(0, taskRepository.All().Count());

            taskQueueStorage.Verify(es => es.Add(It.IsAny <InsideModel.Models.Task>()), Times.Never);
        }
        public void CanUnsetTagsForContactForClient()
        {
            var tagRepository     = new LocalRepository <Tag>();
            var userManager       = new Mock <IIdentityMembershipProvider>();
            var contactRepository = new LocalRepository <Contact>();

            var tag1 = new Tag
            {
                Id       = 1,
                Name     = "Tag1",
                ClientId = 1
            };

            tagRepository.Add(tag1);

            var tag2 = new Tag
            {
                Id       = 2,
                Name     = "Tag2",
                ClientId = 1
            };

            tagRepository.Add(tag2);

            var contact = new Contact
            {
                Id       = 1,
                ClientId = 1
            };

            contact.Tags.Add(tag1);
            contact.Tags.Add(tag2);
            contactRepository.Add(contact);

            var controller = new TagController(userManager.Object, tagRepository, contactRepository);

            var result = controller.UnSetTag(contact.ClientId, contact.Id, tag1.Id);

            Assert.AreEqual(2, tagRepository.All().Count());

            Assert.AreEqual(1, contactRepository.Single(c => c.Id == 1).Tags.Count());
            Assert.AreEqual("Tag2", contactRepository.Single(c => c.Id == 1).Tags.First().Name);

            var result2 = controller.UnSetTag(contact.ClientId, 123, tag1.Id);

            Assert.AreEqual(HttpStatusCode.NotFound, result2.StatusCode);
        }