Beispiel #1
0
        /// <summary>
        /// Prefills the visible fields with info from the specified rock person
        /// if there is a logged in user than the name fields will be disabled.
        /// </summary>
        /// <param name="rockUserId">The rock user identifier.</param>
        protected void Prefill(Person person)
        {
            if (person == null)
            {
                return;
            }

            if (tbFirstName.Visible == true)
            {
                tbFirstName.Text    = person.FirstName;
                tbFirstName.Enabled = CurrentPerson == null;

                tbLastName.Text    = person.LastName;
                tbLastName.Enabled = CurrentPerson == null;
            }

            if (tbMobilePhone.Visible)
            {
                PhoneNumberService phoneNumberService = new PhoneNumberService(new RockContext());
                int         mobilePhoneTypeId         = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE).Id;
                PhoneNumber phoneNumber = phoneNumberService.Queryable().Where(p => p.PersonId == person.Id && p.NumberTypeValueId == mobilePhoneTypeId).FirstOrDefault();
                tbMobilePhone.Text = phoneNumber == null? string.Empty : phoneNumber.Number;
            }

            if (tbEmail.Visible == true)
            {
                tbEmail.Text = person.Email;
            }
        }
Beispiel #2
0
        public void ShouldJustDashedReturnPhoneNumber()
        {
            var service = new PhoneNumberService(new DataManager(), new RandomNumberGenerator());
            var actual  = service.GetDashedUSPhoneNumber();

            actual.Length.ShouldBe(12);
        }
        /// <summary>
        /// Searches the with details.
        /// </summary>
        /// <param name="reversed">if set to <c>true</c> [reversed].</param>
        /// <param name="sortedPersonQry">The sorted person qry.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        private List <PersonSearchResult> SearchWithDetails(IQueryable <Person> sortedPersonQry, bool showFullNameReversed)
        {
            var  rockContext      = this.Service.Context as Rock.Data.RockContext;
            var  phoneNumbersQry  = new PhoneNumberService(rockContext).Queryable();
            var  sortedPersonList = sortedPersonQry.Include(a => a.PhoneNumbers).AsNoTracking().ToList();
            Guid activeRecord     = new Guid(SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE);

            List <PersonSearchResult> searchResult = new List <PersonSearchResult>();

            foreach (var person in sortedPersonList)
            {
                PersonSearchResult personSearchResult = new PersonSearchResult();
                personSearchResult.Id   = person.Id;
                personSearchResult.Name = showFullNameReversed ? person.FullNameReversed : person.FullName;
                if (person.RecordStatusValueId.HasValue)
                {
                    var recordStatus = DefinedValueCache.Read(person.RecordStatusValueId.Value);
                    personSearchResult.RecordStatus = recordStatus.Value;
                    personSearchResult.IsActive     = recordStatus.Guid.Equals(activeRecord);
                }
                else
                {
                    personSearchResult.RecordStatus = string.Empty;
                    personSearchResult.IsActive     = false;
                }

                GetPersonSearchDetails(personSearchResult, person);

                searchResult.Add(personSearchResult);
            }

            return(searchResult);
        }
Beispiel #4
0
        /// <summary>
        /// Gets first person associated with a specific phone number. If there is more
        /// than one person, the oldest adult will be returned first. If no adults, the
        /// oldest child.
        /// </summary>
        /// <param name="fromPhone">From phone.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        private static Person GetPerson(string fromPhone, RockContext rockContext)
        {
            Person fromPerson = null;

            var personService      = new PersonService(rockContext);
            var phoneNumberService = new PhoneNumberService(rockContext);

            var phoneNumber = fromPhone.Replace("+", "");

            // Get the person ids for people who's Mobile number matches the received From number
            var mobilePhoneType        = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE);
            var peopleWithMobileNumber = phoneNumberService
                                         .Queryable().AsNoTracking()
                                         .Where(n => (n.CountryCode ?? "") + (n.Number ?? "") == phoneNumber)
                                         .Select(n => new
            {
                n.PersonId,
                n.NumberTypeValueId
            })
                                         // Query the database using only the number, to ensure index is used and only returns minimal data
                                         .ToList()
                                         // then filter by type in memory
                                         .Where(v => v.NumberTypeValueId == mobilePhoneType.Id)
                                         .Select(v => v.PersonId)
                                         .ToList();

            // If there were any people found, find the first person (adults before children, and then by age)
            if (peopleWithMobileNumber.Any())
            {
                fromPerson = personService.Queryable()
                             .Where(p => peopleWithMobileNumber.Contains(p.Id))
                             .OrderBy(p => p.AgeClassification)
                             .ThenBy(p => p.BirthDate ?? DateTime.MinValue)
                             .FirstOrDefault();
            }

            // If we have a person, return it
            if (fromPerson != null)
            {
                return(fromPerson);
            }

            // Otherwise, See if a person matches by any other type of phone (other than mobile)
            var peopleWithAnyNumber = phoneNumberService
                                      .Queryable().AsNoTracking()
                                      .Where(n => (n.CountryCode ?? "") + (n.Number ?? "") == phoneNumber)
                                      .Select(n => n.PersonId)
                                      .ToList();

            if (peopleWithAnyNumber.Any())
            {
                fromPerson = personService.Queryable()
                             .Where(p => peopleWithAnyNumber.Contains(p.Id))
                             .OrderBy(p => p.AgeClassification)
                             .ThenBy(p => p.BirthDate ?? DateTime.MinValue)
                             .FirstOrDefault();
            }

            return(fromPerson);
        }
