Esempio n. 1
0
        public int Handle(EditActivityCommand message)
        {
            var activity = GetActivity(message);

            if (activity == null)
            {
                activity = new Activity();
            }

            activity.Name         = message.Activity.Name;
            activity.Description  = message.Activity.Description;
            activity.ActivityType = message.Activity.ActivityType;

            TimeZoneInfo timeZone            = TimeZoneInfo.FindSystemTimeZoneById(message.Activity.TimeZoneId);
            var          startDateTimeOffset = timeZone.GetUtcOffset(message.Activity.StartDateTime);

            activity.StartDateTime = new DateTimeOffset(message.Activity.StartDateTime.Year, message.Activity.StartDateTime.Month, message.Activity.StartDateTime.Day, message.Activity.StartDateTime.Hour, message.Activity.StartDateTime.Minute, 0, startDateTimeOffset);

            var endDateTimeOffset = timeZone.GetUtcOffset(message.Activity.EndDateTime);

            activity.EndDateTime = new DateTimeOffset(message.Activity.EndDateTime.Year, message.Activity.EndDateTime.Month, message.Activity.EndDateTime.Day, message.Activity.EndDateTime.Hour, message.Activity.EndDateTime.Minute, 0, endDateTimeOffset);
            activity.CampaignId  = message.Activity.CampaignId;

            activity.ImageUrl = message.Activity.ImageUrl;
            activity.NumberOfVolunteersRequired = message.Activity.NumberOfVolunteersRequired;

            if (activity.IsLimitVolunteers != message.Activity.IsLimitVolunteers || activity.IsAllowWaitList != message.Activity.IsAllowWaitList)
            {
                activity.IsAllowWaitList   = message.Activity.IsAllowWaitList;
                activity.IsLimitVolunteers = message.Activity.IsLimitVolunteers;

                // cascade values to all tasks associated with this activity
                foreach (var task in _context.Tasks.Where(task => task.Activity.Id == activity.Id))
                {
                    task.IsLimitVolunteers = activity.IsLimitVolunteers;
                    task.IsAllowWaitList   = activity.IsAllowWaitList;
                    _context.Update(task);
                }
            }

            if (activity.Id > 0)
            {
                var skillsToRemove = _context.ActivitySkills.Where(skill => skill.ActivityId == activity.Id && (message.Activity.RequiredSkills == null ||
                                                                                                                !message.Activity.RequiredSkills.Any(ts1 => ts1.SkillId == skill.SkillId)));
                _context.ActivitySkills.RemoveRange(skillsToRemove);
            }
            if (message.Activity.RequiredSkills != null)
            {
                activity.RequiredSkills.AddRange(message.Activity.RequiredSkills.Where(mt => !activity.RequiredSkills.Any(ts => ts.SkillId == mt.SkillId)));
            }
            if (message.Activity.Location != null)
            {
                activity.Location = activity.Location.UpdateModel(message.Activity.Location);
                _context.Update(activity.Location);
            }

            _context.Update(activity);
            _context.SaveChanges();
            return(activity.Id);
        }
        public int Handle(OrganizationEditCommand message)
        {
            var org = _context
                      .Organizations
                      .Include(l => l.Location)
                      .Include(tc => tc.OrganizationContacts)
                      .SingleOrDefault(t => t.Id == message.Organization.Id) ?? new Organization();

            org.Name    = message.Organization.Name;
            org.LogoUrl = message.Organization.LogoUrl;
            org.WebUrl  = message.Organization.WebUrl;

            org.DescriptionHtml = message.Organization.Description;
            org.Summary         = message.Organization.Summary;

            org                     = org.UpdateOrganizationContact(message.Organization, _context);
            org.Location            = org.Location.UpdateModel(message.Organization.Location);
            org.Location.PostalCode = message.Organization.Location.PostalCode;

            org.PrivacyPolicy    = message.Organization.PrivacyPolicy;
            org.PrivacyPolicyUrl = message.Organization.PrivacyPolicyUrl;

            _context.Update(org);
            _context.SaveChanges();

            return(org.Id);
        }
Esempio n. 3
0
        public int Handle(OrganizationEditCommand message)
        {
            var organization = _context
                               .Organizations
                               .Include(l => l.Location)
                               .Include(tc => tc.OrganizationContacts)
                               .SingleOrDefault(t => t.Id == message.Organization.Id);

            if (organization == null)
            {
                organization = new Organization();
            }

            organization.Name    = message.Organization.Name;
            organization.LogoUrl = message.Organization.LogoUrl;
            organization.WebUrl  = message.Organization.WebUrl;

            organization                     = organization.UpdateOrganizationContact(message.Organization, _context);
            organization.Location            = organization.Location.UpdateModel(message.Organization.Location);
            organization.Location.PostalCode = message.Organization.Location.PostalCode;

            organization.PrivacyPolicy = message.Organization.PrivacyPolicy;

            _context.Update(organization);
            _context.SaveChanges();

            return(organization.Id);
        }
        public IEnumerable <ImportRequestError> Handle(ImportRequestsCommand message)
        {
            var errors = new List <ImportRequestError>();

            foreach (var request in message.Requests)
            {
                // todo: do basic data validation
                if (!_context.Requests.Any(r => r.ProviderId == request.ProviderId))
                {
                    //If lat/long not provided, use geocoding API to get them
                    if (request.Latitude == 0 && request.Longitude == 0)
                    {
                        //Assume the first returned address is correct
                        var address = _geocoder.Geocode(request.Address, request.City, request.State, request.Zip, string.Empty)
                                      .FirstOrDefault();
                        request.Latitude  = address?.Coordinates.Latitude ?? 0;
                        request.Longitude = address?.Coordinates.Longitude ?? 0;
                    }

                    _context.Requests.Add(request);
                }
            }
            _context.SaveChanges();

            return(errors);
        }
        public static void LoadOrganizationHandlerTestData(AllReadyContext context)
        {
            var htmlPrivacyPolicy = "<h2>Line 1</h2><p>Line 2</p>";

            // Organizations
            context.Organizations.Add(new Organization {
                Id = 1, Name = "Org 1"
            });
            context.Organizations.Add(new Organization {
                Id = 2, Name = "Org 2", PrivacyPolicy = htmlPrivacyPolicy
            });

            // Campaigns
            context.Campaigns.Add(new Campaign {
                Name = "Campaign 1", ManagingOrganizationId = 1
            });
            context.Campaigns.Add(new Campaign {
                Name = "Campaign 2", ManagingOrganizationId = 1
            });
            context.Campaigns.Add(new Campaign {
                Name = "Locked Campaign", ManagingOrganizationId = 1, Locked = true
            });
            context.Campaigns.Add(new Campaign {
                Name = "Unlocked Campaign", ManagingOrganizationId = 1, Locked = false
            });

            context.SaveChanges();
        }
Esempio n. 6
0
        public static void LoadOrganizationHandlerTestData(AllReadyContext context)
        {
            const string htmlPrivacyPolicy = "<h2>Line 1</h2><p>Line 2</p>";

            var org1 = new Organization {
                Id = 1, Name = "Org 1", Location = new Location()
            };
            var org2 = new Organization
            {
                Id            = 2,
                Name          = "Org 2",
                PrivacyPolicy = htmlPrivacyPolicy,
                Location      = new Location()
            };

            // Organizations
            context.Organizations.Add(org1);
            context.Organizations.Add(org2);

            // Campaigns
            context.Campaigns.Add(new Campaign {
                Name = "Campaign 1", ManagingOrganization = org1, Location = new Location()
            });
            context.Campaigns.Add(new Campaign {
                Name = "Campaign 2", ManagingOrganization = org1, Location = new Location()
            });
            context.Campaigns.Add(new Campaign {
                Name = "Locked Campaign", Locked = true, ManagingOrganization = org1, Location = new Location()
            });
            context.Campaigns.Add(new Campaign {
                Name = "Unlocked Campaign", Locked = false, ManagingOrganization = org1, Location = new Location()
            });

            context.SaveChanges();
        }
        protected override void HandleCore(OrganizationDeleteCommand message)
        {
            var organization = _context.Organizations.SingleOrDefault(t => t.Id == message.Id);

            if (organization != null)
            {
                _context.Organizations.Remove(organization);
                _context.SaveChanges();
            }
        }
        protected override void HandleCore(DeleteTaskCommand message)
        {
            var task = _context.Tasks.SingleOrDefault(c => c.Id == message.TaskId);

            if (task != null)
            {
                _context.Tasks.Remove(task);
                _context.SaveChanges();
            }
        }
