public IEnumerable<ChildReportDto> GetListOfChildrenForAChurch(Person personRunningReport, IEnumerable<int> roles)
        {
            if (!personRunningReport.HasPermission(Permissions.ViewAdminReports))
                return new List<ChildReportDto>();

            var list = Context.PersonChurches
                .Where(pc => pc.ChurchId == personRunningReport.ChurchId && roles.Contains(pc.RoleId))
                .Select(pc => new ChildReportDto
                {
                    PersonId = pc.PersonId,
                    Firstname = pc.Person.Firstname,
                    Surname = pc.Person.Family.FamilyName,
                    HomePhone = pc.Person.Family.HomePhone,
                    DateOfBirth = pc.Person.DateOfBirth,
                    CellNo = pc.Person.PersonOptionalFields.FirstOrDefault(o => o.OptionalFieldId == (int) OptionalFields.CellPhone).Value,
                    AddressLine1 = pc.Person.Family.Address.Line1,
                    AddressLine2 = pc.Person.Family.Address.Line2,
                    AddressLine3 = pc.Person.Family.Address.Line3,
                    AddressLine4 = pc.Person.Family.Address.Line4,
                    Father = pc.Person.PersonRelationships.FirstOrDefault(r => r.RelationshipId == (int) Relationships.Father).Person1.Firstname,
                    FatherEmail = pc.Person.PersonRelationships.FirstOrDefault(r => r.RelationshipId == (int)Relationships.Father).Person1.Email,
                    FatherCell = pc.Person.PersonRelationships.FirstOrDefault(r => r.RelationshipId == (int)Relationships.Father).Person1==null ? null :
                                 pc.Person.PersonRelationships.FirstOrDefault(r => r.RelationshipId == (int)Relationships.Father).Person1.PersonOptionalFields.FirstOrDefault(o => o.OptionalFieldId == (int)OptionalFields.CellPhone).Value,
                    Mother = pc.Person.PersonRelationships.FirstOrDefault(r => r.RelationshipId == (int) Relationships.Mother).Person1.Firstname,
                    MotherEmail = pc.Person.PersonRelationships.FirstOrDefault(r => r.RelationshipId == (int)Relationships.Mother).Person1.Email,
                    MotherCell = pc.Person.PersonRelationships.FirstOrDefault(r => r.RelationshipId == (int)Relationships.Mother).Person1 == null ? null :
                                 pc.Person.PersonRelationships.FirstOrDefault(r => r.RelationshipId == (int)Relationships.Mother).Person1.PersonOptionalFields.FirstOrDefault(o => o.OptionalFieldId == (int)OptionalFields.CellPhone).Value,
                    GroupName = pc.Person.PersonGroups.FirstOrDefault(g=>g.PrimaryGroup).Group.Name

                })
                .Where(c=>c.Father != null || c.Mother !=null);

            return list.ToList().Where(c=>c.Age <= 21);
        }
 public void CheckThatChurchIdsMatch(int personId, Person currentPerson)
 {
     if (currentPerson.HasPermission(Permissions.SystemAdministrator))
         return;
     if (!Context.People.First(p => p.PersonId == personId).PersonChurches.Select(c => c.ChurchId).ToList().Contains(currentPerson.ChurchId))
         throw new ApplicationException("ChurchId does not match currentPerson ChurchId");
 }
 public Church SetNewChurch(Person currentPerson, int churchId)
 {
     if (currentPerson.HasPermission(Permissions.SystemAdministrator))
     {
         var church = _churchRepository.GetChurch(churchId);
         _permissionRepository.SetupPermissions(currentPerson, church, true);
         return church;
     }
     return null;
 }
 public void RemovePersonFromGroup(Person currentPerson, int personId, int groupId)
 {
     if (!currentPerson.HasPermission(Permissions.RemovePersonFromGroup)) return;
     //Fetch the record
     var personToRemove = (from pg in Context.PersonGroups
                           where pg.PersonId == personId
                                 && pg.GroupId == groupId
                           select pg).FirstOrDefault();
     if (personToRemove == null) return;
     //Remove them
     Context.PersonGroups.DeleteObject(personToRemove);
     Context.SaveChanges();
 }
 public IEnumerable<RoleViewModel> FetchSecurityRoles(Person currentPerson)
 {
     List<RoleViewModel> roles;
     if (currentPerson.HasPermission(common.Permissions.SystemAdministrator))
         roles = (from r in Context.Roles
                  where r.ChurchId == currentPerson.ChurchId
                  select new RoleViewModel { RoleId = r.RoleId, Name = r.Name }).ToList();
     else
         roles = (from r in Context.Roles
                  from canSetRole in r.CanBeSetByRoles
                  where r.ChurchId == currentPerson.ChurchId
                        && canSetRole.RoleId == currentPerson.RoleId
                  select new RoleViewModel { RoleId = r.RoleId, Name = r.Name }).ToList();
     return roles;
 }
        public bool SendEmailAndPassword(Person currentPerson, int personId, out string message)
        {
            if (personId == 0)
            {
                message = "You need to save the person before sending the email";
                return false;
            }

            if (!currentPerson.HasPermission(Permissions.SendEmailAndPassword))
            {
                message = "You don't have permission to perform this action";
                return false;
            }

            var personToUpdate = _personRepository.FetchPerson(personId, currentPerson);

            if (personToUpdate == null)
            {
                message = "Error sending Email";
                return false;
            }

            if (personToUpdate.HasPermission(Permissions.Login))
            {
                if (personToUpdate.HasValidEmail())
                {
                    SendEmailAndPassword(personToUpdate.Firstname,
                                         personToUpdate.Family.FamilyName,
                                         personToUpdate.Email,
                                         personToUpdate,
                                         currentPerson);

                    message = "Email sent succesfully";
                    return true;
                }
                message = "Invalid Email address";
                return false;
            }
            message = string.Format("You cannot send login details to a person with a role of {0}", personToUpdate.Role.Name);
            return false;
        }
 public bool CheckSavePermissionGroup(PersonViewModel person, Person currentPerson)
 {
     var canSave = false;
     if (person.PersonId > 0)
     {
         var groupPerson = (from pg in Context.PersonGroups
                            join g in Context.Groups
                                on pg.GroupId equals g.GroupId
                            where pg.PersonId == person.PersonId
                                  && g.ChurchId == currentPerson.ChurchId
                                  && (g.LeaderId == currentPerson.PersonId || g.AdministratorId == currentPerson.PersonId)
                            select pg).FirstOrDefault();
         if (groupPerson != null)
         {
             canSave = true;
         }
     }
     else
     {
         canSave = currentPerson.HasPermission(Permissions.AddNewPerson);
     }
     return canSave;
 }
        public void EmailGroupLeader(PersonViewModel person, Person currentPerson, Church church, Person personToSave, bool addedToNewGroup)
        {
            if (!personToSave.HasPermission(Permissions.NotifyGroupLeaderOfVisit) || person.GroupId <= 0) return;
            var sendEmailToGroupLeader = person.PersonId == 0;
            var group = _groupRepository.GetGroup(person.GroupId);

            if (group==null)
                return;
            if (addedToNewGroup)
                sendEmailToGroupLeader = true;

            if (group.LeaderId == currentPerson.PersonId || group.AdministratorId == currentPerson.PersonId)
                sendEmailToGroupLeader = false;  //This is the groupleader

            if (!sendEmailToGroupLeader) return;
            if (group.Leader != null && group.Leader.HasValidEmail() && group.LeaderId != currentPerson.PersonId)
            {
                SendNewVisitorEmail(person, church, group.Leader.Firstname, group.Leader.Family.FamilyName, group.Leader.Email, currentPerson);
            }
            else if (group.Administrator != null && group.Administrator.HasValidEmail() && group.LeaderId != currentPerson.PersonId)
            {
                SendNewVisitorEmail(person, church, group.Administrator.Firstname, group.Administrator.Family.FamilyName, group.Administrator.Email, currentPerson);
            }
        }
        public static List<HomeGroupsViewModel> FetchHomeGroups(int churchId, Person person)
        {
            using (oikonomosEntities context = new oikonomosEntities(ConfigurationManager.ConnectionStrings["oikonomosEntities"].ConnectionString))
            {
                var groups = (from g in context.Groups.Include("Address").Include("GroupClassification")
                              where g.ChurchId == churchId
                              orderby g.Name
                              select g);

                if (person.HasPermission(Permissions.EditAllGroups))
                {
                    return (from g in groups
                            select new HomeGroupsViewModel
                            {
                                GroupId = g.GroupId,
                                GroupName = g.Name,
                                LeaderName = g.Leader.Firstname + " " + g.Leader.Family.FamilyName,
                                LeaderId = g.LeaderId.HasValue ? g.LeaderId.Value : 0,
                                AdministratorName = g.Administrator == null ? string.Empty : g.Administrator.Firstname + " " + g.Administrator.Family.FamilyName,
                                AdministratorId = g.AdministratorId.HasValue ? g.AdministratorId.Value : 0,
                                AddressId = g.AddressId.HasValue ? g.AddressId.Value : 0,
                                Address1 = g.Address.Line1,
                                Address2 = g.Address.Line2,
                                Address3 = g.Address.Line3,
                                Address4 = g.Address.Line4,
                                AddressType = g.Address.AddressType,
                                Lat = g.Address != null ? g.Address.Lat : 0,
                                Lng = g.Address != null ? g.Address.Long : 0,
                                GroupClassificationId = g.GroupClassificationId.HasValue ? g.GroupClassificationId.Value : 0,
                                SuburbId = g.AddressId == null ? 0 : (g.Address.ChurchSuburbId == null ? 0 : (int)g.Address.ChurchSuburbId)
                            }).ToList();
                }

                if (person.HasPermission(Permissions.EditOwnGroups))
                {
                    return (from g in groups
                            where g.LeaderId == person.PersonId || g.AdministratorId == person.PersonId
                            select new HomeGroupsViewModel
                            {
                                GroupId = g.GroupId,
                                GroupName = g.Name,
                                LeaderName = g.Leader.Firstname + " " + g.Leader.Family.FamilyName,
                                LeaderId = g.LeaderId.HasValue ? g.LeaderId.Value : 0,
                                AdministratorName = g.Administrator == null ? string.Empty : g.Administrator.Firstname + " " + g.Administrator.Family.FamilyName,
                                AdministratorId = g.AdministratorId.HasValue ? g.AdministratorId.Value : 0,
                                AddressId = g.AddressId.HasValue ? g.AddressId.Value : 0,
                                Address1 = g.Address.Line1,
                                Address2 = g.Address.Line2,
                                Address3 = g.Address.Line3,
                                Address4 = g.Address.Line4,
                                AddressType = g.Address.AddressType,
                                Lat = g.Address == null ? 0 : g.Address.Lat,
                                Lng = g.Address == null ? 0 : g.Address.Long
                            }).ToList();
                }

                return new List<HomeGroupsViewModel>();
            }
        }
        private static IQueryable<Group> FetchGroupList(Person currentPerson, bool search, IEnumerable<JqGridFilterRule> rules, oikonomosEntities context)
        {
            IQueryable<Group> groups = null;
            if (currentPerson.HasPermission(Permissions.EditAllGroups))
            {
                groups = (from g in context.Groups.Include("Address").Include("GroupClassification")
                          where g.ChurchId == currentPerson.ChurchId
                          select g);
            }
            else if (!(currentPerson.HasPermission(Permissions.EditAllGroups)) && currentPerson.HasPermission(Permissions.EditOwnGroups))
            {
                groups = (from g in context.Groups
                          where (g.LeaderId == currentPerson.PersonId || g.AdministratorId == currentPerson.PersonId)
                          && g.ChurchId == currentPerson.ChurchId
                          select g);
            }

            if (groups == null)
                throw new Exception("Invalid security Role");

            if (search)
            {
                foreach (var rule in rules)
                {
                    //If we use rule.data throughout we get some strange errors in the SQL that Linq generates
                    switch (rule.field)
                    {
                        case "GroupName":
                        {
                            var groupName = rule.data;
                            groups = (from g in groups
                                where g.Name.Contains(groupName)
                                select g);
                            break;
                        }
                        case "LeaderName":
                        {
                            groups = Filters.ApplyNameSearchGroupLeader(rule.data, groups);
                            break;
                        }
                        case "Administrator":
                        {
                            groups = Filters.ApplyNameSearchGroupAdministrator(rule.data, groups);
                            break;
                        }
                        case "Suburb":
                        {
                            var suburb = rule.data;
                            groups = (from g in groups
                                where g.Address.ChurchSuburb.Suburb.Contains(suburb)
                                      || g.Address.Line3.Contains(suburb)
                                select g);
                            break;
                        }
                        case "GroupClassification":
                        {
                            var classification = rule.data;
                            groups = (from g in groups
                                where g.GroupClassification.Name.Contains(classification)
                                select g);
                            break;
                        }
                        case "OverseeingElder":
                        {
                            groups = Filters.ApplyNameSearchOverseeingElder(rule.data, groups);
                            break;
                        }
                    }
                }
            }

            return groups;
        }
 public static void SetHomeGroupLeader(Person currentPerson, int groupId, int leaderId)
 {
     using (oikonomosEntities context = new oikonomosEntities(ConfigurationManager.ConnectionStrings["oikonomosEntities"].ConnectionString))
     {
         if (currentPerson.HasPermission(Permissions.SetGroupLeaderOrAdministrator))
         {
             //Fetch the record
             var groupToUpdate = (from g in context.Groups
                                  where g.GroupId == groupId
                                  && g.ChurchId == currentPerson.ChurchId
                                  select g).FirstOrDefault();
             if (groupToUpdate != null)
             {
                 groupToUpdate.LeaderId = leaderId;
                 context.SaveChanges();
             }
         }
     }
 }
        public static int SaveHomeGroup(Person currentPerson, HomeGroupsViewModel hgvm)
        {
            if (currentPerson.HasPermission(Permissions.EditGroups) || currentPerson.HasPermission(Permissions.AddGroups))
            {
                using (var context = new oikonomosEntities(ConfigurationManager.ConnectionStrings["oikonomosEntities"].ConnectionString))
                {
                    var hg = new Group();
                    if (hgvm.GroupId != 0)
                    {
                        hg = (from g in context.Groups
                              where g.GroupId == hgvm.GroupId
                              select g).FirstOrDefault();
                    }
                    else
                    {
                        hg.ChurchId = currentPerson.ChurchId;
                        hg.Created = DateTime.Now;
                        if (currentPerson.ChurchId == 3) //Ebenezer
                        {
                            hg.GroupTypeId = (int)GroupTypes.LifeGroup;
                        }
                        else
                        {
                            hg.GroupTypeId = (int)GroupTypes.HomeGroup;
                        }
                        context.Groups.AddObject(hg);
                    }

                    hg.Name = hgvm.GroupName;
                    if (hgvm.LeaderId == 0 || string.IsNullOrEmpty(hgvm.LeaderName))
                        hg.LeaderId = null;
                    else
                        hg.LeaderId = hgvm.LeaderId;
                    if (hgvm.AdministratorId == 0 || string.IsNullOrEmpty(hgvm.AdministratorName))
                        hg.AdministratorId = null;
                    else
                        hg.AdministratorId = hgvm.AdministratorId;

                    hg.Changed = DateTime.Now;

                    //Check to see if the address already exists
                    if (hgvm.AddressId>0 || hgvm.Address1 != null || hgvm.Address2 != null || hgvm.Address3 != null || hgvm.Address4 != null || hgvm.SuburbId!=0)
                    {
                        var address = new Address();

                        if (hgvm.AddressId > 0)
                        {
                            address = (from a in context.Addresses
                                       where a.AddressId == hgvm.AddressId
                                       select a).FirstOrDefault();

                            if (address == null) //Should never happen, but just to be sure
                            {
                                address = new Address {Created = DateTime.Now};
                                hgvm.AddressId = 0;
                            }
                        }
                        else
                        {
                            address.Created = DateTime.Now;
                        }

                        address.Line1 = hgvm.Address1 ?? "";
                        address.Line2 = hgvm.Address2 ?? "";
                        address.Line3 = hgvm.Address3 ?? "";
                        address.Line4 = hgvm.Address4 ?? "";
                        address.AddressType = hgvm.AddressType ?? "";
                        address.Lat = hgvm.Lat;
                        address.Long = hgvm.Lng;
                        address.ChurchSuburbId = hgvm.SuburbId != 0 ? hgvm.SuburbId : (int?)null;
                        address.Changed = DateTime.Now;

                        if (hgvm.AddressId == 0)
                        {
                            context.Addresses.AddObject(address);
                        }

                        hg.Address = address;
                    }

                    hg.GroupClassificationId = hgvm.GroupClassificationId == 0 ? (int?)null : hgvm.GroupClassificationId;

                    context.SaveChanges();
                    if (hgvm.OverseeingElderId == 0 || string.IsNullOrEmpty(hgvm.OverseeingElderName))
                    {
                        var linkedPersonToDelete = context.PersonLinkedToGroups.FirstOrDefault(p => p.GroupId == hgvm.GroupId && p.Description == CacheNames.OverseeingElder);
                        if(linkedPersonToDelete!=null)
                            context.PersonLinkedToGroups.DeleteObject(linkedPersonToDelete);
                    }
                    else
                    {
                        var linkedPersonToDelete = context.PersonLinkedToGroups.FirstOrDefault(p => p.GroupId == hgvm.GroupId && p.Description == CacheNames.OverseeingElder);
                        if (linkedPersonToDelete != null)
                        {
                            context.PersonLinkedToGroups.DeleteObject(linkedPersonToDelete);
                        }
                        addNewElder(context, hg.GroupId, hgvm.OverseeingElderId);
                    }
                    context.SaveChanges();
                    return hg.GroupId;
                }
            }

            throw new ApplicationException("You do not have the required permission");
        }
 public Person FetchPerson(int personId, Person currentPerson)
 {
     var sysAdmin = currentPerson != null && currentPerson.Permissions != null && currentPerson.HasPermission(Permissions.SystemAdministrator);
     return FetchPerson(personId, sysAdmin);
 }
        IEnumerable<PersonEventDto> IEventRepository.GetPersonEventsForGroup(int groupId, Person currentPerson)
        {
            if(!currentPerson.HasPermission(Permissions.ViewDiscipleship101)) return new List<PersonEventDto>();
            var group = Context.Groups.FirstOrDefault(g => g.GroupId == groupId);
            if (group == null)
                throw new ApplicationException("Invalid GroupId");

            var people = GroupDataAccessor.FetchPeopleInGroup(currentPerson, groupId);

            var events = ListOfEventsForGroup(group.ChurchId);
            return people.Select(person => new PersonEventDto
                                                       {
                                                           FullName = person.FullName,
                                                           PersonId = person.PersonId,
                                                           CompletedEvents = GetCompletedEvents(events, person.PersonId)
                                                       }).ToList();
        }
        public int Save(PersonViewModel person, Person currentPerson)
        {
            if (!currentPerson.HasPermission(Permissions.EditChurchPersonalDetails))
            {
                if (currentPerson.HasPermission(Permissions.EditOwnDetails))
                {
                    if (!_permissionRepository.CheckSavePermissionPersonal(person, currentPerson))
                    {
                        if (currentPerson.HasPermission(Permissions.EditGroupPersonalDetails))
                        {
                            if (!_permissionRepository.CheckSavePermissionGroup(person, currentPerson))
                            {
                                return person.PersonId;
                            }
                        }
                    }
                }
                else
                {
                    return person.PersonId;
                }
            }

            bool sendWelcomeEmail;
            Church church;
            var personToSave = _personRepository.UpdatePerson(person, currentPerson, out sendWelcomeEmail, out church);
            var anniversaryHasChanged = _personRepository.SavePersonalDetails(person, currentPerson, personToSave);
            _personRoleRepository.SavePersonChurchRole(person, currentPerson, personToSave);
            var addedToNewGroup = _personGroupRepository.AddPersonToGroup(person, currentPerson, personToSave);
            _personOptionalFieldRepository.SaveOptionalFields(person, personToSave);
            _addressRepository.SaveAddressInformation(person, personToSave.Family.Address, personToSave.Family);
            _relationshipRepository.UpdateRelationships(person, personToSave, anniversaryHasChanged);
            personToSave = _personRepository.FetchPerson(personToSave.PersonId, currentPerson);
            _personRepository.SaveWindowsLiveId(person, personToSave);
            _emailService.SendWelcomeEmail(person, sendWelcomeEmail, church, personToSave, currentPerson);
            _emailService.EmailGroupLeader(person, currentPerson, church, personToSave, addedToNewGroup);

            if (personToSave.FamilyId == currentPerson.FamilyId)
                _emailService.SendUpdateNotification(currentPerson.ChurchId, currentPerson, personToSave);

            return personToSave.PersonId;
        }
        public PersonViewModel FetchPersonViewModel(int personId, Person currentPerson)
        {
            if (currentPerson.HasPermission(Permissions.EditChurchPersonalDetails) ||
                currentPerson.HasPermission(Permissions.EditGroupPersonalDetails) ||
                currentPerson.HasPermission(Permissions.EditOwnDetails))
            {
                try
                {
                    _churchMatcherRepository.CheckThatChurchIdsMatch(personId, currentPerson);

                    var person = _personRepository.FetchPerson(personId, currentPerson);

                    if (person == null)
                        throw new ApplicationException("Invalid PersonId");

                    var imageLink = string.Empty;
                    var imageLinkLarge = string.Empty;
                    var faceBookId = person.PersonOptionalFields.FirstOrDefault(c => c.OptionalFieldId == (int) OptionalFields.Facebook) == null ? string.Empty : person.PersonOptionalFields.First(c => c.OptionalFieldId == (int) OptionalFields.Facebook).Value;
                    var imageExists = _photoRepository.ImageExists(person.PersonId);
                    if (imageExists)
                    {
                        imageLink = string.Format("/Images/GetImage?personId={0}&imageSize={1}", person.PersonId, ImageSize.Small);
                        imageLinkLarge = string.Format("/Images/GetImage?personId={0}&imageSize={1}", person.PersonId, ImageSize.Large);
                    }
                    else
                    {
                        if (faceBookId != string.Empty)
                        {
                            imageLink = string.Format("https://graph.facebook.com/{0}/picture", faceBookId);
                            imageLinkLarge = string.Format("https://graph.facebook.com/{0}/picture?type=large", faceBookId);
                        }
                        else
                        {
                            imageLink = "/Content/images/unknown.png";
                        }
                    }

                    var personViewModel = new PersonViewModel
                        {
                            PersonId = person.PersonId,
                            FamilyId = person.FamilyId,
                            Firstname = person.Firstname,
                            Surname = person.Family.FamilyName,
                            Email = person.Email,
                            DateOfBirth_Value = person.DateOfBirth,
                            Anniversary_Value = person.Anniversary,
                            HomePhone = person.Family.HomePhone,
                            CellPhone = person.PersonOptionalFields.FirstOrDefault(c => c.OptionalFieldId == (int) OptionalFields.CellPhone) == null ? string.Empty : person.PersonOptionalFields.First(c => c.OptionalFieldId == (int) OptionalFields.CellPhone).Value,
                            WorkPhone = person.PersonOptionalFields.FirstOrDefault(c => c.OptionalFieldId == (int) OptionalFields.WorkPhone) == null ? string.Empty : person.PersonOptionalFields.First(c => c.OptionalFieldId == (int) OptionalFields.WorkPhone).Value,
                            Skype = person.PersonOptionalFields.FirstOrDefault(c => c.OptionalFieldId == (int) OptionalFields.Skype) == null ? string.Empty : person.PersonOptionalFields.First(c => c.OptionalFieldId == (int) OptionalFields.Skype).Value,
                            Twitter = person.PersonOptionalFields.FirstOrDefault(c => c.OptionalFieldId == (int) OptionalFields.Twitter) == null ? string.Empty : person.PersonOptionalFields.First(c => c.OptionalFieldId == (int) OptionalFields.Twitter).Value,
                            ImageLink = imageLink,
                            ImageLinkLarge = imageLinkLarge,
                            FacebookId = faceBookId,
                            Occupation = person.PersonOptionalFields.FirstOrDefault(c => c.OptionalFieldId == (int)OptionalFields.Occupation) == null ? string.Empty : person.PersonOptionalFields.First(c => c.OptionalFieldId == (int)OptionalFields.Occupation).Value,
                            MaritalStatus = person.PersonOptionalFields.FirstOrDefault(c => c.OptionalFieldId == (int)OptionalFields.MaritalStatus) == null ? string.Empty : person.PersonOptionalFields.First(c => c.OptionalFieldId == (int)OptionalFields.MaritalStatus).Value,
                            Gender = person.PersonOptionalFields.FirstOrDefault(c => c.OptionalFieldId == (int)OptionalFields.Gender) == null ? string.Empty : person.PersonOptionalFields.First(c => c.OptionalFieldId == (int)OptionalFields.Gender).Value,
                            Address1 = person.Family.Address.Line1,
                            Address2 = person.Family.Address.Line2,
                            Address3 = person.Family.Address.Line3,
                            Address4 = person.Family.Address.Line4,
                            Lat = person.Family.Address.Lat,
                            Lng = person.Family.Address.Long,
                            HasUsername = person.Username != null,
                            FindFamily = false,
                            GroupId = 0,
                            Site = person.SiteId.HasValue ? person.Site.Name : "Select site...",
                            HeardAbout =
                                person.PersonOptionalFields.FirstOrDefault(
                                    c => c.OptionalFieldId == (int) OptionalFields.HeardAbout) == null
                                    ? string.Empty
                                    : person.PersonOptionalFields.First(
                                        c => c.OptionalFieldId == (int) OptionalFields.HeardAbout).Value,
                            RoleId = person.RoleId,
                            RoleName = person.Role.Name
                        };

                    _groupRepository.PopulateGroupId(personId, currentPerson, personViewModel);

                    personViewModel.FamilyMembers = _familyRepository.FetchFamilyMembers(personId, person.FamilyId);
                    personViewModel.SecurityRoles = _personRoleRepository.FetchSecurityRoles(currentPerson);

                    return personViewModel;
                }
                catch (Exception ex)
                {
                    _emailService.SendExceptionEmail(ex);
                    return null;
                }
            }
            throw new Exception(ExceptionMessage.InvalidCredentials);
        }
        public void SetupPermissions(Person currentPerson, Church church, bool sysAdmin)
        {
            currentPerson.Permissions = (from pr in Context.PersonChurches
                                         join r in Context.Roles
                                             on pr.RoleId equals r.RoleId
                                         join permissions in Context.PermissionRoles
                                             on r.RoleId equals permissions.RoleId
                                         where pr.PersonId == currentPerson.PersonId
                                               && r.ChurchId == church.ChurchId
                                         select permissions.PermissionId)
                .ToList();

            if (sysAdmin) currentPerson.Permissions.Add((int)Permissions.SystemAdministrator);
            var surname = currentPerson.Family.FamilyName;
            currentPerson.Church = church;
            currentPerson.ChurchId = church.ChurchId;
            var personChurch = currentPerson.PersonChurches.FirstOrDefault(pc => pc.ChurchId == currentPerson.ChurchId);
            Role role = null;
            if (personChurch != null)
            {
                role = Context.Roles.First(r => r.RoleId == personChurch.RoleId);
            }
            else if (currentPerson.HasPermission(Permissions.SystemAdministrator))
            {
                role = Context.Roles.FirstOrDefault(r => r.ChurchId == church.ChurchId && r.Name.Contains("Administrator"));
                if (role == null)
                    throw new ApplicationException("Cannot set role for new church");
            }
            else
            {
                throw new ApplicationException("Cannot set role for new church");
            }
            currentPerson.RoleId = role.RoleId;
            currentPerson.Role = role;
            var churchIds = (from p in currentPerson.PersonChurches select p.ChurchId).ToList();
            currentPerson.Churches = Context.Churches.Where(c => churchIds.Contains(c.ChurchId)).ToList();
        }
 public static void RemovePersonFromGroup(Person currentPerson, int groupId, int personId)
 {
     using (oikonomosEntities context = new oikonomosEntities(ConfigurationManager.ConnectionStrings["oikonomosEntities"].ConnectionString))
     {
         if (currentPerson.HasPermission(Permissions.RemovePersonFromGroup))
         {
             //Fetch the record
             var personToRemove = (from pg in context.PersonGroups
                                   where pg.PersonId == personId
                                   && pg.GroupId == groupId
                                   select pg).FirstOrDefault();
             if (personToRemove != null)
             {
                 //Remove them
                 context.PersonGroups.DeleteObject(personToRemove);
                 context.SaveChanges();
             }
         }
     }
 }
        public static void SaveHomeGroup(Person currentPerson, HomeGroupsViewModel hgvm)
        {
            if (currentPerson.HasPermission(Permissions.EditGroups) || currentPerson.HasPermission(Permissions.AddGroups))
            {
                using (oikonomosEntities context = new oikonomosEntities(ConfigurationManager.ConnectionStrings["oikonomosEntities"].ConnectionString))
                {
                    Group hg = new Group();
                    if (hgvm.GroupId != 0)
                    {
                        hg = (from g in context.Groups
                              where g.GroupId == hgvm.GroupId
                              select g).FirstOrDefault();
                    }
                    else
                    {
                        hg.ChurchId = currentPerson.ChurchId;
                        hg.Created = DateTime.Now;
                        if (currentPerson.ChurchId == 3) //Ebenezer
                        {
                            hg.GroupTypeId = (int)GroupTypes.LifeGroup;
                        }
                        else
                        {
                            hg.GroupTypeId = (int)GroupTypes.HomeGroup;
                        }
                        context.Groups.AddObject(hg);
                    }

                    hg.Name = hgvm.GroupName;
                    if (hgvm.LeaderId == 0 || hgvm.LeaderName == null || hgvm.LeaderName == string.Empty)
                        hg.LeaderId = null;
                    else
                        hg.LeaderId = hgvm.LeaderId;
                    if (hgvm.AdministratorId == 0 || hgvm.AdministratorName == null || hgvm.AdministratorName == string.Empty)
                        hg.AdministratorId = null;
                    else
                        hg.AdministratorId = hgvm.AdministratorId;
                    hg.Changed = DateTime.Now;

                    //Check to see if the address already exists
                    if (hgvm.AddressId>0 || hgvm.Address1 != null || hgvm.Address2 != null || hgvm.Address3 != null || hgvm.Address4 != null || hgvm.SuburbId!=0)
                    {
                        var address = new Address();

                        if (hgvm.AddressId > 0)
                        {
                            address = (from a in context.Addresses
                                       where a.AddressId == hgvm.AddressId
                                       select a).FirstOrDefault();

                            if (address == null) //Should never happen, but just to be sure
                            {
                                address = new Address();
                                address.Created = DateTime.Now;
                                hgvm.AddressId = 0;
                            }
                        }
                        else
                        {
                            address.Created = DateTime.Now;
                        }

                        address.Line1 = hgvm.Address1 == null ? "" : hgvm.Address1;
                        address.Line2 = hgvm.Address2 == null ? "" : hgvm.Address2;
                        address.Line3 = hgvm.Address3 == null ? "" : hgvm.Address3;
                        address.Line4 = hgvm.Address4 == null ? "" : hgvm.Address4;
                        address.AddressType = hgvm.AddressType == null ? "" : hgvm.AddressType;
                        address.Lat = hgvm.Lat == null ? 0 : hgvm.Lat;
                        address.Long = hgvm.Lng == null ? 0 : hgvm.Lng;
                        address.ChurchSuburbId = hgvm.SuburbId != 0 ? hgvm.SuburbId : (int?)null;
                        address.Changed = DateTime.Now;

                        if (hgvm.AddressId == 0)
                        {
                            context.Addresses.AddObject(address);
                        }

                        hg.Address = address;
                    }

                    hg.GroupClassificationId = hgvm.GroupClassificationId == 0 ? (int?)null : hgvm.GroupClassificationId;

                    context.SaveChanges();
                }
            }
            else
            {
                throw new ApplicationException("You do not have the required permission");
            }
        }
        public static JqGridData FetchHomeGroupsJQGrid(Person currentPerson, JqGridRequest request)
        {
            if (!(currentPerson.HasPermission(Permissions.EditOwnGroups) || currentPerson.HasPermission(Permissions.EditAllGroups)))
            {
                throw new Exception("Invalid security Role");
            }

            using (oikonomosEntities context = new oikonomosEntities(ConfigurationManager.ConnectionStrings["oikonomosEntities"].ConnectionString))
            {
                List<JqGridFilterRule> rules = request.filters == null ? null : request.filters.rules;
                var groups = FetchGroupList(currentPerson, request._search, rules, context);

                int totalRecords = groups.Count();

                switch (request.sidx)
                {
                    case "GroupName":
                        {
                            if (request.sord.ToLower() == "asc")
                            {
                                groups = groups.OrderBy(g => g.Name).Skip((request.page - 1) * request.rows).Take(request.rows);
                            }
                            else
                            {
                                groups = groups.OrderByDescending(g => g.Name).Skip((request.page - 1) * request.rows).Take(request.rows);
                            }
                            break;
                        }
                    case "LeaderName":
                        {
                            if (request.sord.ToLower() == "asc")
                            {
                                groups = groups.OrderBy(g => g.Leader.Firstname).Skip((request.page - 1) * request.rows).Take(request.rows);
                            }
                            else
                            {
                                groups = groups.OrderByDescending(g => g.Leader.Firstname).Skip((request.page - 1) * request.rows).Take(request.rows);
                            }
                            break;
                        }
                    case "Administrator":
                        {
                            if (request.sord.ToLower() == "asc")
                            {
                                groups = groups.OrderBy(g => g.Administrator.Firstname).Skip((request.page - 1) * request.rows).Take(request.rows);
                            }
                            else
                            {
                                groups = groups.OrderByDescending(g => g.Administrator.Firstname).Skip((request.page - 1) * request.rows).Take(request.rows);
                            }
                            break;
                        }
                    case "Suburb":
                        {
                            if (request.sord.ToLower() == "asc")
                            {
                                groups = groups.OrderBy(g => g.Address.ChurchSuburb.Suburb).ThenBy(g => g.Address.Line3).Skip((request.page - 1) * request.rows).Take(request.rows);
                            }
                            else
                            {
                                groups = groups.OrderByDescending(g => g.Address.ChurchSuburb.Suburb).ThenByDescending(g => g.Address.Line3).Skip((request.page - 1) * request.rows).Take(request.rows);
                            }
                            break;
                        }
                    case "GroupClassification":
                        {
                            if (request.sord.ToLower() == "asc")
                            {
                                groups = groups.OrderBy(g => g.GroupClassification.Name).Skip((request.page - 1) * request.rows).Take(request.rows);
                            }
                            else
                            {
                                groups = groups.OrderByDescending(g => g.GroupClassification.Name).Skip((request.page - 1) * request.rows).Take(request.rows);
                            }
                            break;
                        }
                }

                JqGridData sitesGridData = new JqGridData()
                {
                    total = (int)Math.Ceiling((float)totalRecords / (float)request.rows),
                    page = request.page,
                    records = totalRecords,
                    rows = (from g in groups.AsEnumerable()
                            select new JqGridRow()
                            {
                                id = g.GroupId.ToString(),
                                cell = new string[] {
                                                    g.GroupId.ToString(),
                                                    g.Name,
                                                    g.Leader==null? string.Empty : g.Leader.Firstname + " " + g.Leader.Family.FamilyName,
                                                    g.Administrator==null? string.Empty : g.Administrator.Firstname + " " + g.Administrator.Family.FamilyName,
                                                    g.Address==null? string.Empty : g.Address.ChurchSuburb==null?g.Address.Line3:g.Address.ChurchSuburb.Suburb,
                                                    g.GroupClassification==null? string.Empty :g.GroupClassification.Name
                                }
                            }).ToArray()
                };

                return sitesGridData;
            }
        }