Beispiel #5
0
 static ServiceLocator()
 {
     AddressService        = new AddressService();
     BoatService           = new BoatService();
     ClubService           = new ClubService();
     UserService           = new UserService();
     EntryService          = new EntryService();
     RaceEventService      = new RaceEventService();
     RegattaService        = new RegattaService();
     SocialEventService    = new SocialEventService();
     TeamService           = new TeamService();
     EmailService          = new EmailService();
     PhoneNumberService    = new PhoneNumberService();
     RegisteredUserService = new RegisteredUserService();
     ResultService         = new ResultService();
     UserRoleService       = new UserRoleService();
     ClubsUsersUserRolesJunctionsService    = new Clubs_Users_UserRoles_JunctionsService();
     RegattasUsersUserRolesJunctionsService = new Regattas_Users_UserRoles_JunctionsService();
     RegisteredUserSocialEventService       = new RegisteredUser_SocialEventService();
     TeamRaceEventService      = new Team_RaceEventService();
     TeamRegisteredUserService = new Team_RegisteredUserService();
     BoatService = new BoatService();
     SocialEventsUsersUserRolesJunctionsService = new SocialEvents_Users_UserRoles_JunctionsService();
     RaceEventsUsersUserRolesJunctionsService   = new RaceEvents_Users_UserRoles_JunctionsService();
     ClubsEmailsService       = new ClubsEmailsService();
     ClubsPhoneNumbersService = new ClubsPhoneNumbersService();
 }
Beispiel #6
0
        private string ValidateMobilePhoneNumber(string number)
        {
            var                person             = GetPerson();
            RockContext        rockContext        = new RockContext();
            PhoneNumberService phoneNumberService = new PhoneNumberService(rockContext);

            var otherOwners = phoneNumberService.Queryable()
                              .Where(pn => pn.Number == number)
                              .Select(pn => pn.Person)
                              .Where(p => p.Id != person.Id)
                              .ToList();

            if (otherOwners.Any())
            {
                var notice = string.Format(
                    "The phone number {0} is on the following records." +
                    "<ul>{1}</ul>" +
                    "Mobile phone numbers should exist on one record only. Please ensure that {0} belongs to {2} and remove this number from all other users.",
                    PhoneNumber.FormattedNumber(PhoneNumber.DefaultCountryCode(), number),
                    string.Join("", otherOwners.Select(p => "<li><a href='/Person/" + p.Id.ToString() + "' target='_blank'>" + p.FullName + "</a></li>")),
                    person.FullName
                    );
                return(notice);
            }
            return(string.Empty);
        }
        protected void btnVerify_Click(object sender, EventArgs e)
        {
            var phoneNumber = pbPhoneNumberLookup.Number;

            using (var rockContext = new RockContext())
            {
                if (!IsVerificationCodeValid(rockContext, phoneNumber))
                {
                    ShowWarningMessage("The verification code information entered is either incorrect or expired.");
                    return;
                }

                var phoneNumberService = new PhoneNumberService(rockContext);
                var personIds          = phoneNumberService.GetPersonIdsByNumber(phoneNumber).ToList();

                if (personIds.Count == 0)
                {
                    ShowPersonNotFound();
                    return;
                }

                if (personIds.Count == 1)
                {
                    AuthenticatePerson(personIds[0]);
                    return;
                }

                if (personIds.Count > 1)
                {
                    ShowPersonChooser(personIds);
                    return;
                }
            }
        }
Beispiel #8
0
        /// <summary>
        /// Prefills the visible fields with info from the specified rock person
        /// if there is a logged in user than the name fields will be disabled.
        /// </summary>
        /// <param name="rockUserId">The rock user identifier.</param>
        protected void Prefill(Person person)
        {
            if (person == null)
            {
                return;
            }

            if (tbFirstName.Visible == true)
            {
                tbFirstName.Text    = person.FirstName;
                tbFirstName.Enabled = CurrentPerson == null;

                tbLastName.Text    = person.LastName;
                tbLastName.Enabled = CurrentPerson == null;
            }

            if (tbMobilePhone.Visible)
            {
                PhoneNumberService phoneNumberService = new PhoneNumberService(new RockContext());
                PhoneNumber        phoneNumber        = phoneNumberService.GetNumberByPersonIdAndType(person.Id, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE);
                tbMobilePhone.Text = phoneNumber == null? string.Empty : phoneNumber.Number;
            }

            if (tbEmail.Visible == true)
            {
                tbEmail.Text = person.Email;
            }
        }
        /// <summary>
        /// Handles the SaveClick event of the mdLinkConversation control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void mdLinkToPerson_SaveClick(object sender, EventArgs e)
        {
            using (var rockContext = new RockContext())
            {
                var personAliasService = new PersonAliasService(rockContext);
                var personService      = new PersonService(rockContext);

                // Get the Person Record from the selected conversation. (It should be a 'NamelessPerson' record type)
                int    namelessPersonAliasId = hfSelectedRecipientPersonAliasId.Value.AsInteger();
                var    phoneNumberService    = new PhoneNumberService(rockContext);
                Person namelessPerson        = personAliasService.GetPerson(namelessPersonAliasId);

                if (namelessPerson == null)
                {
                    // shouldn't happen, but just in case
                    return;
                }

                EntitySet mergeRequest = null;
                if (pnlLinkToExistingPerson.Visible)
                {
                    var existingPersonId = ppPerson.PersonId;
                    if (!existingPersonId.HasValue)
                    {
                        return;
                    }

                    var existingPerson = personService.Get(existingPersonId.Value);
                    mergeRequest = namelessPerson.CreateMergeRequest(existingPerson);
                    var entitySetService = new EntitySetService(rockContext);
                    entitySetService.Add(mergeRequest);

                    rockContext.SaveChanges();
                    hfSelectedRecipientPersonAliasId.Value = existingPerson.PrimaryAliasId.ToString();
                }
                else
                {
                    // new Person and new family
                    var newPerson = new Person();

                    newPersonEditor.UpdatePerson(newPerson, rockContext);

                    personService.Add(newPerson);
                    rockContext.SaveChanges();

                    mergeRequest = namelessPerson.CreateMergeRequest(newPerson);
                    var entitySetService = new EntitySetService(rockContext);
                    entitySetService.Add(mergeRequest);
                    rockContext.SaveChanges();

                    hfSelectedRecipientPersonAliasId.Value = newPerson.PrimaryAliasId.ToString();
                }

                RedirectToMergeRequest(mergeRequest);
            }

            mdLinkToPerson.Hide();
            LoadResponseListing();
        }