Esempio n. 9
0
        public int Handle(EditTaskCommand message)
        {
            var task = _context.Tasks.Include(t => t.RequiredSkills).SingleOrDefault(t => t.Id == message.Task.Id);

            if (task == null)
            {
                task = new AllReadyTask();
            }

            task.Name         = message.Task.Name;
            task.Description  = message.Task.Description;
            task.Activity     = _context.Activities.SingleOrDefault(a => a.Id == message.Task.ActivityId);
            task.Organization = _context.Organizations.SingleOrDefault(t => t.Id == message.Task.OrganizationId);

            TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById(message.Task.TimeZoneId);

            if (message.Task.StartDateTime.HasValue)
            {
                var startDateValue      = message.Task.StartDateTime.Value;
                var startDateTimeOffset = timeZone.GetUtcOffset(startDateValue);
                task.StartDateTime = new DateTimeOffset(startDateValue.Year, startDateValue.Month, startDateValue.Day, startDateValue.Hour, startDateValue.Minute, 0, startDateTimeOffset);
            }
            else
            {
                task.StartDateTime = null;
            }

            if (message.Task.EndDateTime.HasValue)
            {
                var endDateValue      = message.Task.EndDateTime.Value;
                var endDateTimeOffset = timeZone.GetUtcOffset(endDateValue);
                task.EndDateTime = new DateTimeOffset(endDateValue.Year, endDateValue.Month, endDateValue.Day, endDateValue.Hour, endDateValue.Minute, 0, endDateTimeOffset);
            }
            else
            {
                task.EndDateTime = null;
            }
            task.NumberOfVolunteersRequired = message.Task.NumberOfVolunteersRequired;
            task.IsLimitVolunteers          = task.Activity.IsLimitVolunteers;
            task.IsAllowWaitList            = task.Activity.IsAllowWaitList;
            if (task.Id > 0)
            {
                var tsToRemove = _context.TaskSkills.Where(ts => ts.TaskId == task.Id && (message.Task.RequiredSkills == null ||
                                                                                          !message.Task.RequiredSkills.Any(ts1 => ts1.SkillId == ts.SkillId)));
                _context.TaskSkills.RemoveRange(tsToRemove);
            }
            if (message.Task.RequiredSkills != null)
            {
                task.RequiredSkills.AddRange(message.Task.RequiredSkills.Where(mt => !task.RequiredSkills.Any(ts => ts.SkillId == mt.SkillId)));
            }

            _context.Update(task);
            _context.SaveChanges();
            return(task.Id);
        }
Esempio n. 10
0
        protected override void HandleCore(DeleteActivityCommand message)
        {
            var activity =
                _context.Activities.SingleOrDefault(c => c.Id == message.ActivityId);

            if (activity != null)
            {
                _context.Activities.Remove(activity);
                _context.SaveChanges();
            }
        }
Esempio n. 11
0
        protected override void HandleCore(DeleteCampaignCommand message)
        {
            var campaign =
                _context.Campaigns.SingleOrDefault(c => c.Id == message.CampaignId);

            if (campaign != null)
            {
                _context.Campaigns.Remove(campaign);
                _context.SaveChanges();
            }
        }
        protected override void HandleCore(SetRequestsToUnassignedCommand message)
        {
            var requests = context.Requests.Where(x => message.RequestIds.Contains(x.RequestId)).ToList();

            requests.ForEach(request => request.Status = RequestStatus.Unassigned);

            var itineraryRequests = context.ItineraryRequests.Where(x => message.RequestIds.Contains(x.RequestId));

            context.ItineraryRequests.RemoveRange(itineraryRequests);

            context.SaveChanges();
        }
        public static void LoadCampaignssHandlerTestData(AllReadyContext context)
        {
            // Organizations
            context.Organizations.Add(new Organization { Id = 1, Name = "Org 1" });
            context.Organizations.Add(new Organization { Id = 2, Name = "Org 2" });

            // Campaigns
            context.Campaigns.Add(new Campaign { Name = "Campaign 1", ManagingOrganizationId = 1 });
            context.Campaigns.Add(new Campaign { Name = "Campaign 2", ManagingOrganizationId = 1 });

            context.SaveChanges();
        }
Esempio n. 14
0
        protected override void HandleCore(ActivitySignupCommand message)
        {
            var activitySignup = message.ActivitySignup;
            var user           = _context.Users
                                 .Include(u => u.AssociatedSkills)
                                 .SingleOrDefault(u => u.Id == activitySignup.UserId);
            var activity = _context.Activities
                           .Include(a => a.RequiredSkills)
                           .Include(a => a.UsersSignedUp).ThenInclude(u => u.User)
                           .SingleOrDefault(a => a.Id == activitySignup.ActivityId);

            activity.UsersSignedUp = activity.UsersSignedUp ?? new List <ActivitySignup>();

            // If the user is already signed up for some reason, stop don't signup again, please
            if (!activity.UsersSignedUp.Any(acsu => acsu.User.Id == user.Id))
            {
                activity.UsersSignedUp.Add(new ActivitySignup
                {
                    Activity             = activity,
                    User                 = user,
                    PreferredEmail       = activitySignup.PreferredEmail,
                    PreferredPhoneNumber = activitySignup.PreferredPhoneNumber,
                    AdditionalInfo       = activitySignup.AdditionalInfo,
                    SignupDateTime       = DateTime.UtcNow
                });

                _context.Update(activity);

                //Add selected new skills (if any) to the current user
                if (activitySignup.AddSkillIds.Count > 0)
                {
                    var skillsToAdd = activity.RequiredSkills
                                      .Where(acsk => activitySignup.AddSkillIds.Contains(acsk.SkillId))
                                      .Select(acsk => new UserSkill()
                    {
                        SkillId = acsk.SkillId, UserId = user.Id
                    });
                    user.AssociatedSkills.AddRange(skillsToAdd.Where(toAdd => !user.AssociatedSkills.Any(existing => existing.SkillId == toAdd.SkillId)));

                    _context.Update(user);
                }

                _context.SaveChanges();

                //Notify admins of a new volunteer
                _bus.Publish(new VolunteerInformationAdded()
                {
                    ActivityId = activitySignup.ActivityId,
                    UserId     = activitySignup.UserId
                });
            }
        }
        protected override void HandleCore(LockUnlockCampaignCommand message)
        {
            var campaign =
                _context.Campaigns.SingleOrDefault(c => c.Id == message.CampaignId);

            if (campaign != null)
            {
                campaign.Locked = !campaign.Locked;

                _context.Update(campaign);
                _context.SaveChanges();
            }
        }
Esempio n. 16
0
        public IEnumerable <RequestImportError> Handle(AddRequestsCommand message)
        {
            var errors = new List <RequestImportError>();

            foreach (var request in message.Requests)
            {
                // todo: do basic data validation
                if (!_context.Requests.Any(r => r.ProviderId == request.ProviderId))
                {
                    _context.Requests.Add(request);
                }
            }
            _context.SaveChanges();

            return(errors);
        }
        public static void LoadOrganizationHandlerTestData(AllReadyContext context)
        {
            var htmlPrivacyPolicy = "<h2>Line 1</h2><p>Line 2</p>";

            // Organizations
            context.Organizations.Add(new Organization { Id = 1, Name = "Org 1" });
            context.Organizations.Add(new Organization { Id = 2, Name = "Org 2", PrivacyPolicy = htmlPrivacyPolicy });

            // Campaigns
            context.Campaigns.Add(new Campaign { Name = "Campaign 1", ManagingOrganizationId = 1 });
            context.Campaigns.Add(new Campaign { Name = "Campaign 2", ManagingOrganizationId = 1 });
            context.Campaigns.Add(new Campaign { Name = "Locked Campaign", ManagingOrganizationId = 1, Locked = true });
            context.Campaigns.Add(new Campaign { Name = "Unlocked Campaign", ManagingOrganizationId = 1, Locked = false });

            context.SaveChanges();
        }
