public List<KeyValuePair<string, string>> Validate(EventEditViewModel model, CampaignSummaryViewModel parentCampaign)
        {
            var result = new List<KeyValuePair<string, string>>();

            if (model.EndDateTime < model.StartDateTime)
            {
                result.Add(new KeyValuePair<string, string>(nameof(model.EndDateTime), "End date cannot be earlier than the start date"));
            }

            if (model.StartDateTime < parentCampaign.StartDate)
            {
                result.Add(new KeyValuePair<string, string>(nameof(model.StartDateTime), "Start date cannot be earlier than the campaign start date " + parentCampaign.StartDate.ToString("d")));
            }

            if (model.EndDateTime > parentCampaign.EndDate)
            {
                result.Add(new KeyValuePair<string, string>(nameof(model.EndDateTime), "End date cannot be later than the campaign end date " + parentCampaign.EndDate.ToString("d")));
            }

            if ( model.EventType == EventType.Rally && string.IsNullOrEmpty(model.Location.Address1) )
            {
                result.Add(new KeyValuePair<string, string>(nameof(model.Location.Address1), "Address1 field is required. "));
            }

            return result;
        }
        public async Task AddNewCampaign()
        {
            // Arrange
            var handler = new EditCampaignCommandHandler(Context);
            var newCampaign = new CampaignSummaryViewModel { Name = "New", Description = "Desc", TimeZoneId ="UTC" };

            // Act
            var result = await handler.Handle(new EditCampaignCommand { Campaign = newCampaign });

            // Assert
            Assert.Equal(5, Context.Campaigns.Count());
            Assert.True(result > 0);
        }
        public void ReturnsCorrectErrorWhenEndDateTimeIsLessThanStartDateTime()
        {
            var validator = new EventEditModelValidator();
            var parentCampaign = new CampaignSummaryViewModel { EndDate = new DateTimeOffset(new DateTime(1999, 2, 1)) };
            var model = new EventEditViewModel
            {
                StartDateTime = new DateTimeOffset(new DateTime(2000, 1, 1)),
                EndDateTime = new DateTimeOffset(new DateTime(1999, 1, 1))
            };

            var errors = validator.Validate(model, parentCampaign);

            Assert.True(errors.Exists(x => x.Key.Equals("EndDateTime")));
            Assert.Equal(errors.Find(x => x.Key == "EndDateTime").Value, "End date cannot be earlier than the start date");
        }
