/// <summary> /// Shows the details. /// </summary> private void ShowDetails() { RockContext rockContext = new RockContext(); pnlAddress.Visible = GetAttributeValue("ShowAddress").AsBoolean(); acAddress.Required = GetAttributeValue("AddressRequired").AsBoolean(); cpFamilyCampus.Required = GetAttributeValue("CampusRequired").AsBoolean(); cpFamilyCampus.Visible = cpFamilyCampus.Items.Count > 2; var person = CurrentPerson; if (person != null) { imgPhoto.BinaryFileId = person.PhotoId; imgPhoto.NoPictureUrl = Person.GetPersonNoPictureUrl(person, 200, 200); ddlTitle.SelectedValue = person.TitleValueId.HasValue ? person.TitleValueId.Value.ToString() : string.Empty; tbFirstName.Text = person.FirstName; tbNickName.Text = person.NickName; tbLastName.Text = person.LastName; ddlSuffix.SelectedValue = person.SuffixValueId.HasValue ? person.SuffixValueId.Value.ToString() : string.Empty; bpBirthDay.SelectedDate = person.BirthDate; rblGender.SelectedValue = person.Gender.ConvertToString(); tbEmail.Text = person.Email; rblEmailPreference.SelectedValue = person.EmailPreference.ConvertToString(false); var familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuidOrNull(); Group familyGroup = null; if (cpFamilyCampus.Visible && familyGroupTypeGuid.HasValue) { familyGroup = new GroupService(rockContext).Queryable() .Where(g => g.GroupType.Guid == familyGroupTypeGuid.Value && g.Members.Any(m => m.PersonId == person.Id)) .FirstOrDefault(); cpFamilyCampus.SelectedCampusId = familyGroup.CampusId; } Guid?locationTypeGuid = GetAttributeValue("LocationType").AsGuidOrNull(); if (locationTypeGuid.HasValue) { var addressTypeDv = DefinedValueCache.Get(locationTypeGuid.Value); // if address type is home enable the move and is mailing/physical if (addressTypeDv.Guid == Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid()) { lbMoved.Visible = true; cbIsMailingAddress.Visible = true; cbIsPhysicalAddress.Visible = true; } else { lbMoved.Visible = false; cbIsMailingAddress.Visible = false; cbIsPhysicalAddress.Visible = false; } lAddressTitle.Text = addressTypeDv.Value + " Address"; if (familyGroupTypeGuid.HasValue) { var familyGroupType = GroupTypeCache.Get(familyGroupTypeGuid.Value); var familyAddress = new GroupLocationService(rockContext).Queryable() .Where(l => l.Group.GroupTypeId == familyGroupType.Id && l.GroupLocationTypeValueId == addressTypeDv.Id && l.Group.Members.Any(m => m.PersonId == person.Id)) .FirstOrDefault(); if (familyAddress != null) { acAddress.SetValues(familyAddress.Location); cbIsMailingAddress.Checked = familyAddress.IsMailingLocation; cbIsPhysicalAddress.Checked = familyAddress.IsMappedLocation; } } } var mobilePhoneType = DefinedValueCache.Get(new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE)); var phoneNumbers = new List <PhoneNumber>(); var phoneNumberTypes = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE)); if (phoneNumberTypes.DefinedValues.Any()) { foreach (var phoneNumberType in phoneNumberTypes.DefinedValues) { var phoneNumber = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberType.Id); if (phoneNumber == null) { var numberType = new DefinedValue(); numberType.Id = phoneNumberType.Id; numberType.Value = phoneNumberType.Value; phoneNumber = new PhoneNumber { NumberTypeValueId = numberType.Id, NumberTypeValue = numberType }; phoneNumber.IsMessagingEnabled = mobilePhoneType != null && phoneNumberType.Id == mobilePhoneType.Id; } else { // Update number format, just in case it wasn't saved correctly phoneNumber.NumberFormatted = PhoneNumber.FormattedNumber(phoneNumber.CountryCode, phoneNumber.Number); } phoneNumbers.Add(phoneNumber); } rContactInfo.DataSource = phoneNumbers; rContactInfo.DataBind(); } } }
/// <summary> /// Shows the edit details. /// </summary> /// <param name="groupType">The groupType.</param> private void ShowEditDetails(GroupType groupType) { if (groupType != null) { if (groupType.Id == 0) { lReadOnlyTitle.Text = ActionTitle.Add("Check-in Configuration").FormatAsHtmlTitle(); } else { lReadOnlyTitle.Text = groupType.ToString().FormatAsHtmlTitle(); } SetEditMode(true); tbName.Text = groupType.Name; tbDescription.Text = groupType.Description; tbIconCssClass.Text = groupType.IconCssClass; var rockContext = new RockContext(); groupType.LoadAttributes(rockContext); cbAgeRequired.Checked = groupType.GetAttributeValue("core_checkin_AgeRequired").AsBoolean(true); cbGradeRequired.Checked = groupType.GetAttributeValue("core_checkin_GradeRequired").AsBoolean(true); cbHidePhotos.Checked = groupType.GetAttributeValue("core_checkin_HidePhotos").AsBoolean(true); cbPreventDuplicateCheckin.Checked = groupType.GetAttributeValue("core_checkin_PreventDuplicateCheckin").AsBoolean(true); cbPreventInactivePeople.Checked = groupType.GetAttributeValue("core_checkin_PreventInactivePeople").AsBoolean(true); ddlType.SetValue(groupType.GetAttributeValue("core_checkin_CheckInType")); cbDisplayLocCount.Checked = groupType.GetAttributeValue("core_checkin_DisplayLocationCount").AsBoolean(true); cbEnableManager.Checked = groupType.GetAttributeValue("core_checkin_EnableManagerOption").AsBoolean(true); cbEnableOverride.Checked = groupType.GetAttributeValue("core_checkin_EnableOverride").AsBoolean(true); nbMaxPhoneLength.Text = groupType.GetAttributeValue("core_checkin_MaximumPhoneSearchLength"); nbMaxResults.Text = groupType.GetAttributeValue("core_checkin_MaxSearchResults"); nbMinPhoneLength.Text = groupType.GetAttributeValue("core_checkin_MinimumPhoneSearchLength"); cbUseSameOptions.Checked = groupType.GetAttributeValue("core_checkin_UseSameOptions").AsBoolean(false); ddlPhoneSearchType.SetValue(groupType.GetAttributeValue("core_checkin_PhoneSearchType")); nbRefreshInterval.Text = groupType.GetAttributeValue("core_checkin_RefreshInterval"); tbSearchRegex.Text = groupType.GetAttributeValue("core_checkin_RegularExpressionFilter"); cbReuseCode.Checked = groupType.GetAttributeValue("core_checkin_ReuseSameCode").AsBoolean(false); var searchType = DefinedValueCache.Get(groupType.GetAttributeValue("core_checkin_SearchType").AsGuid()); if (searchType != null) { ddlSearchType.SetValue(searchType.Id.ToString()); } nbCodeAlphaNumericLength.Text = groupType.GetAttributeValue("core_checkin_SecurityCodeLength"); nbCodeAlphaLength.Text = groupType.GetAttributeValue("core_checkin_SecurityCodeAlphaLength"); nbCodeNumericLength.Text = groupType.GetAttributeValue("core_checkin_SecurityCodeNumericLength"); cbCodeRandom.Checked = groupType.GetAttributeValue("core_checkin_SecurityCodeNumericRandom").AsBoolean(true); cbAllowCheckout.Checked = groupType.GetAttributeValue("core_checkin_AllowCheckout").AsBoolean(true); cbEnablePresence.Checked = groupType.GetAttributeValue("core_checkin_EnablePresence").AsBoolean(); nbAutoSelectDaysBack.Text = groupType.GetAttributeValue("core_checkin_AutoSelectDaysBack"); ddlAutoSelectOptions.SetValue(groupType.GetAttributeValue("core_checkin_AutoSelectOptions")); // Registration Settings cbRegistrationDisplayAlternateIdFieldForAdults.Checked = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DISPLAYALTERNATEIDFIELDFORADULTS).AsBoolean(); cbRegistrationDisplayAlternateIdFieldForChildren.Checked = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DISPLAYALTERNATEIDFIELDFORCHILDREN).AsBoolean(); cbRegistrationDisplaySmsEnabled.Checked = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DISPLAYSMSBUTTON).AsBoolean(); cbRegistrationSmsEnabledByDefault.Checked = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DEFAULTSMSENABLED).AsBoolean(); lbRegistrationRequiredAttributesForAdults.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_REQUIREDATTRIBUTESFORADULTS).SplitDelimitedValues()); lbRegistrationOptionalAttributesForAdults.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_OPTIONALATTRIBUTESFORADULTS).SplitDelimitedValues()); lbRegistrationRequiredAttributesForChildren.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_REQUIREDATTRIBUTESFORCHILDREN).SplitDelimitedValues()); lbRegistrationOptionalAttributesForChildren.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_OPTIONALATTRIBUTESFORCHILDREN).SplitDelimitedValues()); lbRegistrationRequiredAttributesForFamilies.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_REQUIREDATTRIBUTESFORFAMILIES).SplitDelimitedValues()); lbRegistrationOptionalAttributesForFamilies.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_OPTIONALATTRIBUTESFORFAMILIES).SplitDelimitedValues()); int? defaultPersonConnectionStatusValueId = null; Guid?defaultPersonConnectionStatusValueGuid = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DEFAULTPERSONCONNECTIONSTATUS).AsGuidOrNull(); if (defaultPersonConnectionStatusValueGuid.HasValue) { var defaultPersonRecordStatusValue = DefinedValueCache.Get(defaultPersonConnectionStatusValueGuid.Value); if (defaultPersonRecordStatusValue != null) { defaultPersonConnectionStatusValueId = defaultPersonRecordStatusValue.Id; } } dvpRegistrationDefaultPersonConnectionStatus.DefinedTypeId = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS.AsGuid()).Id; dvpRegistrationDefaultPersonConnectionStatus.SetValue(defaultPersonConnectionStatusValueId); var workflowTypeService = new WorkflowTypeService(rockContext); wftpRegistrationAddFamilyWorkflowTypes.SetValues(workflowTypeService.GetByGuids(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_ADDFAMILYWORKFLOWTYPES).SplitDelimitedValues().AsGuidList())); wftpRegistrationAddPersonWorkflowTypes.SetValues(workflowTypeService.GetByGuids(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_ADDPERSONWORKFLOWTYPES).SplitDelimitedValues().AsGuidList())); cbEnableCheckInAfterRegistration.Checked = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_ENABLECHECKINAFTERREGISTRATION).AsBoolean(); lbKnownRelationshipTypes.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_KNOWNRELATIONSHIPTYPES).SplitDelimitedValues()); lbSameFamilyKnownRelationshipTypes.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_SAMEFAMILYKNOWNRELATIONSHIPTYPES).SplitDelimitedValues()); lbCanCheckInKnownRelationshipTypes.SetValues(groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_CANCHECKINKNOWNRELATIONSHIPTYPES).SplitDelimitedValues()); ceStartTemplate.Text = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_START_LAVA_TEMPLATE); ceFamilySelectTemplate.Text = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_FAMILYSELECT_LAVA_TEMPLATE); ceSuccessTemplate.Text = groupType.GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_SUCCESS_LAVA_TEMPLATE); // Other GroupType Attributes BuildAttributeEdits(groupType, true); SetFieldVisibility(); } }
private void ShowData(Guid?categoryGuid, int?entityTypeId) { if (EntityCategories == null) { LoadCategories(); } hfSelectedCategoryGuid.Value = categoryGuid.ToString(); hfSelectedEntityId.Value = null; // Bind Categories rptCategory.DataSource = EntityCategories; rptCategory.DataBind(); pnlModels.Visible = false; pnlKey.Visible = false; lCategoryName.Text = string.Empty; EntityTypeCache entityType = null; var entityTypeList = new List <EntityTypeCache>(); if (categoryGuid.HasValue) { var category = EntityCategories.Where(c => c.Guid.Equals(categoryGuid)).FirstOrDefault(); if (category != null) { lCategoryName.Text = category.Name.SplitCase() + " Models"; pnlModels.Visible = true; entityTypeList = category .RockEntityIds .Select(a => EntityTypeCache.Get(a)) .Where(a => a != null) .OrderBy(et => et.FriendlyName) .ToList(); if (entityTypeId.HasValue) { entityType = entityTypeList.Where(t => t.Id == entityTypeId.Value).FirstOrDefault(); hfSelectedEntityId.Value = entityType != null?entityType.Id.ToString() : null; } else { entityType = entityTypeList.FirstOrDefault(); hfSelectedEntityId.Value = entityTypeList.Any() ? entityTypeList.First().Id.ToString() : null; } } } // Bind Models rptModel.DataSource = entityTypeList; rptModel.DataBind(); string details = string.Empty; nbClassesWarning.Visible = false; pnlClassDetail.Visible = false; if (entityType != null) { try { var type = entityType.GetEntityType(); if (type != null) { pnlKey.Visible = true; var xmlComments = GetXmlComments(); var mClass = new MClass(); mClass.Name = type.Name; mClass.Comment = GetComments(type, xmlComments); PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(m => m.MemberType == MemberTypes.Method || m.MemberType == MemberTypes.Property) .ToArray(); foreach (PropertyInfo p in properties.OrderBy(i => i.Name).ToArray()) { #pragma warning disable CS0618 // LavaIncludeAttribute is obsolete var property = new MProperty { Name = p.Name, IsInherited = p.DeclaringType != type, IsVirtual = p.GetGetMethod() != null && p.GetGetMethod().IsVirtual&& !p.GetGetMethod().IsFinal, IsLavaInclude = p.IsDefined(typeof(LavaIncludeAttribute)) || p.IsDefined(typeof(LavaVisibleAttribute)) || p.IsDefined(typeof(DataMemberAttribute)), IsObsolete = p.IsDefined(typeof(ObsoleteAttribute)), ObsoleteMessage = GetObsoleteMessage(p), NotMapped = p.IsDefined(typeof(NotMappedAttribute)), Required = p.IsDefined(typeof(RequiredAttribute)), Id = p.MetadataToken, Comment = GetComments(p, xmlComments, properties), IsEnum = p.PropertyType.IsEnum, IsDefinedValue = p.Name.EndsWith("ValueId") && p.IsDefined(typeof(DefinedValueAttribute)) }; #pragma warning restore CS0618 // LavaIncludeAttribute is obsolete if (property.IsEnum) { property.KeyValues = new Dictionary <string, string>(); var values = p.PropertyType.GetEnumValues(); foreach (var value in values) { property.KeyValues.AddOrReplace((( int )value).ToString(), value.ToString()); } } else if (property.IsDefinedValue) { var definedValueAttribute = p.GetCustomAttribute <Rock.Data.DefinedValueAttribute>(); if (definedValueAttribute != null && definedValueAttribute.DefinedTypeGuid.HasValue) { property.KeyValues = new Dictionary <string, string>(); var definedTypeGuid = definedValueAttribute.DefinedTypeGuid.Value; var definedType = DefinedTypeCache.Get(definedTypeGuid); property.DefinedTypeId = definedType.Id; foreach (var definedValue in definedType.DefinedValues) { property.KeyValues.AddOrReplace(string.Format("{0} = {1}", definedValue.Id, definedValue.Value), definedValue.Description); } } } mClass.Properties.Add(property); } MethodInfo[] methods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance) .Where(m => !m.IsSpecialName && (m.MemberType == MemberTypes.Method || m.MemberType == MemberTypes.Property)) .ToArray(); foreach (MethodInfo m in methods.OrderBy(i => i.Name).ToArray()) { // crazy, right? var param = string.Join(", ", m.GetParameters().Select(pi => { var x = pi.ParameterType + " " + pi.Name; return(x); })); mClass.Methods.Add(new MMethod { Name = m.Name, IsInherited = m.DeclaringType != type, Id = m.MetadataToken, Signature = string.Format("{0}({1})", m.Name, param), Comment = GetComments(m, xmlComments), IsObsolete = m.IsDefined(typeof(ObsoleteAttribute)), ObsoleteMessage = GetObsoleteMessage(m) }); } var pageReference = new Rock.Web.PageReference(CurrentPageReference); pageReference.QueryString = new System.Collections.Specialized.NameValueCollection(); pageReference.QueryString["EntityType"] = entityType.Guid.ToString(); lClassName.Text = mClass.Name; hlAnchor.NavigateUrl = pageReference.BuildUrl(); lClassDescription.Text = mClass.Comment != null ? mClass.Comment.Summary : string.Empty; lClasses.Text = ClassNode(mClass); pnlClassDetail.Visible = true; } else { nbClassesWarning.Text = "Unable to get class details for " + entityType.FriendlyName; nbClassesWarning.Details = entityType.AssemblyName; nbClassesWarning.Dismissable = true; nbClassesWarning.Visible = true; } } catch (Exception ex) { nbClassesWarning.Text = string.Format("Error getting class details for <code>{0}</code>", entityType); nbClassesWarning.Details = ex.Message; nbClassesWarning.Dismissable = true; nbClassesWarning.Visible = true; } } }
/// <summary> /// Renders the base control. /// </summary> /// <param name="writer">The writer.</param> public void RenderBaseControl(HtmlTextWriter writer) { if (this.Visible) { bool showAddressLine2 = ShowAddressLine2; string cityLabel = "City"; string stateLabel = "Region"; string postalCodeLabel = "Postal Code"; var countryValue = DefinedTypeCache.Get(new Guid(SystemGuid.DefinedType.LOCATION_COUNTRIES)) .DefinedValues .Where(v => v.Value.Equals(_ddlCountry.SelectedValue, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (countryValue != null) { cityLabel = countryValue.GetAttributeValue("CityLabel"); stateLabel = countryValue.GetAttributeValue("StateLabel"); postalCodeLabel = countryValue.GetAttributeValue("PostalCodeLabel"); // only show Address Line 2 if this Control's ShowAddressLine2 and the Country's ShowAddressLine2 are both true if (showAddressLine2) { showAddressLine2 = countryValue.GetAttributeValue("ShowAddressLine2").AsBoolean(); } } // if this address has a value for Street2, show it regardless of the ShowAddressLine2 showAddressLine2 = showAddressLine2 || !string.IsNullOrWhiteSpace(_tbStreet2.Text); if (_ddlCountry.Visible) { writer.AddAttribute("class", "form-row"); writer.RenderBeginTag(HtmlTextWriterTag.Div); writer.AddAttribute("class", "form-group col-sm-6"); writer.RenderBeginTag(HtmlTextWriterTag.Div); _ddlCountry.RenderControl(writer); writer.RenderEndTag(); // div.form-group writer.AddAttribute("class", "form-group col-sm-6"); writer.RenderBeginTag(HtmlTextWriterTag.Div); writer.RenderEndTag(); // div.form-group writer.RenderEndTag(); // div.row } writer.AddAttribute("class", "js-addressControl"); writer.AddAttribute("data-required", this.Required.ToTrueFalse().ToLower()); writer.AddAttribute("data-itemlabel", this.Label != string.Empty ? this.Label : "Address"); writer.AddAttribute("id", this.ClientID); writer.RenderBeginTag(HtmlTextWriterTag.Div); writer.AddAttribute("class", "form-group " + (this.Required ? "required" : string.Empty)); writer.RenderBeginTag(HtmlTextWriterTag.Div); _tbStreet1.Attributes["placeholder"] = showAddressLine2 ? "Address Line 1" : "Address"; _tbStreet1.Attributes["autocomplete"] = showAddressLine2 ? "address-line1" : "street-address"; _tbStreet1.RenderControl(writer); writer.RenderEndTag(); // div.form-group if (showAddressLine2) { writer.AddAttribute("class", "form-group"); writer.RenderBeginTag(HtmlTextWriterTag.Div); _tbStreet2.Attributes["placeholder"] = "Address Line 2"; _tbStreet2.Attributes["autocomplete"] = "address-line2"; _tbStreet2.RenderControl(writer); writer.RenderEndTag(); // div.form-group } writer.AddAttribute("class", "form-row"); writer.RenderBeginTag(HtmlTextWriterTag.Div); writer.AddAttribute("class", (ShowCounty ? "form-group col-sm-3 " : "form-group col-sm-6 " + (this.Required ? "required" : string.Empty))); writer.RenderBeginTag(HtmlTextWriterTag.Div); _tbCity.Attributes["placeholder"] = cityLabel; _tbCity.Attributes["autocomplete"] = "address-level2"; _tbCity.RenderControl(writer); writer.RenderEndTag(); // div.form-group if (ShowCounty) { writer.AddAttribute("class", "form-group col-sm-3"); writer.RenderBeginTag(HtmlTextWriterTag.Div); _tbCounty.Attributes["placeholder"] = "County"; _tbCounty.Attributes["autocomplete"] = "country"; _tbCounty.RenderControl(writer); writer.RenderEndTag(); // div.form-group } writer.AddAttribute("class", "form-group col-sm-3 " + (this.Required ? "required" : string.Empty)); writer.RenderBeginTag(HtmlTextWriterTag.Div); _tbState.Attributes["placeholder"] = stateLabel; _tbState.Attributes["autocomplete"] = "address-level1"; _tbState.RenderControl(writer); _ddlState.RenderControl(writer); writer.RenderEndTag(); // div.form-group writer.AddAttribute("class", "form-group col-sm-3"); writer.RenderBeginTag(HtmlTextWriterTag.Div); _tbPostalCode.Attributes["placeholder"] = postalCodeLabel; _tbPostalCode.Attributes["autocomplete"] = "postal-code"; _tbPostalCode.RenderControl(writer); writer.RenderEndTag(); // div.form-group writer.RenderEndTag(); // div.form-row CustomValidator.RenderControl(writer); writer.RenderEndTag(); // div } }
/// <summary> /// Maps the communication data. /// </summary> /// <param name="tableData">The table data.</param> /// <param name="totalRows">The total rows.</param> private void MapCommunication(IQueryable <Row> tableData, long totalRows = 0) { var lookupContext = new RockContext(); var personService = new PersonService(lookupContext); var phoneTypeValues = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE), lookupContext).DefinedValues; // Look up existing Person attributes var personAttributes = new AttributeService(lookupContext).GetByEntityTypeId(PersonEntityTypeId).AsNoTracking().ToList(); // Cached Rock attributes: Facebook, Twitter, Instagram var twitterAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals("Twitter", StringComparison.InvariantCultureIgnoreCase)); var facebookAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals("Facebook", StringComparison.InvariantCultureIgnoreCase)); var instagramAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals("Instagram", StringComparison.InvariantCultureIgnoreCase)); var newNumbers = new List <PhoneNumber>(); var existingNumbers = new PhoneNumberService(lookupContext).Queryable().AsNoTracking().ToList(); var newPeopleAttributes = new Dictionary <int, Person>(); if (totalRows == 0) { totalRows = tableData.Count(); } var completed = 0; var percentage = (totalRows - 1) / 100 + 1; ReportProgress(0, $"Verifying communication import ({totalRows:N0} found, {existingNumbers.Count:N0} already exist)."); foreach (var groupedRows in tableData.OrderByDescending(r => r["LastUpdatedDate"]).GroupBy <Row, int?>(r => r["Household_ID"] as int?)) { foreach (var row in groupedRows.Where(r => r != null)) { var value = row["Communication_Value"] as string; var individualId = row["Individual_ID"] as int?; var householdId = row["Household_ID"] as int?; var peopleToUpdate = new List <PersonKeys>(); if (individualId != null) { var matchingPerson = GetPersonKeys(individualId, householdId, includeVisitors: false); if (matchingPerson != null) { peopleToUpdate.Add(matchingPerson); } } else { peopleToUpdate = GetFamilyByHouseholdId(householdId, includeVisitors: false); } if (peopleToUpdate.Any() && !string.IsNullOrWhiteSpace(value)) { var lastUpdated = row["LastUpdatedDate"] as DateTime?; var communicationComment = row["Communication_Comment"] as string; var type = row["Communication_Type"] as string; var isListed = ( bool )row["Listed"]; value = value.RemoveWhitespace(); // Communication value is a number if (type.Contains("Phone") || type.Contains("Mobile") || type.Contains("Fax")) { var extension = string.Empty; var countryCode = PhoneNumber.DefaultCountryCode(); var normalizedNumber = string.Empty; var countryIndex = value.IndexOf('+'); var 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 personKeys in peopleToUpdate) { var phoneTypeId = phoneTypeValues.Where(v => type.StartsWith(v.Value, StringComparison.CurrentCultureIgnoreCase)) .Select(v => ( int? )v.Id).FirstOrDefault(); if (!phoneTypeId.HasValue) { var newPhoneType = AddDefinedValue(lookupContext, Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE, type); if (newPhoneType != null) { phoneTypeValues.Add(newPhoneType); phoneTypeId = newPhoneType.Id; } } var numberExists = existingNumbers.Any(n => n.PersonId == personKeys.PersonId && n.Number.Equals(normalizedNumber) && n.NumberTypeValueId == phoneTypeId); if (!numberExists) { var newNumber = new PhoneNumber(); newNumber.CreatedByPersonAliasId = ImportPersonAliasId; newNumber.ModifiedDateTime = lastUpdated; newNumber.PersonId = ( int )personKeys.PersonId; newNumber.IsMessagingEnabled = type.StartsWith("Mobile", StringComparison.CurrentCultureIgnoreCase); newNumber.CountryCode = countryCode; newNumber.IsUnlisted = !isListed; newNumber.Extension = extension.Left(20) ?? string.Empty; newNumber.Number = normalizedNumber.Left(20); newNumber.Description = communicationComment; newNumber.NumberFormatted = PhoneNumber.FormattedNumber(countryCode, newNumber.Number, true); newNumber.NumberTypeValueId = phoneTypeId; newNumbers.Add(newNumber); existingNumbers.Add(newNumber); } } completed++; } } else { var personKeys = peopleToUpdate.FirstOrDefault(); var person = !newPeopleAttributes.ContainsKey(personKeys.PersonId) ? personService.Queryable(includeDeceased: true).FirstOrDefault(p => p.Id == personKeys.PersonId) : newPeopleAttributes[personKeys.PersonId]; if (person != null) { if (person.Attributes == null || person.AttributeValues == null) { // make sure we have valid objects to assign to person.Attributes = new Dictionary <string, AttributeCache>(); person.AttributeValues = new Dictionary <string, AttributeValueCache>(); } // Check for an InFellowship ID/email before checking other types of email var isLoginValue = type.IndexOf("InFellowship", StringComparison.OrdinalIgnoreCase) >= 0; var personAlreadyHasLogin = person.Attributes.ContainsKey(InFellowshipLoginAttribute.Key); if (isLoginValue && !personAlreadyHasLogin) { // add F1 authentication capability AddEntityAttributeValue(lookupContext, InFellowshipLoginAttribute, person, value); //AddUserLogin( f1AuthProviderId, person, value ); } // also add the Infellowship Email to anyone who doesn't have one if (value.IsEmail()) { // person email is empty if (string.IsNullOrWhiteSpace(person.Email)) { person.Email = value.Left(75); person.IsEmailActive = isListed; person.EmailPreference = isListed ? EmailPreference.EmailAllowed : EmailPreference.DoNotEmail; person.ModifiedDateTime = lastUpdated; person.EmailNote = communicationComment; lookupContext.SaveChanges(DisableAuditing); } // this is a different email, assign it to SecondaryEmail else if (!person.Email.Equals(value) && !person.Attributes.ContainsKey(SecondaryEmailAttribute.Key)) { AddEntityAttributeValue(lookupContext, SecondaryEmailAttribute, person, value); } } else if (type.Contains("Twitter") && !person.Attributes.ContainsKey(twitterAttribute.Key)) { AddEntityAttributeValue(lookupContext, twitterAttribute, person, value); } else if (type.Contains("Facebook") && !person.Attributes.ContainsKey(facebookAttribute.Key)) { AddEntityAttributeValue(lookupContext, facebookAttribute, person, value); } else if (type.Contains("Instagram") && !person.Attributes.ContainsKey(instagramAttribute.Key)) { AddEntityAttributeValue(lookupContext, instagramAttribute, person, value); } if (!newPeopleAttributes.ContainsKey(personKeys.PersonId)) { newPeopleAttributes.Add(personKeys.PersonId, person); } else { newPeopleAttributes[personKeys.PersonId] = person; } } completed++; } if (completed % percentage < 1) { var percentComplete = completed / percentage; ReportProgress(percentComplete, $"{completed:N0} communication items imported ({percentComplete}% complete)."); } if (completed % ReportingNumber < 1) { if (newNumbers.Any() || newPeopleAttributes.Any()) { SaveCommunication(newNumbers, newPeopleAttributes); } // reset so context doesn't bloat lookupContext = new RockContext(); personService = new PersonService(lookupContext); newPeopleAttributes.Clear(); newNumbers.Clear(); ReportPartialProgress(); } } } } if (newNumbers.Any() || newPeopleAttributes.Any()) { SaveCommunication(newNumbers, newPeopleAttributes); } ReportProgress(100, $"Finished communications import: {completed:N0} items imported."); }
/// <summary> /// Gets the payments that have been processed for any scheduled transactions /// </summary> /// <param name="financialGateway"></param> /// <param name="startDate">The start date.</param> /// <param name="endDate">The end date.</param> /// <param name="errorMessage">The error message.</param> /// <returns></returns> public override List <Payment> GetPayments(FinancialGateway financialGateway, DateTime startDate, DateTime endDate, out string errorMessage) { // set the encryption protocols that are permissible for external SSL connections System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12; var reportingApi = new Rock.PayFlowPro.Reporting.Api( GetAttributeValue(financialGateway, "User"), GetAttributeValue(financialGateway, "Vendor"), GetAttributeValue(financialGateway, "Partner"), GetAttributeValue(financialGateway, "Password"), GetAttributeValue(financialGateway, "Mode").Equals("Test", StringComparison.CurrentCultureIgnoreCase)); // Query the PayFlowPro Recurring Billing Report for transactions that were processed during data range var recurringBillingParams = new Dictionary <string, string>(); recurringBillingParams.Add("start_date", startDate.ToString("yyyy-MM-dd HH:mm:ss")); recurringBillingParams.Add("end_date", endDate.ToString("yyyy-MM-dd HH:mm:ss")); recurringBillingParams.Add("include_declines", "false"); DataTable recurringBillingTable = reportingApi.GetReport("RecurringBillingReport", recurringBillingParams, out errorMessage); if (recurringBillingTable != null) { // The Recurring Billing Report items does not include the amounts for each transaction, so need // to run a custom report to try and get the amount/tender type for each transaction var transactionCodes = new Dictionary <string, int>(); var customParams = new Dictionary <string, string>(); customParams.Add("start_date", startDate.ToString("yyyy-MM-dd HH:mm:ss")); customParams.Add("end_date", endDate.ToString("yyyy-MM-dd HH:mm:ss")); customParams.Add("maximum_amount", "1000000"); customParams.Add("results", "Approvals Only"); customParams.Add("recurring_only", "true"); customParams.Add("show_order_id", "false"); customParams.Add("show_transaction_id", "true"); customParams.Add("show_time", "false"); customParams.Add("show_type", "false"); customParams.Add("show_tender_type", "true"); customParams.Add("show_account_number", "false"); customParams.Add("show_expires", "false"); customParams.Add("show_aba_routing_number", "false"); customParams.Add("show_amount", "true"); customParams.Add("show_result_code", "true"); customParams.Add("show_response_msg", "false"); customParams.Add("show_comment1", "false"); customParams.Add("show_comment2", "false"); customParams.Add("show_tax_amount", "false"); customParams.Add("show_purchase_order", "false"); customParams.Add("show_original_transaction_id", "false"); customParams.Add("show_avs_street_match", "false"); customParams.Add("show_avs_zip_match", "false"); customParams.Add("show_invoice_number", "false"); customParams.Add("show_authcode", "false"); customParams.Add("show_batch_id", "false"); customParams.Add("show_csc_match", "false"); customParams.Add("show_billing_first_name", "false"); customParams.Add("show_billing_last_name", "false"); customParams.Add("show_billing_company_name", "false"); customParams.Add("show_billing_address", "false"); customParams.Add("show_billing_city", "false"); customParams.Add("show_billing_state", "false"); customParams.Add("show_billing_zip", "false"); customParams.Add("show_billing_email", "true"); customParams.Add("show_billing_country", "false"); customParams.Add("show_shipping_first_name", "false"); customParams.Add("show_shipping_last_name", "false"); customParams.Add("show_shipping_address", "false"); customParams.Add("show_shipping_city", "false"); customParams.Add("show_shipping_state", "false"); customParams.Add("show_shipping_zip", "false"); customParams.Add("show_shipping_country", "false"); customParams.Add("show_customer_code", "false"); customParams.Add("show_freight_amount", "false"); customParams.Add("show_duty_amount", "false"); DataTable customTable = reportingApi.GetReport("CustomReport", customParams, out errorMessage); if (customTable != null) { for (int i = 0; i < customTable.Rows.Count; i++) { transactionCodes.Add(customTable.Rows[i]["Transaction Id"].ToString().Trim(), i); } } var txns = new List <Payment>(); var transactionIdParams = new Dictionary <string, string>(); transactionIdParams.Add("transaction_id", string.Empty); var creditCardTypes = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.FINANCIAL_CREDIT_CARD_TYPE.AsGuid()).DefinedValues; foreach (DataRow recurringBillingRow in recurringBillingTable.Rows) { bool foundTxn = false; string transactionId = recurringBillingRow["Transaction ID"].ToString().Trim(); decimal amount = decimal.MinValue; string tenderType = string.Empty; string email = null; if (transactionCodes.ContainsKey(transactionId)) { int rowNumber = transactionCodes[transactionId]; amount = decimal.TryParse(customTable.Rows[rowNumber]["Amount"].ToString(), out amount) ? (amount / 100) : 0.0M; tenderType = customTable.Rows[rowNumber]["Tender Type"].ToString(); email = customTable.Rows[rowNumber]["PayPal Email ID"].ToString(); foundTxn = true; } else { // If the custom report did not include the transaction, run a transactionIDSearch report to get the amount and tender type transactionIdParams["transaction_id"] = transactionId; DataTable transactionIdTable = reportingApi.GetSearch("TransactionIDSearch", transactionIdParams, out errorMessage); if (transactionIdTable != null && transactionIdTable.Rows.Count == 1) { amount = decimal.TryParse(transactionIdTable.Rows[0]["Amount"].ToString(), out amount) ? (amount / 100) : 0.0M; tenderType = transactionIdTable.Rows[0]["Tender Type"].ToString(); foundTxn = true; } } if (foundTxn) { var payment = new Payment(); payment.Amount = amount; payment.TransactionDateTime = recurringBillingRow["Time"].ToString().AsDateTime() ?? DateTime.MinValue; payment.TransactionCode = recurringBillingRow["Transaction ID"].ToString().Trim(); payment.GatewayScheduleId = recurringBillingRow["Profile ID"].ToString(); payment.ScheduleActive = recurringBillingRow["Status"].ToString() == "Active"; payment.CreditCardTypeValue = creditCardTypes.Where(t => t.Value == tenderType).FirstOrDefault(); if (payment.CreditCardTypeValue != null) { payment.CurrencyTypeValue = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CREDIT_CARD); } else { payment.CurrencyTypeValue = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_ACH); } if (!string.IsNullOrEmpty(email)) { payment.Attributes = new Dictionary <string, string>(); payment.Attributes.Add("CCEmail", email); } txns.Add(payment); } else { errorMessage = "The TransactionIDSearch report did not return a value for transaction: " + recurringBillingRow["Transaction ID"].ToString(); return(null); } } return(txns); } errorMessage = "The RecurringBillingReport report did not return any data"; return(null); }
/// <summary> /// Maps the pledge. /// </summary> /// <param name="csvData">todo: describe csvData parameter on MapPledge</param> /// <returns></returns> /// <exception cref="System.NotImplementedException"></exception> private int MapPledge(CSVInstance csvData) { var lookupContext = new RockContext(); var accountList = new FinancialAccountService(lookupContext).Queryable().AsNoTracking().ToList(); var importedPledges = new FinancialPledgeService(lookupContext).Queryable().AsNoTracking() .Where(p => p.ForeignId != null) .ToDictionary(t => (int)t.ForeignId, t => (int?)t.Id); var pledgeFrequencies = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_FREQUENCY), lookupContext).DefinedValues; var oneTimePledgeFrequencyId = pledgeFrequencies.FirstOrDefault(f => f.Guid == new Guid(Rock.SystemGuid.DefinedValue.TRANSACTION_FREQUENCY_ONE_TIME)).Id; var newPledges = new List <FinancialPledge>(); var completed = 0; ReportProgress(0, $"Verifying pledge import ({importedPledges.Count:N0} already exist)."); string[] row; // Uses a look-ahead enumerator: this call will move to the next record immediately while ((row = csvData.Database.FirstOrDefault()) != null) { var amountKey = row[TotalPledge]; var amount = amountKey.AsType <decimal?>(); var startDate = ParseDateOrDefault(row[StartDate], new DateTime(1, 1, 1)); var endDate = ParseDateOrDefault(row[EndDate], new DateTime(9999, 12, 31)); var createdDate = ParseDateOrDefault(row[PledgeCreatedDate], ImportDateTime); var modifiedDate = ParseDateOrDefault(row[PledgeModifiedDate], ImportDateTime); var pledgeIdKey = row[PledgeId]; var pledgeId = pledgeIdKey.AsType <int?>(); if (amount != null && !importedPledges.ContainsKey((int)pledgeId)) { var individualIdKey = row[IndividualID]; var personKeys = GetPersonKeys(individualIdKey); if (personKeys != null && personKeys.PersonAliasId > 0) { var pledge = new FinancialPledge { PersonAliasId = personKeys.PersonAliasId, CreatedByPersonAliasId = ImportPersonAliasId, StartDate = (DateTime)startDate, EndDate = (DateTime)endDate, TotalAmount = (decimal)amount, CreatedDateTime = createdDate, ModifiedDateTime = modifiedDate, ModifiedByPersonAliasId = ImportPersonAliasId, ForeignKey = pledgeIdKey, ForeignId = pledgeId }; var frequency = row[PledgeFrequencyName].ToString().ToLower(); if (!string.IsNullOrWhiteSpace(frequency)) { frequency = frequency.ToLower(); if (frequency.Equals("one time") || frequency.Equals("one-time") || frequency.Equals("as can")) { pledge.PledgeFrequencyValueId = oneTimePledgeFrequencyId; } else { pledge.PledgeFrequencyValueId = pledgeFrequencies .Where(f => f.Value.ToLower().StartsWith(frequency) || f.Description.ToLower().StartsWith(frequency)) .Select(f => f.Id).FirstOrDefault(); } } var fundName = row[FundName] as string; var subFund = row[SubFundName] as string; var fundGLAccount = row[FundGLAccount] as string; var subFundGLAccount = row[SubFundGLAccount] as string; var isFundActiveKey = row[FundIsActive]; var isFundActive = isFundActiveKey.AsType <bool?>(); var isSubFundActiveKey = row[SubFundIsActive]; var isSubFundActive = isSubFundActiveKey.AsType <bool?>(); if (!string.IsNullOrWhiteSpace(fundName)) { var parentAccount = accountList.FirstOrDefault(a => a.Name.Equals(fundName.Truncate(50))); if (parentAccount == null) { parentAccount = AddAccount(lookupContext, fundName, string.Empty, null, null, isFundActive, null, null, null, null, "", "", null); accountList.Add(parentAccount); } if (!string.IsNullOrWhiteSpace(subFund)) { int?campusFundId = null; // assign a campus if the subfund is a campus fund var campusFund = CampusList.FirstOrDefault(c => subFund.Contains(c.Name) || subFund.Contains(c.ShortCode)); if (campusFund != null) { campusFundId = campusFund.Id; } // add info to easily find/assign this fund in the view subFund = $"{fundName} {subFund}"; var childAccount = accountList.FirstOrDefault(c => c.Name.Equals(subFund.Truncate(50)) && c.ParentAccountId == parentAccount.Id); if (childAccount == null) { // create a child account with a campusId if it was set childAccount = AddAccount(lookupContext, subFund, string.Empty, campusFundId, parentAccount.Id, isSubFundActive, null, null, null, null, "", "", null); accountList.Add(childAccount); } pledge.AccountId = childAccount.Id; } else { pledge.AccountId = parentAccount.Id; } } newPledges.Add(pledge); completed++; if (completed % (ReportingNumber * 10) < 1) { ReportProgress(0, $"{completed:N0} pledges imported."); } else if (completed % ReportingNumber < 1) { SavePledges(newPledges); ReportPartialProgress(); newPledges.Clear(); } } } } if (newPledges.Any()) { SavePledges(newPledges); } ReportProgress(100, $"Finished pledge import: {completed:N0} pledges imported."); return(completed); }
/// <summary> /// Loads the group data. /// </summary> /// <param name="csvData">The CSV data.</param> private int LoadGroup(CSVInstance csvData) { // Required variables var lookupContext = new RockContext(); var locationService = new LocationService(lookupContext); var groupTypeService = new GroupTypeService(lookupContext); var topicTypes = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.SMALL_GROUP_TOPIC), lookupContext).DefinedValues; var numImportedGroups = ImportedGroups.Count(); var newGroupLocations = new Dictionary <GroupLocation, string>(); var currentGroup = new Group(); var newGroupList = new List <Group>(); // Look for custom attributes in the Individual file var allFields = csvData.TableNodes.FirstOrDefault().Children.Select((node, index) => new { node = node, index = index }).ToList(); var customAttributes = allFields .Where(f => f.index > GroupCapacity) .ToDictionary(f => f.index, f => f.node.Name); var groupAttributes = new AttributeService(lookupContext).GetByEntityTypeId(new Group().TypeId).ToList(); var completed = 0; ReportProgress(0, $"Starting group import ({numImportedGroups:N0} already exist)."); string[] row; // Uses a look-ahead enumerator: this call will move to the next record immediately while ((row = csvData.Database.FirstOrDefault()) != null) { var rowGroupKey = row[GroupId]; // // Determine if we are still working with the same group or not. // if (rowGroupKey != null && rowGroupKey != currentGroup.ForeignKey) { currentGroup = LoadGroupBasic(lookupContext, rowGroupKey, row[GroupName], row[GroupCreatedDate], row[GroupType], row[GroupParentGroupId], row[GroupActive], row[GroupDescription]); // // Set the group campus // var campusName = row[GroupCampus]; if (!string.IsNullOrWhiteSpace(campusName)) { var groupCampus = CampusList.FirstOrDefault(c => c.Name.Equals(campusName, StringComparison.InvariantCultureIgnoreCase) || c.ShortCode.Equals(campusName, StringComparison.InvariantCultureIgnoreCase)); if (groupCampus == null) { groupCampus = new Campus { IsSystem = false, Name = campusName, ShortCode = campusName.RemoveWhitespace(), IsActive = true }; lookupContext.Campuses.Add(groupCampus); lookupContext.SaveChanges(DisableAuditing); CampusList.Add(groupCampus); } currentGroup.CampusId = groupCampus.Id; } // // If the group type has one or more location types defined then import the // primary address as the first location type. // var groupType = groupTypeService.Get(currentGroup.GroupTypeId); if (groupType.LocationTypes.Count > 0 && (!string.IsNullOrWhiteSpace(row[GroupAddress]) || !string.IsNullOrWhiteSpace(row[GroupNamedLocation])) && currentGroup.GroupLocations.Count == 0) { var primaryLocationTypeId = groupType.LocationTypes.ToList()[0].LocationTypeValueId; var grpAddress = row[GroupAddress]; var grpAddress2 = row[GroupAddress2]; var grpCity = row[GroupCity]; var grpState = row[GroupState]; var grpZip = row[GroupZip]; var grpCountry = row[GroupCountry]; var namedLocation = row[GroupNamedLocation]; if (string.IsNullOrWhiteSpace(namedLocation)) { var primaryAddress = locationService.Get(grpAddress, grpAddress2, grpCity, grpState, grpZip, grpCountry, verifyLocation: false); if (primaryAddress != null) { var primaryLocation = new GroupLocation { LocationId = primaryAddress.Id, IsMailingLocation = true, IsMappedLocation = true, GroupLocationTypeValueId = primaryLocationTypeId }; newGroupLocations.Add(primaryLocation, rowGroupKey); } } else { var primaryAddress = locationService.Queryable().FirstOrDefault(l => l.Name.Equals(namedLocation) || l.ForeignKey.Equals(namedLocation)); if (primaryAddress != null) { var primaryLocation = new GroupLocation { LocationId = primaryAddress.Id, IsMailingLocation = true, IsMappedLocation = true, GroupLocationTypeValueId = primaryLocationTypeId }; newGroupLocations.Add(primaryLocation, rowGroupKey); } else { LogException("Group Import", string.Format("The named location {0} was not found and will not be mapped.", namedLocation)); } } } // // If the group type has two or more location types defined then import the // secondary address as the group type's second location type. // if (groupType.LocationTypes.Count > 1 && !string.IsNullOrWhiteSpace(row[GroupSecondaryAddress]) && currentGroup.GroupLocations.Count < 2) { var secondaryLocationTypeId = groupType.LocationTypes.ToList()[1].LocationTypeValueId; var grpSecondAddress = row[GroupSecondaryAddress]; var grpSecondAddress2 = row[GroupSecondaryAddress2]; var grpSecondCity = row[GroupSecondaryCity]; var grpSecondState = row[GroupSecondaryState]; var grpSecondZip = row[GroupSecondaryZip]; var grpSecondCountry = row[GroupSecondaryCountry]; var secondaryAddress = locationService.Get(grpSecondAddress, grpSecondAddress2, grpSecondCity, grpSecondState, grpSecondZip, grpSecondCountry, verifyLocation: false); if (secondaryAddress != null) { var secondaryLocation = new GroupLocation { LocationId = secondaryAddress.Id, IsMailingLocation = true, IsMappedLocation = true, GroupLocationTypeValueId = secondaryLocationTypeId }; newGroupLocations.Add(secondaryLocation, rowGroupKey); } } // // Set the group's sorting order. // var groupOrder = 9999; int.TryParse(row[GroupOrder], out groupOrder); currentGroup.Order = groupOrder; // // Set the group's capacity // var capacity = row[GroupCapacity].AsIntegerOrNull(); if (capacity.HasValue) { currentGroup.GroupCapacity = capacity; if (groupType.GroupCapacityRule == GroupCapacityRule.None) { groupType.GroupCapacityRule = GroupCapacityRule.Hard; } } // // Set the group's schedule // if (!string.IsNullOrWhiteSpace(row[GroupDayOfWeek])) { DayOfWeek dayEnum; if (Enum.TryParse(row[GroupDayOfWeek], true, out dayEnum)) { if (groupType.AllowedScheduleTypes != ScheduleType.Weekly) { groupType.AllowedScheduleTypes = ScheduleType.Weekly; } var day = dayEnum; var time = row[GroupTime].AsDateTime(); currentGroup.ScheduleId = AddNamedSchedule(lookupContext, string.Empty, string.Empty, day, time, null, rowGroupKey).Id; } } // // Assign Attributes // if (customAttributes.Any()) { lookupContext.SaveChanges(); foreach (var attributePair in customAttributes) { var pairs = attributePair.Value.Split('^'); var categoryName = string.Empty; var attributeName = string.Empty; var attributeTypeString = string.Empty; var attributeForeignKey = string.Empty; var definedValueForeignKey = string.Empty; var fieldTypeId = TextFieldTypeId; if (pairs.Length == 1) { attributeName = pairs[0]; } else if (pairs.Length == 2) { attributeName = pairs[0]; attributeTypeString = pairs[1]; } else if (pairs.Length >= 3) { categoryName = pairs[1]; attributeName = pairs[2]; if (pairs.Length >= 4) { attributeTypeString = pairs[3]; } if (pairs.Length >= 5) { attributeForeignKey = pairs[4]; } if (pairs.Length >= 6) { definedValueForeignKey = pairs[5]; } } var definedValueForeignId = definedValueForeignKey.AsType <int?>(); // // Translate the provided attribute type into one we know about. // fieldTypeId = GetAttributeFieldType(attributeTypeString); Rock.Model.Attribute currentAttribute = null; if (string.IsNullOrEmpty(attributeName)) { LogException("Group Attribute", string.Format("Group Attribute Name cannot be blank '{0}'.", attributePair.Value)); } else { if (string.IsNullOrWhiteSpace(attributeForeignKey)) { attributeForeignKey = string.Format("Bulldozer_{0}_{1}_{2}", groupType.Id, categoryName.RemoveWhitespace(), attributeName.RemoveWhitespace()).Left(100); } currentAttribute = groupAttributes.FirstOrDefault(a => a.Name.Equals(attributeName, StringComparison.OrdinalIgnoreCase) && a.FieldTypeId == fieldTypeId && a.EntityTypeId == currentGroup.TypeId && a.EntityTypeQualifierValue == groupType.Id.ToString() ); if (currentAttribute == null) { currentAttribute = AddEntityAttribute(lookupContext, currentGroup.TypeId, "GroupTypeId", groupType.Id.ToString(), attributeForeignKey, categoryName, attributeName, string.Empty, fieldTypeId, true, definedValueForeignId, definedValueForeignKey, attributeTypeString: attributeTypeString); groupAttributes.Add(currentAttribute); } var attributeValue = row[attributePair.Key]; if (!string.IsNullOrEmpty(attributeValue)) { AddEntityAttributeValue(lookupContext, currentAttribute, currentGroup, row[attributePair.Key], null, true); } } } } // // Changes to groups need to be saved right away since one group // will reference another group. // lookupContext.SaveChanges(); // // Keep the user informed as to what is going on and save in batches. // completed++; if (completed % (ReportingNumber * 10) < 1) { ReportProgress(0, $"{completed:N0} groups imported."); } if (completed % ReportingNumber < 1) { SaveGroups(newGroupList, newGroupLocations); ReportPartialProgress(); // Reset lookup context lookupContext.SaveChanges(); lookupContext = new RockContext(); locationService = new LocationService(lookupContext); groupTypeService = new GroupTypeService(lookupContext); newGroupList.Clear(); newGroupLocations.Clear(); } } } // // Check to see if any rows didn't get saved to the database // if (newGroupLocations.Any()) { SaveGroups(newGroupList, newGroupLocations); } lookupContext.SaveChanges(); lookupContext.Dispose(); ReportProgress(0, $"Finished group import: {completed:N0} groups added or updated."); return(completed); }
/// <summary> /// Handles a received message and sets the response using the Workflow's "SMSResponse" attribute value (if any). /// If a keyword match cannot be found, it returns an 'unrecognized keyword' response message. /// </summary> /// <param name="toPhone">To phone.</param> /// <param name="fromPhone">From phone.</param> /// <param name="message">The message.</param> /// <param name="response">The response from the Workflow's "SMSResponse" attribute value.</param> public static void MessageRecieved(string toPhone, string fromPhone, string message, out string response) { response = "The keyword you provided was not recognized as a valid keyword."; // get TextToWorkflow defined types for this number var definedType = DefinedTypeCache.Get(SystemGuid.DefinedType.TEXT_TO_WORKFLOW.AsGuid()); // If there are not any defined values, then return with the invalid keyword response if (definedType == null || definedType.DefinedValues == null || !definedType.DefinedValues.Any()) { return; } // get the TextToWorkflow values for the selected "To" number var smsWorkflows = definedType.DefinedValues.Where(v => v.Value.AsNumeric() == toPhone.AsNumeric()) .OrderBy(v => v.Order).ToList(); // Iterate through workflows looking for a keyword match (Only the first match will be processed) foreach (DefinedValueCache dvWorkflow in smsWorkflows) { // Get the Keyword expression attribute and see if it matches the message that was received string keywordExpression = dvWorkflow.GetAttributeValue("KeywordExpression"); if (string.IsNullOrWhiteSpace(keywordExpression)) { // if there was no keyword expression add wildcard expression keywordExpression = ".*"; } if (keywordExpression == "*") { // if the keyword is just a * then replace it keywordExpression = ".*"; } if (!keywordExpression.StartsWith("^")) { // Prefix keyword with start-of-string assertion (input needs to start with selected expression) keywordExpression = $"^{keywordExpression}"; } // If the keyword expression does not match the message that was received ignore this TextToWorkflow value and continue to the next var match = Regex.Match(message, keywordExpression, RegexOptions.IgnoreCase); if (!match.Success) { continue; } // Get the workflow type, If there is not a valid workflow type defined, return with invalid keyword response var workflowTypeGuid = dvWorkflow.GetAttributeValue("WorkflowType").AsGuidOrNull(); if (!workflowTypeGuid.HasValue) { return; } // Get the configured workflow type, if it is not valid return with invalid keyword response var workflowType = WorkflowTypeCache.Get(workflowTypeGuid.Value); if (workflowType == null) { return; } // Get the list of workflow attributes to set var workflowAttributesSettings = new List <KeyValuePair <string, object> >(); var workflowAttributes = dvWorkflow.Attributes["WorkflowAttributes"]; if (workflowAttributes != null) { var keyValueField = workflowAttributes.FieldType.Field as KeyValueListFieldType; if (keyValueField != null) { workflowAttributesSettings = keyValueField.GetValuesFromString(null, dvWorkflow.GetAttributeValue("WorkflowAttributes"), workflowAttributes.QualifierValues, false); } } // Get the template for the workflow name string nameTemplate = dvWorkflow.GetAttributeValue("WorkflowNameTemplate"); using (var rockContext = new RockContext()) { // Try to find a person associated with phone number received var fromPerson = GetPerson(fromPhone, rockContext); // Activate a new workflow var workflow = Model.Workflow.Activate(workflowType, "Request from " + (fromPhone ?? "??"), rockContext); // Set the workflow initiator if (fromPerson != null) { workflow.InitiatorPersonAliasId = fromPerson.PrimaryAliasId; } // Format the phone number that was received var formattedPhoneNumber = PhoneNumber.CleanNumber(PhoneNumber.FormattedNumber(PhoneNumber.DefaultCountryCode(), fromPhone)); // Create list of the keyword expressions that matched the received message var matchGroups = new List <string>(); foreach (var matchItem in match.Groups) { matchGroups.Add(matchItem.ToString()); } // Create a list of mergefields used to update workflow attribute values and the workflow name var mergeValues = new Dictionary <string, object> { { "FromPhone", formattedPhoneNumber }, { "ToPhone", toPhone }, { "MessageBody", message }, { "MatchedGroups", matchGroups }, { "ReceivedTime", RockDateTime.Now.ToString("HH:mm:ss") }, { "ReceivedDate", RockDateTime.Now.ToShortDateString() }, { "ReceivedDateTime", RockDateTime.Now.ToString("o") }, { "FromPerson", fromPerson } }; // Set the workflow's FromPhone attribute workflow.SetAttributeValue("FromPhone", fromPhone); // Set any other workflow attributes that could have lava foreach (var attribute in workflowAttributesSettings) { workflow.SetAttributeValue(attribute.Key, attribute.Value.ToString().ResolveMergeFields(mergeValues)); } // Set the workflow name var name = nameTemplate.ResolveMergeFields(mergeValues); if (name.IsNotNullOrWhiteSpace()) { workflow.Name = name; } // Process the workflow List <string> workflowErrors; new WorkflowService(rockContext).Process(workflow, out workflowErrors); // Check to see if there is a response to return var responseAttribute = workflow.GetAttributeValue("SMSResponse"); response = !string.IsNullOrWhiteSpace(responseAttribute) ? responseAttribute : string.Empty; } // once we find one match stop processing break; } }
/// <summary> /// Maps the contribution. /// </summary> /// <param name="csvData">The table data.</param> private int MapContribution(CSVInstance csvData) { var lookupContext = new RockContext(); var currencyTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_CURRENCY_TYPE)); var currencyTypeACH = currencyTypes.DefinedValues.FirstOrDefault(dv => dv.Guid.Equals(new Guid(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_ACH))).Id; var currencyTypeCash = currencyTypes.DefinedValues.FirstOrDefault(dv => dv.Guid.Equals(new Guid(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CASH))).Id; var currencyTypeCheck = currencyTypes.DefinedValues.FirstOrDefault(dv => dv.Guid.Equals(new Guid(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CHECK))).Id; var currencyTypeCreditCard = currencyTypes.DefinedValues.FirstOrDefault(dv => dv.Guid.Equals(new Guid(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CREDIT_CARD))).Id; var currencyTypeNonCash = currencyTypes.DefinedValues.Where(dv => dv.Value.Equals("Non-Cash")).Select(dv => (int?)dv.Id).FirstOrDefault(); if (currencyTypeNonCash == null) { var newTenderNonCash = new DefinedValue { Value = "Non-Cash", Description = "Non-Cash", DefinedTypeId = currencyTypes.Id }; lookupContext.DefinedValues.Add(newTenderNonCash); lookupContext.SaveChanges(); currencyTypeNonCash = newTenderNonCash.Id; } var creditCardTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_CREDIT_CARD_TYPE)).DefinedValues; var sourceTypeOnsite = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.FINANCIAL_SOURCE_TYPE_ONSITE_COLLECTION), lookupContext).Id; var sourceTypeWebsite = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.FINANCIAL_SOURCE_TYPE_WEBSITE), lookupContext).Id; var sourceTypeKiosk = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.FINANCIAL_SOURCE_TYPE_KIOSK), lookupContext).Id; var refundReasons = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.FINANCIAL_TRANSACTION_REFUND_REASON), lookupContext).DefinedValues; var accountList = new FinancialAccountService(lookupContext).Queryable().AsNoTracking().ToList(); int?defaultBatchId = null; if (ImportedBatches.ContainsKey(0)) { defaultBatchId = ImportedBatches[0]; } // Look for custom attributes in the Contribution file var allFields = csvData.TableNodes.FirstOrDefault().Children.Select((node, index) => new { node = node, index = index }).ToList(); var customAttributes = allFields .Where(f => f.index > ContributionCreditCardType) .ToDictionary(f => f.index, f => f.node.Name); // Get all imported contributions var importedContributions = new FinancialTransactionService(lookupContext).Queryable().AsNoTracking() .Where(c => c.ForeignId != null) .Select(t => (int)t.ForeignId) .OrderBy(t => t).ToList(); // List for batching new contributions var newTransactions = new List <FinancialTransaction>(); var completed = 0; ReportProgress(0, $"Verifying contribution import ({importedContributions.Count:N0} already exist)."); string[] row; // Uses a look-ahead enumerator: this call will move to the next record immediately while ((row = csvData.Database.FirstOrDefault()) != null) { var individualIdKey = row[IndividualID]; var contributionIdKey = row[ContributionID]; var contributionId = contributionIdKey.AsType <int?>(); if (contributionId != null && !importedContributions.Contains((int)contributionId)) { var transaction = new FinancialTransaction { CreatedByPersonAliasId = ImportPersonAliasId, ModifiedByPersonAliasId = ImportPersonAliasId, TransactionTypeValueId = TransactionTypeContributionId, ForeignKey = contributionId.ToString(), ForeignId = contributionId }; int?giverAliasId = null; var personKeys = GetPersonKeys(individualIdKey); if (personKeys != null && personKeys.PersonAliasId > 0) { giverAliasId = personKeys.PersonAliasId; transaction.CreatedByPersonAliasId = giverAliasId; transaction.AuthorizedPersonAliasId = giverAliasId; transaction.ProcessedByPersonAliasId = giverAliasId; } else if (AnonymousGiverAliasId != null && AnonymousGiverAliasId > 0) { giverAliasId = AnonymousGiverAliasId; transaction.AuthorizedPersonAliasId = giverAliasId; transaction.ProcessedByPersonAliasId = giverAliasId; } var summary = row[Memo] as string; if (!string.IsNullOrWhiteSpace(summary)) { transaction.Summary = summary; } var batchIdKey = row[ContributionBatchID]; var batchId = batchIdKey.AsType <int?>(); if (batchId != null && ImportedBatches.Any(b => b.Key.Equals(batchId))) { transaction.BatchId = ImportedBatches.FirstOrDefault(b => b.Key.Equals(batchId)).Value; } else { // use the default batch for any non-matching transactions transaction.BatchId = defaultBatchId; } var receivedDate = ParseDateOrDefault(row[ReceivedDate], null); if (receivedDate.HasValue) { transaction.TransactionDateTime = receivedDate; transaction.CreatedDateTime = receivedDate; transaction.ModifiedDateTime = ImportDateTime; } var contributionType = row[ContributionTypeName]; var creditCardType = row[ContributionCreditCardType]; if (!string.IsNullOrWhiteSpace(contributionType)) { // set default source to onsite, exceptions listed below transaction.SourceTypeValueId = sourceTypeOnsite; int?paymentCurrencyTypeId = null, creditCardTypeId = null; if (contributionType.Equals("cash", StringComparison.CurrentCultureIgnoreCase)) { paymentCurrencyTypeId = currencyTypeCash; } else if (contributionType.Equals("check", StringComparison.CurrentCultureIgnoreCase)) { paymentCurrencyTypeId = currencyTypeCheck; } else if (contributionType.Equals("ach", StringComparison.CurrentCultureIgnoreCase)) { paymentCurrencyTypeId = currencyTypeACH; transaction.SourceTypeValueId = sourceTypeWebsite; } else if (contributionType.Equals("credit card", StringComparison.CurrentCultureIgnoreCase)) { paymentCurrencyTypeId = currencyTypeCreditCard; transaction.SourceTypeValueId = sourceTypeWebsite; // Determine CC Type if (!string.IsNullOrWhiteSpace(creditCardType)) { creditCardTypeId = creditCardTypes.Where(c => c.Value.StartsWith(creditCardType, StringComparison.CurrentCultureIgnoreCase) || c.Description.StartsWith(creditCardType, StringComparison.CurrentCultureIgnoreCase)) .Select(c => c.Id).FirstOrDefault(); } } else { paymentCurrencyTypeId = currencyTypeNonCash; } var paymentDetail = new FinancialPaymentDetail { CreatedDateTime = receivedDate, CreatedByPersonAliasId = giverAliasId, ModifiedDateTime = ImportDateTime, ModifiedByPersonAliasId = giverAliasId, CurrencyTypeValueId = paymentCurrencyTypeId, CreditCardTypeValueId = creditCardTypeId, ForeignKey = contributionId.ToString(), ForeignId = contributionId }; transaction.FinancialPaymentDetail = paymentDetail; } var transactionCode = row[CheckNumber] as string; // if transaction code provided, put it in the transaction code if (!string.IsNullOrEmpty(transactionCode)) { transaction.TransactionCode = transactionCode; // check for SecureGive kiosk transactions if (transactionCode.StartsWith("SG")) { transaction.SourceTypeValueId = sourceTypeKiosk; } } var fundName = row[FundName] as string; var subFund = row[SubFundName] as string; var fundGLAccount = row[FundGLAccount] as string; var subFundGLAccount = row[SubFundGLAccount] as string; var isFundActiveKey = row[FundIsActive]; var isFundActive = isFundActiveKey.AsType <bool?>(); var isSubFundActiveKey = row[SubFundIsActive]; var isSubFundActive = isSubFundActiveKey.AsType <bool?>(); var statedValueKey = row[StatedValue]; var statedValue = statedValueKey.AsType <decimal?>(); var amountKey = row[Amount]; var amount = amountKey.AsType <decimal?>(); if (!string.IsNullOrWhiteSpace(fundName) & amount != null) { int transactionAccountId; var parentAccount = accountList.FirstOrDefault(a => a.Name.Equals(fundName.Truncate(50))); if (parentAccount == null) { parentAccount = AddAccount(lookupContext, fundName, fundGLAccount, null, null, isFundActive, null, null, null, null, "", "", null); accountList.Add(parentAccount); } if (!string.IsNullOrWhiteSpace(subFund)) { int?campusFundId = null; // assign a campus if the subfund is a campus fund var campusFund = CampusList.FirstOrDefault(c => subFund.Contains(c.Name) || subFund.Contains(c.ShortCode)); if (campusFund != null) { campusFundId = campusFund.Id; } // add info to easily find/assign this fund in the view subFund = $"{fundName} {subFund}"; var childAccount = accountList.FirstOrDefault(c => c.Name.Equals(subFund.Truncate(50)) && c.ParentAccountId == parentAccount.Id); if (childAccount == null) { // create a child account with a campusId if it was set childAccount = AddAccount(lookupContext, subFund, subFundGLAccount, campusFundId, parentAccount.Id, isSubFundActive, null, null, null, null, "", "", null); accountList.Add(childAccount); } transactionAccountId = childAccount.Id; } else { transactionAccountId = parentAccount.Id; } if (amount == 0 && statedValue != null && statedValue != 0) { amount = statedValue; } var transactionDetail = new FinancialTransactionDetail { Amount = (decimal)amount, CreatedDateTime = receivedDate, AccountId = transactionAccountId }; transaction.TransactionDetails.Add(transactionDetail); if (amount < 0) { transaction.RefundDetails = new FinancialTransactionRefund(); transaction.RefundDetails.CreatedDateTime = receivedDate; transaction.RefundDetails.RefundReasonValueId = refundReasons.Where(dv => summary != null && dv.Value.Contains(summary)) .Select(dv => (int?)dv.Id).FirstOrDefault(); transaction.RefundDetails.RefundReasonSummary = summary; } } newTransactions.Add(transaction); completed++; if (completed % (ReportingNumber * 10) < 1) { ReportProgress(0, $"{completed:N0} contributions imported."); } else if (completed % ReportingNumber < 1) { SaveContributions(newTransactions); newTransactions.Clear(); ReportPartialProgress(); } } } if (newTransactions.Any()) { SaveContributions(newTransactions); } ReportProgress(100, $"Finished contribution import: {completed:N0} contributions imported."); return(completed); }
/// <summary> /// Loads the drop downs. /// </summary> private bool SetFilterControls() { // Get and verify the calendar id if (_calendarId <= 0) { ShowError("Configuration Error", "The 'Event Calendar' setting has not been set correctly."); return(false); } // Get and verify the view mode ViewMode = GetAttributeValue("DefaultViewOption"); if (!GetAttributeValue(string.Format("Show{0}View", ViewMode)).AsBoolean()) { ShowError("Configuration Error", string.Format("The Default View Option setting has been set to '{0}', but the Show {0} View setting has not been enabled.", ViewMode)); return(false); } // Show/Hide calendar control pnlCalendar.Visible = GetAttributeValue("ShowSmallCalendar").AsBoolean(); // Get the first/last dates based on today's date and the viewmode setting var today = RockDateTime.Today; FilterStartDate = today; FilterEndDate = today; if (ViewMode == "Week") { FilterStartDate = today.StartOfWeek(_firstDayOfWeek); FilterEndDate = today.EndOfWeek(_firstDayOfWeek); } else if (ViewMode == "Month") { FilterStartDate = new DateTime(today.Year, today.Month, 1); FilterEndDate = FilterStartDate.Value.AddMonths(1).AddDays(-1); } // Setup small calendar Filter calEventCalendar.FirstDayOfWeek = _firstDayOfWeek.ConvertToInt().ToString().ConvertToEnum <FirstDayOfWeek>(); calEventCalendar.SelectedDates.Clear(); calEventCalendar.SelectedDates.SelectRange(FilterStartDate.Value, FilterEndDate.Value); // Setup Campus Filter rcwCampus.Visible = GetAttributeValue("CampusFilterDisplayMode").AsInteger() > 1; cblCampus.DataSource = CampusCache.All(); cblCampus.DataBind(); if (GetAttributeValue("EnableCampusContext").AsBoolean()) { var contextCampus = RockPage.GetCurrentContext(EntityTypeCache.Read("Rock.Model.Campus")) as Campus; if (contextCampus != null) { cblCampus.SetValue(contextCampus.Id); } } // Setup Category Filter var selectedCategoryGuids = GetAttributeValue("FilterCategories").SplitDelimitedValues(true).AsGuidList(); rcwCategory.Visible = selectedCategoryGuids.Any() && GetAttributeValue("CategoryFilterDisplayMode").AsInteger() > 1; var definedType = DefinedTypeCache.Read(Rock.SystemGuid.DefinedType.MARKETING_CAMPAIGN_AUDIENCE_TYPE.AsGuid()); if (definedType != null) { cblCategory.DataSource = definedType.DefinedValues.Where(v => selectedCategoryGuids.Contains(v.Guid)); cblCategory.DataBind(); } // Date Range Filter drpDateRange.Visible = GetAttributeValue("ShowDateRangeFilter").AsBoolean(); lbDateRangeRefresh.Visible = drpDateRange.Visible; drpDateRange.LowerValue = FilterStartDate; drpDateRange.UpperValue = FilterEndDate; // Get the View Modes, and only show them if more than one is visible var viewsVisible = new List <bool> { GetAttributeValue("ShowDayView").AsBoolean(), GetAttributeValue("ShowWeekView").AsBoolean(), GetAttributeValue("ShowMonthView").AsBoolean() }; var howManyVisible = viewsVisible.Where(v => v).Count(); btnDay.Visible = howManyVisible > 1 && viewsVisible[0]; btnWeek.Visible = howManyVisible > 1 && viewsVisible[1]; btnMonth.Visible = howManyVisible > 1 && viewsVisible[2]; // Set filter visibility bool showFilter = (pnlCalendar.Visible || rcwCampus.Visible || rcwCategory.Visible || drpDateRange.Visible); pnlFilters.Visible = showFilter; pnlList.CssClass = showFilter ? "col-md-9" : "col-md-12"; return(true); }
/// <summary> /// Maps the family address. /// </summary> /// <param name="tableData">The table data.</param> /// <returns></returns> private void MapFamilyAddress(IQueryable <Row> tableData) { var lookupContext = new RockContext(); var locationService = new LocationService(lookupContext); List <GroupMember> familyGroupMemberList = new GroupMemberService(lookupContext).Queryable().AsNoTracking() .Where(gm => gm.Group.GroupType.Guid == new Guid(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY)).ToList(); var groupLocationDefinedType = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.GROUP_LOCATION_TYPE), lookupContext); int homeGroupLocationTypeId = groupLocationDefinedType.DefinedValues .FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME)).Id; int workGroupLocationTypeId = groupLocationDefinedType.DefinedValues .FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK)).Id; int previousGroupLocationTypeId = groupLocationDefinedType.DefinedValues .FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS)).Id; string otherGroupLocationName = "Other (Imported)"; int? otherGroupLocationTypeId = groupLocationDefinedType.DefinedValues .Where(dv => dv.TypeName == otherGroupLocationName) .Select(dv => (int?)dv.Id).FirstOrDefault(); if (otherGroupLocationTypeId == null) { var otherGroupLocationType = new DefinedValue(); otherGroupLocationType.Value = otherGroupLocationName; otherGroupLocationType.DefinedTypeId = groupLocationDefinedType.Id; otherGroupLocationType.IsSystem = false; otherGroupLocationType.Order = 0; lookupContext.DefinedValues.Add(otherGroupLocationType); lookupContext.SaveChanges(DisableAuditing); otherGroupLocationTypeId = otherGroupLocationType.Id; } var newGroupLocations = new List <GroupLocation>(); int completed = 0; int totalRows = tableData.Count(); int percentage = (totalRows - 1) / 100 + 1; ReportProgress(0, string.Format("Verifying address import ({0:N0} found).", totalRows)); foreach (var row in tableData.Where(r => r != null)) { int?individualId = row["Individual_ID"] as int?; int?householdId = row["Household_ID"] as int?; var personKeys = GetPersonKeys(individualId, householdId, includeVisitors: false); if (personKeys != null) { var familyGroup = familyGroupMemberList.Where(gm => gm.PersonId == personKeys.PersonId) .Select(gm => gm.Group).FirstOrDefault(); if (familyGroup != null) { var groupLocation = new GroupLocation(); string street1 = row["Address_1"] as string; string street2 = row["Address_2"] as string; string city = row["City"] as string; string state = row["State"] as string; string country = row["country"] as string; // NOT A TYPO: F1 has property in lower-case string zip = row["Postal_Code"] as string ?? string.Empty; // restrict zip to 5 places to prevent duplicates Location familyAddress = locationService.Get(street1, street2, city, state, zip.Left(5), country, verifyLocation: false); if (familyAddress != null) { familyAddress.CreatedByPersonAliasId = ImportPersonAliasId; familyAddress.Name = familyGroup.Name; familyAddress.IsActive = true; groupLocation.GroupId = familyGroup.Id; groupLocation.LocationId = familyAddress.Id; groupLocation.IsMailingLocation = true; groupLocation.IsMappedLocation = true; string addressType = row["Address_Type"].ToString().ToLower(); if (addressType.Equals("primary")) { groupLocation.GroupLocationTypeValueId = homeGroupLocationTypeId; } else if (addressType.Equals("business") || addressType.ToLower().Equals("org")) { groupLocation.GroupLocationTypeValueId = workGroupLocationTypeId; } else if (addressType.Equals("previous")) { groupLocation.GroupLocationTypeValueId = previousGroupLocationTypeId; } else if (!string.IsNullOrEmpty(addressType)) { // look for existing group location types, otherwise mark as imported var customTypeId = groupLocationDefinedType.DefinedValues.Where(dv => dv.Value.ToLower().Equals(addressType)) .Select(dv => (int?)dv.Id).FirstOrDefault(); groupLocation.GroupLocationTypeValueId = customTypeId ?? otherGroupLocationTypeId; } newGroupLocations.Add(groupLocation); completed++; if (completed % percentage < 1) { int percentComplete = completed / percentage; ReportProgress(percentComplete, string.Format("{0:N0} addresses imported ({1}% complete).", completed, percentComplete)); } else if (completed % ReportingNumber < 1) { SaveFamilyAddress(newGroupLocations); // Reset context newGroupLocations.Clear(); lookupContext = new RockContext(); locationService = new LocationService(lookupContext); ReportPartialProgress(); } } } } } if (newGroupLocations.Any()) { SaveFamilyAddress(newGroupLocations); } ReportProgress(100, string.Format("Finished address import: {0:N0} addresses imported.", completed)); }
private void LoadDropdowns() { ddlSearchType.Items.Clear(); var searchTypes = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.CHECKIN_SEARCH_TYPE.AsGuid()); if (searchTypes != null) { foreach (var searchType in searchTypes.DefinedValues) { if (searchType.GetAttributeValue("UserSelectable").AsBooleanOrNull() ?? true) { ddlSearchType.Items.Add(new System.Web.UI.WebControls.ListItem(searchType.Value, searchType.Id.ToString())); } } } lbKnownRelationshipTypes.Items.Clear(); lbKnownRelationshipTypes.Items.Add(new ListItem("Child", "0")); lbSameFamilyKnownRelationshipTypes.Items.Clear(); lbSameFamilyKnownRelationshipTypes.Items.Add(new ListItem("Child", "0")); lbCanCheckInKnownRelationshipTypes.Items.Clear(); var knownRelationShipRoles = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS).Roles; foreach (var knownRelationShipRole in knownRelationShipRoles.Where(a => a.Name != "Child")) { lbKnownRelationshipTypes.Items.Add(new ListItem(knownRelationShipRole.Name, knownRelationShipRole.Id.ToString())); lbSameFamilyKnownRelationshipTypes.Items.Add(new ListItem(knownRelationShipRole.Name, knownRelationShipRole.Id.ToString())); lbCanCheckInKnownRelationshipTypes.Items.Add(new ListItem(knownRelationShipRole.Name, knownRelationShipRole.Id.ToString())); } lbRegistrationRequiredAttributesForAdults.Items.Clear(); lbRegistrationOptionalAttributesForAdults.Items.Clear(); lbRegistrationRequiredAttributesForChildren.Items.Clear(); lbRegistrationOptionalAttributesForChildren.Items.Clear(); var fakePerson = new Person(); fakePerson.LoadAttributes(); foreach (var personAttribute in fakePerson.Attributes.Select(a => new { Name = a.Value.Name, Value = a.Value.Guid.ToString() })) { lbRegistrationRequiredAttributesForAdults.Items.Add(new ListItem(personAttribute.Name, personAttribute.Value)); lbRegistrationOptionalAttributesForAdults.Items.Add(new ListItem(personAttribute.Name, personAttribute.Value)); lbRegistrationRequiredAttributesForChildren.Items.Add(new ListItem(personAttribute.Name, personAttribute.Value)); lbRegistrationOptionalAttributesForChildren.Items.Add(new ListItem(personAttribute.Name, personAttribute.Value)); } lbRegistrationOptionalAttributesForFamilies.Items.Clear(); lbRegistrationRequiredAttributesForFamilies.Items.Clear(); var fakeFamily = new Group { GroupTypeId = GroupTypeCache.GetFamilyGroupType().Id }; fakeFamily.LoadAttributes(); foreach (var groupTypeFamilyAttribute in fakeFamily.Attributes.Select(a => new { Name = a.Value.Name, Value = a.Value.Guid.ToString() })) { lbRegistrationRequiredAttributesForFamilies.Items.Add(new ListItem(groupTypeFamilyAttribute.Name, groupTypeFamilyAttribute.Value)); lbRegistrationOptionalAttributesForFamilies.Items.Add(new ListItem(groupTypeFamilyAttribute.Name, groupTypeFamilyAttribute.Value)); } }
/// <summary> /// Maps the person. /// </summary> /// <param name="tableData">The table data.</param> /// <param name="totalRows">The total rows.</param> public void MapPerson(IQueryable <Row> tableData, long totalRows = 0) { var lookupContext = new RockContext(); // Marital statuses: Married, Single, Separated, etc var maritalStatusTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS), lookupContext).DefinedValues; // Connection statuses: Member, Visitor, Attendee, etc var connectionStatusTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS), lookupContext).DefinedValues; // Title type: Mr., Mrs., Dr., etc var titleTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_TITLE), lookupContext).DefinedValues; // Suffix type: Sr., Jr., II, etc var suffixTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_SUFFIX), lookupContext).DefinedValues; // Look up additional Person attributes (existing) var personAttributes = new AttributeService(lookupContext).GetByEntityTypeId(PersonEntityTypeId).AsNoTracking().ToList(); // F1 attributes: IndividualId, HouseholdId // Core attributes: PreviousChurch, Membership Date, First Visit, Allergy, Employer, Position, School var previousChurchAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals("PreviousChurch", StringComparison.InvariantCultureIgnoreCase)); var membershipDateAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals("MembershipDate", StringComparison.InvariantCultureIgnoreCase)); var firstVisitAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals("FirstVisit", StringComparison.InvariantCultureIgnoreCase)); var allergyNoteAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals("Allergy", StringComparison.InvariantCultureIgnoreCase)); var employerAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals("Employer", StringComparison.InvariantCultureIgnoreCase)); var positionAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals("Position", StringComparison.InvariantCultureIgnoreCase)); var schoolAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals("School", StringComparison.InvariantCultureIgnoreCase)); var familyList = new List <Group>(); var visitorList = new List <Group>(); var previousNamesList = new Dictionary <Guid, string>(); var householdCampusList = new List <string>(); if (totalRows == 0) { totalRows = tableData.Count(); } var importedPeopleCount = ImportedPeople.Count; var completedItems = importedPeopleCount; var percentage = (totalRows - 1) / 100 + 1; ReportProgress(0, $"Verifying person import ({totalRows:N0} found, {importedPeopleCount:N0} already exist)."); foreach (var groupedRows in tableData.GroupBy(r => r["Household_ID"] as int?)) { var familyGroup = new Group(); householdCampusList.Clear(); foreach (var row in groupedRows.Where(r => r != null)) { var familyRoleId = FamilyRole.Adult; var currentCampus = string.Empty; var individualId = row["Individual_ID"] as int?; var householdId = row["Household_ID"] as int?; var personKeys = GetPersonKeys(individualId, householdId); if (personKeys == null) { var person = new Person(); person.FirstName = row["First_Name"] as string; person.MiddleName = row["Middle_Name"] as string; person.NickName = row["Goes_By"] as string ?? person.FirstName; person.LastName = row["Last_Name"] as string; person.IsDeceased = false; var DOB = row["Date_Of_Birth"] as DateTime?; if (DOB.HasValue) { var birthDate = (DateTime)DOB; person.BirthDay = birthDate.Day; person.BirthMonth = birthDate.Month; person.BirthYear = birthDate.Year; } person.CreatedByPersonAliasId = ImportPersonAliasId; person.RecordTypeValueId = PersonRecordTypeId; person.ForeignKey = individualId.ToString(); person.ForeignId = individualId; var gender = row["Gender"] as string; if (!string.IsNullOrWhiteSpace(gender)) { person.Gender = (Gender)Enum.Parse(typeof(Gender), gender); } var prefix = row["Prefix"] as string; if (!string.IsNullOrWhiteSpace(prefix)) { prefix = prefix.RemoveSpecialCharacters(); person.TitleValueId = titleTypes.Where(s => prefix.Equals(s.Value.RemoveSpecialCharacters(), StringComparison.CurrentCultureIgnoreCase)) .Select(s => (int?)s.Id).FirstOrDefault(); if (!person.TitleValueId.HasValue) { var newTitle = AddDefinedValue(lookupContext, Rock.SystemGuid.DefinedType.PERSON_TITLE, prefix); if (newTitle != null) { titleTypes.Add(newTitle); person.TitleValueId = newTitle.Id; } } } var suffix = row["Suffix"] as string; if (!string.IsNullOrWhiteSpace(suffix)) { suffix = suffix.RemoveSpecialCharacters(); person.SuffixValueId = suffixTypes.Where(s => suffix.Equals(s.Value.RemoveSpecialCharacters(), StringComparison.CurrentCultureIgnoreCase)) .Select(s => (int?)s.Id).FirstOrDefault(); if (!person.SuffixValueId.HasValue) { var newSuffix = AddDefinedValue(lookupContext, Rock.SystemGuid.DefinedType.PERSON_SUFFIX, suffix); if (newSuffix != null) { suffixTypes.Add(newSuffix); person.SuffixValueId = newSuffix.Id; } } } var maritalStatus = row["Marital_Status"] as string; if (!string.IsNullOrWhiteSpace(maritalStatus)) { maritalStatus = maritalStatus.RemoveSpecialCharacters(); person.MaritalStatusValueId = maritalStatusTypes.Where(s => maritalStatus.Equals(s.Value.RemoveSpecialCharacters(), StringComparison.CurrentCultureIgnoreCase)) .Select(dv => (int?)dv.Id).FirstOrDefault(); if (!person.MaritalStatusValueId.HasValue) { var newMaritalStatus = AddDefinedValue(lookupContext, Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS, maritalStatus); if (newMaritalStatus != null) { maritalStatusTypes.Add(newMaritalStatus); person.MaritalStatusValueId = newMaritalStatus.Id; } } } else { person.MaritalStatusValueId = maritalStatusTypes.Where(dv => dv.Value.Equals("Unknown", StringComparison.CurrentCultureIgnoreCase)) .Select(dv => (int?)dv.Id).FirstOrDefault(); } var familyRole = row["Household_Position"] as string; if (!string.IsNullOrWhiteSpace(familyRole)) { if (familyRole.Equals("Visitor", StringComparison.CurrentCultureIgnoreCase)) { familyRoleId = FamilyRole.Visitor; } else if (familyRole.Equals("Child", StringComparison.CurrentCultureIgnoreCase) || person.Age < 18) { familyRoleId = FamilyRole.Child; } } var memberStatus = row["Status_Name"] as string; if (!string.IsNullOrWhiteSpace(memberStatus)) { memberStatus = memberStatus.Trim(); if (memberStatus.Equals("Member", StringComparison.CurrentCultureIgnoreCase)) { person.ConnectionStatusValueId = MemberConnectionStatusId; person.RecordStatusValueId = ActivePersonRecordStatusId; } else if (memberStatus.Equals("Visitor", StringComparison.CurrentCultureIgnoreCase)) { person.ConnectionStatusValueId = VisitorConnectionStatusId; person.RecordStatusValueId = ActivePersonRecordStatusId; // F1 can designate visitors by member status or household position familyRoleId = FamilyRole.Visitor; } else if (memberStatus.Equals("Deceased", StringComparison.CurrentCultureIgnoreCase)) { person.IsDeceased = true; person.RecordStatusReasonValueId = DeceasedPersonRecordReasonId; person.RecordStatusValueId = InactivePersonRecordStatusId; } else if (memberStatus.Equals("Dropped", StringComparison.CurrentCultureIgnoreCase) || memberStatus.StartsWith("Inactive", StringComparison.CurrentCultureIgnoreCase)) { person.RecordStatusReasonValueId = NoActivityPersonRecordReasonId; person.RecordStatusValueId = InactivePersonRecordStatusId; } else { // create user-defined connection type if it doesn't exist person.RecordStatusValueId = ActivePersonRecordStatusId; person.ConnectionStatusValueId = connectionStatusTypes.Where(dv => dv.Value.Equals(memberStatus, StringComparison.CurrentCultureIgnoreCase)) .Select(dv => (int?)dv.Id).FirstOrDefault(); if (!person.ConnectionStatusValueId.HasValue) { var newConnectionStatus = AddDefinedValue(lookupContext, Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS, memberStatus); if (newConnectionStatus != null) { connectionStatusTypes.Add(newConnectionStatus); person.ConnectionStatusValueId = newConnectionStatus.Id; } } } } else { person.ConnectionStatusValueId = VisitorConnectionStatusId; person.RecordStatusValueId = ActivePersonRecordStatusId; } var campus = row["SubStatus_Name"] as string; if (!string.IsNullOrWhiteSpace(campus)) { currentCampus = campus; } var status_comment = row["Status_Comment"] as string; if (!string.IsNullOrWhiteSpace(status_comment)) { person.SystemNote = status_comment; } var previousName = row["Former_Name"] as string; if (!string.IsNullOrWhiteSpace(previousName)) { previousNamesList.Add(person.Guid, previousName); } // set a flag to keep visitors from receiving household info person.ReviewReasonNote = familyRoleId.ToString(); // Map F1 attributes person.Attributes = new Dictionary <string, AttributeCache>(); person.AttributeValues = new Dictionary <string, AttributeValueCache>(); // IndividualId already defined in scope AddEntityAttributeValue(lookupContext, IndividualIdAttribute, person, individualId.ToString()); // HouseholdId already defined in scope AddEntityAttributeValue(lookupContext, HouseholdIdAttribute, person, householdId.ToString()); var previousChurch = row["Former_Church"] as string; if (!string.IsNullOrWhiteSpace(previousChurch)) { AddEntityAttributeValue(lookupContext, previousChurchAttribute, person, previousChurch); } var employer = row["Employer"] as string; if (!string.IsNullOrWhiteSpace(employer)) { AddEntityAttributeValue(lookupContext, employerAttribute, person, employer); } var position = row["Occupation_Name"] as string ?? row["Occupation_Description"] as string; if (!string.IsNullOrWhiteSpace(position)) { AddEntityAttributeValue(lookupContext, positionAttribute, person, position); } var school = row["School_Name"] as string; if (!string.IsNullOrWhiteSpace(school)) { AddEntityAttributeValue(lookupContext, schoolAttribute, person, school); } var firstVisit = row["First_Record"] as DateTime?; if (firstVisit.HasValue) { person.CreatedDateTime = firstVisit; AddEntityAttributeValue(lookupContext, firstVisitAttribute, person, firstVisit.Value.ToString("yyyy-MM-dd")); } // Only import membership date if they are a member var membershipDate = row["Status_Date"] as DateTime?; if (membershipDate.HasValue && memberStatus.Contains("member")) { AddEntityAttributeValue(lookupContext, membershipDateAttribute, person, membershipDate.Value.ToString("yyyy-MM-dd")); } var checkinNote = row["Default_tag_comment"] as string; if (!string.IsNullOrWhiteSpace(checkinNote)) { AddEntityAttributeValue(lookupContext, allergyNoteAttribute, person, checkinNote); } var groupMember = new GroupMember { Person = person, GroupRoleId = familyRoleId != FamilyRole.Child ? FamilyAdultRoleId : FamilyChildRoleId, GroupMemberStatus = GroupMemberStatus.Active }; if (familyRoleId != FamilyRole.Visitor) { householdCampusList.Add(currentCampus); familyGroup.Members.Add(groupMember); familyGroup.ForeignKey = householdId.ToString(); familyGroup.ForeignId = householdId; } else { var visitorGroup = new Group { GroupTypeId = FamilyGroupTypeId, ForeignKey = householdId.ToString(), ForeignId = householdId, Name = person.LastName + " Family", CampusId = GetCampusId(currentCampus) }; visitorGroup.Members.Add(groupMember); familyList.Add(visitorGroup); completedItems += visitorGroup.Members.Count; visitorList.Add(visitorGroup); } } } if (familyGroup.Members.Any()) { familyGroup.Name = familyGroup.Members.OrderByDescending(p => p.Person.Age) .FirstOrDefault().Person.LastName + " Family"; familyGroup.GroupTypeId = FamilyGroupTypeId; var primaryCampusTag = householdCampusList.GroupBy(c => c).OrderByDescending(c => c.Count()) .Select(c => c.Key).FirstOrDefault(); if (!string.IsNullOrWhiteSpace(primaryCampusTag)) { familyGroup.CampusId = GetCampusId(primaryCampusTag); } familyList.Add(familyGroup); completedItems += familyGroup.Members.Count; // average family has 2.3 members, so fudge the math a little if (completedItems % percentage < 2) { var percentComplete = completedItems / percentage; ReportProgress(percentComplete, $"{completedItems - importedPeopleCount:N0} people imported ({percentComplete}% complete)."); } else if (completedItems % ReportingNumber < 1) { SavePeople(familyList, visitorList, previousNamesList); familyList.Clear(); visitorList.Clear(); previousNamesList.Clear(); ReportPartialProgress(); } } } // Save any remaining families in the batch if (familyList.Any()) { SavePeople(familyList, visitorList, previousNamesList); } ReportProgress(100, $"Finished person import: {completedItems - importedPeopleCount:N0} people imported."); }
/// <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 existing Person attributes var personAttributes = attributeService.GetByEntityTypeId(PersonEntityTypeId).ToList(); // 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.IsEmail()) { string secondaryEmail = string.Empty; // person email is empty if (string.IsNullOrWhiteSpace(person.Email)) { person.Email = value.Left(75); person.IsEmailActive = isListed; person.EmailPreference = isListed ? EmailPreference.EmailAllowed : EmailPreference.DoNotEmail; person.ModifiedDateTime = lastUpdated; person.EmailNote = communicationComment; lookupContext.SaveChanges(DisableAudit); } // person email not empty and this is a different email else if (!person.Email.Equals(value)) { secondaryEmail = value; } // person has two email addresses, make sure the second if (!string.IsNullOrWhiteSpace(secondaryEmail)) { AddPersonAttribute(secondaryEmailAttribute, person, secondaryEmail); } } else if (type.Contains("Twitter")) { AddPersonAttribute(twitterAttribute, person, value); } else if (type.Contains("Facebook")) { AddPersonAttribute(facebookAttribute, person, value); } else if (type.Contains("Instagram")) { AddPersonAttribute(instagramAttribute, person, 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)); }
/// <summary> /// Gets the expression. /// </summary> /// <param name="entityType">Type of the entity.</param> /// <param name="serviceInstance">The service instance.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <param name="selection">The selection.</param> /// <returns></returns> public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection) { // see if they have a grade transition date bool hasGradeTransitionDate = GlobalAttributesCache.Get().GetValue("GradeTransitionDate").MonthDayStringAsDateTime().HasValue; var values = selection.Split('|'); ComparisonType comparisonType = values[0].ConvertToEnum <ComparisonType>(ComparisonType.EqualTo); Guid? gradeDefinedValueGuid = values[1].AsGuidOrNull(); DefinedTypeCache gradeDefinedType = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.SCHOOL_GRADES.AsGuid()); DefinedValueCache gradeDefinedValue = gradeDefinedType.DefinedValues.FirstOrDefault(a => a.Guid == gradeDefinedValueGuid); int? gradeOffset = gradeDefinedValue != null?gradeDefinedValue.Value.AsIntegerOrNull() : null; var personGradeQuery = new PersonService((RockContext)serviceInstance.Context).Queryable(); int currentSchoolYear = RockDateTime.CurrentGraduationYear; if (hasGradeTransitionDate && gradeOffset.HasValue) { /* * example (assuming defined values are the stock values): * Billy graduates in 2020, the transition date is 6/1 * In other words, Billy graduates on 6/1/2020 * and current date is Feb 1, 2015. * * Stock Example: * 9th Grade offset is 3 * 8th Grade offset is 4 * 7th Grade offset is 5 * 6th Grade offset is 6 * Billy graduates on 6/1/2020 and current date is Feb 1, 2015 * Therefore, his current grade offset is 5 yrs, which would mean he is in 7th grade * * * If the filter is: * Equal to 7th grade... * 7th Graders would be included. * Grade offset must be LessThanOrEqualTo 5 and GreaterThan 4 * Not-Equal to 7th grade... * 7th Graders would not be included. * Grade offset must be LessThanOrEqualTo 4 or GreaterThan 5 * Less than 7th grade.. * 7th Graders would not be included, 6th and younger would be included. * Grade offset must be GreaterThan 5 * Less than or Equal to 7th grade.. * 7th Graders and younger would be included. * Grade offset must be GreaterThan 4 * Greater than 7th grade.. * 7th Graders would not be included, 8th Graders and older would be included. * Grade offset must be LessThanOrEqualTo 4 * Greater than or Equal to 7th grade.. * 7th Graders and older would be included. * Grade offset must be LessThanOrEqualTo 5 * * Combined Example: * High School offset is 3 * Jr High offset is 5 * K-6 offset is 12 * Billy graduates on 6/1/2020 and current date is Feb 1, 2015 * Therefore, his current grade offset is 5 yrs, which would mean he is in Jr High * * If the filter is: * Equal to Jr High... * Jr High would be included. * Grade offset must be LessThanOrEqualTo 5 and GreaterThan 3 * Not-Equal to Jr High... * Jr High would not be included. * Grade offset must be LessThanOrEqualTo 3 or GreaterThan 5 * Less than Jr High.. * Jr High would not be included, K-6 and younger would be included. * Grade offset must be GreaterThan 5 * Less than or Equal to Jr High.. * Jr High and younger would be included. * Grade offset must be GreaterThan 3 * Greater than Jr High.. * Jr High would not be included, High School and older would be included. * Grade offset must be LessThanOrEqualTo 3 * Greater than or Equal to Jr High.. * Jr High and older would be included. * Grade offset must be LessThanOrEqualTo 5 */ DefinedValueCache nextGradeDefinedValue = gradeDefinedType.DefinedValues .OrderByDescending(a => a.Value.AsInteger()).Where(a => a.Value.AsInteger() < gradeOffset).FirstOrDefault(); int nextGradeOffset = nextGradeDefinedValue != null?nextGradeDefinedValue.Value.AsInteger() : -1; switch (comparisonType) { case ComparisonType.EqualTo: // Include people who have have a grade offset LessThanOrEqualTo selected grade's offset, but GreaterThan the next grade's offset personGradeQuery = personGradeQuery.Where(p => p.GraduationYear - currentSchoolYear <= gradeOffset && p.GraduationYear - currentSchoolYear > nextGradeOffset); break; case ComparisonType.NotEqualTo: // Include people who have have a grade offset LessThanOrEqualTo next grade's offset, or GreaterThan the selected grade's offset (and not already graduated) personGradeQuery = personGradeQuery.Where(p => (p.GraduationYear - currentSchoolYear <= nextGradeOffset || p.GraduationYear - currentSchoolYear > gradeOffset) && p.GraduationYear - currentSchoolYear >= 0); break; case ComparisonType.LessThan: // Grade offset must be GreaterThan selected grade's offset personGradeQuery = personGradeQuery.Where(p => p.GraduationYear - currentSchoolYear > gradeOffset); break; case ComparisonType.LessThanOrEqualTo: // Grade offset must be GreaterThan next grade's offset personGradeQuery = personGradeQuery.Where(p => p.GraduationYear - currentSchoolYear > nextGradeOffset); break; case ComparisonType.GreaterThan: // Grade offset must be LessThanOrEqualTo next grade's offset (and not already graduated) personGradeQuery = personGradeQuery.Where(p => p.GraduationYear - currentSchoolYear <= nextGradeOffset && p.GraduationYear - currentSchoolYear >= 0); break; case ComparisonType.GreaterThanOrEqualTo: // Grade offset must be LessThanOrEqualTo selected grade's offset (and not already graduated) personGradeQuery = personGradeQuery.Where(p => p.GraduationYear - currentSchoolYear <= gradeOffset && p.GraduationYear - currentSchoolYear >= 0); break; case ComparisonType.IsBlank: // only return people that don't have a graduation year, or have already graduated personGradeQuery = personGradeQuery.Where(p => !p.GraduationYear.HasValue || (p.GraduationYear - currentSchoolYear) < 0); break; case ComparisonType.IsNotBlank: // only return people that have a graduation date, and haven't graduated yet personGradeQuery = personGradeQuery.Where(p => p.GraduationYear.HasValue && (p.GraduationYear - currentSchoolYear) >= 0); break; } Expression result = FilterExpressionExtractor.Extract <Rock.Model.Person>(personGradeQuery, parameterExpression, "p"); return(result); } else { if (!hasGradeTransitionDate) { if (comparisonType == ComparisonType.IsBlank) { // if no gradeTransitionDate, return true (everybody has a blank grade) personGradeQuery = personGradeQuery.Where(p => true); } else { // if no gradeTransitionDate, return false (nobody has a grade) personGradeQuery = personGradeQuery.Where(p => false); } } else { // there is a grade transition date, but the selected gradeOffset is null if (comparisonType == ComparisonType.IsBlank) { // if trying to find people without a Grade only include people that don't have a graduation date or already graduated personGradeQuery = personGradeQuery.Where(p => !p.GraduationYear.HasValue || p.GraduationYear.Value < currentSchoolYear); } else if (comparisonType == ComparisonType.IsNotBlank) { // if trying to find people with a Grade only include people that have a graduation date and haven't already graduated personGradeQuery = personGradeQuery.Where(p => p.GraduationYear.HasValue && !(p.GraduationYear.Value < currentSchoolYear)); } else { // if no grade selected and they are comparing return false (nobody meets the condition since the condition is invalid) personGradeQuery = personGradeQuery.Where(p => false); } } return(FilterExpressionExtractor.Extract <Rock.Model.Person>(personGradeQuery, parameterExpression, "p")); } }
/// <summary> /// Handles the SelectPerson event of the 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 ppSource_SelectPerson(object sender, EventArgs e) { nbSuccess.Text = string.Empty; nbWarning.Text = string.Empty; nbError.Text = string.Empty; pnlToBusiness.Visible = false; pnlToPerson.Visible = false; if (ppSource.PersonId.HasValue) { var person = new PersonService(new RockContext()).Get(ppSource.PersonId.Value); if (person.RecordTypeValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid()) { pnlToPerson.Visible = true; tbPersonFirstName.Text = string.Empty; tbPersonLastName.Text = person.LastName; dvpPersonConnectionStatus.DefinedTypeId = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS.AsGuid()).Id; dvpMaritalStatus.DefinedTypeId = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS.AsGuid()).Id; rblGender.BindToEnum <Gender>(); rblGender.SetValue(Gender.Unknown.ConvertToInt()); if (!string.IsNullOrWhiteSpace(GetAttributeValue("DefaultConnectionStatus"))) { var dv = DefinedValueCache.Get(GetAttributeValue("DefaultConnectionStatus").AsGuid()); if (dv != null) { dvpPersonConnectionStatus.SetValue(dv.Id); } } } else { // // Ensure person record is a member of only one family. // var families = person.GetFamilies(); if (families.Count() != 1) { nbError.Heading = "Cannot convert person record to a business"; nbError.Text = "To avoid data loss move this person to one family before proceeding."; return; } // // Ensure person record is only record in family. // var family = families.First(); if (family.Members.Count != 1) { nbError.Heading = "Cannot convert person record to a business"; nbError.Text = "To avoid data loss move this person to their own family before proceeding."; return; } // // Ensure giving group is correct. // if (person.GivingGroup == null || person.GivingGroup.Members.Count != 1 || person.GivingLeaderId != person.Id) { nbError.Heading = "Cannot convert person record to a business"; nbError.Text = "Please fix the giving group and then try again."; return; } pnlToBusiness.Visible = true; tbBusinessName.Text = string.Format("{0} {1}", person.FirstName, person.LastName).Trim(); } } }
/// <summary> /// Loads the group type data. /// </summary> /// <param name="csvData">The CSV data.</param> private int LoadGroupType(CSVInstance csvData) { // Required variables var lookupContext = new RockContext(); var newGroupTypeList = new List <GroupType>(); var purposeTypeValues = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.GROUPTYPE_PURPOSE), lookupContext).DefinedValues; var locationMeetingId = DefinedValueCache.Get(new Guid(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_MEETING_LOCATION), lookupContext).Id; var numImportedGroupTypes = ImportedGroupTypes.Count(); var completed = 0; ReportProgress(0, $"Starting group type import ({numImportedGroupTypes:N0} already exist)."); string[] row; // Uses a look-ahead enumerator: this call will move to the next record immediately while ((row = csvData.Database.FirstOrDefault()) != null) { var rowGroupTypeKey = row[GroupTypeId]; var groupTypeForeignId = rowGroupTypeKey.AsType <int?>(); // Check that this group type isn't already in our data var groupTypeExists = false; if (numImportedGroupTypes > 0) { groupTypeExists = ImportedGroupTypes.Any(t => t.ForeignKey == rowGroupTypeKey); } if (!groupTypeExists) { var rowGroupTypeName = row[GroupTypeName].Left(100); var newGroupType = new GroupType { // set required properties (terms set by default) IsSystem = false, Name = rowGroupTypeName, Order = 1000 + completed, // set optional properties CreatedDateTime = ParseDateOrDefault(row[GroupTypeCreatedDate], ImportDateTime), ModifiedDateTime = ImportDateTime, CreatedByPersonAliasId = ImportPersonAliasId, ModifiedByPersonAliasId = ImportPersonAliasId, ForeignKey = rowGroupTypeKey, ForeignId = groupTypeForeignId }; // set meeting location var definedValueService = new DefinedValueService(lookupContext); newGroupType.LocationTypes = new List <GroupTypeLocationType>(); newGroupType.LocationTypes.Clear(); var meetingLocationType = definedValueService.Get(locationMeetingId); if (meetingLocationType != null) { newGroupType.LocationTypes.Add(new GroupTypeLocationType { LocationTypeValueId = meetingLocationType.Id }); } // set provided optional properties newGroupType.TakesAttendance = ( bool )ParseBoolOrDefault(row[GroupTypeTakesAttendance], false); newGroupType.AttendanceCountsAsWeekendService = ( bool )ParseBoolOrDefault(row[GroupTypeWeekendService], false); newGroupType.ShowInGroupList = ( bool )ParseBoolOrDefault(row[GroupTypeShowInGroupList], false); newGroupType.ShowInNavigation = ( bool )ParseBoolOrDefault(row[GroupTypeShowInNav], false); // set schedule var allowGroupScheduleWeekly = ( bool )ParseBoolOrDefault(row[GroupTypeWeeklySchedule], false); if (allowGroupScheduleWeekly) { newGroupType.AllowedScheduleTypes = ScheduleType.Weekly; } var rowGroupTypePurpose = row[GroupTypePurpose]; if (!string.IsNullOrWhiteSpace(rowGroupTypePurpose)) { var purposeId = purposeTypeValues.Where(v => v.Value.Equals(rowGroupTypePurpose) || v.Id.Equals(rowGroupTypePurpose) || v.Guid.ToString().ToLower().Equals(rowGroupTypePurpose.ToLower())) .Select(v => ( int? )v.Id).FirstOrDefault(); newGroupType.GroupTypePurposeValueId = purposeId; } var inheritedGroupType = GroupTypeCache.Get(LoadGroupTypeId(lookupContext, row[GroupTypeInheritedGroupType])); if (inheritedGroupType.Id != GroupTypeCache.Get(new Guid("8400497B-C52F-40AE-A529-3FCCB9587101"), lookupContext).Id) { newGroupType.InheritedGroupTypeId = inheritedGroupType.Id; } // add default role of member var defaultRoleGuid = Guid.NewGuid(); var memberRole = new GroupTypeRole { Guid = defaultRoleGuid, Name = "Member" }; newGroupType.Roles.Add(memberRole); // save changes each loop newGroupTypeList.Add(newGroupType); lookupContext.WrapTransaction(() => { lookupContext.GroupTypes.AddRange(newGroupTypeList); lookupContext.SaveChanges(DisableAuditing); }); // Set Parent Group Type var rowGroupTypeParentId = row[GroupTypeParentId]; if (!string.IsNullOrWhiteSpace(rowGroupTypeParentId)) { var parentGroupType = ImportedGroupTypes.FirstOrDefault(t => t.ForeignKey.Equals(rowGroupTypeParentId)); var parentGroupTypeList = new List <GroupType>(); parentGroupTypeList.Add(parentGroupType); newGroupType.ParentGroupTypes = parentGroupTypeList; } // Set Self Reference bool selfRef; TryParseBool(row[GroupTypeSelfReference], out selfRef); if (selfRef) { var selfReferenceList = new List <GroupType>(); selfReferenceList.Add(newGroupType); newGroupType.ChildGroupTypes = selfReferenceList; } // set default role newGroupType.DefaultGroupRole = newGroupType.Roles.FirstOrDefault(); // save changes lookupContext.SaveChanges(); // add these new groups to the global list ImportedGroupTypes.AddRange(newGroupTypeList); newGroupTypeList.Clear(); // // Keep the user informed as to what is going on and save in batches. // completed++; if (completed % (ReportingNumber * 10) < 1) { ReportProgress(0, $"{completed:N0} groups imported."); } if (completed % ReportingNumber < 1) { ReportPartialProgress(); } } } ReportProgress(0, $"Finished group type import: {completed:N0} group types added or updated."); return(completed); }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnInit(EventArgs e) { base.OnInit(e); var rockPage = Page as RockPage; if (rockPage != null) { string script = rockPage.GetSharedItem("org.RockRMS.PhoneNumberBox.script") as string; if (script == null) { StringBuilder sbScript = new StringBuilder(); sbScript.Append("\tvar phoneNumberFormats = {\n"); var definedType = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.COMMUNICATION_PHONE_COUNTRY_CODE.AsGuid()); if (definedType != null) { var definedValues = definedType.DefinedValues; foreach (var countryCode in definedValues.OrderBy(v => v.Order).Select(v => v.Value).Distinct()) { sbScript.AppendFormat("\t\t'{0}' : [\n", countryCode); foreach (var definedValue in definedValues.Where(v => v.Value == countryCode).OrderBy(v => v.Order)) { string match = definedValue.GetAttributeValue("MatchRegEx"); string replace = definedValue.GetAttributeValue("FormatRegEx"); if (!string.IsNullOrWhiteSpace(match) && !string.IsNullOrWhiteSpace(replace)) { sbScript.AppendFormat("\t\t\t{{ 'match' : '{0}', 'replace' : '{1}' }},\n", match.Replace(@"\", @"\\"), replace.Replace(@"\", @"\\")); } } sbScript.Append("\t\t],\n"); } } sbScript.Append("\t};\n"); sbScript.Append(@" function phoneNumberBoxFormatNumber( tb ) { var countryCode = tb.closest('div.input-group').find('input:hidden').val(); var origValue = tb.val(); var number = tb.val().replace(/\D/g,'').substring( 0, 20 ); var formats = phoneNumberFormats[countryCode]; for ( var i = 0; i < formats.length; i++) { var matchRegex = new RegExp(formats[i].match); number = number.replace(matchRegex, formats[i].replace); } if (number != origValue) { tb.val(number); } } $('div.phone-number-box input:text').on('change', function(e) { phoneNumberBoxFormatNumber($(this)); }); $('div.phone-number-box ul.dropdown-menu a').click( function(e) { e.preventDefault(); $(this).closest('div.input-group').find('input:hidden').val($(this).html()); $(this).closest('div.input-group-btn').find('button').html($(this).html() + ' <span class=""caret""></span>'); phoneNumberBoxFormatNumber($(this).closest('div.input-group').find('input:text').first()); }); "); script = sbScript.ToString(); rockPage.SaveSharedItem("org.RockRMS.PhoneNumberBox.script", script); } ScriptManager.RegisterStartupScript(this, this.GetType(), "phone-number-box", script, true); } }
/// <summary> /// Loads the individual data. /// </summary> /// <param name="csvData">The CSV data.</param> private int LoadIndividuals(CSVInstance csvData) { var lookupContext = new RockContext(); // Marital statuses: Married, Single, Separated, etc var maritalStatusTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS), lookupContext).DefinedValues; // Connection statuses: Member, Visitor, Attendee, etc var connectionStatusTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS), lookupContext).DefinedValues; // Suffix types: Dr., Jr., II, etc var suffixTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_SUFFIX), lookupContext).DefinedValues; // Title types: Mr., Mrs. Dr., etc var titleTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_TITLE), lookupContext).DefinedValues; // Group roles: Owner, Adult, Child, others var familyRoles = GroupTypeCache.Read(new Guid(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY), lookupContext).Roles; // Phone types: Home, Work, Mobile var numberTypeValues = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE), lookupContext).DefinedValues; // School Person attribute var schoolAttribute = FindEntityAttribute(lookupContext, "Education", "School", PersonEntityTypeId); // Visit info category var visitInfoCategory = new CategoryService(lookupContext).GetByEntityTypeId(AttributeEntityTypeId) .Where(c => c.Name == "Visit Information").FirstOrDefault(); // Look for custom attributes in the Individual file var allFields = csvData.TableNodes.FirstOrDefault().Children.Select((node, index) => new { node = node, index = index }).ToList(); var customAttributes = allFields .Where(f => f.index > SecurityNote) .ToDictionary(f => f.index, f => f.node.Name); var personAttributes = new List <Rock.Model.Attribute>(); // Add any attributes if they don't already exist if (customAttributes.Any()) { foreach (var newAttributePair in customAttributes.Where(ca => !personAttributes.Any(a => a.Key == ca.Value))) { var newAttribute = AddEntityAttribute(lookupContext, PersonEntityTypeId, string.Empty, string.Empty, newAttributePair.Value.RemoveWhitespace(), string.Empty, newAttributePair.Value, string.Empty, TextFieldTypeId, true, null, null, ImportPersonAliasId ); personAttributes.Add(newAttribute); } } // Set the supported date formats var dateFormats = new[] { "yyyy-MM-dd", "MM/dd/yyyy", "MM/dd/yy" }; var currentFamilyGroup = new Group(); var newFamilyList = new List <Group>(); var newVisitorList = new List <Group>(); var newNoteList = new List <Note>(); var completed = 0; var newFamilies = 0; var newPeople = 0; ReportProgress(0, string.Format("Starting Individual import ({0:N0} already exist).", ImportedPeopleKeys.Count())); string[] row; row = csvData.Database.FirstOrDefault(); while (row != null) { int?groupRoleId = null; var isFamilyRelationship = true; var rowFamilyName = row[FamilyName]; var rowFamilyKey = row[FamilyId]; var rowPersonKey = row[PersonId]; var rowFamilyId = rowFamilyKey.AsType <int?>(); var rowPersonId = rowPersonKey.AsType <int?>(); // Check that this person isn't already in our data var newPerson = true; if (ImportedPeopleKeys.Count() > 0) { var personKeys = GetPersonKeys(rowPersonKey); if (personKeys != null) { newPerson = false; } } if (newPerson) { #region person create var person = new Person { ForeignKey = rowPersonKey, ForeignId = rowPersonId, SystemNote = string.Format("Imported via Excavator on {0}", ImportDateTime), RecordTypeValueId = PersonRecordTypeId, CreatedByPersonAliasId = ImportPersonAliasId }; var firstName = row[FirstName].Left(50); var nickName = row[NickName].Left(50); person.FirstName = firstName; person.NickName = string.IsNullOrWhiteSpace(nickName) ? firstName : nickName; person.MiddleName = row[MiddleName].Left(50); person.LastName = row[LastName].Left(50); var createdDateValue = ParseDateOrDefault(row[CreatedDate], null); if (createdDateValue.HasValue) { person.CreatedDateTime = createdDateValue; person.ModifiedDateTime = ImportDateTime; } else { person.CreatedDateTime = ImportDateTime; person.ModifiedDateTime = ImportDateTime; } var birthDate = ParseDateOrDefault(row[DateOfBirth], null); if (birthDate.HasValue) { person.BirthDay = ((DateTime)birthDate).Day; person.BirthMonth = ((DateTime)birthDate).Month; person.BirthYear = ((DateTime)birthDate).Year; } var graduationDate = ParseDateOrDefault(row[GraduationDate], null); if (graduationDate.HasValue) { person.GraduationYear = ((DateTime)graduationDate).Year; } var anniversary = ParseDateOrDefault(row[Anniversary], null); if (anniversary.HasValue) { person.AnniversaryDate = anniversary; } var gender = row[Gender]; if (gender != null) { switch (gender.Trim().ToLower()) { case "m": case "male": person.Gender = Rock.Model.Gender.Male; break; case "f": case "female": person.Gender = Rock.Model.Gender.Female; break; default: person.Gender = Rock.Model.Gender.Unknown; break; } } var prefix = row[Prefix]; if (!string.IsNullOrWhiteSpace(prefix)) { prefix = prefix.RemoveSpecialCharacters(); person.TitleValueId = titleTypes.Where(s => prefix.Equals(s.Value.RemoveSpecialCharacters(), StringComparison.CurrentCultureIgnoreCase)) .Select(s => (int?)s.Id).FirstOrDefault(); if (!person.TitleValueId.HasValue) { var newTitle = AddDefinedValue(lookupContext, Rock.SystemGuid.DefinedType.PERSON_TITLE, prefix); if (newTitle != null) { titleTypes.Add(newTitle); person.TitleValueId = newTitle.Id; } } } var suffix = row[Suffix]; if (!string.IsNullOrWhiteSpace(suffix)) { suffix = suffix.RemoveSpecialCharacters(); person.SuffixValueId = suffixTypes.Where(s => suffix.Equals(s.Value.RemoveSpecialCharacters(), StringComparison.CurrentCultureIgnoreCase)) .Select(s => (int?)s.Id).FirstOrDefault(); if (!person.SuffixValueId.HasValue) { var newSuffix = AddDefinedValue(lookupContext, Rock.SystemGuid.DefinedType.PERSON_SUFFIX, suffix); if (newSuffix != null) { suffixTypes.Add(newSuffix); person.SuffixValueId = newSuffix.Id; } } } var maritalStatus = row[MaritalStatus]; if (!string.IsNullOrWhiteSpace(maritalStatus)) { maritalStatus = maritalStatus.RemoveSpecialCharacters(); person.MaritalStatusValueId = maritalStatusTypes.Where(s => maritalStatus.Equals(s.Value.RemoveSpecialCharacters(), StringComparison.CurrentCultureIgnoreCase)) .Select(dv => (int?)dv.Id).FirstOrDefault(); if (!person.MaritalStatusValueId.HasValue) { var newMaritalStatus = AddDefinedValue(lookupContext, Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS, maritalStatus); if (newMaritalStatus != null) { maritalStatusTypes.Add(newMaritalStatus); person.MaritalStatusValueId = newMaritalStatus.Id; } } } if (person.MaritalStatusValueId == null) { person.MaritalStatusValueId = maritalStatusTypes.Where(dv => dv.Value.Equals("Unknown", StringComparison.CurrentCultureIgnoreCase)) .Select(dv => (int?)dv.Id).FirstOrDefault(); } var familyRole = row[FamilyRole]; if (!string.IsNullOrWhiteSpace(familyRole)) { familyRole = familyRole.RemoveSpecialCharacters().Trim(); groupRoleId = familyRoles.Where(dv => string.Equals(dv.Name, familyRole, StringComparison.CurrentCultureIgnoreCase)) .Select(dv => (int?)dv.Id).FirstOrDefault(); if (!groupRoleId.HasValue) { AddGroupRole(lookupContext, Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY, familyRole); familyRoles = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY).Roles; groupRoleId = familyRoles.Where(dv => dv.Name == familyRole) .Select(dv => (int?)dv.Id).FirstOrDefault(); } if (familyRole.Equals("Visitor", StringComparison.CurrentCultureIgnoreCase)) { isFamilyRelationship = false; } } if (groupRoleId == null) { groupRoleId = FamilyAdultRoleId; } var recordStatus = row[RecordStatus]; if (!string.IsNullOrWhiteSpace(recordStatus)) { switch (recordStatus.Trim().ToLower()) { case "active": person.RecordStatusValueId = ActivePersonRecordStatusId; break; case "inactive": person.RecordStatusValueId = InactivePersonRecordStatusId; break; default: person.RecordStatusValueId = PendingPersonRecordStatusId; break; } } else { person.RecordStatusValueId = ActivePersonRecordStatusId; } var connectionStatus = row[ConnectionStatus]; if (!string.IsNullOrWhiteSpace(connectionStatus)) { if (connectionStatus.Equals("Member", StringComparison.CurrentCultureIgnoreCase)) { person.ConnectionStatusValueId = MemberConnectionStatusId; } else if (connectionStatus.Equals("Visitor", StringComparison.CurrentCultureIgnoreCase)) { person.ConnectionStatusValueId = VisitorConnectionStatusId; } else if (connectionStatus.Equals("Business", StringComparison.CurrentCultureIgnoreCase)) { person.RecordTypeValueId = BusinessRecordTypeId; } else if (connectionStatus.Equals("Inactive", StringComparison.CurrentCultureIgnoreCase)) { person.RecordStatusValueId = InactivePersonRecordStatusId; } else { // create user-defined connection type if it doesn't exist person.ConnectionStatusValueId = connectionStatusTypes.Where(dv => dv.Value.Equals(connectionStatus, StringComparison.CurrentCultureIgnoreCase)) .Select(dv => (int?)dv.Id).FirstOrDefault(); if (!person.ConnectionStatusValueId.HasValue) { var newConnectionStatus = AddDefinedValue(lookupContext, Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS, connectionStatus); if (newConnectionStatus != null) { connectionStatusTypes.Add(newConnectionStatus); person.ConnectionStatusValueId = newConnectionStatus.Id; } } } } else { person.ConnectionStatusValueId = VisitorConnectionStatusId; } var isDeceasedValue = row[IsDeceased]; if (!string.IsNullOrWhiteSpace(isDeceasedValue)) { switch (isDeceasedValue.Trim().ToLower()) { case "y": case "yes": case "true": person.IsDeceased = true; person.RecordStatusReasonValueId = DeceasedPersonRecordReasonId; person.RecordStatusValueId = InactivePersonRecordStatusId; break; default: person.IsDeceased = false; break; } } var personNumbers = new Dictionary <string, string>(); personNumbers.Add("Home", row[HomePhone]); personNumbers.Add("Mobile", row[MobilePhone]); personNumbers.Add("Work", row[WorkPhone]); var smsAllowed = row[AllowSMS]; foreach (var numberPair in personNumbers.Where(n => !string.IsNullOrWhiteSpace(n.Value) && n.Value.AsNumeric().AsType <Int64>() > 0)) { var extension = string.Empty; var countryCode = PhoneNumber.DefaultCountryCode(); var normalizedNumber = string.Empty; var countryIndex = numberPair.Value.IndexOf('+'); var extensionIndex = numberPair.Value.LastIndexOf('x') > 0 ? numberPair.Value.LastIndexOf('x') : numberPair.Value.Length; if (countryIndex >= 0) { countryCode = numberPair.Value.Substring(countryIndex, countryIndex + 3); normalizedNumber = numberPair.Value.Substring(countryIndex + 3, extensionIndex - 3).AsNumeric().TrimStart(new Char[] { '0' }); extension = numberPair.Value.Substring(extensionIndex); } else if (extensionIndex > 0) { normalizedNumber = numberPair.Value.Substring(0, extensionIndex).AsNumeric(); extension = numberPair.Value.Substring(extensionIndex).AsNumeric(); } else { normalizedNumber = numberPair.Value.AsNumeric(); } if (!string.IsNullOrWhiteSpace(normalizedNumber)) { var currentNumber = new PhoneNumber(); currentNumber.CountryCode = countryCode; currentNumber.CreatedByPersonAliasId = ImportPersonAliasId; currentNumber.Extension = extension.Left(20); currentNumber.Number = normalizedNumber.TrimStart(new char[] { '0' }).Left(20); currentNumber.NumberFormatted = PhoneNumber.FormattedNumber(currentNumber.CountryCode, currentNumber.Number); currentNumber.NumberTypeValueId = numberTypeValues.Where(v => v.Value.Equals(numberPair.Key, StringComparison.CurrentCultureIgnoreCase)) .Select(v => (int?)v.Id).FirstOrDefault(); if (numberPair.Key == "Mobile") { switch (smsAllowed.Trim().ToLower()) { case "y": case "yes": case "active": case "true": currentNumber.IsMessagingEnabled = true; break; default: currentNumber.IsMessagingEnabled = false; break; } } person.PhoneNumbers.Add(currentNumber); } } // Map Person attributes person.Attributes = new Dictionary <string, AttributeCache>(); person.AttributeValues = new Dictionary <string, AttributeValueCache>(); bool isEmailActive; switch (row[IsEmailActive].Trim().ToLower()) { case "n": case "no": case "inactive": isEmailActive = false; break; default: isEmailActive = true; break; } EmailPreference emailPreference; switch (row[AllowBulkEmail].Trim().ToLower()) { case "n": case "no": case "inactive": emailPreference = EmailPreference.NoMassEmails; break; default: emailPreference = EmailPreference.EmailAllowed; break; } person.EmailPreference = emailPreference; var primaryEmail = row[Email].Trim().Left(75); if (!string.IsNullOrWhiteSpace(primaryEmail)) { if (primaryEmail.IsEmail()) { person.Email = primaryEmail; person.IsEmailActive = isEmailActive; } else { LogException("InvalidPrimaryEmail", string.Format("PersonId: {0} - Email: {1}", rowPersonKey, primaryEmail)); } } var schoolName = row[School]; if (!string.IsNullOrWhiteSpace(schoolName)) { AddEntityAttributeValue(lookupContext, schoolAttribute, person, schoolName, null, true); } foreach (var attributePair in customAttributes) { string newAttributeValue = row[attributePair.Key]; if (!string.IsNullOrWhiteSpace(newAttributeValue)) { // check if this attribute value is a date DateTime valueAsDateTime; if (DateTime.TryParseExact(newAttributeValue, dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out valueAsDateTime)) { newAttributeValue = valueAsDateTime.ToString("yyyy-MM-dd"); } var newAttribute = personAttributes.Where(a => a.Key == attributePair.Value.RemoveWhitespace()) .FirstOrDefault(); if (newAttribute != null) { AddEntityAttributeValue(lookupContext, newAttribute, person, newAttributeValue, null, false); } } } // Add notes to timeline var notePairs = new Dictionary <string, string> { { "General", row[GeneralNote] }, { "Medical", row[MedicalNote] }, { "Security", row[SecurityNote] } }; foreach (var notePair in notePairs.Where(n => !string.IsNullOrWhiteSpace(n.Value))) { var splitNotePair = notePair.Value.Split('^'); foreach (string noteValue in splitNotePair) { var newNote = new Note { NoteTypeId = PersonalNoteTypeId, CreatedByPersonAliasId = ImportPersonAliasId, CreatedDateTime = ImportDateTime, Text = noteValue, ForeignKey = rowPersonKey, ForeignId = rowPersonId, Caption = string.Format("{0} Note", notePair.Key) }; if (noteValue.StartsWith("[ALERT]", StringComparison.CurrentCultureIgnoreCase)) { newNote.IsAlert = true; } if (notePair.Key.Equals("Security")) { // Pastoral note type id var securityNoteType = new NoteTypeService(lookupContext).Get(PersonEntityTypeId, "Secure Note", true); if (securityNoteType != null) { newNote.NoteTypeId = securityNoteType.Id; } } if (notePair.Key.Equals("Medical")) { newNote.IsAlert = true; } newNoteList.Add(newNote); } } #endregion person create var groupMember = new GroupMember { Person = person, GroupRoleId = (int)groupRoleId, CreatedDateTime = ImportDateTime, ModifiedDateTime = ImportDateTime, CreatedByPersonAliasId = ImportPersonAliasId, GroupMemberStatus = GroupMemberStatus.Active }; if (rowFamilyKey != currentFamilyGroup.ForeignKey) { // person not part of the previous family, see if that family exists or create a new one currentFamilyGroup = ImportedFamilies.FirstOrDefault(g => g.ForeignKey == rowFamilyKey); if (currentFamilyGroup == null) { currentFamilyGroup = CreateFamilyGroup(row[FamilyName], rowFamilyKey); newFamilyList.Add(currentFamilyGroup); newFamilies++; } else { lookupContext.Groups.Attach(currentFamilyGroup); lookupContext.Entry(currentFamilyGroup).State = EntityState.Modified; } currentFamilyGroup.Members.Add(groupMember); } else { // person is part of this family group, check if they're a visitor if (isFamilyRelationship || currentFamilyGroup.Members.Count() < 1) { currentFamilyGroup.Members.Add(groupMember); } else { var visitorFamily = CreateFamilyGroup(person.LastName + " Family", rowFamilyKey); visitorFamily.Members.Add(groupMember); newFamilyList.Add(visitorFamily); newVisitorList.Add(visitorFamily); newFamilies++; } } // look ahead 1 row var rowNextFamilyKey = "-1"; if ((row = csvData.Database.FirstOrDefault()) != null) { rowNextFamilyKey = row[FamilyId]; } newPeople++; completed++; if (completed % (ReportingNumber * 10) < 1) { ReportProgress(0, string.Format("{0:N0} people processed.", completed)); } if (newPeople >= ReportingNumber && rowNextFamilyKey != currentFamilyGroup.ForeignKey) { SaveIndividuals(newFamilyList, newVisitorList, newNoteList); lookupContext.SaveChanges(); ReportPartialProgress(); // Clear out variables currentFamilyGroup = new Group(); newFamilyList.Clear(); newVisitorList.Clear(); newNoteList.Clear(); newPeople = 0; } } else { row = csvData.Database.FirstOrDefault(); } } // Save any changes to new families if (newFamilyList.Any()) { SaveIndividuals(newFamilyList, newVisitorList, newNoteList); } // Save any changes to existing families lookupContext.SaveChanges(); DetachAllInContext(lookupContext); lookupContext.Dispose(); ReportProgress(0, string.Format("Finished individual import: {0:N0} families and {1:N0} people added.", newFamilies, completed)); return(completed); }
/// <summary> /// Renders the base control. /// </summary> /// <param name="writer">The writer.</param> public void RenderBaseControl(HtmlTextWriter writer) { string cssClass = this.CssClass; writer.AddAttribute(HtmlTextWriterAttribute.Class, "input-group phone-number-box" + cssClass); if (this.Style[HtmlTextWriterStyle.Display] == "none") { // render the display:none in the inputgroup div instead of the control itself writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "none"); this.Style[HtmlTextWriterStyle.Display] = string.Empty; } writer.RenderBeginTag(HtmlTextWriterTag.Div); this.CssClass = string.Empty; bool renderCountryCodeButton = false; var definedType = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.COMMUNICATION_PHONE_COUNTRY_CODE.AsGuid()); if (definedType != null) { var countryCodes = definedType.DefinedValues.OrderBy(v => v.Order).Select(v => v.Value).Distinct(); if (countryCodes != null && countryCodes.Any()) { if (string.IsNullOrWhiteSpace(CountryCode)) { CountryCode = countryCodes.FirstOrDefault(); } if (countryCodes.Count() > 1) { renderCountryCodeButton = true; writer.AddAttribute(HtmlTextWriterAttribute.Class, "input-group-btn"); writer.RenderBeginTag(HtmlTextWriterTag.Div); writer.AddAttribute(HtmlTextWriterAttribute.Class, "btn btn-default dropdown-toggle"); writer.AddAttribute(HtmlTextWriterAttribute.Type, "button"); writer.AddAttribute("data-toggle", "dropdown"); writer.RenderBeginTag(HtmlTextWriterTag.Button); writer.Write(CountryCode + " "); writer.AddAttribute(HtmlTextWriterAttribute.Class, "caret"); writer.RenderBeginTag(HtmlTextWriterTag.Span); writer.RenderEndTag(); writer.RenderEndTag(); // Button writer.AddAttribute(HtmlTextWriterAttribute.Class, "dropdown-menu"); writer.RenderBeginTag(HtmlTextWriterTag.Ul); foreach (string countryCode in countryCodes) { writer.RenderBeginTag(HtmlTextWriterTag.Li); writer.AddAttribute(HtmlTextWriterAttribute.Href, "#"); writer.RenderBeginTag(HtmlTextWriterTag.A); writer.Write(countryCode); writer.RenderEndTag(); writer.RenderEndTag(); // Li } writer.RenderEndTag(); // Ul writer.RenderEndTag(); // div.input-group-btn } } } if (!renderCountryCodeButton) { writer.AddAttribute(HtmlTextWriterAttribute.Class, "input-group-addon"); writer.RenderBeginTag(HtmlTextWriterTag.Span); writer.Write("<i class='fa fa-phone-square'></i>"); writer.RenderEndTag(); } _hfCountryCode.RenderControl(writer); ((WebControl)this).AddCssClass("form-control"); if (!string.IsNullOrWhiteSpace(Placeholder)) { this.Attributes["placeholder"] = Placeholder; } this.Attributes["type"] = "tel"; base.RenderControl(writer); writer.RenderEndTag(); // div.input-group this.CssClass = cssClass; }
/// <summary> /// Updates any Cache Objects that are associated with this entity /// </summary> /// <param name="entityState">State of the entity.</param> /// <param name="dbContext">The database context.</param> public void UpdateCache(System.Data.Entity.EntityState entityState, Rock.Data.DbContext dbContext) { AttributeCache.UpdateCachedEntity(this.Id, entityState); AttributeCache.UpdateCacheEntityAttributes(this, entityState); int? entityTypeId; string entityTypeQualifierColumn; string entityTypeQualifierValue; if (entityState == System.Data.Entity.EntityState.Deleted) { entityTypeId = originalEntityTypeId; entityTypeQualifierColumn = originalEntityTypeQualifierColumn; entityTypeQualifierValue = originalEntityTypeQualifierValue; } else { entityTypeId = this.EntityTypeId; entityTypeQualifierColumn = this.EntityTypeQualifierColumn; entityTypeQualifierValue = this.EntityTypeQualifierValue; } if ((!entityTypeId.HasValue || entityTypeId.Value == 0) && string.IsNullOrEmpty(entityTypeQualifierColumn) && string.IsNullOrEmpty(entityTypeQualifierValue)) { GlobalAttributesCache.Remove(); } if ((!entityTypeId.HasValue || entityTypeId.Value == 0) && entityTypeQualifierColumn == Attribute.SYSTEM_SETTING_QUALIFIER && string.IsNullOrEmpty(entityTypeQualifierValue)) { if (entityState != System.Data.Entity.EntityState.Modified) { // if a SystemSettings was Added or Removed, flush the SystemSettings cache (if it was only modified, it'll will point to the updated AttributeCache value) Rock.Web.SystemSettings.Remove(); } } if (entityTypeId.HasValue) { if (entityTypeId == EntityTypeCache.GetId <Block>()) { // Update BlockTypes/Blocks that reference this attribute if (entityTypeQualifierColumn.Equals("BlockTypeId", StringComparison.OrdinalIgnoreCase)) { int?blockTypeId = entityTypeQualifierValue.AsIntegerOrNull(); if (blockTypeId.HasValue) { BlockTypeCache.FlushItem(blockTypeId.Value); foreach (var blockId in new BlockService(dbContext as RockContext).GetByBlockTypeId(blockTypeId.Value).Select(a => a.Id).ToList()) { BlockCache.FlushItem(blockId); } } } } else if (entityTypeId == EntityTypeCache.GetId <DefinedValue>()) { // Update DefinedTypes/DefinedValues that reference this attribute if (entityTypeQualifierColumn.Equals("DefinedTypeId", StringComparison.OrdinalIgnoreCase)) { int?definedTypeId = entityTypeQualifierValue.AsIntegerOrNull(); if (definedTypeId.HasValue) { DefinedTypeCache.FlushItem(definedTypeId.Value); foreach (var definedValueId in new DefinedValueService(dbContext as RockContext).GetByDefinedTypeId(definedTypeId.Value).Select(a => a.Id).ToList()) { DefinedValueCache.FlushItem(definedValueId); } } } } else if (entityTypeId == EntityTypeCache.GetId <WorkflowActivityType>()) { if (entityTypeQualifierColumn.Equals("ActivityTypeId", StringComparison.OrdinalIgnoreCase)) { int?activityTypeId = entityTypeQualifierValue.AsIntegerOrNull(); if (activityTypeId.HasValue) { WorkflowActivityTypeCache.FlushItem(activityTypeId.Value); } } } else if (entityTypeId == EntityTypeCache.GetId <GroupType>()) { if (entityTypeQualifierColumn.Equals("Id", StringComparison.OrdinalIgnoreCase)) { int?groupTypeId = entityTypeQualifierValue.AsIntegerOrNull(); if (groupTypeId.HasValue) { GroupTypeCache.FlushItem(groupTypeId.Value); } } } else if (entityTypeId.HasValue) { // some other EntityType. If it the EntityType has a CacheItem associated with it, clear out all the CachedItems of that type to ensure they have a clean read of the Attributes that were Added, Changed or Removed EntityTypeCache entityType = EntityTypeCache.Get(entityTypeId.Value, dbContext as RockContext); if (entityType?.HasEntityCache() == true) { entityType.ClearCachedItems(); } } } }
void gPeople_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { var person = e.Row.DataItem as PersonSearchResult; if (person != null) { if (_inactiveStatus != null && person.RecordStatusValueId.HasValue && person.RecordStatusValueId.Value == _inactiveStatus.Id) { e.Row.AddCssClass("inactive"); } if (person.IsDeceased) { e.Row.AddCssClass("deceased"); } string delimitedCampuses = string.Empty; if (person.CampusIds.Any()) { var campuses = new List <string>(); foreach (var campusId in person.CampusIds) { var campus = CampusCache.Get(campusId); if (campus != null) { campuses.Add(campus.Name); } } if (campuses.Any()) { delimitedCampuses = campuses.AsDelimited(", "); var lCampus = e.Row.FindControl("lCampus") as Literal; if (lCampus != null) { lCampus.Text = delimitedCampuses; } } } var lPerson = e.Row.FindControl("lPerson") as Literal; if (!person.IsBusiness) { StringBuilder sbPersonDetails = new StringBuilder(); sbPersonDetails.Append(string.Format("<div class=\"photo-round photo-round-sm pull-left\" data-original=\"{0}&w=100\" style=\"background-image: url('{1}');\"></div>", person.PhotoUrl, ResolveUrl("~/Assets/Images/person-no-photo-unknown.svg"))); sbPersonDetails.Append("<div class=\"pull-left margin-l-sm\">"); sbPersonDetails.Append(string.Format("<strong>{0}</strong> ", person.FullNameReversed)); sbPersonDetails.Append(string.Format("{0} ", Person.GetSignalMarkup(person.TopSignalColor, person.TopSignalIconCssClass))); sbPersonDetails.Append(string.Format("<small class=\"hidden-sm hidden-md hidden-lg\"><br>{0}<br></small>", delimitedCampuses)); sbPersonDetails.Append(string.Format("<small class=\"hidden-sm hidden-md hidden-lg\">{0}</small>", DefinedValueCache.GetName(person.ConnectionStatusValueId))); sbPersonDetails.Append(string.Format(" <small class=\"hidden-md hidden-lg\">{0}</small>", person.AgeFormatted)); foreach (Guid phGuid in _phoneTypeGuids) { var dv = DefinedValueCache.Get(phGuid); if (dv != null) { var pn = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == dv.Id); if (pn != null) { sbPersonDetails.Append(string.Format("<br/><small>{0}: {1}</small>", dv.Value.Left(1).ToUpper(), pn.Number)); } } } if (!string.IsNullOrWhiteSpace(person.Email)) { sbPersonDetails.Append(string.Format("<br/><small>{0}</small>", person.Email)); } // add home addresses foreach (var location in person.HomeAddresses) { if (string.IsNullOrWhiteSpace(location.Street1) && string.IsNullOrWhiteSpace(location.Street2) && string.IsNullOrWhiteSpace(location.City)) { continue; } string format = string.Empty; var countryValue = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.LOCATION_COUNTRIES.AsGuid()) .DefinedValues .Where(v => v.Value.Equals(location.Country, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (countryValue != null) { format = countryValue.GetAttributeValue("AddressFormat"); } if (!string.IsNullOrWhiteSpace(format)) { var dict = location.ToDictionary(); dict["Country"] = countryValue.Description; sbPersonDetails.Append(string.Format("<small><br>{0}</small>", format.ResolveMergeFields(dict).ConvertCrLfToHtmlBr().Replace("<br><br>", "<br>"))); } else { sbPersonDetails.Append(string.Format(string.Format("<small><br>{0}<br>{1} {2}, {3} {4}</small>", location.Street1, location.Street2, location.City, location.State, location.PostalCode))); } } sbPersonDetails.Append("</div>"); lPerson.Text = sbPersonDetails.ToString(); if (_showSpouse) { using (var rockContext = new RockContext()) { var personRec = new PersonService(rockContext).Get(person.Id); if (personRec != null) { var lSpouse = e.Row.FindControl("lSpouse") as Literal; var spouse = personRec.GetSpouse(rockContext); if (lSpouse != null && spouse != null) { lSpouse.Text = spouse.FullName; } } } } if (_envelopeNumbers != null && _envelopeNumbers.ContainsKey(person.Id)) { var lEnvelopeNumber = e.Row.FindControl("lEnvelopeNumber") as Literal; if (lEnvelopeNumber != null) { lEnvelopeNumber.Text = _envelopeNumbers[person.Id]; } } } else { lPerson.Text = string.Format("{0}", person.LastName); } } } }
/// <summary> /// Shows the view. /// </summary> private void ShowForm() { lReceipt.Visible = false; pnlAddPledge.Visible = true; if (CurrentPerson != null) { lName.Text = CurrentPerson.FullName; lName.Visible = true; tbFirstName.Visible = false; tbLastName.Visible = false; tbEmail.Visible = false; using (var rockContext = new RockContext()) { Guid?groupTypeGuid = GetAttributeValue("SelectGroupType").AsGuidOrNull(); if (groupTypeGuid.HasValue) { var groups = new GroupMemberService(rockContext) .Queryable().AsNoTracking() .Where(m => m.Group.GroupType.Guid == groupTypeGuid.Value && m.PersonId == CurrentPerson.Id && m.GroupMemberStatus == GroupMemberStatus.Active && m.Group.IsActive) .Select(m => new { m.GroupId, Name = m.Group.Name, GroupTypeName = m.Group.GroupType.Name }) .ToList() .Distinct() .OrderBy(g => g.Name) .ToList(); if (groups.Any()) { ddlGroup.Label = "For " + groups.First().GroupTypeName; ddlGroup.DataSource = groups; ddlGroup.DataBind(); ddlGroup.Visible = true; } else { ddlGroup.Visible = false; } } else { ddlGroup.Visible = false; } } } else { lName.Visible = false; ddlGroup.Visible = false; tbFirstName.Visible = true; tbLastName.Visible = true; tbEmail.Visible = true; tbFirstName.Text = string.Empty; tbLastName.Text = string.Empty; tbEmail.Text = string.Empty; } // Warn if Financial Account is not specified (must be set up by administrator) var financialAccount = new FinancialAccountService(new RockContext()).Get(GetAttributeValue("Account").AsGuid()); if (financialAccount == null) { nbWarningMessage.Text = "Warning: No Account is specified for this pledge. Please contact the administrator."; nbWarningMessage.Visible = true; } else { nbWarningMessage.Visible = false; } drpDateRange.DelimitedValues = GetAttributeValue("PledgeDateRange"); // only show the date range picker if the block setting for date range isn't fully specified drpDateRange.Visible = drpDateRange.LowerValue == null || drpDateRange.UpperValue == null; ddlFrequency.Items.Clear(); var frequencies = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.FINANCIAL_FREQUENCY.AsGuid()).DefinedValues.OrderBy(a => a.Order).ThenBy(a => a.Value); foreach (var frequency in frequencies) { ddlFrequency.Items.Add(new ListItem(frequency.Value, frequency.Id.ToString())); } ddlFrequency.Visible = GetAttributeValue("ShowPledgeFrequency").AsBooleanOrNull() ?? false; ddlFrequency.SelectedValue = null; // if Frequency is Visible, require it if RequirePledgeFrequency ddlFrequency.Required = ddlFrequency.Visible && (GetAttributeValue("RequirePledgeFrequency").AsBooleanOrNull() ?? false); string saveButtonText = GetAttributeValue("SaveButtonText"); if (!string.IsNullOrWhiteSpace(saveButtonText)) { btnSave.Text = saveButtonText; } else { btnSave.Text = "Save"; } lNote.Text = GetAttributeValue("NoteMessage"); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { phSummary.Controls.Clear(); rFilter.Visible = true; gList.Visible = true; RockContext rockContext = new RockContext(); BenevolenceRequestService benevolenceRequestService = new BenevolenceRequestService(rockContext); var qry = benevolenceRequestService.Queryable("BenevolenceResults,RequestedByPersonAlias,RequestedByPersonAlias.Person,CaseWorkerPersonAlias,CaseWorkerPersonAlias.Person").AsNoTracking(); // Filter by Start Date DateTime?startDate = drpDate.LowerValue; if (startDate != null) { qry = qry.Where(b => b.RequestDateTime >= startDate); } // Filter by End Date DateTime?endDate = drpDate.UpperValue; if (endDate != null) { qry = qry.Where(b => b.RequestDateTime <= endDate); } // Filter by Campus if (cpCampus.SelectedCampusId.HasValue) { qry = qry.Where(b => b.CampusId == cpCampus.SelectedCampusId); } if (TargetPerson != null) { // show benevolence request for the target person and also for their family members var qryFamilyMembers = TargetPerson.GetFamilyMembers(true, rockContext); qry = qry.Where(a => a.RequestedByPersonAliasId.HasValue && qryFamilyMembers.Any(b => b.PersonId == a.RequestedByPersonAlias.PersonId)); } else { // Filter by First Name string firstName = tbFirstName.Text; if (!string.IsNullOrWhiteSpace(firstName)) { qry = qry.Where(b => b.FirstName.StartsWith(firstName)); } // Filter by Last Name string lastName = tbLastName.Text; if (!string.IsNullOrWhiteSpace(lastName)) { qry = qry.Where(b => b.LastName.StartsWith(lastName)); } } // Filter by Government Id string governmentId = tbGovernmentId.Text; if (!string.IsNullOrWhiteSpace(governmentId)) { qry = qry.Where(b => b.GovernmentId.StartsWith(governmentId)); } // Filter by Case Worker int?caseWorkerPersonAliasId = ddlCaseWorker.SelectedItem.Value.AsIntegerOrNull(); if (caseWorkerPersonAliasId != null) { qry = qry.Where(b => b.CaseWorkerPersonAliasId == caseWorkerPersonAliasId); } // Filter by Result int?resultTypeValueId = dvpResult.SelectedItem.Value.AsIntegerOrNull(); if (resultTypeValueId != null) { qry = qry.Where(b => b.BenevolenceResults.Where(r => r.ResultTypeValueId == resultTypeValueId).Count() > 0); } // Filter by Request Status int?requestStatusValueId = dvpStatus.SelectedItem.Value.AsIntegerOrNull(); if (requestStatusValueId != null) { qry = qry.Where(b => b.RequestStatusValueId == requestStatusValueId); } SortProperty sortProperty = gList.SortProperty; if (sortProperty != null) { if (sortProperty.Property == "TotalAmount") { if (sortProperty.Direction == SortDirection.Descending) { qry = qry.OrderByDescending(a => a.BenevolenceResults.Sum(b => b.Amount)); } else { qry = qry.OrderBy(a => a.BenevolenceResults.Sum(b => b.Amount)); } } else { qry = qry.Sort(sortProperty); } } else { qry = qry.OrderByDescending(a => a.RequestDateTime).ThenByDescending(a => a.Id); } // Filter query by any configured attribute filters if (AvailableAttributes != null && AvailableAttributes.Any()) { foreach (var attribute in AvailableAttributes) { var filterControl = phAttributeFilters.FindControl("filter_" + attribute.Id.ToString()); qry = attribute.FieldType.Field.ApplyAttributeQueryFilter(qry, filterControl, attribute, benevolenceRequestService, Rock.Reporting.FilterMode.SimpleFilter); } } var list = qry.ToList(); gList.DataSource = list; gList.DataBind(); // Hide the campus column if the campus filter is not visible. gList.ColumnsOfType <RockBoundField>().First(c => c.DataField == "Campus.Name").Visible = cpCampus.Visible; // Builds the Totals section var definedTypeCache = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.BENEVOLENCE_RESULT_TYPE)); Dictionary <string, decimal> resultTotals = new Dictionary <string, decimal>(); decimal grandTotal = 0; foreach (BenevolenceRequest request in list) { foreach (BenevolenceResult result in request.BenevolenceResults) { if (result.Amount != null) { if (resultTotals.ContainsKey(result.ResultTypeValue.Value)) { resultTotals[result.ResultTypeValue.Value] += result.Amount.Value; } else { resultTotals.Add(result.ResultTypeValue.Value, result.Amount.Value); } grandTotal += result.Amount.Value; } } } foreach (KeyValuePair <string, decimal> keyValuePair in resultTotals) { phSummary.Controls.Add(new LiteralControl(string.Format("<div class='row'><div class='col-xs-8'>{0}: </div><div class='col-xs-4 text-right'>{1}{2:#,##0.00}</div></div>", keyValuePair.Key, GlobalAttributesCache.Value("CurrencySymbol"), keyValuePair.Value))); } phSummary.Controls.Add(new LiteralControl(string.Format("<div class='row'><div class='col-xs-8'><b>Total: </div><div class='col-xs-4 text-right'>{0}{1:#,##0.00}</b></div></div>", GlobalAttributesCache.Value("CurrencySymbol"), grandTotal))); }
/// <summary> /// Binds the states. /// </summary> /// <param name="country">The country.</param> private void BindStates(string country) { if (country.IsNullOrWhiteSpace()) { country = GetDefaultCountry(); } string countryGuid = DefinedTypeCache.Get(new Guid(SystemGuid.DefinedType.LOCATION_COUNTRIES)) .DefinedValues .Where(v => v.Value.Equals(country, StringComparison.OrdinalIgnoreCase)) .Select(v => v.Guid) .FirstOrDefault() .ToString(); var definedType = DefinedTypeCache.Get(new Guid(SystemGuid.DefinedType.LOCATION_ADDRESS_STATE)); var stateList = definedType .DefinedValues .Where(v => ( v.AttributeValues.ContainsKey("Country") && v.AttributeValues["Country"] != null && v.AttributeValues["Country"].Value.Equals(countryGuid, StringComparison.OrdinalIgnoreCase) ) || ( (!v.AttributeValues.ContainsKey("Country") || v.AttributeValues["Country"] == null) && v.Attributes.ContainsKey("Country") && v.Attributes["Country"].DefaultValue.Equals(countryGuid, StringComparison.OrdinalIgnoreCase) )) .OrderBy(v => v.Order) .ThenBy(v => v.Value) .Select(v => new { Id = v.Value, Value = v.Description }) .ToList(); if (stateList.Any()) { HasStateList = true; _ddlState.Visible = true; _tbState.Visible = false; string currentValue = _ddlState.SelectedValue; _ddlState.Items.Clear(); _ddlState.SelectedIndex = -1; _ddlState.SelectedValue = null; _ddlState.ClearSelection(); _ddlState.DataTextField = UseStateAbbreviation ? "Id" : "Value"; _ddlState.DataSource = stateList; _ddlState.DataBind(); if (!string.IsNullOrWhiteSpace(currentValue)) { _ddlState.SetValue(currentValue, GetDefaultState()); } } else { HasStateList = false; _ddlState.Visible = false; _tbState.Visible = true; } }
public IQueryable <NursingHomeRow> GetQuery(RockContext rockContext) { var contextEntity = this.ContextEntity(); var workflowService = new WorkflowService(rockContext); var workflowActivityService = new WorkflowActivityService(rockContext); var attributeService = new AttributeService(rockContext); var attributeValueService = new AttributeValueService(rockContext); var personAliasService = new PersonAliasService(rockContext); var definedValueService = new DefinedValueService(rockContext); var entityTypeService = new EntityTypeService(rockContext); var groupMemberService = new GroupMemberService(rockContext); var groupService = new GroupService(rockContext); Guid nursingHomeAdmissionWorkflow = GetAttributeValue("NursingHomeResidentWorkflow").AsGuid(); Guid nursingHomeList = GetAttributeValue("NursingHomeList").AsGuid(); Guid volunteerGroup = GetAttributeValue("VolunteerGroup").AsGuid(); Group groupId = new Group(); List <DefinedValueCache> facilities = DefinedTypeCache.Get(nursingHomeList).DefinedValues; Dictionary <Guid, string> volunteerList = new Dictionary <Guid, string>(); groupId = groupService.GetByGuid(volunteerGroup); var groupMemberEntityTypeId = EntityTypeCache.Get(typeof(GroupMember)).Id; var groupMemberAttributeQry = attributeService.Queryable() .Where(a => a.EntityTypeId == groupMemberEntityTypeId) .Select(a => a.Id); var groupMemberAttributeValueQry = attributeValueService.Queryable() .Where(av => groupMemberAttributeQry.Contains(av.AttributeId)); if (groupId.IsNotNull()) { var groupMemberList = groupMemberService.Queryable() .Where(a => a.GroupId == groupId.Id && a.GroupMemberStatus == GroupMemberStatus.Active) .GroupJoin(groupMemberAttributeValueQry, gm => gm.Id, av => av.EntityId, (gm, av) => new { GroupMember = gm, GroupMemberAttributeValues = av }) .ToList(); var groupMembers = new List <GroupMember>(); foreach (var set in groupMemberList) { var groupMember = set.GroupMember; groupMember.Attributes = set.GroupMemberAttributeValues .ToDictionary(av => av.AttributeKey, av => AttributeCache.Get(av.AttributeId)); groupMember.AttributeValues = set.GroupMemberAttributeValues .ToDictionary(av => av.AttributeKey, av => new AttributeValueCache(av)); groupMembers.Add(groupMember); } foreach (var nursingHome in facilities) { foreach (var groupMember in groupMembers) { if (groupMember.GetAttributeValue("NursingHomes").IsNotNullOrWhiteSpace()) { if (groupMember.GetAttributeValue("NursingHomes").ToLower().Contains(nursingHome.Guid.ToString().ToLower())) { if (volunteerList.ContainsKey(nursingHome.Guid)) { volunteerList[nursingHome.Guid] = volunteerList[nursingHome.Guid] + ", " + groupMember.EntityStringValue; } else { volunteerList.Add(nursingHome.Guid, groupMember.EntityStringValue); } } } } } } int entityTypeId = entityTypeService.Queryable().Where(et => et.Name == typeof(Workflow).FullName).FirstOrDefault().Id; string status = (contextEntity != null ? "Completed" : "Active"); var workflowType = new WorkflowTypeService(rockContext).Get(nursingHomeAdmissionWorkflow); var workflowTypeIdAsString = workflowType.Id.ToString(); var attributeIds = attributeService.Queryable() .Where(a => a.EntityTypeQualifierColumn == "WorkflowTypeId" && a.EntityTypeQualifierValue == workflowTypeIdAsString) .Select(a => a.Id).ToList(); // Look up the activity type for "Visitation" var visitationActivityIdAsString = workflowType.ActivityTypes.Where(at => at.Name == "Visitation Info").Select(at => at.Id.ToString()).FirstOrDefault(); var activityAttributeIds = attributeService.Queryable() .Where(a => a.EntityTypeQualifierColumn == "ActivityTypeId" && a.EntityTypeQualifierValue == visitationActivityIdAsString) .Select(a => a.Id).ToList(); var wfTmpqry = workflowService.Queryable().AsNoTracking() .Where(w => (w.WorkflowType.Guid == nursingHomeAdmissionWorkflow) && (w.Status == "Active" || w.Status == status)); var visitQry = workflowActivityService.Queryable() .Join( attributeValueService.Queryable(), wa => wa.Id, av => av.EntityId.Value, (wa, av) => new { WorkflowActivity = wa, AttributeValue = av }) .Where(a => activityAttributeIds.Contains(a.AttributeValue.AttributeId)) .GroupBy(wa => wa.WorkflowActivity) .Select(obj => new { WorkflowActivity = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) }); if (contextEntity != null) { var personGuid = (( Person )contextEntity).Aliases.Select(a => a.Guid.ToString()).ToList(); var validWorkflowIds = new AttributeValueService(rockContext).Queryable() .Where(av => av.Attribute.Key == "PersonToVisit" && personGuid.Contains(av.Value)).Select(av => av.EntityId); wfTmpqry = wfTmpqry.Where(w => validWorkflowIds.Contains(w.Id)); visitQry = visitQry.Where(w => validWorkflowIds.Contains(w.WorkflowActivity.WorkflowId)); gReport.Columns[10].Visible = true; } var visits = visitQry.ToList(); var workflows = wfTmpqry.Join( attributeValueService.Queryable(), obj => obj.Id, av => av.EntityId.Value, (obj, av) => new { Workflow = obj, AttributeValue = av }) .Where(a => attributeIds.Contains(a.AttributeValue.AttributeId)) .GroupBy(obj => obj.Workflow) .Select(obj => new { Workflow = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) }) .ToList(); var qry = workflows.AsQueryable().GroupJoin(visits.AsQueryable(), wf => wf.Workflow.Id, wa => wa.WorkflowActivity.WorkflowId, (Workflow, wa) => new { Workflow = Workflow, WorkflowActivities = wa }) .Select(obj => new { Workflow = obj.Workflow.Workflow, AttributeValues = obj.Workflow.AttributeValues, VisitationActivities = obj.WorkflowActivities }).ToList(); if (contextEntity == null) { // Make sure they aren't deceased qry = qry.AsQueryable().Where(w => ! (personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()) != null ? personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()).Person.IsDeceased : false)).ToList(); } var newQry = qry.Select(w => new NursingHomeRow { Id = w.Workflow.Id, Workflow = w.Workflow, NursingHome = new Func <string>(() => { if (w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).Any()) { return(facilities.Where(h => h.Guid == w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid()).Select(dv => dv.Value).FirstOrDefault()); } return("N/A"); })(), Person = new Func <Person>(() => { AttributeValue personAliasAV = w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").FirstOrDefault(); if (personAliasAV != null) { PersonAlias pa = personAliasService.Get(personAliasAV.Value.AsGuid()); return(pa != null ? pa.Person : new Person()); } return(new Person()); })(), Address = new Func <string>(() => { DefinedValueCache dv = facilities.Where(h => h.Guid == w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid()).FirstOrDefault(); if (dv != null) { return(dv.AttributeValues["Qualifier1"].ValueFormatted + " " + dv.AttributeValues["Qualifier2"].ValueFormatted + " " + dv.AttributeValues["Qualifier3"].ValueFormatted + ", " + dv.AttributeValues["Qualifier4"].ValueFormatted); } return(""); })(), PastoralMinister = new Func <string>(() => { DefinedValueCache dv = facilities.Where(h => h.Guid == w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid()).FirstOrDefault(); if (dv != null && (dv.AttributeValues.ContainsKey("PastoralMinister") || dv.AttributeValues.ContainsKey("Qualifier6"))) { return(dv.AttributeValues.ContainsKey("PastoralMinister") ? dv.AttributeValues["PastoralMinister"].ValueFormatted : dv.AttributeValues["Qualifier6"].ValueFormatted); } return(""); })(), Volunteers = new Func <string>(() => { String vList = ""; if (volunteerList.TryGetValue(w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid(), out vList)) { return(vList); } else { return(""); } })(), Room = w.AttributeValues.Where(av => av.AttributeKey == "Room").Select(av => av.ValueFormatted).FirstOrDefault(), AdmitDate = w.AttributeValues.Where(av => av.AttributeKey == "AdmitDate").Select(av => av.ValueAsDateTime).FirstOrDefault(), Description = w.AttributeValues.Where(av => av.AttributeKey == "VisitationRequestDescription").Select(av => av.ValueFormatted).FirstOrDefault(), Visits = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Count(), LastVisitor = new Func <string>(() => { var visitor = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "Visitor").LastOrDefault()).LastOrDefault(); if (visitor != null) { return(visitor.ValueFormatted); } return("N/A"); })(), LastVisitDate = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitDate").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(), LastVisitNotes = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitNote").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(), DischargeDate = w.AttributeValues.Where(av => av.AttributeKey == "DischargeDate").Select(av => av.ValueFormatted).FirstOrDefault(), Status = w.Workflow.Status, Communion = w.AttributeValues.Where(av => av.AttributeKey == "Communion").Select(av => av.ValueFormatted).FirstOrDefault(), Actions = "" }).ToList().AsQueryable().OrderBy(p => p.NursingHome).ThenBy(p => p.Person.FullName); return(newQry); }
/// <summary> /// Updates any Cache Objects that are associated with this entity /// </summary> /// <param name="entityState">State of the entity.</param> /// <param name="dbContext">The database context.</param> public void UpdateCache(EntityState entityState, Rock.Data.DbContext dbContext) { DefinedValueCache.UpdateCachedEntity(this.Id, entityState); DefinedTypeCache.Get(this.DefinedTypeId, (RockContext)dbContext)?.ReloadDefinedValues(); }
public static IEnumerable <Person> GetByMatch(this PersonService personService, String firstName, String lastName, DateTime?birthDate, String email = null, String phone = null, String street1 = null, String postalCode = null) { using (Rock.Data.RockContext context = new Rock.Data.RockContext()) { LocationService locationService = new LocationService(context); AttributeValueService attributeValueService = new AttributeValueService(context); List <AttributeValue> attributeValues = attributeValueService.GetByAttributeId(AttributeCache.Read(GOES_BY_ATTRIBUTE.AsGuid()).Id).ToList(); var diminutiveName = DefinedTypeCache.Read(DIMINUTIVE_NAMES.AsGuid()); firstName = firstName ?? string.Empty; lastName = lastName ?? string.Empty; email = email.ToLower() ?? string.Empty; phone = phone ?? string.Empty; List <Person> matchingPersons = new List <Person>(); // Do a quick check to see if we get a match right up front List <Person> persons = new List <Person>(); if (birthDate.HasValue || !string.IsNullOrEmpty(email)) { var fastQuery = personService.Queryable(false, false).Where(p => (p.FirstName.ToLower() == firstName.ToLower() || p.NickName.ToLower() == firstName.ToLower()) && p.LastName == lastName); if (birthDate.HasValue) { fastQuery = fastQuery.Where(p => p.BirthDate == birthDate); } if (!String.IsNullOrEmpty(email)) { fastQuery = fastQuery.Where(p => p.Email.ToLower() == email); } persons = fastQuery.ToList(); } // We have an exact match. Just be done. if (persons.Count == 1) { return(persons); } // Go ahead and do this more leniant search if we don't have an exact match already if (persons.Count != 1) { persons = personService.Queryable(false, false) .Where(p => p.LastName == lastName && (p.BirthDate == null || p.BirthDate.Value == birthDate.Value)) .ToList(); } // Check the address if it was passed Location location = new Location(); if (persons.Count() > 0 && !string.IsNullOrEmpty(street1) && !string.IsNullOrEmpty(postalCode)) { location.Street1 = street1; location.PostalCode = postalCode; locationService.Verify(location, true); } foreach (Person person in persons) { // Check to see if the phone exists anywhere in the family Boolean phoneExists = person.GetFamilies().Where(f => f.Members.Where(m => m.Person.PhoneNumbers.Where(pn => pn.Number == phone).Any()).Any()).Any(); // Check to see if the email exists anywhere in the family Boolean emailExists = person.GetFamilies().Where(f => f.Members.Where(m => m.Person.Email == email).Any()).Any(); Boolean addressMatches = false; // Check the address if it was passed if (!string.IsNullOrEmpty(street1) && !string.IsNullOrEmpty(postalCode)) { if (person.GetHomeLocation() != null) { if (person.GetHomeLocation().Street1 == street1) { addressMatches = true; } // If it doesn't match, we need to geocode it and check it again if (!addressMatches) { if (person.GetHomeLocation().Street1 == location.Street1) { addressMatches = true; } } } } // At least phone, email, or address have to match if (phoneExists || emailExists || addressMatches) { matchingPersons.Add(person); } } List <Person> firstNameMatchingPersons = new List <Person>(); // Now narrow down the list by looking for the first name (or diminutive name) foreach (Person matchingPerson in matchingPersons) { if (firstName != null && ((matchingPerson.FirstName != null && matchingPerson.FirstName.ToLower() != firstName.ToLower()) || (matchingPerson.NickName != null && matchingPerson.NickName.ToLower() != firstName.ToLower()))) { foreach (DefinedValueCache dv in diminutiveName.DefinedValues) { AttributeValue av = attributeValues.Where(av2 => av2.EntityId == dv.Id).FirstOrDefault(); List <string> nameList = new List <string>(); nameList = av.Value.Split('|').ToList(); nameList.Add(dv.Value); if (nameList.Contains(firstName.ToLower()) && (nameList.Contains(matchingPerson.FirstName.ToLower()) || nameList.Contains(matchingPerson.NickName.ToLower()))) { firstNameMatchingPersons.Add(matchingPerson); break; } } } else { firstNameMatchingPersons.Add(matchingPerson); } } return(firstNameMatchingPersons); } }