Esempio n. 18
0
        public int Handle(OrganizationEditCommand message)
        {
            var organization = _context
                               .Organizations
                               .Include(l => l.Location).ThenInclude(p => p.PostalCode)
                               .Include(tc => tc.OrganizationContacts)
                               .SingleOrDefault(t => t.Id == message.Organization.Id);

            if (organization == null)
            {
                organization = new Organization();
            }

            organization.Name    = message.Organization.Name;
            organization.LogoUrl = message.Organization.LogoUrl;
            organization.WebUrl  = message.Organization.WebUrl;

            organization          = organization.UpdateOrganizationContact(message.Organization, _context);
            organization.Location = organization.Location.UpdateModel(message.Organization.Location);

            if (organization.Location != null)
            {
                if (!string.IsNullOrWhiteSpace(message.Organization.Location.PostalCode))
                {
                    PostalCodeGeo postalCode = _context.PostalCodes.SingleOrDefault(pc => pc.PostalCode.Equals(message.Organization.Location.PostalCode, System.StringComparison.InvariantCultureIgnoreCase));
                    if (postalCode == null)
                    {
                        postalCode = new PostalCodeGeo {
                            PostalCode = message.Organization.Location.PostalCode, City = message.Organization.Location.City, State = message.Organization.Location.State
                        };
                        _context.PostalCodes.Add(postalCode);
                    }
                    organization.Location.PostalCode = postalCode;
                }

                _context.Update(organization.Location);
            }

            organization.PrivacyPolicy = message.Organization.PrivacyPolicy;

            _context.Update(organization);
            _context.SaveChanges();

            return(organization.Id);
        }
Esempio n. 19
0
        public static void LoadGoalsHandlerTestData(AllReadyContext context)
        {
            // Organizations
            context.Organizations.Add(new Organization {
                Id = 1, Name = "Org 1"
            });
            context.Organizations.Add(new Organization {
                Id = 2, Name = "Org 2"
            });

            // Campaigns
            context.Campaigns.Add(new Campaign {
                Id = 1, Name = "Campaign 1", ManagingOrganizationId = 1
            });
            context.Campaigns.Add(new Campaign {
                Id = 2, Name = "Campaign 2", ManagingOrganizationId = 2
            });

            // Goals
            context.CampaignGoals.Add(new CampaignGoal {
                TextualGoal = "Goal 1"
            });
            context.CampaignGoals.Add(new CampaignGoal {
                TextualGoal = "Goal 2"
            });
            context.CampaignGoals.Add(new CampaignGoal {
                TextualGoal = "Goal 3"
            });

            context.CampaignGoals.Add(new CampaignGoal {
                TextualGoal = "Goal 4"
            });
            context.CampaignGoals.Add(new CampaignGoal {
                TextualGoal = "Goal 5"
            });
            context.CampaignGoals.Add(new CampaignGoal {
                TextualGoal = "Goal 6"
            });

            context.CampaignGoals.Add(new CampaignGoal {
                TextualGoal = "Goal 7"
            });

            context.SaveChanges();
        }
Esempio n. 20
0
        protected override void LoadTestData()
        {
            rnd     = new Random();
            context = ServiceProvider.GetService <AllReadyContext>();
            var tasks = context.Tasks.ToList();

            _task = GenerateTask();

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

            var firePrev = new Campaign
            {
                Name = "test Campaign",
                ManagingOrganization = htb
            };

            var myEvent = new Event
            {
                Id            = rnd.Next(3, 1000),
                Campaign      = firePrev,
                CampaignId    = firePrev.Id,
                StartDateTime = new DateTime(2015, 7, 4, 10, 0, 0).ToUniversalTime(),
                EndDateTime   = new DateTime(2015, 12, 31, 15, 0, 0).ToUniversalTime(),
                Location      = new Location {
                    Id = 1
                },
                RequiredSkills = new List <EventSkill>()
            };

            _task.Event = myEvent;
            context.Organizations.Add(htb);

            context.Campaigns.Add(firePrev);
            context.Events.Add(myEvent);
            context.Tasks.Add(_task);
            tasks = context.Tasks.ToList();
            context.SaveChanges();
        }
Esempio n. 21
0
        public void Process(RequestApiViewModel viewModel)
        {
            //since this is Hangfire job code, it needs to be idempotent, this could be re-tried if there is a failure
            if (context.Requests.Any(x => x.ProviderRequestId == viewModel.ProviderRequestId))
            {
                return;
            }

            var requestIsFromApprovedRegion = RequestIsFromApprovedRegion(viewModel.ProviderData);

            if (requestIsFromApprovedRegion)
            {
                var request = new Request
                {
                    RequestId = NewRequestId(),
                    //TODO mgmccarthy: this is hard-coded for now to 1, which is HTBox Org's Id in dev b/c SampleDataGenerator always creates it first. We'll need something more robust when we go to production.
                    OrganizationId    = 1,
                    ProviderRequestId = viewModel.ProviderRequestId,
                    ProviderData      = viewModel.ProviderData,
                    Address           = viewModel.Address,
                    City       = viewModel.City,
                    DateAdded  = DateTimeUtcNow(),
                    Email      = viewModel.Email,
                    Name       = viewModel.Name,
                    Phone      = viewModel.Phone,
                    State      = viewModel.State,
                    PostalCode = viewModel.PostalCode,
                    Status     = RequestStatus.Unassigned,
                    Source     = RequestSource.Api
                };

                //this is a web service call
                var coordinates = geocoder.GetCoordinatesFromAddress(request.Address, request.City, request.State, request.PostalCode, string.Empty).Result;

                request.Latitude  = coordinates?.Latitude ?? 0;
                request.Longitude = coordinates?.Longitude ?? 0;

                context.Add(request);
                context.SaveChanges();
            }

            //acceptance is true if we can service the Request or false if can't service it
            backgroundJobClient.Enqueue <ISendRequestStatusToGetASmokeAlarm>(x => x.Send(viewModel.ProviderRequestId, GasaStatus.New, requestIsFromApprovedRegion));
        }
        public int Handle(EditActivityCommand message)
        {
            var activity =
                _context.Activities
                .Include(a => a.RequiredSkills)
                .SingleOrDefault(c => c.Id == message.Activity.Id);

            if (activity == null)
            {
                activity = new Activity();
            }

            activity.Name        = message.Activity.Name;
            activity.Description = message.Activity.Description;

            TimeZoneInfo timeZone            = TimeZoneInfo.FindSystemTimeZoneById(message.Activity.TimeZoneId);
            var          startDateTimeOffset = timeZone.GetUtcOffset(message.Activity.StartDateTime);

            activity.StartDateTime = new DateTimeOffset(message.Activity.StartDateTime.Year, message.Activity.StartDateTime.Month, message.Activity.StartDateTime.Day, message.Activity.StartDateTime.Hour, message.Activity.StartDateTime.Minute, 0, startDateTimeOffset);

            var endDateTimeOffset = timeZone.GetUtcOffset(message.Activity.EndDateTime);

            activity.EndDateTime = new DateTimeOffset(message.Activity.EndDateTime.Year, message.Activity.EndDateTime.Month, message.Activity.EndDateTime.Day, message.Activity.EndDateTime.Hour, message.Activity.EndDateTime.Minute, 0, endDateTimeOffset);
            activity.CampaignId  = message.Activity.CampaignId;

            activity.ImageUrl = message.Activity.ImageUrl;
            activity.NumberOfVolunteersRequired = message.Activity.NumberOfVolunteersRequired;

            if (activity.Id > 0)
            {
                var skillsToRemove = _context.ActivitySkills.Where(skill => skill.ActivityId == activity.Id && (message.Activity.RequiredSkills == null ||
                                                                                                                !message.Activity.RequiredSkills.Any(ts1 => ts1.SkillId == skill.SkillId)));
                _context.ActivitySkills.RemoveRange(skillsToRemove);
            }
            if (message.Activity.RequiredSkills != null)
            {
                activity.RequiredSkills.AddRange(message.Activity.RequiredSkills.Where(mt => !activity.RequiredSkills.Any(ts => ts.SkillId == mt.SkillId)));
            }

            _context.Update(activity);
            _context.SaveChanges();
            return(activity.Id);
        }
        public int Handle(EditCampaignCommand message)
        {
            var campaign = _context.Campaigns
                           .Include(l => l.Location).ThenInclude(p => p.PostalCode)
                           .Include(tc => tc.CampaignContacts)
                           .Include(i => i.CampaignImpact)

                           .SingleOrDefault(c => c.Id == message.Campaign.Id);

            if (campaign == null)
            {
                campaign = new Campaign();
            }

            campaign.Name            = message.Campaign.Name;
            campaign.Description     = message.Campaign.Description;
            campaign.FullDescription = message.Campaign.FullDescription;
            campaign.TimeZoneId      = message.Campaign.TimeZoneId;
            TimeZoneInfo timeZoneInfo        = TimeZoneInfo.FindSystemTimeZoneById(campaign.TimeZoneId);
            var          startDateTimeOffset = timeZoneInfo.GetUtcOffset(message.Campaign.StartDate);

            campaign.StartDateTime = new DateTimeOffset(message.Campaign.StartDate.Year, message.Campaign.StartDate.Month, message.Campaign.StartDate.Day, 0, 0, 0, startDateTimeOffset);
            var endDateTimeOffset = timeZoneInfo.GetUtcOffset(message.Campaign.EndDate);

            campaign.EndDateTime            = new DateTimeOffset(message.Campaign.EndDate.Year, message.Campaign.EndDate.Month, message.Campaign.EndDate.Day, 23, 59, 59, endDateTimeOffset);
            campaign.ManagingOrganizationId = message.Campaign.OrganizationId;
            campaign.ImageUrl = message.Campaign.ImageUrl;

            campaign = campaign.UpdateCampaignContact(message.Campaign, _context);
            campaign.CampaignImpact = campaign.CampaignImpact.UpdateModel(message.Campaign.CampaignImpact);
            campaign.Location       = campaign.Location.UpdateModel(message.Campaign.Location);
            if (campaign.CampaignImpact != null)
            {
                _context.Update(campaign.CampaignImpact);
            }
            if (campaign.Location != null)
            {
                _context.Update(campaign.Location);
            }
            _context.Update(campaign);
            _context.SaveChanges();
            return(campaign.Id);
        }