Beispiel #4
0
        public async Task CampaignDoesNotExist()
        {
            var context = ServiceProvider.GetService<AllReadyContext>();
            var vm = new CampaignSummaryViewModel
            {
                TimeZoneId = "Eastern Standard Time"
            };
            var query = new EditCampaignCommand { Campaign = vm };
            var handler = new EditCampaignCommandHandler(context);
            var result = await handler.Handle(query);
            Assert.True(result > 0);

            var data = context.Campaigns.Count(_ => _.Id == result);
            Assert.True(data == 1);
        }
        public void RetrunsCorrectErrorWhenModelsEndDateTimeIsGreaterThanParentCampaignsEndDate()
        {
            var validator = new EventEditModelValidator();
            var parentCampaign = new CampaignSummaryViewModel
            {
                StartDate = new DateTimeOffset(new DateTime(2000, 1, 1)),
                EndDate = new DateTimeOffset(new DateTime(2001, 1, 1))
            };
            var model = new EventEditViewModel
            {
                StartDateTime = new DateTimeOffset(new DateTime(2001, 1, 1)),
                EndDateTime = new DateTimeOffset(new DateTime(2001, 2, 1)),
            };

            var errors = validator.Validate(model, parentCampaign);

            Assert.True(errors.Exists(x => x.Key.Equals("EndDateTime")));
            Assert.Equal(errors.Find(x => x.Key == "EndDateTime").Value, "End date cannot be later than the campaign end date " + parentCampaign.EndDate.ToString("d"));
        }
        public async Task UpdatingExistingCampaign_UpdatesAllCoreProperties()
        {
            CampaignsHandlerTestHelper.LoadCampaignssHandlerTestData(Context);

            // Arrange
            const string name = "New Name";
            const string desc = "New Desc";
            const string fullDesc = "New Full Desc";
            const string timezoneId = "GMT Standard Time";
            var startDate = DateTime.Now;
            var endDate = DateTime.Now.AddDays(30);
            const int org = 2;

            var handler = new EditCampaignCommandHandler(Context, Mock.Of<IConvertDateTimeOffset>());
            var updatedCampaign = new CampaignSummaryViewModel
            {
                Id = 2,
                Name = name,
                Description = desc,
                FullDescription = fullDesc,
                TimeZoneId = timezoneId,
                StartDate = startDate,
                EndDate = endDate,
                OrganizationId = org,
            };

            //Act
            var result = await handler.Handle(new EditCampaignCommand { Campaign = updatedCampaign });
            var savedCampaign = Context.Campaigns.SingleOrDefault(s => s.Id == 2);

            // Assert
            Assert.Equal(4, Context.Campaigns.Count());
            Assert.Equal(2, result);

            Assert.Equal(name, savedCampaign.Name);
            Assert.Equal(desc, savedCampaign.Description);
            Assert.Equal(fullDesc, savedCampaign.FullDescription);
            Assert.Equal(timezoneId, savedCampaign.TimeZoneId);
            Assert.NotEqual(startDate.Date, new DateTime()); // We're not testing the date logic in this test, only that a datetime value is saved
            Assert.NotEqual(endDate.Date, new DateTime()); // We're not testing the date logic in this test, only that a datetime value is saved
            Assert.Equal(org, savedCampaign.ManagingOrganizationId);
        }
        public async Task WhenCampaignDoesNotExist_NewCampaignIsAddedToTheDatabase()
        {
            const string name = "Test campaign";

            // arrange
            var vm = new CampaignSummaryViewModel
            {
                Name = name
            };

            var sut = new EditCampaignCommandHandler(Context, Mock.Of<IConvertDateTimeOffset>());
            var query = new EditCampaignCommand { Campaign = vm };

            // act
            var result = await sut.Handle(query);
            var data = Context.Campaigns.Single(rec => rec.Id == result);

            // assert
            result.ShouldBe(1); // Since no prior records ID should be 1
            data.Name.ShouldBe(name); // The name stored in the DB should match the value passed into the command
        }
        public async Task UpdatingExistingCampaignUpdatesLocationWithAllProperties()
        {
            // Arrange
            var name = "New Name";
            var desc = "New Desc";            
            var org = 2;
            var address1 = "Address 1";
            var address2 = "Address 1";
            var city = "City";
            var state = "State";
            var postcode = "45231";
            var country = "USA";

            var handler = new EditCampaignCommandHandler(Context);
            var updatedCampaign = new CampaignSummaryViewModel
            {
                Id = 2,
                Name = name,
                Description = desc,
                OrganizationId = org,
                TimeZoneId = "GMT Standard Time",
                Location = new LocationEditViewModel {  Address1 = address1, Address2 = address2, City = city, State = state, PostalCode = postcode }
            };

            // Act
            await handler.Handle(new EditCampaignCommand { Campaign = updatedCampaign });
            var savedCampaign = Context.Campaigns.SingleOrDefault(s => s.Id == 2);

            // Assert
            Assert.Equal(address1, savedCampaign.Location.Address1);
            Assert.Equal(address2, savedCampaign.Location.Address2);
            Assert.Equal(city, savedCampaign.Location.City);
            Assert.Equal(state, savedCampaign.Location.State);
            Assert.Equal(postcode, savedCampaign.Location.PostalCode);
            Assert.Equal(country, savedCampaign.Location.Country);
        }
        public async Task UpdatingExistingCampaignWithNoPriorContactAddsContactWithAllProperties()
        {
            // Arrange
            var name = "New Name";
            var desc = "New Desc";
            var org = 2;
            var contactEmail = "*****@*****.**";
            var firstname = "John";
            var lastname = "Doe";
            var telephone = "01323 111111";

            var handler = new EditCampaignCommandHandler(Context);
            var updatedCampaign = new CampaignSummaryViewModel
            {
                Id = 2,
                Name = name,
                Description = desc,
                OrganizationId = org,
                TimeZoneId = "GMT Standard Time",
                PrimaryContactEmail = contactEmail,
                PrimaryContactFirstName =firstname,
                PrimaryContactLastName = lastname,
                PrimaryContactPhoneNumber = telephone
            };

            // Act
            await handler.Handle(new EditCampaignCommand { Campaign = updatedCampaign });
            var newContact = Context.Contacts.OrderBy(c=>c.Id).LastOrDefault();

            // Assert
            Assert.Equal(2, Context.CampaignContacts.Count());
            Assert.Equal(2, Context.Contacts.Count());

            Assert.NotNull(newContact);

            Assert.Equal(contactEmail, newContact.Email);
            Assert.Equal(firstname, newContact.FirstName);
            Assert.Equal(lastname, newContact.LastName);
            Assert.Equal(telephone, newContact.PhoneNumber);
        }
        public async Task<IActionResult> Edit(CampaignSummaryViewModel campaign, IFormFile fileUpload)
        {
            if (campaign == null)
            {
                return BadRequest();
            }

            if (!User.IsOrganizationAdmin(campaign.OrganizationId))
            {
                return Unauthorized();
            }

            if (campaign.EndDate < campaign.StartDate)
            {
                ModelState.AddModelError(nameof(campaign.EndDate), "The end date must fall on or after the start date.");
            }

            if (ModelState.IsValid)
            {
                if (fileUpload != null)
                {
                    if (fileUpload.IsAcceptableImageContentType())
                    {
                        var existingImageUrl = campaign.ImageUrl;
                        var newImageUrl = await _imageService.UploadCampaignImageAsync(campaign.OrganizationId, campaign.Id, fileUpload);
                        if (!string.IsNullOrEmpty(newImageUrl))
                        {
                            campaign.ImageUrl = newImageUrl;
                            if (existingImageUrl != null)
                            {
                                await _imageService.DeleteImageAsync(existingImageUrl);
                            }
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("ImageUrl", "You must upload a valid image file for the logo (.jpg, .png, .gif)");
                        return View(campaign);
                    }
                }

                var id = await _mediator.SendAsync(new EditCampaignCommand { Campaign = campaign });

                return RedirectToAction(nameof(Details), new { area = "Admin", id });
            }

            return View(campaign);
        }
        public async Task DeleteCampaignImageReturnsJsonObjectWithStatusOfNothingToDeleteIfThereWasNoExistingImage()
        {
            var mediatorMock = new Mock<IMediator>();

            var campaignSummaryViewModel = new CampaignSummaryViewModel
            {
                OrganizationId = 1
            };

            mediatorMock.Setup(m => m.SendAsync(It.IsAny<CampaignSummaryQuery>())).ReturnsAsync(campaignSummaryViewModel);

            var imageServiceMock = new Mock<IImageService>();

            var sut = new CampaignController(mediatorMock.Object, imageServiceMock.Object);
            sut.MakeUserAnOrgAdmin(campaignSummaryViewModel.OrganizationId.ToString());

            var result = await sut.DeleteCampaignImage(It.IsAny<int>());

            result.Value.GetType()
                .GetProperty("status")
                .GetValue(result.Value)
                .ShouldBe("NothingToDelete");
        }
        public async Task DeleteCampaignImageCallsEditCampaignCommandWithCorrectData()
        {
            var mediatorMock = new Mock<IMediator>();

            var campaignSummaryViewModel = new CampaignSummaryViewModel
            {
                OrganizationId = 1,
                ImageUrl = "URL!"
            };

            mediatorMock.Setup(m => m.SendAsync(It.IsAny<CampaignSummaryQuery>())).ReturnsAsync(campaignSummaryViewModel);

            var imageServiceMock = new Mock<IImageService>();

            var sut = new CampaignController(mediatorMock.Object, imageServiceMock.Object);
            sut.MakeUserAnOrgAdmin(campaignSummaryViewModel.OrganizationId.ToString());

            await sut.DeleteCampaignImage(It.IsAny<int>());

            mediatorMock.Verify(m => m.SendAsync(It.Is<EditCampaignCommand>(s => s.Campaign == campaignSummaryViewModel)), Times.Once);
        }
        public async Task DeleteCampaignImageReturnsJsonObjectWithStatusOfDateInvalidIfCampaignEndDateIsLessThanStartDate()
        {
            var mediatorMock = new Mock<IMediator>();

            var campaignSummaryViewModel = new CampaignSummaryViewModel
            {
                OrganizationId = 1,
                StartDate = DateTimeOffset.Now.AddDays(10),
                EndDate = DateTimeOffset.Now
            };
            mediatorMock.Setup(m => m.SendAsync(It.IsAny<CampaignSummaryQuery>())).ReturnsAsync(campaignSummaryViewModel);

            var imageServiceMock = new Mock<IImageService>();

            var sut = new CampaignController(mediatorMock.Object, imageServiceMock.Object);
            sut.MakeUserAnOrgAdmin(campaignSummaryViewModel.OrganizationId.ToString());

            var result = await sut.DeleteCampaignImage(It.IsAny<int>());

            result.Value.GetType()
                .GetProperty("status")
                .GetValue(result.Value)
                .ShouldBe("DateInvalid");

            result.Value.GetType()
                .GetProperty("message")
                .GetValue(result.Value)
                .ShouldBe("The end date must fall on or after the start date.");
        }
Beispiel #14
0
        public async Task ExistingCampaign()
        {
            var context = ServiceProvider.GetService<AllReadyContext>();

            var htb = new Organization()
            {
                Name = "Humanitarian Toolbox",
                LogoUrl = "http://www.htbox.org/upload/home/ht-hero.png",
                WebUrl = "http://www.htbox.org",
                Campaigns = new List<Campaign>()
            };

            var firePrev = new Campaign()
            {
                Name = "Neighborhood Fire Prevention Days",
                ManagingOrganization = htb,
                TimeZoneId = "Eastern Standard Time"
            };
            htb.Campaigns.Add(firePrev);
            context.Organizations.Add(htb);
            context.SaveChanges();

            const string NEW_NAME = "Some new name value";

            var startDate = new DateTime(2014, 12, 10);
            var endDate = new DateTime(2015, 7, 3);
            var vm = new CampaignSummaryViewModel
            {
                Description = firePrev.Description,
                EndDate = endDate,
                FullDescription = firePrev.FullDescription,
                StartDate = startDate,
                Id = firePrev.Id,
                ImageUrl = firePrev.ImageUrl,
                Name = NEW_NAME,
                OrganizationId = firePrev.ManagingOrganizationId,
                OrganizationName = firePrev.ManagingOrganization.Name,
                TimeZoneId = "Eastern Standard Time"
            };
            var query = new EditCampaignCommand { Campaign = vm };
            var handler = new EditCampaignCommandHandler(context);
            var result = await handler.Handle(query);
            Assert.Equal(1, result); // should get back the Campaign id

            var data = context.Campaigns.Single(_ => _.Id == 1);
            Assert.Equal(NEW_NAME, data.Name);

            Assert.Equal(2014, data.StartDateTime.Year);
            Assert.Equal(12, data.StartDateTime.Month);
            Assert.Equal(10, data.StartDateTime.Day);
            Assert.Equal(00, data.StartDateTime.Hour);
            Assert.Equal(00, data.StartDateTime.Minute);
            Assert.Equal(-5, data.StartDateTime.Offset.TotalHours);

            Assert.Equal(2015, data.EndDateTime.Year);
            Assert.Equal(7, data.EndDateTime.Month);
            Assert.Equal(3, data.EndDateTime.Day);
            Assert.Equal(23, data.EndDateTime.Hour);
            Assert.Equal(59, data.EndDateTime.Minute);
            Assert.Equal(-4, data.EndDateTime.Offset.TotalHours);   
        }
        public async Task EditPostDoesNotInvokeDeleteImageAsync__WhenCampaignDoesNotHaveAnImage()
        {
            const int organizationId = 1;
            const int campaignId = 100;

            var mockMediator = new Mock<IMediator>();
            var mockImageService = new Mock<IImageService>();

            var file = FormFile("image/jpeg");
            mockImageService.Setup(x => x.UploadCampaignImageAsync(It.IsAny<int>(), It.IsAny<int>(), file)).ReturnsAsync("newImageUrl");

            var sut = new CampaignController(mockMediator.Object, mockImageService.Object);
            sut.MakeUserAnOrgAdmin(organizationId.ToString());

            var campaignSummaryViewModel = new CampaignSummaryViewModel
            {
                OrganizationId = organizationId,
                Id = campaignId,
                StartDate = new DateTimeOffset(new DateTime(2016, 2, 13)),
                EndDate = new DateTimeOffset(new DateTime(2016, 2, 14)),
            };

            await sut.Edit(campaignSummaryViewModel, file);
            mockImageService.Verify(mock => mock.DeleteImageAsync(It.IsAny<string>()), Times.Never);
        }
        public async Task EditPostAddsCorrectKeyAndErrorMessageToModelStateWhenCampaignEndDateIsLessThanCampainStartDate()
        {
            var campaignSummaryModel = new CampaignSummaryViewModel { OrganizationId = 1, StartDate = DateTime.Now.AddDays(1), EndDate = DateTime.Now.AddDays(-1)};

            var sut = new CampaignController(null, null);
            sut.MakeUserAnOrgAdmin(campaignSummaryModel.OrganizationId.ToString());

            await sut.Edit(campaignSummaryModel, null);
            var modelStateErrorCollection = sut.ModelState.GetErrorMessagesByKey(nameof(CampaignSummaryViewModel.EndDate));

            Assert.Equal(modelStateErrorCollection.Single().ErrorMessage, "The end date must fall on or after the start date.");
        }
 public PartialViewResult CampaignPreview(CampaignSummaryViewModel campaign, IFormFile fileUpload)
 {
     return PartialView("_CampaignPreview", campaign);
 }