Beispiel #10
0
        public void ShouldReturnAreaCode()
        {
            _moqDatamanager.Setup(x => x.GetData(DataType.AreaCode)).Returns("222");
            var service  = new PhoneNumberService(_moqDatamanager.Object, _mockRandomNumberGenerator.Object);
            var areaCode = service.GetAreaCode();

            areaCode.ShouldBe("222");
        }
Beispiel #11
0
 public TimeSlotsController(
     TimeSlotService service,
     AppointmentService appointmentService,
     PhoneNumberService phoneNumberService
     ) : base(service)
 {
     this.appointmentService = appointmentService;
     this.phoneNumberService = phoneNumberService;
 }
Beispiel #12
0
 public JobsController(JobService service,
                       AppointmentService appointmentService,
                       PhoneNumberService phoneNumberService,
                       IConfiguration configuration) : base(service)
 {
     this.appointmentService = appointmentService;
     this.phoneNumberService = phoneNumberService;
     this.configuration      = configuration;
 }
Beispiel #13
0
        /// <summary>
        /// Returns a list of matching people
        /// </summary>
        /// <param name="searchterm"></param>
        /// <returns></returns>
        public override IQueryable <string> Search(string searchterm)
        {
            var phoneNumberService = new PhoneNumberService();

            return(phoneNumberService.Queryable().
                   Where(n => n.Number.Contains(searchterm)).
                   OrderBy(n => n.Number).
                   Select(n => n.Number).Distinct());
        }
        public List <OfficeDTO> GetAllOfficePhoneNumber()
        {
            IList <Office>   offices    = _uoW.OfficeRepository.GetAll();
            List <OfficeDTO> dtoResults = _officeMapper.Map(offices);
            var phoneNumberService      = new PhoneNumberService(_domainEventPublisher, _uoW);

            dtoResults.Select(o => o.PhoneNumber = _officeMapper.Map(phoneNumberService.GetOfficeFullNumber(o.Id)));

            return(dtoResults);
        }
Beispiel #15
0
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            var service = new PhoneNumberService();

            foreach (dynamic item in service.Queryable()
                     .Where(n => n.PersonId == Person.Id)
                     .OrderBy(n => n.NumberTypeValue.Order)
                     .Select(n => new
            {
                Number = n.Number,
                Unlisted = n.IsUnlisted,
                Type = n.NumberTypeValue.Name
            }
                             ))
            {
                var li = new HtmlGenericControl("li");
                ulPhoneNumbers.Controls.Add(li);

                var anchor = new HtmlGenericControl("a");
                li.Controls.Add(anchor);
                anchor.Attributes.Add("href", "#");
                anchor.AddCssClass("highlight");

                var icon = new HtmlGenericControl("i");
                anchor.Controls.Add(icon);
                icon.AddCssClass("fa fa-phone");

                if (item.Unlisted)
                {
                    var span = new HtmlGenericControl("span");
                    anchor.Controls.Add(span);
                    span.AddCssClass("phone-unlisted");
                    span.Attributes.Add("data-value", PhoneNumber.FormattedNumber(item.Number));
                    span.InnerText = "Unlisted";
                }
                else
                {
                    anchor.Controls.Add(new LiteralControl(PhoneNumber.FormattedNumber(item.Number)));
                }

                anchor.Controls.Add(new LiteralControl(" "));

                var small = new HtmlGenericControl("small");
                anchor.Controls.Add(small);
                small.InnerText = item.Type;
            }

            if (!String.IsNullOrWhiteSpace(Person.Email))
            {
                hlEmail.Text        = Person.Email;
                hlEmail.NavigateUrl = "mailto:" + Person.Email;
            }
        }
Beispiel #16
0
        public void ShouldReturnUSPhoneNumberPaddedWithZeros()
        {
            _moqDatamanager.Setup(x => x.GetData(DataType.AreaCode)).Returns("123");
            _mockRandomNumberGenerator.Setup(x => x.GetRandomIntegerBetween(100, 999)).Returns(123);
            _mockRandomNumberGenerator.Setup(x => x.GetRandomIntegerBetween(0, 9999)).Returns(1);
            var          service  = new PhoneNumberService(_moqDatamanager.Object, _mockRandomNumberGenerator.Object);
            const string expected = "123-123-0001";
            var          actual   = service.GetDashedUSPhoneNumber();

            actual.ShouldMatch(expected);
        }