Esempio n. 24
0
        public static void LoadSkillsHandlerTestData(AllReadyContext context)
        {
            // Organizations
            context.Organizations.Add(new Organization { Id = 1, Name = "Org 1" });
            context.Organizations.Add(new Organization { Id = 2, Name = "Org 2" });

            // Skills
            context.Skills.Add(new Skill { Name = "Skill 1", Description = "Description 1", OwningOrganizationId = 1 });
            context.Skills.Add(new Skill { Name = "Skill 2", Description = "Description 2", OwningOrganizationId = 1 });
            context.Skills.Add(new Skill { Name = "Skill 3", Description = "Child of Skill 2", OwningOrganizationId = 1, ParentSkillId = 2 });

            context.Skills.Add(new Skill { Name = "Skill 4", Description = "Description 4", });
            context.Skills.Add(new Skill { Name = "Skill 5", Description = "Child of Skill 4", ParentSkillId = 4 });
            context.Skills.Add(new Skill { Name = "Skill 6", Description = "Child of skill 4", ParentSkillId = 4 });

            context.Skills.Add(new Skill { Name = "Skill 7", Description = "Description 7", OwningOrganizationId = 2 });

            context.SaveChanges();
        }
Esempio n. 25
0
        public static void LoadCampaignssHandlerTestData(AllReadyContext context)
        {
            // Organizations
            context.Organizations.Add(new Organization {
                Id = 1, Name = "Org 1"
            });
            context.Organizations.Add(new Organization {
                Id = 2, Name = "Org 2"
            });

            // Campaigns
            context.Campaigns.Add(new Campaign {
                Name = "Campaign 1", ManagingOrganizationId = 1
            });
            context.Campaigns.Add(new Campaign {
                Name = "Campaign 2", ManagingOrganizationId = 1
            });
            context.Campaigns.Add(new Campaign {
                Name = "Locked Campaign", ManagingOrganizationId = 1, Locked = true
            });
            context.Campaigns.Add(new Campaign {
                Name = "Unlocked Campaign", ManagingOrganizationId = 1, Locked = false
            });

            // Contacts

            var newContact = new Contact {
                Email = "*****@*****.**", FirstName = "Bill", LastName = "Gates", PhoneNumber = "01323 000000"
            };

            context.Contacts.Add(newContact);
            context.CampaignContacts.Add(new CampaignContact {
                CampaignId = 1, ContactId = newContact.Id
            });

            // Geo
            context.PostalCodes.Add(new PostalCodeGeo {
                City = "Cincinnati", PostalCode = "45231", State = "OH"
            });

            context.SaveChanges();
        }
        public static void LoadCampaignssHandlerTestData(AllReadyContext context)
        {
            // Organizations
            context.Organizations.Add(new Organization {
                Id = 1, Name = "Org 1"
            });
            context.Organizations.Add(new Organization {
                Id = 2, Name = "Org 2"
            });

            // Campaigns
            context.Campaigns.Add(new Campaign {
                Name = "Campaign 1", ManagingOrganizationId = 1
            });
            context.Campaigns.Add(new Campaign {
                Name = "Campaign 2", ManagingOrganizationId = 1
            });

            context.SaveChanges();
        }
