Exemplo n.º 1
0
        /// <summary>
        /// Sends a background request to Trak-1
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="workflow">The Workflow initiating the request.</param>
        /// <param name="personAttribute">The person attribute.</param>
        /// <param name="ssnAttribute">The SSN attribute.</param>
        /// <param name="requestTypeAttribute">The request type attribute.</param>
        /// <param name="billingCodeAttribute">The billing code attribute.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns>
        /// True/False value of whether the request was successfully sent or not
        /// </returns>
        /// <exception cref="System.NotImplementedException"></exception>
        /// <remarks>
        /// Note: If the associated workflow type does not have attributes with the following keys, they
        /// will automatically be added to the workflow type configuration in order to store the results
        /// of the background check request
        ///     RequestStatus:          The request status returned by request
        ///     RequestMessage:         Any error messages returned by request
        ///     ReportStatus:           The report status returned
        ///     ReportLink:             The location of the background report on server
        ///     ReportRecommendation:   Recomendataion
        ///     Report (BinaryFile):    The downloaded background report
        /// </remarks>
        public override bool SendRequest(RockContext rockContext, Rock.Model.Workflow workflow,
                                         AttributeCache personAttribute, AttributeCache ssnAttribute, AttributeCache requestTypeAttribute,
                                         AttributeCache billingCodeAttribute, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            try
            {
                // Check to make sure workflow is not null
                if (workflow == null)
                {
                    errorMessages.Add("Trak-1 background check provider requires a valid workflow.");
                    return(false);
                }

                // Get the person that the request is for
                Person person = null;
                if (personAttribute != null)
                {
                    Guid?personAliasGuid = workflow.GetAttributeValue(personAttribute.Key).AsGuidOrNull();
                    if (personAliasGuid.HasValue)
                    {
                        person = new PersonAliasService(rockContext).Queryable()
                                 .Where(p => p.Guid.Equals(personAliasGuid.Value))
                                 .Select(p => p.Person)
                                 .FirstOrDefault();
                        person.LoadAttributes(rockContext);
                    }
                }

                if (person == null)
                {
                    errorMessages.Add("Trak-1 background check provider requires the workflow to have a 'Person' attribute that contains the person who the background check is for.");
                    return(false);
                }

                //Get required fields from workflow
                var packageList = GetPackageList();
                var packageName = workflow.GetAttributeValue(requestTypeAttribute.Key);
                // If this is a defined value, fetch the value
                if (requestTypeAttribute.FieldType.Guid.ToString().ToUpper() == Rock.SystemGuid.FieldType.DEFINED_VALUE)
                {
                    packageName = DefinedValueCache.Get(packageName).Value;
                }
                var package = packageList.Where(p => p.PackageName == packageName).FirstOrDefault();
                if (package == null)
                {
                    errorMessages.Add("Package name not valid");
                    return(false);
                }

                var requiredFields     = package.Components.SelectMany(c => c.RequiredFields).ToList();
                var requiredFieldsDict = new Dictionary <string, string>();
                foreach (var field in requiredFields)
                {
                    if (!workflow.Attributes.ContainsKey(field.Name))
                    {
                        errorMessages.Add("Workflow does not contain attribute for required field " + field.Name);
                        return(false);
                    }
                    requiredFieldsDict[field.Name] = workflow.GetAttributeValue(field.Name);
                }


                //Generate Request
                var authentication = new Trak1Authentication
                {
                    UserName       = GetAttributeValue("UserName"),
                    SubscriberCode = Encryption.DecryptString(GetAttributeValue("SubscriberCode")),
                    CompanyCode    = Encryption.DecryptString(GetAttributeValue("CompanyCode")),
                    BranchName     = "Main"
                };

                var ssn = "";
                if (ssnAttribute != null)
                {
                    ssn = Rock.Field.Types.SSNFieldType.UnencryptAndClean(workflow.GetAttributeValue(ssnAttribute.Key));
                    if (!string.IsNullOrWhiteSpace(ssn) && ssn.Length == 9)
                    {
                        ssn = ssn.Insert(5, "-").Insert(3, "-");
                    }
                }

                Location homeLocation = null;

                var homeAddressDv = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME);
                foreach (var family in person.GetFamilies(rockContext))
                {
                    var loc = family.GroupLocations
                              .Where(l =>
                                     l.GroupLocationTypeValueId == homeAddressDv.Id)
                              .Select(l => l.Location)
                              .FirstOrDefault();
                    if (loc != null)
                    {
                        homeLocation = loc;
                    }
                }

                if (homeLocation == null)
                {
                    errorMessages.Add("A valid home location to submit a Trak-1 background check.");
                    return(false);
                }

                var applicant = new Trak1Applicant
                {
                    SSN            = ssn,
                    FirstName      = person.FirstName,
                    MiddleName     = person.MiddleName,
                    LastName       = person.LastName,
                    DateOfBirth    = (person.BirthDate ?? new DateTime()).ToString("yyyy-MM-dd"),
                    Address1       = homeLocation.Street1,
                    Address2       = homeLocation.Street2,
                    City           = homeLocation.City,
                    State          = homeLocation.State,
                    Zip            = homeLocation.PostalCode,
                    RequiredFields = requiredFieldsDict
                };

                var request = new Trak1Request
                {
                    Authentication = authentication,
                    Applicant      = applicant,
                    PackageName    = packageName
                };


                var content = JsonConvert.SerializeObject(request);

                Trak1Response response = null;

                using (var client = new HttpClient(new HttpClientHandler()))
                {
                    client.BaseAddress = new Uri(GetAttributeValue("RequestURL"));
                    var clientResponse = client.PostAsync("", new StringContent(content, Encoding.UTF8, "application/json")).Result.Content.ReadAsStringAsync().Result;
                    response = JsonConvert.DeserializeObject <Trak1Response>(clientResponse);
                }

                if (!string.IsNullOrWhiteSpace(response.Error?.Message))
                {
                    errorMessages.Add(response.Error.Message);
                    return(false);
                }

                var transactionId = response.TransactionId;


                int?personAliasId = person.PrimaryAliasId;

                if (personAliasId.HasValue)
                {
                    // Create a background check file
                    using (var newRockContext = new RockContext())
                    {
                        var backgroundCheckService = new BackgroundCheckService(newRockContext);
                        var backgroundCheck        = backgroundCheckService.Queryable()
                                                     .Where(c =>
                                                            c.WorkflowId.HasValue &&
                                                            c.WorkflowId.Value == workflow.Id)
                                                     .FirstOrDefault();

                        if (backgroundCheck == null)
                        {
                            backgroundCheck = new Rock.Model.BackgroundCheck();
                            backgroundCheck.PersonAliasId = personAliasId.Value;
                            backgroundCheck.WorkflowId    = workflow.Id;
                            backgroundCheckService.Add(backgroundCheck);
                        }

                        backgroundCheck.RequestDate = RockDateTime.Now;
                        backgroundCheck.RequestId   = transactionId.ToString();
                        backgroundCheck.PackageName = request.PackageName;
                        newRockContext.SaveChanges();
                    }
                }
                return(true);
            }

            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, null);
                errorMessages.Add(ex.Message);
                return(false);
            }
        }
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            if (_rockContext == null)
            {
                _rockContext = new RockContext();
            }

            if (_workflowService == null)
            {
                _workflowService = new WorkflowService(_rockContext);
            }
            var paramWorkflowId = PageParameter("WorkflowId");

            WorkflowId = paramWorkflowId.AsIntegerOrNull();
            if (!WorkflowId.HasValue)
            {
                Guid guid = PageParameter("WorkflowGuid").AsGuid();
                if (!guid.IsEmpty())
                {
                    _workflow = _workflowService.Queryable()
                                .Where(w => w.Guid.Equals(guid))
                                .FirstOrDefault();
                    if (_workflow != null)
                    {
                        WorkflowId = _workflow.Id;
                    }
                }
            }

            if (WorkflowId.HasValue)
            {
                if (_workflow == null)
                {
                    _workflow = _workflowService.Queryable()
                                .Where(w => w.Id == WorkflowId.Value)
                                .FirstOrDefault();
                }
                //-------------------------------
                if (_workflow != null)
                {
                    _workflow.LoadAttributes();
                }
            }

            if (_workflow != null)
            {
                if (_workflow.IsActive)
                {
                    int personId = CurrentPerson != null ? CurrentPerson.Id : 0;
                    foreach (var activity in _workflow.Activities
                             .Where(a =>
                                    a.IsActive &&
                                    (
                                        (!a.AssignedGroupId.HasValue && !a.AssignedPersonAliasId.HasValue) ||
                                        (a.AssignedPersonAlias != null && a.AssignedPersonAlias.PersonId == personId) ||
                                        (a.AssignedGroup != null && a.AssignedGroup.Members.Any(m => m.PersonId == personId))
                                    )
                                    )
                             .OrderBy(a => a.ActivityType.Order))
                    {
                        if ((activity.ActivityType.IsAuthorized(Authorization.VIEW, CurrentPerson)))
                        {
                            foreach (var action in activity.ActiveActions)
                            {
                                if (action.ActionType.WorkflowForm != null && action.IsCriteriaValid)
                                {
                                    _activity = activity;
                                    _activity.LoadAttributes(_rockContext);
                                }
                            }
                        }
                    }

                    if (_activity != null)
                    {
                        var entryPage = _workflow.GetAttributeValue("EntryFormPage");

                        if (!String.IsNullOrEmpty(entryPage))
                        {
                            var queryParams = new Dictionary <string, string>();
                            queryParams.Add("WorkflowTypeId", _activity.Workflow.WorkflowTypeId.ToString());
                            queryParams.Add("WorkflowId", _activity.WorkflowId.ToString());

                            var attrsToSend = GetAttributeValue("WorkflowAttributes");

                            if (!String.IsNullOrWhiteSpace(attrsToSend))
                            {
                                foreach (var attr in attrsToSend.Split(','))
                                {
                                    var attrName = attr.Trim();
                                    if (!String.IsNullOrEmpty(_activity.GetAttributeValue(attrName)))
                                    {
                                        queryParams.Add(attrName, _activity.GetAttributeValue(attrName));
                                    }
                                    else if (!String.IsNullOrEmpty(_activity.Workflow.GetAttributeValue(attrName)))
                                    {
                                        queryParams.Add(attrName, _activity.Workflow.GetAttributeValue(attrName));
                                    }
                                }
                            }

                            var pageReference = new Rock.Web.PageReference(entryPage, queryParams);

                            bool paramsDiffer = false;

                            foreach (var pair in queryParams)
                            {
                                if (pair.Value != PageParameter(pair.Key))
                                {
                                    paramsDiffer = true;
                                    break;
                                }
                            }

                            if (paramsDiffer || (pageReference.PageId != CurrentPageReference.PageId))
                            {
                                Response.Redirect(pageReference.BuildUrl(), true);
                            }
                        }
                    }
                }
            }
        }