public void UpdateRelationships(PersonViewModel person, Person personToSave, bool anniversaryHasChanged)
        {
            if (person.FamilyMembers == null) return;
            foreach (var familyMember in person.FamilyMembers)
            {
                if (familyMember.Relationship == null) continue;
                var relationship = (Relationships)Enum.Parse(typeof(Relationships), familyMember.Relationship);
                if (anniversaryHasChanged && (relationship == Relationships.Husband || relationship == Relationships.Wife))
                {
                    var spouse = (from p in Context.People
                                  where p.PersonId == familyMember.PersonId
                                  select p).FirstOrDefault();

                    if (spouse != null)
                    {
                        spouse.Anniversary = personToSave.Anniversary;
                    }
                }

                AddPersonRelationship(personToSave.PersonId, familyMember.PersonId, (int)relationship, personToSave);

                //Check the opposite relationship
                UpdateOtherRelationships(familyMember, person);
            }
            Context.SaveChanges();
        }
 public void SaveOptionalFields(PersonViewModel person, Person personToSave)
 {
     personToSave.Family.HomePhone = person.HomePhone;
     UpdatePersonOptionalField(personToSave, OptionalFields.CellPhone, person.CellPhone);
     UpdatePersonOptionalField(personToSave, OptionalFields.Skype, person.Skype);
     UpdatePersonOptionalField(personToSave, OptionalFields.Twitter, person.Twitter);
     UpdatePersonOptionalField(personToSave, OptionalFields.WorkPhone, person.WorkPhone);
     UpdatePersonOptionalField(personToSave, OptionalFields.HeardAbout, person.HeardAbout);
     UpdatePersonOptionalField(personToSave, OptionalFields.Gender, person.Gender);
     UpdatePersonOptionalField(personToSave, OptionalFields.Occupation, person.Occupation);
     UpdatePersonOptionalField(personToSave, OptionalFields.MaritalStatus, person.MaritalStatus);
     Context.SaveChanges();
 }
        public void SavePersonChurchRole(PersonViewModel person, Person currentPerson, Person personToSave)
        {
            if (person.RoleId == 0)
                return;

            var personRole = Context.PersonChurches.FirstOrDefault(pr => (pr.Role.ChurchId == currentPerson.ChurchId) && (pr.PersonId == personToSave.PersonId));
            if (personRole == null)
            {
                SavePersonRole(personToSave, person.RoleId);
                return;
            }

            if (personRole.RoleId == person.RoleId)
                return;

            Context.DeleteObject(personRole);
            SavePersonRole(personToSave, person.RoleId);
        }
 public bool CheckSavePermissionPersonal(PersonViewModel person, Person currentPerson)
 {
     var canSave = false;
     if (person.PersonId > 0)
     {
         var familyPerson = (from p in Context.People
                             where p.PersonId == person.PersonId
                             && p.FamilyId == currentPerson.FamilyId
                             select p).FirstOrDefault();
         if (familyPerson != null)
         {
             canSave = true;
         }
     }
     else
     {
         canSave = true;
     }
     return canSave;
 }
        public void PopulateGroupId(int personId, Person currentPerson, PersonViewModel personViewModel)
        {
            Group group = null;
            if (Context.PersonGroups.Count(pg => pg.PersonId == personId && pg.Group.ChurchId == currentPerson.ChurchId) == 1)
                group = (from pg in Context.PersonGroups
                         where pg.PersonId == personId && pg.Group.ChurchId == currentPerson.ChurchId
                         select pg.Group).FirstOrDefault();
            else
                group = (from pg in Context.PersonGroups
                         where pg.PersonId == personId && pg.Group.ChurchId == currentPerson.ChurchId && pg.PrimaryGroup
                         select pg.Group).FirstOrDefault()
                        ?? (from pg in Context.PersonGroups
                            where pg.PersonId == personId && pg.Group.ChurchId == currentPerson.ChurchId
                            select pg.Group).FirstOrDefault();

            personViewModel.GroupId = group == null ? 0 : group.GroupId;
            personViewModel.GroupName = group == null ? "None" : group.Name;

            personViewModel.IsInMultipleGroups = Context.PersonGroups.Count(pg => pg.PersonId == personId && pg.Group.ChurchId == currentPerson.ChurchId) > 1;
        }
        public void SaveAddressInformation(PersonViewModel person, Address address, Family family)
        {
            if (address == null)
            {
                address = new Address { Created = DateTime.Now, Changed = DateTime.Now };
                family.Address = address;
            }

            if (address.Line1 != person.Address1 ||
                address.Line2 != person.Address2 ||
                address.Line3 != person.Address3 ||
                address.Line4 != person.Address4)
                address.Changed = DateTime.Now;

            address.Line1 = person.Address1 ?? string.Empty;
            address.Line2 = person.Address2 ?? string.Empty;
            address.Line3 = person.Address3 ?? string.Empty;
            address.Line4 = person.Address4 ?? string.Empty;
            address.Lat = person.Lat;
            address.Long = person.Lng;

            Context.SaveChanges();
        }
 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);
            }
        }
 private void CreatePersonItem(PersonViewModel person, ICollection<Item> items, Group group, string backgroundImage)
 {
     items.Add(new Item
     {
         backgroundImage = backgroundImage,
         content         = CreateContent(person.CellPhone, person.Email),
         title           = person.FullName,
         subtitle        = person.RoleName,
         description     = "",
         group           = group
     });
 }
        public static int SavePerson(PersonViewModel person, Person currentPerson)
        {
            using (var context = new oikonomosEntities(ConfigurationManager.ConnectionStrings["oikonomosEntities"].ConnectionString))
            {
                if (!currentPerson.HasPermission(Permissions.EditChurchPersonalDetails))
                {
                    if (currentPerson.HasPermission(Permissions.EditGroupPersonalDetails))
                    {
                        if (!CheckSavePermissionGroup(person, currentPerson, context)) { return person.PersonId; }
                    }
                    else if (currentPerson.HasPermission(Permissions.EditOwnDetails))
                    {
                        if (!CheckSavePermissionPersonal(person, currentPerson, context)) { return person.PersonId; }
                    }
                    else
                    {
                        return person.PersonId;
                    }
                }

                bool sendWelcomeEmail;
                Church church;
                Person personToSave;

                GetPersonToSaveEntity(person, currentPerson, context, out sendWelcomeEmail, out church, out personToSave);
                bool anniversaryHasChanged = SavePersonalDetails(person, currentPerson, context, personToSave);
                SaveRole(person, currentPerson, context, personToSave);
                bool addedToNewGroup = AddPersonToGroup(person, currentPerson, context, personToSave);
                SaveContactInformation(person, personToSave);
                SaveAddressInformation(person, personToSave);

                UpdateRelationships(person, context, personToSave, anniversaryHasChanged);
                context.SaveChanges();
                personToSave = FetchPerson(personToSave.PersonId, context, currentPerson);
                SaveWindowsLiveId(person, personToSave, context);
                SendEmails(person, sendWelcomeEmail, church, personToSave);
                EmailGroupLeader(person, currentPerson, context, church, personToSave, addedToNewGroup);

                context.SaveChanges();

                return personToSave.PersonId;
            }
        }
        private static void UpdateRelationships(PersonViewModel person, oikonomosEntities context, Person personToSave, bool anniversaryHasChanged)
        {
            if (person.FamilyMembers != null)
            {
                foreach (FamilyMemberViewModel familyMember in person.FamilyMembers)
                {
                    if (familyMember.Relationship != null)
                    {
                        var relationship = (Relationships)Enum.Parse(typeof(Relationships), familyMember.Relationship);
                        if (anniversaryHasChanged && (relationship == Relationships.Husband || relationship == Relationships.Wife))
                        {
                            var spouse = (from p in context.People
                                          where p.PersonId == familyMember.PersonId
                                          select p).FirstOrDefault();

                            if (spouse != null)
                            {
                                spouse.Anniversary = personToSave.Anniversary;
                            }
                        }

                        AddPersonRelationship(personToSave.PersonId, familyMember.PersonId, (int)relationship, personToSave, context);

                        //Check the opposite relationship
                        UpdateOtherRelationships(familyMember, person, context);
                    }
                }
            }
        }
 private static void SetGroupId(int personId, Person currentPerson, oikonomosEntities context, PersonViewModel personViewModel)
 {
     if (context.PersonGroups.Count(pg => pg.PersonId == personId && pg.Group.ChurchId == currentPerson.ChurchId) == 1)
         personViewModel.GroupId = (from pg in context.PersonGroups
                                    where pg.PersonId == personId && pg.Group.ChurchId == currentPerson.ChurchId
                                    select pg.GroupId).FirstOrDefault();
     personViewModel.IsInMultipleGroups =
         context.PersonGroups.Count(pg => pg.PersonId == personId && pg.Group.ChurchId == currentPerson.ChurchId) > 1;
 }
 private static void SaveWindowsLiveId(PersonViewModel person, Person personToSave, oikonomosEntities context)
 {
     if (string.IsNullOrEmpty(person.WindowsLiveId)) return;
     var windowsLiveId = context.PersonOptionalFields.FirstOrDefault(p =>p.OptionalFieldId == (int) OptionalFields.WindowsLive && p.PersonId == personToSave.PersonId);
     if(windowsLiveId==null)
     {
         windowsLiveId = new PersonOptionalField
                             {
                                 Changed = DateTime.Now,
                                 Created = DateTime.Now,
                                 OptionalFieldId = (int) OptionalFields.WindowsLive,
                                 PersonId = personToSave.PersonId,
                                 Value = person.WindowsLiveId
                             };
         context.AddToPersonOptionalFields(windowsLiveId);
         context.SaveChanges();
     }
     else
     {
         if(windowsLiveId.Value!=person.WindowsLiveId)
         {
             windowsLiveId.Value = person.WindowsLiveId;
             context.SaveChanges();
         }
     }
 }
        private static bool SavePersonalDetails(PersonViewModel person, Person currentPerson, oikonomosEntities context, Person personToSave)
        {
            bool anniversaryHasChanged = false;
            if (personToSave.Anniversary != person.Anniversary_Value)
            {
                anniversaryHasChanged = true;
            }
            personToSave.Anniversary = person.Anniversary_Value;

            personToSave.Occupation = person.Occupation;
            Site selectedSite = (from s in context.Sites where s.ChurchId == currentPerson.ChurchId && s.Name == person.Site select s).FirstOrDefault();
            if (selectedSite == null)
            {
                personToSave.SiteId = null;
            }
            else
            {
                personToSave.SiteId = selectedSite.SiteId;
                if (person.FamilyId > 0)
                {
                    var familyMembers = (from p in context.People
                                         where p.FamilyId == person.FamilyId
                                         && p.SiteId == null
                                         select p);
                    foreach (Person p in familyMembers)
                    {
                        p.SiteId = selectedSite.SiteId;
                    }
                }
            }

            personToSave.Family.Changed = DateTime.Now;
            personToSave.Changed = DateTime.Now;
            return anniversaryHasChanged;
        }
        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);
        }
        private static void SaveAddressInformation(PersonViewModel person, Person personToSave)
        {
            if (personToSave.Family.Address == null)
            {
                personToSave.Family.Address = new Address {Created = DateTime.Now, Changed = DateTime.Now};
            }

            if (personToSave.Family.Address.Line1 != person.Address1 ||
                personToSave.Family.Address.Line2 != person.Address2 ||
                personToSave.Family.Address.Line3 != person.Address3 ||
                personToSave.Family.Address.Line4 != person.Address4)
                personToSave.Family.Address.Changed = DateTime.Now;

            personToSave.Family.Address.Line1 = person.Address1 ?? string.Empty;
            personToSave.Family.Address.Line2 = person.Address2 ?? string.Empty;
            personToSave.Family.Address.Line3 = person.Address3 ?? string.Empty;
            personToSave.Family.Address.Line4 = person.Address4 ?? string.Empty;
            personToSave.Family.Address.Lat = person.Lat;
            personToSave.Family.Address.Long = person.Lng;
        }
 private static void SaveContactInformation(PersonViewModel person, Person personToSave)
 {
     personToSave.Family.HomePhone = person.HomePhone;
     UpdatePersonOptionalField(personToSave, OptionalFields.CellPhone, person.CellPhone);
     UpdatePersonOptionalField(personToSave, OptionalFields.Skype, person.Skype);
     UpdatePersonOptionalField(personToSave, OptionalFields.Twitter, person.Twitter);
     UpdatePersonOptionalField(personToSave, OptionalFields.WorkPhone, person.WorkPhone);
     UpdatePersonOptionalField(personToSave, OptionalFields.HeardAbout, person.HeardAbout);
     UpdatePersonOptionalField(personToSave, OptionalFields.Gender, person.Gender);
 }
        private void UpdateOtherRelationships(FamilyMemberViewModel familyMember, PersonViewModel person)
        {
            try
            {
                var relationship = (Relationships)Enum.Parse(typeof(Relationships), familyMember.Relationship);
                var oppositeRelationship = Relationships.Unknown;
                var familyMemberToUpdate = (from p in Context.People.Include("PersonRelationships")
                                               where p.PersonId == familyMember.PersonId
                                               select p).FirstOrDefault();

                var isMale = (from pr in Context.PersonRelationships
                               where pr.PersonRelatedToId == person.PersonId
                                     && (pr.RelationshipId == (int)Relationships.Husband ||
                                         pr.RelationshipId == (int)Relationships.Brother ||
                                         pr.RelationshipId == (int)Relationships.Father ||
                                         pr.RelationshipId == (int)Relationships.Grandfather ||
                                         pr.RelationshipId == (int)Relationships.Grandson ||
                                         pr.RelationshipId == (int)Relationships.Son)
                               select pr).Any();

                var isFemale = (from pr in Context.PersonRelationships
                                 where pr.PersonRelatedToId == person.PersonId
                                       && (pr.RelationshipId == (int)Relationships.Wife ||
                                           pr.RelationshipId == (int)Relationships.Sister ||
                                           pr.RelationshipId == (int)Relationships.Mother ||
                                           pr.RelationshipId == (int)Relationships.Grandmother ||
                                           pr.RelationshipId == (int)Relationships.Granddaughter ||
                                           pr.RelationshipId == (int)Relationships.Daughter)
                                 select pr).Any();

                switch (relationship)
                {
                    case Relationships.Husband:
                        {
                            oppositeRelationship = Relationships.Wife;
                            break;
                        }
                    case Relationships.Wife:
                        {
                            oppositeRelationship = Relationships.Husband;
                            break;
                        }
                    case Relationships.Son:
                    case Relationships.Daughter:
                        {
                            if (isMale)
                            {
                                oppositeRelationship = Relationships.Father;
                            }

                            if (isFemale)
                            {
                                oppositeRelationship = Relationships.Mother;
                            }
                            break;
                        }
                    case Relationships.Brother:
                    case Relationships.Sister:
                        {
                            if (isMale)
                            {
                                oppositeRelationship = Relationships.Brother;
                            }

                            if (isFemale)
                            {
                                oppositeRelationship = Relationships.Sister;
                            }
                            break;
                        }
                    case Relationships.Father:
                    case Relationships.Mother:
                        {
                            if (isMale)
                            {
                                oppositeRelationship = Relationships.Son;
                            }

                            if (isFemale)
                            {
                                oppositeRelationship = Relationships.Daughter;
                            }
                            break;
                        }
                    case Relationships.Grandfather:
                    case Relationships.Grandmother:
                        {
                            if (isMale)
                            {
                                oppositeRelationship = Relationships.Grandson;
                            }

                            if (isFemale)
                            {
                                oppositeRelationship = Relationships.Granddaughter;
                            }
                            break;
                        }
                    case Relationships.Grandson:
                    case Relationships.Granddaughter:
                        {
                            if (isMale)
                            {
                                oppositeRelationship = Relationships.Grandfather;
                            }

                            if (isFemale)
                            {
                                oppositeRelationship = Relationships.Grandmother;
                            }
                            break;
                        }
                }

                if (oppositeRelationship == Relationships.Unknown) return;
                AddPersonRelationship(familyMember.PersonId, person.PersonId, (int)oppositeRelationship, familyMemberToUpdate);

                var personToUpdate = _personRepository.FetchPerson(person.PersonId, null);

                //What about the rest of the family
                if (relationship == Relationships.Husband || relationship == Relationships.Wife)
                {
                    var spouseRelationships = (from pr in Context.PersonRelationships
                                               where pr.PersonId == familyMember.PersonId
                                                     && (pr.RelationshipId == (int)Relationships.Son ||
                                                         pr.RelationshipId == (int)Relationships.Daughter ||
                                                         pr.RelationshipId == (int)Relationships.Grandson ||
                                                         pr.RelationshipId == (int)Relationships.Granddaughter)
                                               select pr);

                    foreach (var pr in spouseRelationships.Where(pr => person.PersonId != pr.PersonRelatedToId))
                    {
                        AddPersonRelationship(person.PersonId, pr.PersonRelatedToId, pr.RelationshipId, personToUpdate);
                    }
                }

                if (relationship != Relationships.Brother && relationship != Relationships.Sister) return;
                //He has a brother - does the brother have a father, grandfather, mother etc
                var siblingRelationships = (from pr in Context.PersonRelationships
                                            where pr.PersonId == familyMember.PersonId
                                                  && (pr.RelationshipId == (int)Relationships.Father ||
                                                      pr.RelationshipId == (int)Relationships.Mother ||
                                                      pr.RelationshipId == (int)Relationships.Grandfather ||
                                                      pr.RelationshipId == (int)Relationships.Grandmother ||
                                                      pr.RelationshipId == (int)Relationships.Sister ||
                                                      pr.RelationshipId == (int)Relationships.Brother)
                                            select pr);

                foreach (var pr in siblingRelationships.Where(pr => person.PersonId != pr.PersonRelatedToId))
                {
                    AddPersonRelationship(personToUpdate.PersonId, pr.PersonRelatedToId, pr.RelationshipId, personToUpdate);
                }
            }
            catch { }
        }
        private static void SaveRole(PersonViewModel person, Person currentPerson, oikonomosEntities context, Person personToSave)
        {
            if (person.RoleId == 0)
                return;

            var personRole = context.PersonChurches.FirstOrDefault(pr => (pr.Role.ChurchId == currentPerson.ChurchId) && (pr.PersonId == personToSave.PersonId));
            if (personRole == null)
            {
                SavePersonRole(context, personToSave, person.RoleId);
                return;
            }

            if (personRole.RoleId == person.RoleId)
                return;

            context.DeleteObject(personRole);
            SavePersonRole(context, personToSave, person.RoleId);
        }