Esempio n. 27
0
        public void Process(RequestApiViewModel viewModel)
        {
            //since this is job code now, it needs to be idempotent, this could be re-tried by Hangire if it fails
            var requestExists = context.Requests.Any(x => x.ProviderRequestId == viewModel.ProviderRequestId);

            if (!requestExists)
            {
                var request = new Request
                {
                    RequestId = NewRequestId(),
                    //TODO mgmccarthy: this is hard-coded for now to 1, which is HTBox Org's Id in dev b/c SampleDataGenerator always creates it first. We'll need something more robust when we go to production.
                    OrganizationId    = 1,
                    ProviderRequestId = viewModel.ProviderRequestId,
                    ProviderData      = viewModel.ProviderData,
                    Address           = viewModel.Address,
                    City      = viewModel.City,
                    DateAdded = DateTimeUtcNow(),
                    Email     = viewModel.Email,
                    Name      = viewModel.Name,
                    Phone     = viewModel.Phone,
                    State     = viewModel.State,
                    Zip       = viewModel.Zip,
                    Status    = RequestStatus.Unassigned,
                    Source    = RequestSource.Api
                };


                //this is a web service call
                var address = geocoder.Geocode(viewModel.Address, viewModel.City, viewModel.State, viewModel.Zip, string.Empty).FirstOrDefault();

                request.Latitude  = address?.Coordinates.Latitude ?? 0;
                request.Longitude = address?.Coordinates.Longitude ?? 0;

                context.Add(request);
                context.SaveChanges();

                mediator.Publish(new ApiRequestProcessedNotification {
                    ProviderRequestId = viewModel.ProviderRequestId
                });
            }
        }
        protected override void LoadTestData()
        {
            rnd = new Random();
            context = ServiceProvider.GetService<AllReadyContext>();
            var tasks = context.Tasks.ToList();
            _task = GenerateTask();

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

            var firePrev = new Campaign
            {
                Name = "test Campaign",
                ManagingOrganization = htb
            };

            var myEvent = new Event
            {
                Id = rnd.Next(3,1000),
                Campaign = firePrev,
                CampaignId = firePrev.Id,
                StartDateTime = new DateTime(2015, 7, 4, 10, 0, 0).ToUniversalTime(),
                EndDateTime = new DateTime(2015, 12, 31, 15, 0, 0).ToUniversalTime(),
                Location = new Location { Id = 1 },
                RequiredSkills = new List<EventSkill>()
            };

            _task.Event = myEvent;
            context.Organizations.Add(htb);

            context.Campaigns.Add(firePrev);
            context.Events.Add(myEvent);
            context.Tasks.Add(_task);
            tasks = context.Tasks.ToList();
            context.SaveChanges();
        }
        public void To(RequestStatus requestStatus, Guid requestId)
        {
            var request = context.Requests.Single(x => x.RequestId == requestId);

            if (requestStatus == RequestStatus.Assigned)
            {
                request.Status = RequestStatus.Assigned;
            }

            if (requestStatus == RequestStatus.Unassigned)
            {
                request.Status = RequestStatus.Unassigned;
                mediator.Send(new SetRequestsToUnassignedCommand {
                    RequestIds = new List <Guid> {
                        requestId
                    }
                });
            }

            context.SaveChanges();
        }
        public static void LoadCampaignssHandlerTestData(AllReadyContext context)
        {
            // Organizations
            context.Organizations.Add(new Organization { Id = 1, Name = "Org 1" });
            context.Organizations.Add(new Organization { Id = 2, Name = "Org 2" });

            // Campaigns
            context.Campaigns.Add(new Campaign { Name = "Campaign 1", ManagingOrganizationId = 1 });
            context.Campaigns.Add(new Campaign { Name = "Campaign 2", ManagingOrganizationId = 1 });
            context.Campaigns.Add(new Campaign { Name = "Locked Campaign", ManagingOrganizationId = 1, Locked = true });
            context.Campaigns.Add(new Campaign { Name = "Unlocked Campaign", ManagingOrganizationId = 1, Locked = false });

            // Contacts

            var newContact = new Contact { Email = "*****@*****.**", FirstName = "Bill", LastName = "Gates", PhoneNumber = "01323 000000" };
            context.Contacts.Add(newContact);
            context.CampaignContacts.Add(new CampaignContact { CampaignId = 1, ContactId = newContact.Id });
            
            // Geo
            context.PostalCodes.Add(new PostalCodeGeo { City = "Cincinnati", PostalCode = "45231", State = "OH" });

            context.SaveChanges();
        }
        public static void LoadSkillsHandlerTestData(AllReadyContext context)
        {
            // Organizations
            context.Organizations.Add(new Organization {
                Id = 1, Name = "Org 1"
            });
            context.Organizations.Add(new Organization {
                Id = 2, Name = "Org 2"
            });

            // Skills
            context.Skills.Add(new Skill {
                Name = "Skill 1", Description = "Description 1", OwningOrganizationId = 1
            });
            context.Skills.Add(new Skill {
                Name = "Skill 2", Description = "Description 2", OwningOrganizationId = 1
            });
            context.Skills.Add(new Skill {
                Name = "Skill 3", Description = "Child of Skill 2", OwningOrganizationId = 1, ParentSkillId = 2
            });

            context.Skills.Add(new Skill {
                Name = "Skill 4", Description = "Description 4",
            });
            context.Skills.Add(new Skill {
                Name = "Skill 5", Description = "Child of Skill 4", ParentSkillId = 4
            });
            context.Skills.Add(new Skill {
                Name = "Skill 6", Description = "Child of skill 4", ParentSkillId = 4
            });

            context.Skills.Add(new Skill {
                Name = "Skill 7", Description = "Description 7", OwningOrganizationId = 2
            });

            context.SaveChanges();
        }
        protected override void HandleCore(ImportRequestsCommand message)
        {
            var requests = message.ImportRequestViewModels.Select(viewModel => new Request
            {
                RequestId         = NewRequestId(),
                ProviderRequestId = viewModel.Id,
                EventId           = message.EventId,
                ProviderData      = viewModel.ProviderData,
                Address           = viewModel.Address,
                City      = viewModel.City,
                DateAdded = DateTimeUtcNow(),
                Email     = viewModel.Email,
                Name      = viewModel.Name,
                Phone     = viewModel.Phone,
                State     = viewModel.State,
                Zip       = viewModel.Zip,
                Status    = RequestStatus.Unassigned,
                Source    = RequestSource.Csv
            }).ToList();

            context.Requests.AddRange(requests);

            //TODO mgmccarthy: eventually move IGeocoder invocations to async using azure. Issue #1626 and #1639
            foreach (var request in requests)
            {
                if (request.Latitude == 0 && request.Longitude == 0)
                {
                    //Assume the first returned address is correct
                    var address = geocoder.Geocode(request.Address, request.City, request.State, request.Zip, string.Empty).FirstOrDefault();
                    request.Latitude  = address?.Coordinates.Latitude ?? 0;
                    request.Longitude = address?.Coordinates.Longitude ?? 0;
                }
            }

            context.SaveChanges();
        }
        public async Task <TaskSignupResult> Handle(TaskUnenrollCommand message)
        {
            var task = _context.Tasks
                       .Include(t => t.AssignedVolunteers)
                       .Include(t => t.Activity).ThenInclude(a => a.UsersSignedUp)
                       .Include(t => t.RequiredSkills).ThenInclude(s => s.Skill)
                       .SingleOrDefault(c => c.Id == message.TaskId);

            var activity = task.Activity;

            var taskSignUp = task.AssignedVolunteers.SingleOrDefault(a => a.User.Id == message.UserId);

            if (taskSignUp != null)
            {
                task.AssignedVolunteers.Remove(taskSignUp);
            }

            if (activity.ActivityType != ActivityTypes.ActivityManaged && !activity.IsUserInAnyTask(message.UserId))
            {
                var activitySignup = activity.UsersSignedUp.FirstOrDefault(u => u.User.Id == message.UserId);
                if (activitySignup != null)
                {
                    activity.UsersSignedUp.Remove(activitySignup);
                }
            }

            _context.SaveChanges();

            await _bus.PublishAsync(new UserUnenrolls { ActivityId = activity.Id, UserId = message.UserId, TaskIds = new List <int> {
                                                            task.Id
                                                        } });

            return(new TaskSignupResult {
                Status = "success", Task = task
            });
        }