Example #21
0
 public void SendWelcomeEmail(PersonViewModel person, bool sendWelcomeEmail, Church church, Person personToSave, Person currentPerson)
 {
     if (sendWelcomeEmail && personToSave.HasValidEmail() && (personToSave.HasPermission(Permissions.Login) || personToSave.HasPermission(Permissions.SendWelcomeLetter)))
     {
         SendEmailAndPassword(
             person.Firstname,
             person.Surname,
             person.Email,
             personToSave,
             currentPerson);
     }
 }
        public static JqGridData FetchHomeGroupsJQGrid(Person currentPerson, JqGridRequest request, int? selectedGroupId, bool? useGroupId)
        {
            if (!(currentPerson.HasPermission(Permissions.EditOwnGroups) || currentPerson.HasPermission(Permissions.EditAllGroups)))
            {
                throw new Exception("Invalid security Role");
            }

            using (var context = new oikonomosEntities(ConfigurationManager.ConnectionStrings["oikonomosEntities"].ConnectionString))
            {
                var rules = request.filters == null ? null : request.filters.rules;
                var groups = FetchGroupList(currentPerson, request._search, rules, context);

                var sortedGroups = sortGroupList(request, groups).ToList();

                if (useGroupId.HasValue && useGroupId.Value)
                {
                    if (selectedGroupId.HasValue && selectedGroupId.Value == 0)
                        request.page = 1;
                    else if(selectedGroupId.HasValue)
                    {
                        var result = sortedGroups
                            .Select((x, i) => new {Item = x, Index = i})
                            .FirstOrDefault(itemWithIndex => itemWithIndex.Item.GroupId == selectedGroupId);

                        request.page = 1;
                        if (result != null)
                            request.page = ((result.Index + request.rows)/request.rows);

                    }
                }

                var totalRecords = sortedGroups.Count();
                var filteredGroups = sortedGroups.Skip((request.page - 1) * request.rows).Take(request.rows).ToList();

                var sitesGridData = new JqGridData()
                {
                    total = (int)Math.Ceiling((float)totalRecords / (float)request.rows),
                    page = request.page,
                    records = totalRecords,
                    rows = (from g in filteredGroups.AsEnumerable()
                            select new JqGridRow()
                            {
                                id = g.GroupId.ToString(),
                                cell = new string[] {
                                                    g.GroupId.ToString(),
                                                    g.Name,
                                                    g.Leader==null? string.Empty : g.Leader.Firstname + " " + g.Leader.Family.FamilyName,
                                                    g.Administrator==null? string.Empty : g.Administrator.Firstname + " " + g.Administrator.Family.FamilyName,
                                                    g.Address==null? string.Empty : g.Address.ChurchSuburb==null?g.Address.Line3:g.Address.ChurchSuburb.Suburb,
                                                    g.GroupClassification==null? string.Empty :g.GroupClassification.Name,
                                                    g.PersonLinkedToGroups.FirstOrDefault(p => p.Description == CacheNames.OverseeingElder)==null? string.Empty : g.PersonLinkedToGroups.First(p => p.Description == CacheNames.OverseeingElder).Person.Firstname + " " + g.PersonLinkedToGroups.First(p => p.Description == CacheNames.OverseeingElder).Person.Family.FamilyName
                                }
                            }).ToArray()
                };

                return sitesGridData;
            }
        }
        public JqGridData GetMessageStatuses(Person currentPerson, JqGridRequest request)
        {
            var messages = new List<MessageWithStatusViewModel>();
            if (currentPerson.HasPermission(Permissions.SystemAdministrator))
            {
                messages = _messageRecepientRepository.FetchMessagesWithStatuses().ToList();
            }
            var totalRecords = messages.Count();

            switch (request.sidx)
            {
                case "Subject":
                {
                    if (request.sord.ToLower() == "asc")
                    {
                        messages = messages.OrderBy(g => g.Subject)
                            .Skip((request.page - 1)*request.rows)
                            .Take(request.rows)
                            .ToList();
                    }
                    else
                    {
                        messages = messages
                            .OrderByDescending(g => g.Subject)
                            .Skip((request.page - 1)*request.rows)
                            .Take(request.rows)
                            .ToList();
                    }
                    break;
                }
                case "Sent":
                {
                    if (request.sord.ToLower() == "asc")
                    {
                        messages = messages.OrderBy(g => g.Sent)
                            .Skip((request.page - 1)*request.rows)
                            .Take(request.rows)
                            .ToList();
                    }
                    else
                    {
                        messages = messages
                            .OrderByDescending(g => g.Sent)
                            .Skip((request.page - 1)*request.rows)
                            .Take(request.rows)
                            .ToList();
                    }
                    break;
                }
                case "Status":
                {
                    if (request.sord.ToLower() == "asc")
                    {
                        messages = messages.OrderBy(g => g.Status)
                            .Skip((request.page - 1)*request.rows)
                            .Take(request.rows)
                            .ToList();
                    }
                    else
                    {
                        messages = messages
                            .OrderByDescending(g => g.Status)
                            .Skip((request.page - 1)*request.rows)
                            .Take(request.rows)
                            .ToList();
                    }
                    break;
                }
                case "From":
                {
                    if (request.sord.ToLower() == "asc")
                    {
                        messages = messages.OrderBy(g => g.From)
                            .Skip((request.page - 1)*request.rows)
                            .Take(request.rows)
                            .ToList();
                    }
                    else
                    {
                        messages = messages
                            .OrderByDescending(g => g.From)
                            .Skip((request.page - 1)*request.rows)
                            .Take(request.rows)
                            .ToList();
                    }
                    break;
                }
                case "To":
                {
                    if (request.sord.ToLower() == "asc")
                    {
                        messages = messages.OrderBy(g => g.To)
                            .Skip((request.page - 1)*request.rows)
                            .Take(request.rows)
                            .ToList();
                    }
                    else
                    {
                        messages = messages
                            .OrderByDescending(g => g.To)
                            .Skip((request.page - 1)*request.rows)
                            .Take(request.rows)
                            .ToList();
                    }
                    break;
                }
            }

            var messagesGridData = new JqGridData()
            {
                total = (int) Math.Ceiling((float) totalRecords/(float) request.rows),
                page = request.page,
                records = totalRecords,
                rows = (from g in messages
                    select new JqGridRow
                    {
                        id = g.MessageRecepientId,
                        cell = new string[]
                        {
                            g.MessageRecepientId,
                            g.Sent.ToString("yyyy-MM-dd"),
                            g.Status,
                            g.From,
                            g.To,
                            g.Subject,
                            g.StatusDetail
                        }
                    }).ToArray()
            };
            return messagesGridData;
        }