Exemple #20
0
        public JsonResult SavePerson(PersonViewModel person)
        {
            bool sessionTimedOut = false;
            int personId = 0;
            if (Session[SessionVariable.LoggedOnPerson] == null)
            {
                sessionTimedOut = true;
            }
            else
            {
                Person currentPerson = (Person)Session[SessionVariable.LoggedOnPerson];
                personId = PersonDataAccessor.SavePerson(person, currentPerson);
            }

            var response = new { PersonId = personId, SessionTimeOut = sessionTimedOut };
            return Json(response, JsonRequestBehavior.DenyGet);
        }
 private static void SendEmails(PersonViewModel person, bool sendWelcomeEmail, Church church, Person personToSave)
 {
     if (sendWelcomeEmail && person.PersonId == 0 && personToSave.HasPermission(Permissions.SendWelcomeLetter) && personToSave.HasValidEmail())
     {
         SendVisitorWelcome(sendWelcomeEmail,
             person.Firstname,
             person.Surname,
             church,
             person.Email,
             personToSave);
     }
     else if (sendWelcomeEmail && personToSave.HasValidEmail() && personToSave.HasPermission(Permissions.Login))
     {
         SendEmailAndPassword(person.Firstname,
             person.Surname,
             church,
             person.Email,
             personToSave);
     }
 }