Esempio n. 34
0
        public void InsertTestData()
        {
            // Avoid polluting the database if there's already something in there.
            if (_context.Locations.Any() ||
                _context.Organizations.Any() ||
                _context.VolunteerTasks.Any() ||
                _context.Campaigns.Any() ||
                _context.Events.Any() ||
                _context.EventSkills.Any() ||
                _context.Skills.Any() ||
                _context.Resources.Any())
            {
                return;
            }

            #region postalCodes
            var existingPostalCode = _context.PostalCodes.ToList();
            _context.PostalCodes.AddRange(GetPostalCodes(existingPostalCode));
            #endregion

            var organizations      = new List <Organization>();
            var organizationSkills = new List <Skill>();
            var locations          = GetLocations();
            var users = new List <ApplicationUser>();
            var volunteerTaskSignups = new List <VolunteerTaskSignup>();
            var events           = new List <Event>();
            var eventSkills      = new List <EventSkill>();
            var campaigns        = new List <Campaign>();
            var volunteerTasks   = new List <VolunteerTask>();
            var resources        = new List <Resource>();
            var contacts         = GetContacts();
            var skills           = new List <Skill>();
            var eventManagers    = new List <EventManager>();
            var campaignManagers = new List <CampaignManager>();

            #region Skills
            var medical = new Skill {
                Name = "Medical", Description = "specific enough, right?"
            };
            var cprCertified = new Skill {
                Name = "CPR Certified", ParentSkill = medical, Description = "ha ha ha ha, stayin alive"
            };
            var md = new Skill {
                Name = "MD", ParentSkill = medical, Description = "Trust me, I'm a doctor"
            };
            var surgeon = new Skill {
                Name = "Surgeon", ParentSkill = md, Description = "cut open; sew shut; play 18 holes"
            };
            skills.AddRange(new[] { medical, cprCertified, md, surgeon });
            #endregion

            #region Organization

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

            #endregion

            #region Organization Skills

            organizationSkills.Add(new Skill
            {
                Name               = "Code Ninja",
                Description        = "Ability to commit flawless code without review or testing",
                OwningOrganization = organization
            });

            #endregion

            #region Campaign
            //TODO: Campaign/Event/Task dates need to be set as a DateTimeOffset, offset to the correct timezone instead of UtcNow or DateTime.Today.
            var firePreventionCampaign = new Campaign
            {
                Name = "Neighborhood Fire Prevention Days",
                ManagingOrganization = organization,
                Resources            = resources,
                TimeZoneId           = _timeZone.Id,
                StartDateTime        = AdjustToTimezone(DateTimeOffset.Now.AddMonths(-1), _timeZone),
                EndDateTime          = AdjustToTimezone(DateTimeOffset.Now.AddMonths(3), _timeZone),
                Location             = GetRandom(locations),
                Published            = true
            };
            organization.Campaigns.Add(firePreventionCampaign);

            var smokeDetectorCampaignGoal = new CampaignGoal
            {
                GoalType         = GoalType.Numeric,
                NumericGoal      = 10000,
                CurrentGoalLevel = 6722,
                Display          = true,
                TextualGoal      = "Total number of smoke detectors installed."
            };
            _context.CampaignGoals.Add(smokeDetectorCampaignGoal);

            var smokeDetectorCampaign = new Campaign
            {
                Name = "Working Smoke Detectors Save Lives",
                ManagingOrganization = organization,
                StartDateTime        = AdjustToTimezone(DateTime.Today.AddMonths(-1), _timeZone),
                EndDateTime          = AdjustToTimezone(DateTime.Today.AddMonths(1), _timeZone),
                CampaignGoals        = new List <CampaignGoal> {
                    smokeDetectorCampaignGoal
                },
                TimeZoneId = _timeZone.Id,
                Location   = GetRandom(locations),
                Published  = true
            };
            organization.Campaigns.Add(smokeDetectorCampaign);

            var financialCampaign = new Campaign
            {
                Name = "Everyday Financial Safety",
                ManagingOrganization = organization,
                TimeZoneId           = _timeZone.Id,
                StartDateTime        = AdjustToTimezone(DateTime.Today.AddMonths(-1), _timeZone),
                EndDateTime          = AdjustToTimezone(DateTime.Today.AddMonths(1), _timeZone),
                Location             = GetRandom(locations),
                Published            = true
            };
            organization.Campaigns.Add(financialCampaign);

            var safetyKitCampaign = new Campaign
            {
                Name = "Simple Safety Kit Building",
                ManagingOrganization = organization,
                TimeZoneId           = _timeZone.Id,
                StartDateTime        = AdjustToTimezone(DateTime.Today.AddMonths(-1), _timeZone),
                EndDateTime          = AdjustToTimezone(DateTime.Today.AddMonths(2), _timeZone),
                Location             = GetRandom(locations),
                Published            = true
            };
            organization.Campaigns.Add(safetyKitCampaign);

            var carSafeCampaign = new Campaign
            {
                Name = "Family Safety In the Car",
                ManagingOrganization = organization,
                TimeZoneId           = _timeZone.Id,
                StartDateTime        = AdjustToTimezone(DateTime.Today.AddMonths(-1), _timeZone),
                EndDateTime          = AdjustToTimezone(DateTime.Today.AddMonths(2), _timeZone),
                Location             = GetRandom(locations),
                Published            = true
            };
            organization.Campaigns.Add(carSafeCampaign);

            var escapePlanCampaign = new Campaign
            {
                Name = "Be Ready to Get Out: Have a Home Escape Plan",
                ManagingOrganization = organization,
                TimeZoneId           = _timeZone.Id,
                StartDateTime        = AdjustToTimezone(DateTime.Today.AddMonths(-6), _timeZone),
                EndDateTime          = AdjustToTimezone(DateTime.Today.AddMonths(6), _timeZone),
                Location             = GetRandom(locations),
                Published            = true
            };
            organization.Campaigns.Add(escapePlanCampaign);

            #endregion

            #region Event
            var queenAnne = new Event
            {
                Name           = "Queen Anne Fire Prevention Day",
                Campaign       = firePreventionCampaign,
                StartDateTime  = AdjustToTimezone(firePreventionCampaign.StartDateTime.AddDays(1), _timeZone),
                EndDateTime    = AdjustToTimezone(firePreventionCampaign.StartDateTime.AddMonths(2), _timeZone),
                TimeZoneId     = firePreventionCampaign.TimeZoneId,
                Location       = GetRandom(locations),
                RequiredSkills = new List <EventSkill>(),
                EventType      = EventType.Itinerary,
            };
            queenAnne.VolunteerTasks = GetSomeVolunteerTasks(queenAnne, organization);
            var ask = new EventSkill {
                Skill = surgeon, Event = queenAnne
            };
            queenAnne.RequiredSkills.Add(ask);
            eventSkills.Add(ask);
            ask = new EventSkill {
                Skill = cprCertified, Event = queenAnne
            };
            queenAnne.RequiredSkills.Add(ask);
            eventSkills.Add(ask);
            volunteerTasks.AddRange(queenAnne.VolunteerTasks);

            var ballard = new Event
            {
                Name          = "Ballard Fire Prevention Day",
                Campaign      = firePreventionCampaign,
                StartDateTime = AdjustToTimezone(firePreventionCampaign.StartDateTime.AddDays(1), _timeZone),
                EndDateTime   = AdjustToTimezone(firePreventionCampaign.StartDateTime.AddMonths(2), _timeZone),
                TimeZoneId    = firePreventionCampaign.TimeZoneId,
                Location      = GetRandom(locations),
                EventType     = EventType.Itinerary,
            };
            ballard.VolunteerTasks = GetSomeVolunteerTasks(ballard, organization);
            volunteerTasks.AddRange(ballard.VolunteerTasks);
            var madrona = new Event
            {
                Name          = "Madrona Fire Prevention Day",
                Campaign      = firePreventionCampaign,
                StartDateTime = AdjustToTimezone(firePreventionCampaign.StartDateTime.AddDays(1), _timeZone),
                EndDateTime   = AdjustToTimezone(firePreventionCampaign.StartDateTime.AddMonths(2), _timeZone),
                TimeZoneId    = firePreventionCampaign.TimeZoneId,
                Location      = GetRandom(locations),
                EventType     = EventType.Itinerary,
            };
            madrona.VolunteerTasks = GetSomeVolunteerTasks(madrona, organization);
            volunteerTasks.AddRange(madrona.VolunteerTasks);
            var southLoopSmoke = new Event
            {
                Name          = "Smoke Detector Installation and Testing-South Loop",
                Campaign      = smokeDetectorCampaign,
                StartDateTime = AdjustToTimezone(smokeDetectorCampaign.StartDateTime.AddDays(1), _timeZone),
                EndDateTime   = AdjustToTimezone(smokeDetectorCampaign.EndDateTime, _timeZone),
                TimeZoneId    = smokeDetectorCampaign.TimeZoneId,
                Location      = GetRandom(locations),
                EventType     = EventType.Itinerary,
            };
            southLoopSmoke.VolunteerTasks = GetSomeVolunteerTasks(southLoopSmoke, organization);
            volunteerTasks.AddRange(southLoopSmoke.VolunteerTasks);
            var northLoopSmoke = new Event
            {
                Name          = "Smoke Detector Installation and Testing-Near North Side",
                Campaign      = smokeDetectorCampaign,
                StartDateTime = AdjustToTimezone(smokeDetectorCampaign.StartDateTime.AddDays(1), _timeZone),
                EndDateTime   = AdjustToTimezone(smokeDetectorCampaign.EndDateTime, _timeZone),
                TimeZoneId    = smokeDetectorCampaign.TimeZoneId,
                Location      = GetRandom(locations),
                EventType     = EventType.Itinerary,
            };
            northLoopSmoke.VolunteerTasks = GetSomeVolunteerTasks(northLoopSmoke, organization);
            volunteerTasks.AddRange(northLoopSmoke.VolunteerTasks);
            var dateTimeToday    = DateTime.Today;
            var rentersInsurance = new Event
            {
                Name          = "Renters Insurance Education Door to Door and a bag of chips",
                Description   = "description for the win",
                Campaign      = financialCampaign,
                StartDateTime = AdjustToTimezone(new DateTime(dateTimeToday.Year, dateTimeToday.Month, dateTimeToday.Day, 8, 0, 0), _timeZone),
                EndDateTime   = AdjustToTimezone(new DateTime(dateTimeToday.Year, dateTimeToday.Month, dateTimeToday.Day, 16, 0, 0), _timeZone),
                TimeZoneId    = financialCampaign.TimeZoneId,
                Location      = GetRandom(locations),
                EventType     = EventType.Rally,
            };
            rentersInsurance.VolunteerTasks = GetSomeVolunteerTasks(rentersInsurance, organization);
            volunteerTasks.AddRange(rentersInsurance.VolunteerTasks);
            var rentersInsuranceEd = new Event
            {
                Name          = "Renters Insurance Education Door to Door (woop woop)",
                Description   = "another great description",
                Campaign      = financialCampaign,
                StartDateTime = AdjustToTimezone(financialCampaign.StartDateTime.AddMonths(1).AddDays(1), _timeZone),
                EndDateTime   = AdjustToTimezone(financialCampaign.EndDateTime, _timeZone),
                TimeZoneId    = financialCampaign.TimeZoneId,
                Location      = GetRandom(locations),
                EventType     = EventType.Itinerary,
            };
            rentersInsuranceEd.VolunteerTasks = GetSomeVolunteerTasks(rentersInsuranceEd, organization);
            volunteerTasks.AddRange(rentersInsuranceEd.VolunteerTasks);
            var safetyKitBuild = new Event
            {
                Name          = "Safety Kit Assembly Volunteer Day",
                Description   = "Full day of volunteers building kits",
                Campaign      = safetyKitCampaign,
                StartDateTime = AdjustToTimezone(safetyKitCampaign.StartDateTime.AddDays(1), _timeZone),
                EndDateTime   = AdjustToTimezone(safetyKitCampaign.StartDateTime.AddMonths(1).AddDays(5), _timeZone),
                TimeZoneId    = safetyKitCampaign.TimeZoneId,
                Location      = GetRandom(locations),
                EventType     = EventType.Itinerary,
            };
            safetyKitBuild.VolunteerTasks = GetSomeVolunteerTasks(safetyKitBuild, organization);
            volunteerTasks.AddRange(safetyKitBuild.VolunteerTasks);

            var safetyKitHandout = new Event
            {
                Name          = "Safety Kit Distribution Weekend",
                Description   = "Handing out kits at local fire stations",
                Campaign      = safetyKitCampaign,
                StartDateTime = AdjustToTimezone(safetyKitCampaign.StartDateTime.AddDays(1), _timeZone),
                EndDateTime   = AdjustToTimezone(safetyKitCampaign.StartDateTime.AddMonths(1).AddDays(5), _timeZone),
                TimeZoneId    = safetyKitCampaign.TimeZoneId,
                Location      = GetRandom(locations),
                EventType     = EventType.Itinerary,
            };
            safetyKitHandout.VolunteerTasks = GetSomeVolunteerTasks(safetyKitHandout, organization);
            volunteerTasks.AddRange(safetyKitHandout.VolunteerTasks);
            var carSeatTest1 = new Event
            {
                Name          = "Car Seat Testing-Naperville",
                Description   = "Checking car seats at local fire stations after last day of school year",
                Campaign      = carSafeCampaign,
                StartDateTime = AdjustToTimezone(carSafeCampaign.StartDateTime.AddDays(1), _timeZone),
                EndDateTime   = AdjustToTimezone(carSafeCampaign.StartDateTime.AddMonths(1).AddDays(5), _timeZone),
                TimeZoneId    = carSafeCampaign.TimeZoneId,
                Location      = GetRandom(locations),
                EventType     = EventType.Itinerary,
            };
            carSeatTest1.VolunteerTasks = GetSomeVolunteerTasks(carSeatTest1, organization);
            volunteerTasks.AddRange(carSeatTest1.VolunteerTasks);
            var carSeatTest2 = new Event
            {
                Name          = "Car Seat and Tire Pressure Checking Volunteer Day",
                Description   = "Checking those things all day at downtown train station parking",
                Campaign      = carSafeCampaign,
                StartDateTime = AdjustToTimezone(carSafeCampaign.StartDateTime.AddDays(1), _timeZone),
                EndDateTime   = AdjustToTimezone(carSafeCampaign.StartDateTime.AddMonths(1).AddDays(5), _timeZone),
                TimeZoneId    = carSafeCampaign.TimeZoneId,
                Location      = GetRandom(locations),
                EventType     = EventType.Itinerary,
            };
            carSeatTest2.VolunteerTasks = GetSomeVolunteerTasks(carSeatTest2, organization);
            volunteerTasks.AddRange(carSeatTest2.VolunteerTasks);
            var homeFestival = new Event
            {
                Name          = "Park District Home Safety Festival",
                Description   = "At downtown park district(adjacent to pool)",
                Campaign      = safetyKitCampaign,
                StartDateTime = AdjustToTimezone(safetyKitCampaign.StartDateTime.AddDays(1), _timeZone),
                EndDateTime   = AdjustToTimezone(safetyKitCampaign.StartDateTime.AddMonths(1), _timeZone),
                TimeZoneId    = safetyKitCampaign.TimeZoneId,
                Location      = GetRandom(locations),
                EventType     = EventType.Itinerary,
            };
            homeFestival.VolunteerTasks = GetSomeVolunteerTasks(homeFestival, organization);
            volunteerTasks.AddRange(homeFestival.VolunteerTasks);
            var homeEscape = new Event
            {
                Name          = "Home Escape Plan Flyer Distribution",
                Description   = "Handing out flyers door to door in several areas of town after school/ work hours.Streets / blocks will vary but number of volunteers.",
                Campaign      = escapePlanCampaign,
                StartDateTime = AdjustToTimezone(escapePlanCampaign.StartDateTime.AddDays(1), _timeZone),
                EndDateTime   = AdjustToTimezone(escapePlanCampaign.StartDateTime.AddMonths(7), _timeZone),
                TimeZoneId    = escapePlanCampaign.TimeZoneId,
                Location      = GetRandom(locations),
                EventType     = EventType.Itinerary,
            };
            homeEscape.VolunteerTasks = GetSomeVolunteerTasks(homeEscape, organization);
            volunteerTasks.AddRange(homeEscape.VolunteerTasks);
            #endregion

            #region Link campaign and event

            firePreventionCampaign.Events = new List <Event> {
                queenAnne, ballard, madrona
            };
            smokeDetectorCampaign.Events = new List <Event> {
                southLoopSmoke, northLoopSmoke
            };
            financialCampaign.Events = new List <Event> {
                rentersInsurance, rentersInsuranceEd
            };
            safetyKitCampaign.Events = new List <Event> {
                safetyKitBuild, safetyKitHandout
            };
            carSafeCampaign.Events = new List <Event> {
                carSeatTest1, carSeatTest2
            };
            escapePlanCampaign.Events = new List <Event> {
                homeFestival, homeEscape
            };

            #endregion

            #region Add Campaigns and Events
            organizations.Add(organization);
            campaigns.Add(firePreventionCampaign);
            campaigns.Add(smokeDetectorCampaign);
            campaigns.Add(financialCampaign);
            campaigns.Add(escapePlanCampaign);
            campaigns.Add(safetyKitCampaign);
            campaigns.Add(carSafeCampaign);

            events.AddRange(firePreventionCampaign.Events);
            events.AddRange(smokeDetectorCampaign.Events);
            events.AddRange(financialCampaign.Events);
            events.AddRange(escapePlanCampaign.Events);
            events.AddRange(safetyKitCampaign.Events);
            events.AddRange(carSafeCampaign.Events);
            #endregion

            #region Insert Resource items into Resources
            resources.Add(new Resource
            {
                Name             = "allReady Partner Name",
                Description      = "allready Partner Description",
                PublishDateBegin = DateTime.Today,
                PublishDateEnd   = DateTime.Today.AddDays(14),
                MediaUrl         = "",
                ResourceUrl      = "",
                CategoryTag      = "Partners",
                CampaignId       = 1
            });
            resources.Add(new Resource
            {
                Name             = "allReady Partner Name 2",
                Description      = "allready Partner Description 2",
                PublishDateBegin = DateTime.Today.AddDays(-3),
                PublishDateEnd   = DateTime.Today.AddDays(-1),
                MediaUrl         = "",
                ResourceUrl      = "",
                CategoryTag      = "Partners",
                CampaignId       = 1,
            });
            #endregion

            #region Insert into DB
            _context.Skills.AddRange(skills);
            _context.Contacts.AddRange(contacts);
            _context.EventSkills.AddRange(eventSkills);
            _context.Locations.AddRange(locations);
            _context.Organizations.AddRange(organizations);
            _context.VolunteerTasks.AddRange(volunteerTasks);
            _context.Campaigns.AddRange(campaigns);
            _context.Events.AddRange(events);
            _context.Resources.AddRange(resources);
            //_context.SaveChanges();
            #endregion

            #region Users for Events
            var username1 = $"{_settings.DefaultUsername}1.com";
            var username2 = $"{_settings.DefaultUsername}2.com";
            var username3 = $"{_settings.DefaultUsername}3.com";

            var user1 = new ApplicationUser
            {
                FirstName      = "FirstName1",
                LastName       = "LastName1",
                UserName       = username1,
                Email          = username1,
                EmailConfirmed = true,
                TimeZoneId     = _timeZone.Id,
                PhoneNumber    = "111-111-1111"
            };
            _userManager.CreateAsync(user1, _settings.DefaultAdminPassword).GetAwaiter().GetResult();
            users.Add(user1);

            var user2 = new ApplicationUser
            {
                FirstName      = "FirstName2",
                LastName       = "LastName2",
                UserName       = username2,
                Email          = username2,
                EmailConfirmed = true,
                TimeZoneId     = _timeZone.Id,
                PhoneNumber    = "222-222-2222"
            };
            _userManager.CreateAsync(user2, _settings.DefaultAdminPassword).GetAwaiter().GetResult();
            users.Add(user2);

            var user3 = new ApplicationUser
            {
                FirstName      = "FirstName3",
                LastName       = "LastName3",
                UserName       = username3,
                Email          = username3,
                EmailConfirmed = true,
                TimeZoneId     = _timeZone.Id,
                PhoneNumber    = "333-333-3333"
            };
            _userManager.CreateAsync(user3, _settings.DefaultAdminPassword).GetAwaiter().GetResult();
            users.Add(user3);
            #endregion

            #region Event Managers

            var eventManagerUser = new ApplicationUser
            {
                FirstName      = "Event",
                LastName       = "Manager",
                UserName       = _settings.DefaultEventManagerUsername,
                Email          = _settings.DefaultEventManagerUsername,
                EmailConfirmed = true,
                TimeZoneId     = _timeZone.Id,
                PhoneNumber    = "333-333-3333"
            };
            _userManager.CreateAsync(eventManagerUser, _settings.DefaultAdminPassword).GetAwaiter().GetResult();
            users.Add(eventManagerUser);

            var eventManager = new EventManager
            {
                Event = queenAnne,
                User  = eventManagerUser
            };
            eventManagers.Add(eventManager);

            _context.EventManagers.AddRange(eventManagers);

            #endregion

            #region Campaign Managers

            var campaignManagerUser = new ApplicationUser
            {
                FirstName      = "Campaign",
                LastName       = "Manager",
                UserName       = _settings.DefaultCampaignManagerUsername,
                Email          = _settings.DefaultCampaignManagerUsername,
                EmailConfirmed = true,
                TimeZoneId     = _timeZone.Id,
                PhoneNumber    = "333-333-3333"
            };
            _userManager.CreateAsync(campaignManagerUser, _settings.DefaultAdminPassword).GetAwaiter().GetResult();
            users.Add(campaignManagerUser);

            var campaignManager = new CampaignManager
            {
                Campaign = firePreventionCampaign,
                User     = campaignManagerUser
            };
            campaignManagers.Add(campaignManager);

            _context.CampaignManagers.AddRange(campaignManagers);

            #endregion

            #region TaskSignups
            var i = 0;
            foreach (var volunteerTask in volunteerTasks.Where(t => t.Event == madrona))
            {
                for (var j = 0; j < i; j++)
                {
                    volunteerTaskSignups.Add(new VolunteerTaskSignup {
                        VolunteerTask = volunteerTask, User = users[j], Status = VolunteerTaskStatus.Assigned
                    });
                }

                i = (i + 1) % users.Count;
            }
            _context.VolunteerTaskSignups.AddRange(volunteerTaskSignups);
            #endregion

            #region OrganizationContacts
            organization.OrganizationContacts.Add(new OrganizationContact {
                Contact = contacts.First(), Organization = organization, ContactType = 1                                                             /*Primary*/
            });
            #endregion

            #region Wrap Up DB
            _context.SaveChanges();
            #endregion
        }