Example #24
0
        private void GetReportViewBagValues(Person currentPerson)
        {
            ViewBag.Title = currentPerson.HasPermission(Permissions.ViewChurchContactDetails) ? "List of People" : "List of People";

            var optionalFields = SettingsDataAccessor.FetchChurchOptionalFields(currentPerson.ChurchId);
            ViewBag.DisplayFacebook = false;
            foreach (var ct in optionalFields)
            {
                switch ((OptionalFields)ct.OptionalFieldId)
                {
                    case OptionalFields.CellPhone:
                        {
                            ViewBag.DisplayCellPhone = ct.Display ? "tableRow" : "displayNone";
                            break;
                        }
                    case OptionalFields.WorkPhone:
                        {
                            ViewBag.DisplayWorkPhone = ct.Display ? "tableRow" : "displayNone";
                            break;
                        }
                    case OptionalFields.Skype:
                        {
                            ViewBag.DisplaySkype = ct.Display ? "tableRow" : "displayNone";
                            break;
                        }
                    case OptionalFields.Twitter:
                        {
                            ViewBag.DisplayTwitter = ct.Display ? "tableRow" : "displayNone";
                            break;
                        }
                    case OptionalFields.Occupation:
                        {
                            ViewBag.DisplayOccupation = ct.Display ? "tableRow" : "displayNone";
                            break;
                        }
                    case OptionalFields.Facebook:
                        {
                            ViewBag.DisplayFacebook = ct.Display;
                            break;
                        }
                    case OptionalFields.ShowWholeChurch:
                        {
                            if (!currentPerson.HasPermission(Permissions.ViewChurchContactDetails))
                            {
                                ViewBag.DislayWholeChurch = ct.Display;
                            }
                            else
                            {
                                ViewBag.DislayWholeChurch = true;
                            }
                            break;
                        }
                }
            }
        }
Example #25
0
 private void SendEmailAndPassword(string firstname, string surname, string email, Person personToSave, Person currentPerson)
 {
     _usernamePasswordRepository.UpdateUsername(personToSave);
     var password = _usernamePasswordRepository.UpdatePassword(personToSave);
     var publicId = _personRepository.UpdatePublicId(personToSave);
     SendWelcomeEmail(firstname,
           surname,
           email,
           password,
           publicId,
           personToSave.HasPermission(Permissions.SendVisitorWelcomeLetter),
           false,
           currentPerson);
 }