Exemple #22
0
        public JsonResult FetchPerson(int personId)
        {
            PersonViewModel personViewModel = new PersonViewModel();
            bool sessionTimedOut = false;
            if (Session[SessionVariable.LoggedOnPerson] == null)
            {
                sessionTimedOut = true;
            }
            else
            {
                Person currentPerson = (Person)Session[SessionVariable.LoggedOnPerson];
                if (personId > 0)
                {
                    personViewModel = PersonDataAccessor.FetchPersonViewModel(personId, currentPerson);

                    if (personViewModel != null && personViewModel.FacebookId == null && personId != currentPerson.PersonId)
                    {
                        if (Session["FacebookClient"] != null)
                        {
                            FacebookClient client = (FacebookClient)Session["FacebookClient"];
                            //Search for facebook Id
                            Task.Factory.StartNew(() => SearchForFacebookId(personId, personViewModel.Firstname, personViewModel.Surname, client));
                        }
                    }
                }
            }

            var response = new
            {
                SessionTimeOut = sessionTimedOut,
                Person = personViewModel
            };
            return Json(response, JsonRequestBehavior.DenyGet);
        }
        private static void UpdateOtherRelationships(FamilyMemberViewModel familyMember, PersonViewModel person, oikonomosEntities context)
        {
            try
            {
                Relationships relationship = (Relationships)Enum.Parse(typeof(Relationships), familyMember.Relationship);
                Relationships oppositeRelationship = Relationships.Unknown;
                Person familyMemberToUpdate = (from p in context.People.Include("PersonRelationships")
                                         where p.PersonId == familyMember.PersonId
                                         select p).FirstOrDefault();

                bool isMale = (from pr in context.PersonRelationships
                               where pr.PersonRelatedToId == person.PersonId
                                    && (pr.RelationshipId == (int)Relationships.Husband ||
                                        pr.RelationshipId == (int)Relationships.Brother ||
                                        pr.RelationshipId == (int)Relationships.Father ||
                                        pr.RelationshipId == (int)Relationships.Grandfather ||
                                        pr.RelationshipId == (int)Relationships.Grandson ||
                                        pr.RelationshipId == (int)Relationships.Son)
                                    select pr).Count()>0;

                bool isFemale = (from pr in context.PersonRelationships
                                 where pr.PersonRelatedToId == person.PersonId
                                    && (pr.RelationshipId == (int)Relationships.Wife ||
                                        pr.RelationshipId == (int)Relationships.Sister ||
                                        pr.RelationshipId == (int)Relationships.Mother ||
                                        pr.RelationshipId == (int)Relationships.Grandmother ||
                                        pr.RelationshipId == (int)Relationships.Granddaughter ||
                                        pr.RelationshipId == (int)Relationships.Daughter)
                                    select pr).Count()>0;

                switch (relationship)
                {
                    case Relationships.Husband:
                        {
                            oppositeRelationship = Relationships.Wife;
                            break;
                        }
                    case Relationships.Wife:
                        {
                            oppositeRelationship = Relationships.Husband;
                            break;
                        }
                    case Relationships.Son:
                    case Relationships.Daughter:
                        {
                            if(isMale)
                            {
                            oppositeRelationship = Relationships.Father;
                            }

                            if(isFemale)
                            {
                                oppositeRelationship = Relationships.Mother;
                            }
                            break;
                        }
                    case Relationships.Brother:
                    case Relationships.Sister:
                        {
                            if(isMale)
                            {
                            oppositeRelationship = Relationships.Brother;
                            }

                            if(isFemale)
                            {
                                oppositeRelationship = Relationships.Sister;
                            }
                            break;
                        }
                    case Relationships.Father:
                    case Relationships.Mother:
                        {
                            if (isMale)
                            {
                                oppositeRelationship = Relationships.Son;
                            }

                            if (isFemale)
                            {
                                oppositeRelationship = Relationships.Daughter;
                            }
                            break;
                        }
                    case Relationships.Grandfather:
                    case Relationships.Grandmother:
                        {
                            if (isMale)
                            {
                                oppositeRelationship = Relationships.Grandson;
                            }

                            if (isFemale)
                            {
                                oppositeRelationship = Relationships.Granddaughter;
                            }
                            break;
                        }
                    case Relationships.Grandson:
                    case Relationships.Granddaughter:
                        {
                            if (isMale)
                            {
                                oppositeRelationship = Relationships.Grandfather;
                            }

                            if (isFemale)
                            {
                                oppositeRelationship = Relationships.Grandmother;
                            }
                            break;
                        }
                }

                if (oppositeRelationship != Relationships.Unknown)
                {
                    AddPersonRelationship(familyMember.PersonId, person.PersonId, (int)oppositeRelationship, familyMemberToUpdate, context);

                    var personToUpdate = FetchPerson(person.PersonId, context, null);

                    //What about the rest of the family
                    if (relationship == Relationships.Husband || relationship == Relationships.Wife)
                    {
                        var spouseRelationships = (from pr in context.PersonRelationships
                                                    where pr.PersonId == familyMember.PersonId
                                                    && (pr.RelationshipId == (int)Relationships.Son ||
                                                        pr.RelationshipId == (int)Relationships.Daughter ||
                                                        pr.RelationshipId == (int)Relationships.Grandson ||
                                                        pr.RelationshipId == (int)Relationships.Granddaughter)
                                                    select pr);

                        foreach (PersonRelationship pr in spouseRelationships)
                        {
                            if (person.PersonId != pr.PersonRelatedToId)
                            {
                                AddPersonRelationship(person.PersonId, pr.PersonRelatedToId, pr.RelationshipId, personToUpdate, context);
                            }
                        }

                    }

                    if (relationship == Relationships.Brother || relationship == Relationships.Sister)
                    {
                        //He has a brother - does the brother have a father, grandfather, mother etc
                        var siblingRelationships = (from pr in context.PersonRelationships
                                                    where pr.PersonId == familyMember.PersonId
                                                    && (pr.RelationshipId == (int)Relationships.Father ||
                                                        pr.RelationshipId == (int)Relationships.Mother ||
                                                        pr.RelationshipId == (int)Relationships.Grandfather ||
                                                        pr.RelationshipId == (int)Relationships.Grandmother ||
                                                        pr.RelationshipId == (int)Relationships.Sister ||
                                                        pr.RelationshipId == (int)Relationships.Brother)
                                                    select pr);

                        foreach (PersonRelationship pr in siblingRelationships)
                        {
                            if (person.PersonId != pr.PersonRelatedToId)
                            {
                                AddPersonRelationship(personToUpdate.PersonId, pr.PersonRelatedToId, pr.RelationshipId, personToUpdate, context);
                            }
                        }

                    }

                    //if (relationship == Relationships.Father || relationship == Relationships.Mother)
                    //{
                    //    //He has a brother - does the brother have a father, grandfather, mother etc
                    //    var siblingRelationships = (from pr in context.PersonRelationships
                    //                                where pr.PersonId == familyMember.PersonId
                    //                                && (pr.RelationshipId == (int)Relationships.Father ||
                    //                                    pr.RelationshipId == (int)Relationships.Mother ||
                    //                                    pr.RelationshipId == (int)Relationships.Grandfather ||
                    //                                    pr.RelationshipId == (int)Relationships.Grandmother ||
                    //                                    pr.RelationshipId == (int)Relationships.Sister ||
                    //                                    pr.RelationshipId == (int)Relationships.Brother)
                    //                                select pr);

                    //    foreach (PersonRelationship pr in siblingRelationships)
                    //    {
                    //        AddPersonRelationship(personToUpdate.PersonId, pr.PersonRelatedToId, pr.RelationshipId, personToUpdate, context);
                    //    }

                    //}
                }

            }
            catch { }
        }
        public static void SavePersonToSampleChurch(string firstname, string surname, string liveId, string cellPhone, string email, int roleId )
        {
            var newPerson = new PersonViewModel
            {
                Firstname = firstname,
                Surname = surname,
                WindowsLiveId = liveId,
                CellPhone = cellPhone,
                Email = email,
                RoleId = roleId
            };

            var currentPerson = FetchPerson(1);
            currentPerson.ChurchId = 6;
            SavePerson(newPerson, currentPerson);
        }
        public static PersonViewModel FetchPersonViewModel(int personId, Person currentPerson)
        {
            if (currentPerson.HasPermission(Permissions.EditChurchPersonalDetails) ||
               currentPerson.HasPermission(Permissions.EditGroupPersonalDetails) ||
               currentPerson.HasPermission(Permissions.EditOwnDetails))
            {
                using (var context = new oikonomosEntities(ConfigurationManager.ConnectionStrings["oikonomosEntities"].ConnectionString))
                {
                    try
                    {
                        CheckThatChurchIdsMatch(personId, currentPerson, context);

                        var familyId = (from p in context.People
                                        where p.PersonId == personId
                                        select p.FamilyId).FirstOrDefault();

                        var person = FetchPerson(personId, context, currentPerson);

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

                        //SetupPermissions(context, person, currentPerson.Church);
                        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,
                                          FacebookId        = person.PersonOptionalFields.FirstOrDefault(c => c.OptionalFieldId == (int)OptionalFields.Facebook) == null ? string.Empty   : person.PersonOptionalFields.First(c => c.OptionalFieldId == (int)OptionalFields.Facebook).Value,
                                          Occupation        = person.Occupation,
                                          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
                                      };

                        SetGroupId(personId, currentPerson, context, personViewModel);

                        personViewModel.FamilyMembers = FetchFamilyMembers(personId, familyId, context);
                        personViewModel.SecurityRoles = Cache.SecurityRoles(context, currentPerson);

                        return personViewModel;
                    }
                    catch (Exception ex)
                    {
                        Email.SendExceptionEmail(ex);
                        return null;
                    }
                }
            }
            throw new Exception(ExceptionMessage.InvalidCredentials);
        }
        private static bool AddPersonToGroup(PersonViewModel person, Person currentPerson, oikonomosEntities context, Person personToSave)
        {
            if (person.IsInMultipleGroups)
                return false;

            if (personToSave.PersonGroups.Count == 1 && personToSave.PersonGroups.First().GroupId != person.GroupId)
            {
                if (person.GroupId == 0)
                {
                    context.DeleteObject(personToSave.PersonGroups.First());
                    return false;
                }
                else
                {
                    personToSave.PersonGroups.First().GroupId = person.GroupId;
                    return true;
                }
            }

            if (personToSave.PersonGroups.Count == 0 && person.GroupId > 0)
            {
                SavePersonGroup(personToSave, person.GroupId);
                return true;
            }
            return false;
        }
 public bool AddPersonToGroup(PersonViewModel person, Person currentPerson, Person personToSave)
 {
     return AddPersonToGroup(person.GroupId, currentPerson, personToSave);
 }
        private static void EmailGroupLeader(PersonViewModel person, Person currentPerson, oikonomosEntities context, Church church, Person personToSave, bool addedToNewGroup)
        {
            if (personToSave.HasPermission(Permissions.NotifyGroupLeaderOfVisit) && person.GroupId > 0)
            {
                bool sendEmailToGroupLeader = person.PersonId == 0;
                var personGroup = (from pg in context.PersonGroups
                                   where pg.PersonId == personToSave.PersonId
                                   select pg).FirstOrDefault();

                if (personGroup == null)
                    return;
                else if (addedToNewGroup)
                    sendEmailToGroupLeader = true;

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

                if (sendEmailToGroupLeader)
                {
                    //Send email to the home group leader
                    var group = (from g in context.Groups
                                 where g.GroupId == person.GroupId
                                 select g).FirstOrDefault();

                    if (group != null)
                    {
                        if (group.Leader != null && group.Leader.HasValidEmail() && group.LeaderId != currentPerson.PersonId)
                        {
                            Email.SendNewVisitorEmail(person, church, group.Leader.Firstname, group.Leader.Family.FamilyName, group.Leader.Email);
                        }
                        else if (group.Administrator != null && group.Administrator.HasValidEmail() && group.LeaderId != currentPerson.PersonId)
                        {
                            Email.SendNewVisitorEmail(person, church, group.Administrator.Firstname, group.Administrator.Family.FamilyName, group.Administrator.Email);
                        }
                    }
                }
            }
        }
        private void CreatePersonItem(PersonViewModel person, ICollection<Item> items, Group group )
        {
            var backgroundImage = "images/unknown.jpg";
            if (!string.IsNullOrEmpty(person.FacebookId))
            {
                backgroundImage = string.Format("https://graph.facebook.com/{0}/picture", person.FacebookId);
            }

            CreatePersonItem(person, items, group, backgroundImage);
        }
        private static void GetPersonToSaveEntity(PersonViewModel person, Person currentPerson, oikonomosEntities context, out bool sendWelcomeEmail, out Church church, out Person personToSave)
        {
            sendWelcomeEmail = false;

            //We need some settings from the Church table
            church = (from c in context.Churches
                      where c.ChurchId == currentPerson.ChurchId
                      select c).FirstOrDefault();

            personToSave = new Person();
            if (person.PersonId != 0)
            {
                personToSave = FetchPerson(person.PersonId, context, currentPerson);
            }
            else
            {
                context.AddToPeople(personToSave);
                personToSave.ChurchId = church.ChurchId;
                personToSave.Church = church;

                personToSave.Created = DateTime.Now;
                if (church.SendWelcome)
                {
                    sendWelcomeEmail = true;
                }

                if (person.GroupId > 0)
                {
                    var pg = new PersonGroup
                                 {
                                     GroupId = person.GroupId,
                                     Person  = personToSave,
                                     Joined  = DateTime.Now,
                                     Created = DateTime.Now,
                                     Changed = DateTime.Now
                                 };
                    personToSave.PersonGroups.Add(pg);
                }
            }

            if (person.FamilyId == 0)
            {
                if (person.FindFamily)
                {
                    var family = (from f in context.Families
                                  join p in context.People
                                      on f.FamilyId equals p.FamilyId
                                  join g in context.PersonGroups
                                      on p.PersonId equals g.PersonId
                                  where f.FamilyName == person.Surname
                                      && g.GroupId == person.GroupId
                                  select f).FirstOrDefault();
                    if (family == null)
                    {
                        personToSave.Family = new Family();
                        personToSave.Family.Created = DateTime.Now;
                    }
                    else
                    {
                        personToSave.Family = family;
                    }
                }
                else
                {
                    personToSave.Family = new Family();
                    personToSave.Family.Created = DateTime.Now;
                }
            }
            else
            {
                personToSave.Family = (from f in context.Families
                                       where f.FamilyId == person.FamilyId
                                       select f).FirstOrDefault();

                if (personToSave.Family == null)
                {
                    personToSave.Family = new Family();
                    personToSave.Family.Created = DateTime.Now;
                }
            }

            personToSave.Firstname = person.Firstname;
            personToSave.Family.FamilyName = person.Surname;
            personToSave.Email = person.Email;
            personToSave.DateOfBirth = person.DateOfBirth_Value;
        }