Esempio n. 35
0
        public TaskChangeResult Handle(TaskStatusChangeCommand message)
        {
            var task = GetTask(message);

            if (task == null)
            {
                throw new InvalidOperationException($"Task {message.TaskId} does not exist");
            }

            var taskSignup = task.AssignedVolunteers.SingleOrDefault(c => c.User.Id == message.UserId);

            if (taskSignup == null)
            {
                throw new InvalidOperationException($"Sign-up for user {message.UserId} does not exist");
            }

            TaskStatus currentStatus;

            if (!Enum.TryParse <TaskStatus>(taskSignup.Status, out currentStatus))
            {
                currentStatus = TaskStatus.Assigned;
            }

            switch (message.TaskStatus)
            {
            case TaskStatus.Assigned:
                break;

            case TaskStatus.Accepted:
                if (currentStatus != TaskStatus.Assigned && currentStatus != TaskStatus.CanNotComplete && currentStatus != TaskStatus.Completed)
                {
                    throw new ArgumentException($"Task must be assigned before being accepted or undoing CanNotComplete or Completed");
                }
                break;

            case TaskStatus.Rejected:
                if (currentStatus != TaskStatus.Assigned)
                {
                    throw new ArgumentException($"Task must be assigned before being rejected");
                }
                break;

            case TaskStatus.Completed:
                if (currentStatus != TaskStatus.Accepted && currentStatus != TaskStatus.Assigned)
                {
                    throw new ArgumentException($"Task must be accepted before being completed");
                }
                break;

            case TaskStatus.CanNotComplete:
                if (currentStatus != TaskStatus.Accepted && currentStatus != TaskStatus.Assigned)
                {
                    throw new ArgumentException($"Task must be assigned or accepted before it can be marked as {message.TaskStatus}");
                }
                break;

            default:
                throw new ArgumentException($"Invalid sign-up status value: {message.TaskStatus}");
            }

            taskSignup.Status            = message.TaskStatus.ToString();
            taskSignup.StatusDateTimeUtc = DateTime.UtcNow;
            taskSignup.StatusDescription = message.TaskStatusDescription;
            _context.SaveChanges();

            var notification = new TaskSignupStatusChanged {
                SignupId = taskSignup.Id
            };

            _mediator.Publish(notification);
            return(new TaskChangeResult()
            {
                Status = "success", Task = task
            });
        }