Beispiel #17
0
        public void FindAllPhoneNumbers()
        {
            PhoneNumberService pns = new PhoneNumberService();

            Assert.AreEqual(0, pns.FindAllPhoneNumbers(Pieces.Pawn.Piece).AllPaths.Count); //pawns can't reverse direction
            Assert.AreEqual(2341, pns.FindAllPhoneNumbers(Pieces.Bishop.Piece).AllPaths.Count);
            Assert.AreEqual(952, pns.FindAllPhoneNumbers(Pieces.Knight.Piece).AllPaths.Count);
            Assert.AreEqual(49326, pns.FindAllPhoneNumbers(Pieces.Rook.Piece).AllPaths.Count);
            Assert.AreEqual(124908, pns.FindAllPhoneNumbers(Pieces.King.Piece).AllPaths.Count);
            Assert.AreEqual(751503, pns.FindAllPhoneNumbers(Pieces.Queen.Piece).AllPaths.Count);
        }
Beispiel #18
0
        public void ShouldReturnA10DigitPhoneNumber()
        {
            _moqDatamanager.Setup(x => x.GetData(DataType.AreaCode)).Returns("206");
            _mockRandomNumberGenerator.Setup(x => x.GetRandomIntegerBetween(100, 999)).Returns(222);
            _mockRandomNumberGenerator.Setup(x => x.GetRandomIntegerBetween(0, 9999)).Returns(2);
            var          service  = new PhoneNumberService(_moqDatamanager.Object, _mockRandomNumberGenerator.Object);
            const string expected = "2062220002";
            var          actual   = service.GetTenDigitPhoneNumber();

            actual.ShouldMatch(expected);
        }
Beispiel #19
0
        /// <inheritdoc/>
        public override IOrderedQueryable <object> SearchQuery(string searchTerm)
        {
            var rockContext        = new RockContext();
            var phoneNumberService = new PhoneNumberService(rockContext);
            var personService      = new PersonService(rockContext);

            var personIdQry = phoneNumberService.GetPersonIdsByNumber(searchTerm);

            return(personService.Queryable()
                   .Where(p => personIdQry.Contains(p.Id))
                   .OrderBy(p => p.NickName)
                   .ThenBy(p => p.LastName));
        }
Beispiel #20
0
        public LeadRepo(int numberToCreate)
        {
            var randomeIzor  = new RandomNumberGenerator();
            var dataManager  = new DataManager();
            var nameService  = new FirstLastNameService(dataManager, randomeIzor);
            var phoneService = new PhoneNumberService(dataManager, randomeIzor);

            //var sha = SHA1.Create();
            for (var i = 0; i < numberToCreate; i++)
            {
                var lead = new Lead(nameService.GetFirstName(), nameService.GetLastName(), phoneService.GetTenDigitPhoneNumber());
                _data.Add(lead.hash, lead);
            }
        }
Beispiel #21
0
        public void BindGrid()
        {
            RockContext rockContext        = new RockContext();
            var         phoneNumberService = new PhoneNumberService(rockContext);

            var numbers = tbNumbers.Text.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            var people  = phoneNumberService.Queryable().Where(ph => numbers.Contains(ph.Number) && ph.NumberTypeValueId == 12)
                          .Select(pn => pn.Person)
                          .DistinctBy(p => p.Id)
                          .ToList();

            gGrid.DataSource    = people;
            gGrid.PersonIdField = "Id";
            gGrid.DataBind();
        }
        /// <summary>
        /// Creates a Linq Expression that can be applied to an IQueryable to filter the result set.
        /// </summary>
        /// <param name="entityType">The type of entity in the result set.</param>
        /// <param name="serviceInstance">A service instance that can be queried to obtain the result set.</param>
        /// <param name="parameterExpression">The input parameter that will be injected into the filter expression.</param>
        /// <param name="selection">A formatted string representing the filter settings.</param>
        /// <returns>
        /// A Linq Expression that can be used to filter an IQueryable.
        /// </returns>
        public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection)
        {
            var qry = new PersonService(( RockContext )serviceInstance.Context).Queryable();
            var qryDuplicatePhoneNumbers = new PhoneNumberService(( RockContext )serviceInstance.Context)
                                           .Queryable()
                                           .AsNoTracking()
                                           .Where(p => p.Number != null && p.Number != string.Empty)
                                           .GroupBy(p => p.Number)
                                           .Where(g => g.Count() > 1)
                                           .Select(g => g.Key);

            qry = qry.Where(p => p.PhoneNumbers.Any(phone => qryDuplicatePhoneNumbers.Contains(phone.Number)));

            return(FilterExpressionExtractor.Extract <Rock.Model.Person>(qry, parameterExpression, "p"));
        }
Beispiel #23
0
        /// <summary>
        /// Finds the owner of the phone number dependant on only one being returned
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <param name="rockContext"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public Person GetNumberOwner(string phoneNumber, RockContext rockContext, out string error)
        {
            error = string.Empty;
            PhoneNumberService phoneNumberService = new PhoneNumberService(rockContext);
            var numberOwners = phoneNumberService.Queryable()
                               .Where(pn => pn.Number == phoneNumber)
                               .Select(pn => pn.Person)
                               .DistinctBy(p => p.Id)
                               .ToList();

            if (numberOwners.Count == 0 || numberOwners.Count > 1)
            {
                error = "There was an issue with your request";
                return(null);
            }

            var person = numberOwners.FirstOrDefault();

            if (person.IsDeceased)
            {
                error = "There was an issue with your request";
                return(null);
            }

            var minimumAge = GetAttributeValue("MinimumAge").AsInteger();

            if (minimumAge != 0)
            {
                if (person.Age == null)
                {
                    error = string.Format("We could not determine your age. You must be at least {0} years old to log in.", minimumAge);
                    return(null);
                }
                if (person.Age.Value < minimumAge)
                {
                    error = string.Format("You must be at least {0} years old to log in.", minimumAge);
                    return(null);
                }
            }

            return(person);
        }
