Пример #1
0
        //
        /// <summary>
        /// Handle component import
        /// TODO - should a save be done for each component or wait until the end
        /// </summary>
        /// <param name="input"></param>
        /// <param name="pathway"></param>
        /// <param name="bnodes"></param>
        /// <param name="status">TODO - do we want to continue using the pathway SaveStatus?</param>
        /// <returns></returns>
        public OutputComponent ImportComponent(InputComponent input, ThisEntity pathway, List <BNode> bnodes, SaveStatus status)
        {
            MappingHelperV3 helper = new MappingHelperV3(CodesManager.ENTITY_TYPE_PATHWAY_COMPONENT);

            //do we need to reference blank nodes here? - if so pass to this method
            helper.entityBlankNodes  = bnodes;
            helper.CurrentEntityCTID = input.CTID;
            helper.CurrentEntityName = input.Name.ToString();
            OutputComponent output = new OutputComponent();

            //
            LoggingHelper.DoTrace(5, "======== Component ======== ");
            LoggingHelper.DoTrace(5, "		type: "+ input.PathwayComponentType.ToString());
            LoggingHelper.DoTrace(5, "		name: "+ (input.Name ?? new JInput.LanguageMap("componentNameMissing")).ToString());
            LoggingHelper.DoTrace(5, "		ctid: "+ input.CTID);
            LoggingHelper.DoTrace(6, "		@Id: "+ input.CtdlId);

            try
            {
                //add/updating Pathway
                if (!DoesComponentExist(input.CTID, ref output))
                {
                    //set the rowid now, so that can be referenced as needed
                    //no, the guid comes from the resolving of entity references
                    //actually OK, as earlier references would result in a pending record
                    output.RowId = Guid.NewGuid();
                }
                helper.currentBaseObject = output;
                if (input.CTID == "ce-fa6c139f-0615-401f-9920-6ec8c445baca")
                {
                }
                //initialize json properties
                output.JsonProperties = new PathwayComponentProperties();
                //
                output.PathwayComponentType = input.PathwayComponentType;
                output.Name           = helper.HandleLanguageMap(input.Name, output, "Name");
                output.Description    = helper.HandleLanguageMap(input.Description, output, "Description");
                output.SubjectWebpage = input.SubjectWebpage;
                output.SourceData     = input.SourceData;

                if (!string.IsNullOrWhiteSpace(output.SourceData) && output.SourceData.IndexOf("/resources/") > 0)
                {
                    var ctid = ResolutionServices.ExtractCtid(output.SourceData);
                    if (!string.IsNullOrWhiteSpace(ctid))
                    {
                        if (output.PathwayComponentType.ToLower().IndexOf("credential") > -1)
                        {
                            var target = CredentialManager.GetMinimumByCtid(ctid);
                            if (target != null && target.Id > 0)
                            {
                                //this approach 'buries' the cred from external references like credential in pathway
                                output.SourceCredential = new TopLevelEntityReference()
                                {
                                    Id             = target.Id,
                                    Name           = target.Name,
                                    Description    = target.Description,
                                    CTID           = target.CTID,
                                    SubjectWebpage = target.SubjectWebpage,
                                    //RowId = target.RowId
                                };
                                output.JsonProperties.SourceCredential = output.SourceCredential;
                            }
                        }
                        else if (output.PathwayComponentType.ToLower().IndexOf("assessmentcomp") > -1)
                        {
                            var target = AssessmentManager.GetSummaryByCtid(ctid);
                            if (target != null && target.Id > 0)
                            {
                                //may not really need this, just the json
                                output.SourceAssessment = new TopLevelEntityReference()
                                {
                                    Id             = target.Id,
                                    Name           = target.Name,
                                    Description    = target.Description,
                                    CTID           = target.CTID,
                                    SubjectWebpage = target.SubjectWebpage,
                                    //RowId = target.RowId
                                };
                                output.JsonProperties.SourceAssessment = output.SourceAssessment;
                            }
                        }
                        else if (output.PathwayComponentType.ToLower().IndexOf("coursecomp") > -1)
                        {
                            var target = LearningOpportunityManager.GetByCtid(ctid);
                            if (target != null && target.Id > 0)
                            {
                                //may not really need this, just the json
                                output.SourceLearningOpportunity = new TopLevelEntityReference()
                                {
                                    Id             = target.Id,
                                    Name           = target.Name,
                                    Description    = target.Description,
                                    CTID           = target.CTID,
                                    SubjectWebpage = target.SubjectWebpage,
                                    //RowId = target.RowId
                                };
                                output.JsonProperties.SourceLearningOpportunity = output.SourceLearningOpportunity;
                            }
                        }
                    }
                }

                output.CTID        = input.CTID;
                output.PathwayCTID = pathway.CTID;


                //output.CodedNotation = input.CodedNotation;
                output.Identifier = helper.MapIdentifierValueListInternal(input.Identifier);
                if (output.Identifier != null && output.Identifier.Count() > 0)
                {
                    output.IdentifierJson = JsonConvert.SerializeObject(output.Identifier, MappingHelperV3.GetJsonSettings());
                }
                //
                output.ComponentDesignationList = helper.MapCAOListToList(input.ComponentDesignation);

                //
                output.CredentialType = input.CredentialType;
                output.CreditValue    = helper.HandleValueProfileList(input.CreditValue, output.PathwayComponentType + ".CreditValue");

                //TBD - how to handle. Will need to have imported the concept scheme/concept
                if (input.HasProgressionLevel != null && input.HasProgressionLevel.Any())
                {
                    foreach (var item in input.HasProgressionLevel)
                    {
                        output.HasProgressionLevels.Add(ResolutionServices.ExtractCtid(item));
                    }
                }

                output.PointValue = helper.HandleQuantitiveValue(input.PointValue, output.PathwayComponentType + ".PointValue");

                //
                output.ProgramTerm = helper.HandleLanguageMap(input.ProgramTerm, output, "ProgramTerm");
                //need to get relationshiptype to store-> this can be done by manager
                //3
                output.HasChildList = helper.MapEntityReferenceGuids("PathwayComponent.HasChild", input.HasChild, CodesManager.ENTITY_TYPE_PATHWAY_COMPONENT, ref status);
                //2
                output.HasIsChildOfList = helper.MapEntityReferenceGuids("PathwayComponent.IsChildOf", input.IsChildOf, CodesManager.ENTITY_TYPE_PATHWAY_COMPONENT, ref status);

                output.HasPrerequisiteList = helper.MapEntityReferenceGuids("PathwayComponent.Prerequisite", input.Prerequisite, CodesManager.ENTITY_TYPE_PATHWAY_COMPONENT, ref status);
                output.HasPreceedsList     = helper.MapEntityReferenceGuids("PathwayComponent.Preceeds", input.Preceeds, CodesManager.ENTITY_TYPE_PATHWAY_COMPONENT, ref status);

                //populate JSON properties
                output.JsonProperties.ComponentDesignationList = output.ComponentDesignationList;
                output.JsonProperties.CreditValue = output.CreditValue;
                output.JsonProperties.Identifier  = output.Identifier;
                output.JsonProperties.PointValue  = output.PointValue;

                //
                if (input.HasCondition != null && input.HasCondition.Count() > 0)
                {
                    output.HasCondition = new List <PathwayComponentCondition>();
                    foreach (var item in input.HasCondition)
                    {
                        //var jcc = JsonConvert.DeserializeObject<JInput.ComponentCondition>( item.ToString() );
                        var cc = new PathwayComponentCondition();
                        cc.Name                   = helper.HandleLanguageMap(item.Name, cc, "ComponentCondition.Name");
                        cc.Description            = helper.HandleLanguageMap(item.Description, cc, "ComponentCondition.Description");
                        cc.RequiredNumber         = item.RequiredNumber;
                        cc.PathwayCTID            = pathway.CTID;
                        cc.HasTargetComponentList = helper.MapEntityReferenceGuids("ComponentCondition.TargetComponent", item.TargetComponent, CodesManager.ENTITY_TYPE_PATHWAY_COMPONENT, ref status);

                        output.HasCondition.Add(cc);
                    }
                }
            } catch (Exception ex)
            {
                LoggingHelper.LogError(ex, "ImportPathways.ImportComponent");
                //status.AddError( string.Format( "ImportPathways.ImportComponent. ComponentType: {0}, Name: {1}, Message: {2}", output.ComponentTypeId, output.Name, ex.Message ) );
            }
            //then save
            return(output);
        }
        public bool ImportV3(string payload, string envelopeIdentifier, SaveStatus status)
        {
            LoggingHelper.DoTrace(6, "ImportV3 Assessment- entered.");
            List <string> messages = new List <string>();

            bool           importSuccessfull = false;
            EntityServices mgr        = new EntityServices();
            InputEntityV3  input      = new InputEntityV3();
            var            bnodes     = new List <BNode>();
            var            mainEntity = new Dictionary <string, object>();

            //status.AddWarning( "The resource uses @graph and is not handled yet" );

            Dictionary <string, object> dictionary = RegistryServices.JsonToDictionary(payload);
            object graph = dictionary["@graph"];
            //serialize the graph object
            var glist = JsonConvert.SerializeObject(graph);

            //parse graph in to list of objects
            JArray graphList = JArray.Parse(glist);
            int    cntr      = 0;

            foreach (var item in graphList)
            {
                cntr++;
                if (cntr == 1)
                {
                    var main = item.ToString();
                    //may not use this. Could add a trace method
                    mainEntity = RegistryServices.JsonToDictionary(main);
                    input      = JsonConvert.DeserializeObject <InputEntityV3>(main);
                }
                else
                {
                    var bn = item.ToString();
                    bnodes.Add(JsonConvert.DeserializeObject <BNode>(bn));
                }
            }
            ///============= process =============================


            MappingHelperV3 helper = new MappingHelperV3(3);

            helper.entityBlankNodes  = bnodes;
            helper.CurrentEntityCTID = input.CTID;
            helper.CurrentEntityName = input.Name.ToString();

            string ctid = input.CTID;

            status.Ctid = ctid;
            string referencedAtId = input.CtdlId;

            LoggingHelper.DoTrace(5, "		name: "+ input.Name.ToString());
            LoggingHelper.DoTrace(6, "		url: "+ input.SubjectWebpage);
            LoggingHelper.DoTrace(5, "		ctid: "+ input.CTID);
            LoggingHelper.DoTrace(5, "		@Id: "+ input.CtdlId);


            if (status.DoingDownloadOnly)
            {
                return(true);
            }

            if (!DoesEntityExist(input.CTID, ref output))
            {
                //set the rowid now, so that can be referenced as needed
                output.RowId = Guid.NewGuid();
                LoggingHelper.DoTrace(1, string.Format(thisClassName + ".ImportV3(). Record was NOT found using CTID: '{0}'", input.CTID));
            }
            else
            {
                LoggingHelper.DoTrace(1, string.Format(thisClassName + ".ImportV3(). Found record: '{0}' using CTID: '{1}'", input.Name, input.CTID));
            }
            helper.currentBaseObject = output;

            //start with language and may use with language maps
            helper.MapInLanguageToTextValueProfile(input.InLanguage, "Assessment.InLanguage.CTID: " + ctid);
            //foreach ( var l in input.InLanguage )
            //{
            //	if ( !string.IsNullOrWhiteSpace( l ) )
            //	{
            //		var language = CodesManager.GetLanguage( l );
            //		output.InLanguageCodeList.Add( new TextValueProfile()
            //		{
            //			CodeId = language.CodeId,
            //			TextTitle = language.Name,
            //			TextValue = language.Value
            //		} );
            //	}
            //}

            if (input.InLanguage.Count > 0)
            {
                //could use to alter helper.DefaultLanguage
            }
            output.Name        = helper.HandleLanguageMap(input.Name, output, "Name");
            output.Description = helper.HandleLanguageMap(input.Description, output, "Description");
            output.CTID        = input.CTID;
            //TBD handling of referencing third party publisher
            if (!string.IsNullOrWhiteSpace(status.DocumentPublishedBy))
            {
                //output.PublishedByOrganizationCTID = status.DocumentPublishedBy;
                var porg = OrganizationManager.GetSummaryByCtid(status.DocumentPublishedBy);
                if (porg != null && porg.Id > 0)
                {
                    //TODO - store this in a json blob??????????
                    //this will result in being added to Entity.AgentRelationship
                    output.PublishedBy = new List <Guid>()
                    {
                        porg.RowId
                    };
                }
                else
                {
                    //if publisher not imported yet, all publishee stuff will be orphaned
                    var entityUid = Guid.NewGuid();
                    var statusMsg = "";
                    var resPos    = referencedAtId.IndexOf("/resources/");
                    var swp       = referencedAtId.Substring(0, (resPos + "/resources/".Length)) + status.DocumentPublishedBy;
                    int orgId     = new OrganizationManager().AddPendingRecord(entityUid, status.DocumentPublishedBy, swp, ref statusMsg);
                }
            }
            else
            {
                //may need a check for existing published by to ensure not lost
                if (output.Id > 0)
                {
                    if (output.OrganizationRole != null && output.OrganizationRole.Any())
                    {
                        var publishedByList = output.OrganizationRole.Where(s => s.RoleTypeId == 30).ToList();
                        if (publishedByList != null && publishedByList.Any())
                        {
                            var pby = publishedByList[0].ActingAgentUid;
                            output.PublishedBy = new List <Guid>()
                            {
                                publishedByList[0].ActingAgentUid
                            };
                        }
                    }
                }
            }
            output.CredentialRegistryId = envelopeIdentifier;
            output.DateEffective        = input.DateEffective;
            output.ExpirationDate       = input.ExpirationDate;

            output.SubjectWebpage = input.SubjectWebpage;
            //
            //BYs - do owned and offered first

            output.OfferedBy = helper.MapOrganizationReferenceGuids("Assessment.OfferedBy", input.OfferedBy, ref status);
            output.OwnedBy   = helper.MapOrganizationReferenceGuids("Assessment.OwnedBy", input.OwnedBy, ref status);
            if (output.OwnedBy != null && output.OwnedBy.Count > 0)
            {
                output.OwningAgentUid        = output.OwnedBy[0];
                helper.CurrentOwningAgentUid = output.OwnedBy[0];
            }
            else
            {
                //add warning?
                if (output.OfferedBy == null && output.OfferedBy.Count == 0)
                {
                    status.AddWarning("document doesn't have an owning or offering organization.");
                }
            }
            output.AccreditedBy = helper.MapOrganizationReferenceGuids("Assessment.AccreditedBy", input.AccreditedBy, ref status);
            output.ApprovedBy   = helper.MapOrganizationReferenceGuids("Assessment.ApprovedBy", input.ApprovedBy, ref status);
            output.RecognizedBy = helper.MapOrganizationReferenceGuids("Assessment.RecognizedBy", input.RecognizedBy, ref status);
            output.RegulatedBy  = helper.MapOrganizationReferenceGuids("Assessment.RegulatedBy", input.RegulatedBy, ref status);


            //
            output.Subject             = helper.MapCAOListToTextValueProfile(input.Subject, CodesManager.PROPERTY_CATEGORY_SUBJECT);
            output.Keyword             = helper.MapToTextValueProfile(input.Keyword, output, "Keyword");
            output.AvailabilityListing = helper.MapListToString(input.AvailabilityListing);
            output.AvailableOnlineAt   = helper.MapListToString(input.AvailableOnlineAt);
            output.AssessmentExample   = input.AssessmentExample;
            output.ExternalResearch    = helper.MapListToString(input.ExternalResearch);

            output.AssessmentExampleDescription = helper.HandleLanguageMap(input.AssessmentExampleDescription, output, "AssessmentExampleDescription");
            output.AssessmentMethodType         = helper.MapCAOListToEnumermation(input.AssessmentMethodType);
            output.AssessmentMethodDescription  = helper.HandleLanguageMap(input.AssessmentMethodDescription, output, "AssessmentMethodDescription");
            //
            output.LearningMethodDescription = helper.HandleLanguageMap(input.LearningMethodDescription, output, "LearningMethodDescription");


            output.AudienceType = helper.MapCAOListToEnumermation(input.AudienceType);
            //CAO
            output.AudienceLevelType = helper.MapCAOListToEnumermation(input.AudienceLevelType);

            output.VersionIdentifier     = helper.MapIdentifierValueListToString(input.VersionIdentifier);
            output.VersionIdentifierList = helper.MapIdentifierValueList(input.VersionIdentifier);

            //To be looked
            output.CodedNotation = input.CodedNotation;
            output.Identifier    = helper.MapIdentifierValueList(input.Identifier);
            if (output.Identifier != null && output.Identifier.Count() > 0)
            {
                output.IdentifierJson = JsonConvert.SerializeObject(output.Identifier, MappingHelperV3.GetJsonSettings());
            }

            output.AssessmentOutput        = helper.HandleLanguageMap(input.AssessmentOutput, output, "AssessmentOutput");
            output.AssessmentUseType       = helper.MapCAOListToEnumermation(input.AssessmentUseType);
            output.DeliveryType            = helper.MapCAOListToEnumermation(input.DeliveryType);
            output.DeliveryTypeDescription = helper.HandleLanguageMap(input.DeliveryTypeDescription, output, "DeliveryTypeDescription");

            output.IsProctored           = input.IsProctored;
            output.HasGroupEvaluation    = input.HasGroupEvaluation;
            output.HasGroupParticipation = input.HasGroupParticipation;

            output.ProcessStandards            = input.ProcessStandards;
            output.ProcessStandardsDescription = helper.HandleLanguageMap(input.ProcessStandardsDescription, output, "ProcessStandardsDescription");
            output.ScoringMethodDescription    = helper.HandleLanguageMap(input.ScoringMethodDescription, output, "ScoringMethodDescription");

            output.ScoringMethodExample            = input.ScoringMethodExample;
            output.ScoringMethodExampleDescription = helper.HandleLanguageMap(input.ScoringMethodExampleDescription, output, "ScoringMethodExampleDescription");
            output.ScoringMethodType = helper.MapCAOListToEnumermation(input.ScoringMethodType);

            //TBD - a custom version
            //output.InstructionalProgramType = helper.MapCAOListToEnumermation( input.InstructionalProgramType );
            //occupations
            output.Occupations = helper.MapCAOListToCAOProfileList(input.OccupationType);
            //just append alternative items. Ensure empty lists are ignored
            //output.Occupations.AddRange( helper.AppendLanguageMapListToCAOProfileList( input.AlternativeOccupationType ) );

            //skip if no occupations
            if (output.Occupations.Count() == 0 &&
                UtilityManager.GetAppKeyValue("skipCredImportIfNoOccupations", false))
            {
                //LoggingHelper.DoTrace( 2, string.Format( "		***Skipping Credential# {0}, {1} as it has no occupations and this is a special run.", output.Id, output.Name ) );
                //return true;
            }
            //Industries
            output.Industries = helper.MapCAOListToCAOProfileList(input.IndustryType);
            //output.Industries.AddRange( helper.AppendLanguageMapListToCAOProfileList( input.AlternativeIndustryType ) );
            //naics
            //output.Naics = input.Naics;

            output.InstructionalProgramTypes = helper.MapCAOListToCAOProfileList(input.InstructionalProgramType);
            //output.InstructionalProgramTypes.AddRange( helper.AppendLanguageMapListToCAOProfileList( input.AlternativeInstructionalProgramType ) );
            if (output.InstructionalProgramTypes.Count() == 0 && UtilityManager.GetAppKeyValue("skipAsmtImportIfNoCIP", false))
            {
                //skip
                LoggingHelper.DoTrace(2, string.Format("		***Skipping asmt# {0}, {1} as it has no InstructionalProgramTypes and this is a special run.", output.Id, output.Name));
                return(true);
            }
            //============================================================
            //handle QuantitativeValue
            //21-03-23 making the move to ValueProfile
            //output.CreditValue = helper.HandleQuantitiveValue( input.CreditValue, "Assessment.CreditValue" );
            //output.QVCreditValueList = helper.HandleValueProfileListToQVList( input.CreditValue, "Assessment.CreditValue" );
            //don't initially need CreditValueList if using CreditValueJson here
            output.CreditValue = helper.HandleValueProfileList(input.CreditValue, "Assessment.CreditValue");
            //however, CreditValueJson must include resolved concepts
            //TODO - take the opportunity to move away from Enumerations
            output.CreditValueJson = JsonConvert.SerializeObject(output.CreditValue, MappingHelperV3.GetJsonSettings());
            //note can still have CreditUnitTypeDescription by itself. What to do if both?
            output.CreditUnitTypeDescription = helper.HandleLanguageMap(input.CreditUnitTypeDescription, output, "Assessment.CreditUnitTypeDescription");
            //if ( output.CreditValueList != null && output.CreditValueList.Any() )
            //	output.CreditValue = output.CreditValueList[ 0 ];
            //


            output.Jurisdiction = helper.MapToJurisdiction(input.Jurisdiction, ref status);

            //EstimatedCost
            //will need to format, all populate Entity.RelatedCosts (for bubble up) - actually this would be for asmts, and lopps
            output.EstimatedCost = helper.FormatCosts(input.EstimatedCost, ref status);

            //assesses compentencies
            output.AssessesCompetencies = helper.MapCAOListToCAOProfileList(input.Assesses);
            if (output.AssessesCompetencies.Count() == 0 && UtilityManager.GetAppKeyValue("skipAsmtImportIfNoCompetencies", false))
            {
                //skip
                LoggingHelper.DoTrace(2, string.Format("		***Skipping asmt# {0}, {1} as it has no competencies and this is a special run.", output.Id, output.Name));
                return(true);
            }

            //common conditions
            output.ConditionManifestIds = helper.MapEntityReferences(input.CommonConditions, CodesManager.ENTITY_TYPE_CONDITION_MANIFEST, CodesManager.ENTITY_TYPE_ASSESSMENT_PROFILE, ref status);
            //common costs
            output.CostManifestIds = helper.MapEntityReferences(input.CommonCosts, CodesManager.ENTITY_TYPE_COST_MANIFEST, CodesManager.ENTITY_TYPE_ASSESSMENT_PROFILE, ref status);

            //connections
            output.AdvancedStandingFrom  = helper.FormatConditionProfile(input.AdvancedStandingFrom, ref status);
            output.IsAdvancedStandingFor = helper.FormatConditionProfile(input.IsAdvancedStandingFor, ref status);

            output.PreparationFrom  = helper.FormatConditionProfile(input.PreparationFrom, ref status);
            output.IsPreparationFor = helper.FormatConditionProfile(input.IsPreparationFor, ref status);

            output.IsRequiredFor    = helper.FormatConditionProfile(input.IsRequiredFor, ref status);
            output.IsRecommendedFor = helper.FormatConditionProfile(input.IsRecommendedFor, ref status);

            //EstimatedDuration ==============================
            output.EstimatedDuration = helper.FormatDuration(input.EstimatedDuration, ref status);

            //conditions ======================================
            output.Requires       = helper.FormatConditionProfile(input.Requires, ref status);
            output.Recommends     = helper.FormatConditionProfile(input.Recommends, ref status);
            output.EntryCondition = helper.FormatConditionProfile(input.EntryCondition, ref status);
            output.Corequisite    = helper.FormatConditionProfile(input.Corequisite, ref status);

            //Process profiles ==============================
            output.AdministrationProcess = helper.FormatProcessProfile(input.AdministrationProcess, ref status);
            output.DevelopmentProcess    = helper.FormatProcessProfile(input.DevelopmentProcess, ref status);
            output.MaintenanceProcess    = helper.FormatProcessProfile(input.MaintenanceProcess, ref status);

            //

            output.Addresses = helper.FormatAvailableAtAddresses(input.AvailableAt, ref status);
            //targets
            if (input.TargetAssessment != null && input.TargetAssessment.Count > 0)
            {
                output.TargetAssessmentIds = helper.MapEntityReferences("Assessment.TargetAssessment", input.TargetAssessment, CodesManager.ENTITY_TYPE_ASSESSMENT_PROFILE, ref status);
            }
            //21-04-13 mp - TargetLearningResource will be URLs not registry resources
            if (input.TargetLearningResource != null && input.TargetLearningResource.Count > 0)
            {
                output.TargetLearningResource = input.TargetLearningResource;
                //output.TargetLearningOpportunityIds = helper.MapEntityReferences( "Assessment.TargetLearningOpportunity", input.TargetLearningResource, CodesManager.ENTITY_TYPE_LEARNING_OPP_PROFILE, ref status );
            }
            //
            if (input.TargetPathway != null && input.TargetPathway.Count > 0)
            {
                output.TargetPathwayIds = helper.MapEntityReferences("Assessment.TargetPathway", input.TargetPathway, CodesManager.ENTITY_TYPE_PATHWAY, ref status);
            }

            //INs
            output.AccreditedIn = helper.MapToJurisdiction(input.AccreditedIn, ref status);
            output.ApprovedIn   = helper.MapToJurisdiction(input.ApprovedIn, ref status);
            output.OfferedIn    = helper.MapToJurisdiction(input.OfferedIn, ref status);
            output.RecognizedIn = helper.MapToJurisdiction(input.RecognizedIn, ref status);
            output.RegulatedIn  = helper.MapToJurisdiction(input.RegulatedIn, ref status);

            //SameAs URI
            output.SameAs = helper.MapToTextValueProfile(input.SameAs);
            //FinancialAssistance ============================
            //output.FinancialAssistanceOLD = helper.FormatFinancialAssistance( input.FinancialAssistance, ref status );
            output.FinancialAssistance = helper.FormatFinancialAssistance(input.FinancialAssistance, ref status);
            if (output.FinancialAssistance != null && output.FinancialAssistance.Any())
            {
                output.FinancialAssistanceJson = JsonConvert.SerializeObject(output.FinancialAssistance, MappingHelperV3.GetJsonSettings());
            }

            //=== if any messages were encountered treat as warnings for now
            if (messages.Count > 0)
            {
                status.SetMessages(messages, true);
            }
            //just in case check if entity added since start
            if (output.Id == 0)
            {
                ThisEntity entity = EntityServices.GetByCtid(ctid);
                if (entity != null && entity.Id > 0)
                {
                    output.Id    = entity.Id;
                    output.RowId = entity.RowId;
                }
            }
            importSuccessfull = mgr.Import(output, ref status);

            status.DocumentId    = output.Id;
            status.DetailPageUrl = string.Format("~/assessment/{0}", output.Id);
            status.DocumentRowId = output.RowId;

            //just in case
            if (status.HasErrors)
            {
                importSuccessfull = false;
            }

            //if record was added to db, add to/or set EntityResolution as resolved
            int ierId = new ImportManager().Import_EntityResolutionAdd(referencedAtId,
                                                                       ctid,
                                                                       CodesManager.ENTITY_TYPE_ASSESSMENT_PROFILE,
                                                                       output.RowId,
                                                                       output.Id,
                                                                       (output.Id > 0),
                                                                       ref messages,
                                                                       output.Id > 0);

            return(importSuccessfull);
        }
        }         //

        public bool Import(string payload, string envelopeIdentifier, SaveStatus status)
        {
            List <string>  messages          = new List <string>();
            bool           importSuccessfull = false;
            EntityServices mgr = new EntityServices();
            //
            InputEntity input      = new InputEntity();
            var         bnodes     = new List <BNode>();
            var         mainEntity = new Dictionary <string, object>();
            //
            Dictionary <string, object> dictionary = RegistryServices.JsonToDictionary(payload);
            object graph = dictionary["@graph"];
            //serialize the graph object
            var glist = JsonConvert.SerializeObject(graph);

            //parse graph in to list of objects
            JArray graphList = JArray.Parse(glist);
            int    cntr      = 0;

            foreach (var item in graphList)
            {
                cntr++;
                if (cntr == 1)
                {
                    var main = item.ToString();
                    //may not use this. Could add a trace method
                    mainEntity = RegistryServices.JsonToDictionary(main);
                    input      = JsonConvert.DeserializeObject <InputEntity>(main);
                }
                else
                {
                    var bn = item.ToString();
                    //20-07-02 need to handle the enhanced bnodes
                    bnodes.Add(JsonConvert.DeserializeObject <BNode>(bn));
                }
            }

            ///============= process =============================
            MappingHelperV3 helper = new MappingHelperV3(3);

            helper.entityBlankNodes  = bnodes;
            helper.CurrentEntityCTID = input.CTID;
            helper.CurrentEntityName = input.Name.ToString();

            string ctid = input.CTID;

            status.Ctid = ctid;
            string referencedAtId = input.CtdlId;

            LoggingHelper.DoTrace(5, "		ctid: "+ ctid);
            LoggingHelper.DoTrace(5, "		@Id: "+ input.CtdlId);
            LoggingHelper.DoTrace(5, "		name: "+ input.Name.ToString());

            if (status.DoingDownloadOnly)
            {
                return(true);
            }

            //add/updating TransferValue
            if (!DoesEntityExist(input.CTID, ref output, ref status))
            {
                //set the rowid now, so that can be referenced as needed
                output.RowId = Guid.NewGuid();
            }
            helper.currentBaseObject = output;

            output.Name        = helper.HandleLanguageMap(input.Name, output, "Name");
            output.Description = helper.HandleLanguageMap(input.Description, output, "Description");
            output.CTID        = input.CTID;
            //TBD handling of referencing third party publisher
            if (!string.IsNullOrWhiteSpace(status.DocumentPublishedBy))
            {
                //output.PublishedByOrganizationCTID = status.DocumentPublishedBy;
                var porg = OrganizationManager.GetSummaryByCtid(status.DocumentPublishedBy);
                if (porg != null && porg.Id > 0)
                {
                    //TODO - store this in a json blob??????????
                    //this will result in being added to Entity.AgentRelationship
                    output.PublishedBy = new List <Guid>()
                    {
                        porg.RowId
                    };
                }
                else
                {
                    //if publisher not imported yet, all publishee stuff will be orphaned
                    var entityUid = Guid.NewGuid();
                    var statusMsg = "";
                    var resPos    = referencedAtId.IndexOf("/resources/");
                    var swp       = referencedAtId.Substring(0, (resPos + "/resources/".Length)) + status.DocumentPublishedBy;
                    int orgId     = new OrganizationManager().AddPendingRecord(entityUid, status.DocumentPublishedBy, swp, ref statusMsg);
                }
            }
            else
            {
                //may need a check for existing published by to ensure not lost
                if (output.Id > 0)
                {
                    if (output.OrganizationRole != null && output.OrganizationRole.Any())
                    {
                        var publishedByList = output.OrganizationRole.Where(s => s.RoleTypeId == 30).ToList();
                        if (publishedByList != null && publishedByList.Any())
                        {
                            var pby = publishedByList[0].ActingAgentUid;
                            output.PublishedBy = new List <Guid>()
                            {
                                publishedByList[0].ActingAgentUid
                            };
                        }
                    }
                }
            }
            output.CredentialRegistryId = envelopeIdentifier;
            output.SubjectWebpage       = input.SubjectWebpage;
            //****owner missing
            output.OwnedBy = helper.MapOrganizationReferenceGuids("TransferValue.OwnedBy", input.OwnedBy, ref status);
            if (output.OwnedBy != null && output.OwnedBy.Count > 0)
            {
                output.OwningAgentUid        = output.OwnedBy[0];
                helper.CurrentOwningAgentUid = output.OwnedBy[0];
            }

            //
            //output.DerivedFromForImport = helper.MapEntityReferenceGuids( "TransferValue.DerivedFrom", input.DerivedFrom, CodesManager.ENTITY_TYPE_TRANSFER_VALUE_PROFILE, ref status );
            output.DerivedFromForImport = helper.MapEntityReferences("TransferValue.DerivedFrom", input.DerivedFrom, CodesManager.ENTITY_TYPE_TRANSFER_VALUE_PROFILE, ref status);
            //
            output.DevelopmentProcess = helper.FormatProcessProfile(input.DevelopmentProcess, ref status);


            //TBD - will replace codedNotation
            //output.CodedNotation = input.CodedNotation;
            //TBD - store more stuff as Json
            output.Identifier = helper.MapIdentifierValueList(input.Identifier);
            if (output.Identifier != null && output.Identifier.Count() > 0)
            {
                output.IdentifierJson = JsonConvert.SerializeObject(output.Identifier, MappingHelperV3.GetJsonSettings());
            }
            //

            //need to handle partial dates
            output.StartDate = input.StartDate;
            output.EndDate   = input.EndDate;
            //
            output.LifecycleStatusType = helper.MapCAOToString(input.LifecycleStatusType);
            //output.LifecycleStatusType = helper.MapCAOToEnumermation( input.LifecycleStatusType );
            //adding common import pattern
            //new PathwayManager().Save( ef, ref status, true );

            //

            output.TransferValue = helper.HandleValueProfileList(input.TransferValue, "TransferValueProfile.TransferValue");
            if (output.TransferValue != null && output.TransferValue.Count() > 0)
            {
                output.TransferValueJson = JsonConvert.SerializeObject(output.TransferValue, MappingHelperV3.GetJsonSettings());
            }
            //the class type must be provided for a blank node
            //TODO - make sure code handles extended properties
            //20-07-29 - getting duplicates - need to properly check for existing
            //			- actually a common approach is to delete all existing. this suggests NOT creating the pending entities!!
            //			- could be part of exists check
            output.TransferValueForImport = helper.MapEntityReferenceGuids("TransferValue.TransferValueFor", input.TransferValueFor, 0, ref status);
            if (output.TransferValueForImport != null && output.TransferValueForImport.Count() > 0)
            {
                //TransferValueForImport is a list of guids which could reference a blank node
                foreach (var item in output.TransferValueForImport)
                {
                    var tlo = ProfileServices.GetEntityAsTopLevelObject(item);
                    if (tlo != null && tlo.Id > 0)
                    {
                        output.TransferValueFor.Add(tlo);
                    }
                    else
                    {
                        //log error
                    }
                }
                //get all object as
                output.TransferValueForJson = JsonConvert.SerializeObject(output.TransferValueFor, MappingHelperV3.GetJsonSettings());
            }
            output.TransferValueFromImport = helper.MapEntityReferenceGuids("TransferValue.TransferValueFrom", input.TransferValueFrom, 0, ref status);
            if (output.TransferValueFromImport != null && output.TransferValueFromImport.Count() > 0)
            {
                //TransferValueFromImport is a list of guids which could reference a blank node
                foreach (var item in output.TransferValueFromImport)
                {
                    var tlo = ProfileServices.GetEntityAsTopLevelObject(item);
                    if (tlo != null && tlo.Id > 0)
                    {
                        output.TransferValueFrom.Add(tlo);
                    }
                    else
                    {
                        //log error
                    }
                }
                //get all object as
                output.TransferValueFromJson = JsonConvert.SerializeObject(output.TransferValueFrom, MappingHelperV3.GetJsonSettings());
            }

            importSuccessfull = new TransferValueServices().Import(output, ref status);
            //
            status.DocumentId    = output.Id;
            status.DetailPageUrl = string.Format("~/transfervalue/{0}", output.Id);
            status.DocumentRowId = output.RowId;

            //just in case
            if (status.HasErrors)
            {
                importSuccessfull = false;
            }

            //if record was added to db, add to/or set EntityResolution as resolved
            int ierId = new ImportManager().Import_EntityResolutionAdd(referencedAtId,
                                                                       ctid, CodesManager.ENTITY_TYPE_TRANSFER_VALUE_PROFILE,
                                                                       output.RowId,
                                                                       output.Id,
                                                                       false,
                                                                       ref messages,
                                                                       output.Id > 0);

            //

            return(importSuccessfull);
        }