Beispiel #24
0
 public Manage(
     SignInManager <ApplicationUser> signInManager, IStringLocalizer <Manage> localizer,
     Axuno.Tools.DateAndTime.TimeZoneConverter timeZoneConverter,
     Axuno.BackgroundTask.IBackgroundQueue queue,
     UserEmailTask userEmailTask,
     MetaDataHelper metaData, SiteContext siteContext,
     RegionInfo regionInfo, PhoneNumberService phoneNumberService,
     ILogger <Manage> logger)
 {
     _userManager        = signInManager.UserManager;
     _signInManager      = signInManager;
     _localizer          = localizer;
     _timeZoneConverter  = timeZoneConverter;
     _queue              = queue;
     _userEmailTask1     = userEmailTask;
     _userEmailTask2     = userEmailTask.CreateNew();
     _metaData           = metaData;
     _siteContext        = siteContext;
     _phoneNumberService = phoneNumberService;
     _regionInfo         = regionInfo;
     _logger             = logger;
 }
Beispiel #25
0
        /// <summary>
        /// Returns a list of people who belong to a family that matches the given number
        /// </summary>
        /// <param name="numericPhone"></param>
        /// <returns></returns>
        private IQueryable <int> PhoneSearch(string numericPhone)
        {
            var rockContext = new RockContext();

            var personService = new PersonService(rockContext);
            var memberService = new GroupMemberService(rockContext);
            var groupService  = new GroupService(rockContext);

            int personRecordTypeId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
            int familyGroupTypeId  = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()).Id;
            var dvInactive         = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE.AsGuid());

            IQueryable <int> personIds = null;

            var phoneQry = new PhoneNumberService(rockContext).Queryable().AsNoTracking();

            phoneQry = phoneQry.Where(o => o.Number.Contains(numericPhone));

            // Similar query used by the FindFamilies check-in workflow action
            var tmpQry = phoneQry
                         .Join(
                personService.Queryable().AsNoTracking(),
                o => new { PersonId = o.PersonId, IsDeceased = false, RecordTypeValueId = personRecordTypeId },
                p => new { PersonId = p.Id, IsDeceased = p.IsDeceased, RecordTypeValueId = p.RecordTypeValueId.Value },
                (pn, p) => new { Person = p, PhoneNumber = pn })
                         .Join(
                memberService.Queryable().AsNoTracking(),
                pn => pn.Person.Id,
                m => m.PersonId,
                (o, m) => new { PersonNumber = o.PhoneNumber, GroupMember = m });

            personIds = groupService.Queryable()
                        .Where(g => tmpQry.Any(o => o.GroupMember.GroupId == g.Id) && g.GroupTypeId == familyGroupTypeId)
                        .SelectMany(g => g.Members.Where(m => m.GroupMemberStatus == GroupMemberStatus.Active))
                        .Select(p => p.PersonId)
                        .Distinct();

            return(personIds);
        }
Beispiel #26
0
 public Manage(
     SignInManager <ApplicationUser> signInManager, IStringLocalizer <Manage> localizer,
     Axuno.Tools.DateAndTime.TimeZoneConverter timeZoneConverter,
     Axuno.BackgroundTask.IBackgroundQueue queue,
     SendEmailTask sendEmailTask,
     IOptions <DataProtectionTokenProviderOptions> dataProtectionTokenProviderOptions,
     MetaDataHelper metaData, ITenantContext tenantContext,
     RegionInfo regionInfo, PhoneNumberService phoneNumberService,
     ILogger <Manage> logger)
 {
     _userManager       = signInManager.UserManager;
     _signInManager     = signInManager;
     _localizer         = localizer;
     _timeZoneConverter = timeZoneConverter;
     _queue             = queue;
     _sendEmailTask     = sendEmailTask;
     _dataProtectionTokenProviderOptions = dataProtectionTokenProviderOptions;
     _metaData           = metaData;
     _tenantContext      = tenantContext;
     _phoneNumberService = phoneNumberService;
     _regionInfo         = regionInfo;
     _logger             = logger;
 }
Beispiel #27
0
        /// <summary>
        /// Binds the person details if they're logged in.
        /// </summary>
        protected void BindPersonDetails()
        {
            var groupLocationService = new GroupLocationService();
            var groupMemberService   = new GroupMemberService();
            var phoneNumberService   = new PhoneNumberService();
            var person = FindPerson();


            var personGroups     = groupMemberService.Queryable().Where(gm => gm.PersonId == person.Id).Select(gm => gm.GroupId).ToList();
            var homePhoneType    = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME);
            var homeLocationType = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.LOCATION_TYPE_HOME);

            Location personLocation = groupLocationService.Queryable().Where(g => personGroups.Contains(g.GroupId) &&
                                                                             g.GroupLocationTypeValueId == homeLocationType.Id)
                                      .Select(g => g.Location).FirstOrDefault();

            txtFirstName.Text = CurrentPerson.GivenName.ToString();
            txtLastName.Text  = CurrentPerson.LastName.ToString();
            txtEmail.Text     = CurrentPerson.Email.ToString();
            txtCardName.Text  = CurrentPerson.FullName;

            if (personLocation != null)
            {
                txtStreet.Text         = personLocation.Street1.ToString() ?? string.Empty;
                txtCity.Text           = personLocation.City.ToString() ?? string.Empty;
                ddlState.SelectedValue = personLocation.State.ToUpper() ?? string.Empty;
                txtZip.Text            = personLocation.Zip.ToString() ?? string.Empty;
            }

            var homePhone = phoneNumberService.Queryable().Where(n => n.PersonId == person.Id &&
                                                                 n.NumberTypeValueId == homePhoneType.Id).FirstOrDefault();

            if (homePhone != null)
            {
                txtPhone.Text = homePhone.Number;
            }
        }
Beispiel #28
0
        public CardFile()
        {
            InitializeComponent();

            InitTheme();

            ISessionFactory mysqlDb = ConfigureMySql();

            _sqlSession = mysqlDb.OpenSession();

            _patientService = new PatientService(_sqlSession);

            _patientCategoryService = new PatientCategoryService(_sqlSession);

            _phoneNumberService = new PhoneNumberService(_sqlSession);

            _firmService = new FirmService(_sqlSession);

            _photoService = new PhotoService(_sqlSession);

            _visitCategoryService = new VisitCategoryService(_sqlSession);

            _visitService = new VisitService(_sqlSession);

            _categories = _patientCategoryService.FindAll();

            _visitCategories = _visitCategoryService.FindAll();

            InitComponents();

            ArchiveCheckBox.Checked = false;

            ArchiveCheckBox_CheckedChanged(this, null);

            MultipleSort_CheckedChanged(RegistrationDateSort, null);
        }
Beispiel #29
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public override bool Execute(RockContext rockContext, Rock.Model.WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            var checkInState = GetCheckInState(entity, out errorMessages);

            if (checkInState != null && checkInState.CheckIn.SearchType != null)
            {
                var                personService      = new PersonService(rockContext);
                var                memberService      = new GroupMemberService(rockContext);
                GroupService       groupService       = new GroupService(rockContext);
                PhoneNumberService phoneNumberService = new PhoneNumberService(rockContext);

                int familyGroupTypeId = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()).Id;

                if (checkInState.CheckIn.SearchType.Guid.Equals(new Guid(Rock.SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_PHONE_NUMBER)))
                {
                    string numericPhone = checkInState.CheckIn.SearchValue.AsNumeric();

                    var personRecordTypeId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;

                    // Find the families with any member who has a phone number that contains selected value
                    var familyQry = phoneNumberService.Queryable().AsNoTracking();

                    if (checkInState.CheckInType == null || checkInState.CheckInType.PhoneSearchType == PhoneSearchType.EndsWith)
                    {
                        char[] charArray = numericPhone.ToCharArray();
                        Array.Reverse(charArray);
                        familyQry = familyQry.Where(o =>
                                                    o.NumberReversed.StartsWith(new string( charArray )));
                    }
                    else
                    {
                        familyQry = familyQry.Where(o =>
                                                    o.Number.Contains(numericPhone));
                    }
                    var tmpQry = familyQry.Join(personService.Queryable().AsNoTracking(),
                                                o => new { PersonId = o.PersonId, IsDeceased = false, RecordTypeValueId = personRecordTypeId },
                                                p => new { PersonId = p.Id, IsDeceased = p.IsDeceased, RecordTypeValueId = p.RecordTypeValueId.Value },
                                                (pn, p) => new { Person = p, PhoneNumber = pn })
                                 .Join(memberService.Queryable().AsNoTracking(),
                                       pn => pn.Person.Id,
                                       m => m.PersonId,
                                       (o, m) => new { PersonNumber = o.PhoneNumber, GroupMember = m });

                    var familyIdQry = groupService.Queryable().Where(g => tmpQry.Any(o => o.GroupMember.GroupId == g.Id) && g.GroupTypeId == familyGroupTypeId)
                                      .Select(g => g.Id)
                                      .Distinct();

                    int maxResults = checkInState.CheckInType != null ? checkInState.CheckInType.MaxSearchResults : 100;
                    if (maxResults > 0)
                    {
                        familyIdQry = familyIdQry.Take(maxResults);
                    }

                    var familyIds = familyIdQry.ToList();

                    // Load the family members
                    var familyMembers = memberService
                                        .Queryable("Group,GroupRole,Person").AsNoTracking()
                                        .Where(m => familyIds.Contains(m.GroupId))
                                        .ToList();

                    // Add each family
                    foreach (int familyId in familyIds)
                    {
                        // Get each of the members for this family
                        var thisFamilyMembers = familyMembers
                                                .Where(m =>
                                                       m.GroupId == familyId &&
                                                       m.Person.NickName != null)
                                                .ToList();

                        if (thisFamilyMembers.Any())
                        {
                            var group = thisFamilyMembers
                                        .Select(m => m.Group)
                                        .FirstOrDefault();

                            var firstNames = thisFamilyMembers
                                             .OrderBy(m => m.GroupRole.Order)
                                             .ThenBy(m => m.Person.BirthYear)
                                             .ThenBy(m => m.Person.BirthMonth)
                                             .ThenBy(m => m.Person.BirthDay)
                                             .ThenBy(m => m.Person.Gender)
                                             .Select(m => m.Person.NickName)
                                             .ToList();

                            var family = new CheckInFamily();
                            family.Group      = group.Clone(false);
                            family.Caption    = group.ToString();
                            family.SubCaption = firstNames.AsDelimited(", ");
                            checkInState.CheckIn.Families.Add(family);
                        }
                    }
                }
                else if (checkInState.CheckIn.SearchType.Guid.Equals(new Guid(Rock.SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_NAME)))
                {
                    foreach (var person in personService.GetByFullName(checkInState.CheckIn.SearchValue, false).AsNoTracking())
                    {
                        foreach (var group in person.Members.Where(m => m.Group.GroupTypeId == familyGroupTypeId).Select(m => m.Group).ToList())
                        {
                            var family = checkInState.CheckIn.Families.Where(f => f.Group.Id == group.Id).FirstOrDefault();
                            if (family == null)
                            {
                                family       = new CheckInFamily();
                                family.Group = group.Clone(false);
                                family.Group.LoadAttributes(rockContext);
                                family.Caption    = group.ToString();
                                family.SubCaption = memberService.GetFirstNames(group.Id).ToList().AsDelimited(", ");
                                checkInState.CheckIn.Families.Add(family);
                            }
                        }
                    }
                }
                else
                {
                    errorMessages.Add("Invalid Search Type");
                    return(false);
                }

                return(true);
            }

            errorMessages.Add("Invalid Check-in State");
            return(false);
        }
        /// <summary>
        /// Maps the communication data.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <returns></returns>
        private void MapCommunication(IQueryable <Row> tableData)
        {
            var lookupContext    = new RockContext();
            var personService    = new PersonService(lookupContext);
            var attributeService = new AttributeService(lookupContext);

            var numberTypeValues = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE), lookupContext).DefinedValues;

            // Look up additional Person attributes (existing)
            var personAttributes = attributeService.GetByEntityTypeId(PersonEntityTypeId).ToList();

            // Remove previously defined Excavator social attributes & categories if they exist
            var oldFacebookAttribute = personAttributes.Where(a => a.Key == "FacebookUsername").FirstOrDefault();

            if (oldFacebookAttribute != null)
            {
                Rock.Web.Cache.AttributeCache.Flush(oldFacebookAttribute.Id);
                attributeService.Delete(oldFacebookAttribute);
                lookupContext.SaveChanges(true);
            }

            var oldTwitterAttribute = personAttributes.Where(a => a.Key == "TwitterUsername").FirstOrDefault();

            if (oldTwitterAttribute != null)
            {
                Rock.Web.Cache.AttributeCache.Flush(oldTwitterAttribute.Id);
                attributeService.Delete(oldTwitterAttribute);
                lookupContext.SaveChanges(true);
            }

            int attributeEntityTypeId = EntityTypeCache.Read("Rock.Model.Attribute").Id;
            var socialMediaCategory   = new CategoryService(lookupContext).GetByEntityTypeId(attributeEntityTypeId)
                                        .Where(c => c.Name == "Social Media" &&
                                               c.EntityTypeQualifierValue == PersonEntityTypeId.ToString() &&
                                               c.IconCssClass == "fa fa-twitter")
                                        .FirstOrDefault();

            if (socialMediaCategory != null)
            {
                lookupContext.Categories.Remove(socialMediaCategory);
                lookupContext.SaveChanges(true);
            }

            // Cached Rock attributes: Facebook, Twitter, Instagram
            var twitterAttribute        = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "Twitter"));
            var facebookAttribute       = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "Facebook"));
            var instagramAttribute      = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "Instagram"));
            var secondaryEmailAttribute = AttributeCache.Read(SecondaryEmailAttributeId);

            var existingNumbers = new PhoneNumberService(lookupContext).Queryable().ToList();

            var newNumberList     = new List <PhoneNumber>();
            var updatedPersonList = new List <Person>();

            int completed  = 0;
            int totalRows  = tableData.Count();
            int percentage = (totalRows - 1) / 100 + 1;

            ReportProgress(0, string.Format("Verifying communication import ({0:N0} found, {1:N0} already exist).", totalRows, existingNumbers.Count()));

            foreach (var row in tableData)
            {
                string value        = row["Communication_Value"] as string;
                int?   individualId = row["Individual_ID"] as int?;
                int?   householdId  = row["Household_ID"] as int?;
                var    personList   = new List <int?>();

                if (individualId != null)
                {
                    int?personId = GetPersonAliasId(individualId, householdId);
                    if (personId != null)
                    {
                        personList.Add(personId);
                    }
                }
                else
                {
                    List <int?> personIds = GetFamilyByHouseholdId(householdId);
                    if (personIds.Any())
                    {
                        personList.AddRange(personIds);
                    }
                }

                if (personList.Any() && !string.IsNullOrWhiteSpace(value))
                {
                    DateTime?lastUpdated          = row["LastUpdatedDate"] as DateTime?;
                    string   communicationComment = row["Communication_Comment"] as string;
                    string   type     = row["Communication_Type"] as string;
                    bool     isListed = (bool)row["Listed"];
                    value = value.RemoveWhitespace();

                    // Communication value is a number
                    if (type.Contains("Phone") || type.Contains("Mobile"))
                    {
                        var extension        = string.Empty;
                        var countryCode      = Rock.Model.PhoneNumber.DefaultCountryCode();
                        var normalizedNumber = string.Empty;
                        var countryIndex     = value.IndexOf('+');
                        int extensionIndex   = value.LastIndexOf('x') > 0 ? value.LastIndexOf('x') : value.Length;
                        if (countryIndex >= 0)
                        {
                            countryCode      = value.Substring(countryIndex, countryIndex + 3).AsNumeric();
                            normalizedNumber = value.Substring(countryIndex + 3, extensionIndex - 3).AsNumeric();
                            extension        = value.Substring(extensionIndex);
                        }
                        else if (extensionIndex > 0)
                        {
                            normalizedNumber = value.Substring(0, extensionIndex).AsNumeric();
                            extension        = value.Substring(extensionIndex).AsNumeric();
                        }
                        else
                        {
                            normalizedNumber = value.AsNumeric();
                        }

                        if (!string.IsNullOrWhiteSpace(normalizedNumber))
                        {
                            foreach (var familyPersonId in personList)
                            {
                                bool numberExists = existingNumbers.Any(n => n.PersonId == familyPersonId && n.Number.Equals(value));
                                if (!numberExists)
                                {
                                    var newNumber = new PhoneNumber();
                                    newNumber.CreatedByPersonAliasId = ImportPersonAlias.Id;
                                    newNumber.ModifiedDateTime       = lastUpdated;
                                    newNumber.PersonId           = (int)familyPersonId;
                                    newNumber.IsMessagingEnabled = false;
                                    newNumber.CountryCode        = countryCode;
                                    newNumber.IsUnlisted         = !isListed;
                                    newNumber.Extension          = extension.Left(20);
                                    newNumber.Number             = normalizedNumber.Left(20);
                                    newNumber.Description        = communicationComment;

                                    newNumber.NumberTypeValueId = numberTypeValues.Where(v => type.StartsWith(v.Value))
                                                                  .Select(v => (int?)v.Id).FirstOrDefault();

                                    newNumberList.Add(newNumber);
                                    existingNumbers.Add(newNumber);
                                }
                            }

                            completed++;
                        }
                    }
                    else
                    {
                        var person = personService.Queryable(includeDeceased: true).FirstOrDefault(p => p.Id == personList.FirstOrDefault());
                        person.Attributes      = new Dictionary <string, AttributeCache>();
                        person.AttributeValues = new Dictionary <string, AttributeValue>();

                        if (value.IsValidEmail())
                        {
                            string secondaryEmail = string.Empty;
                            if (string.IsNullOrWhiteSpace(person.Email))
                            {
                                secondaryEmail          = person.Email;
                                person.Email            = value.Left(75);
                                person.IsEmailActive    = isListed;
                                person.ModifiedDateTime = lastUpdated;
                                person.EmailNote        = communicationComment;
                                lookupContext.SaveChanges(true);
                            }
                            else if (!person.Email.Equals(value))
                            {
                                secondaryEmail = value;
                            }

                            var existingSecondaryEmail = new AttributeValueService(lookupContext).Queryable().Where(av => av.AttributeId == SecondaryEmailAttributeId && av.EntityId == person.Id).FirstOrDefault();

                            if (!string.IsNullOrWhiteSpace(secondaryEmail) && existingSecondaryEmail == null)
                            {
                                person.Attributes.Add(secondaryEmailAttribute.Key, secondaryEmailAttribute);
                                person.AttributeValues.Add(secondaryEmailAttribute.Key, new AttributeValue()
                                {
                                    AttributeId = secondaryEmailAttribute.Id,
                                    Value       = secondaryEmail
                                });
                            }
                        }
                        else if (type.Contains("Twitter"))
                        {
                            person.Attributes.Add(twitterAttribute.Key, twitterAttribute);
                            person.AttributeValues.Add(twitterAttribute.Key, new AttributeValue()
                            {
                                AttributeId = twitterAttribute.Id,
                                Value       = value
                            });
                        }
                        else if (type.Contains("Facebook"))
                        {
                            var existingFacebook = new AttributeValueService(lookupContext).Queryable().Where(av => av.AttributeId == facebookAttribute.Id && av.EntityId == person.Id).FirstOrDefault();
                            if (existingFacebook == null)
                            {
                                person.Attributes.Add(facebookAttribute.Key, facebookAttribute);
                                person.AttributeValues.Add(facebookAttribute.Key, new AttributeValue()
                                {
                                    AttributeId = facebookAttribute.Id,
                                    Value       = value
                                });
                            }
                        }
                        else if (type.Contains("Instagram"))
                        {
                            person.Attributes.Add(instagramAttribute.Key, instagramAttribute);
                            person.AttributeValues.Add(instagramAttribute.Key, new AttributeValue()
                            {
                                AttributeId = instagramAttribute.Id,
                                Value       = value
                            });
                        }

                        updatedPersonList.Add(person);
                        completed++;
                    }

                    if (completed % percentage < 1)
                    {
                        int percentComplete = completed / percentage;
                        ReportProgress(percentComplete, string.Format("{0:N0} records imported ({1}% complete).", completed, percentComplete));
                    }
                    else if (completed % ReportingNumber < 1)
                    {
                        SaveCommunication(newNumberList, updatedPersonList);

                        // reset so context doesn't bloat
                        lookupContext = new RockContext();
                        personService = new PersonService(lookupContext);
                        updatedPersonList.Clear();
                        newNumberList.Clear();
                        ReportPartialProgress();
                    }
                }
            }

            if (newNumberList.Any() || updatedPersonList.Any())
            {
                SaveCommunication(newNumberList, updatedPersonList);
            }

            ReportProgress(100, string.Format("Finished communication import: {0:N0} records imported.", completed));
        }