Exemple #1
0
    public void Execute()
        {
            try
            {                 
                //We get the patient's care team               
                var getCareTeamRequest = new GetCareTeamRequest()
                {
                    ContactId = _contactId,
                    ContractNumber = _request.ContractNumber,
                    UserId = _request.UserId,
                    Version = _request.Version
                };
                var careTeamData = _contactEndpointUtil.GetCareTeam(getCareTeamRequest);

                if (careTeamData!=null)
                {
                    _careTeam = Mapper.Map<CareTeam>(careTeamData);

                    // We send a request to the data domain to delete care team by care tam Id  
                    var request = new DeleteCareTeamRequest()
                    {
                        ContactId = _careTeam.ContactId,
                        Id = _careTeam.Id,
                        ContractNumber = _request.ContractNumber,
                        UserId = _request.UserId,
                        Version = _request.Version
                    };
                    _contactEndpointUtil.DeleteCareTeam(request);
                }                
            }
            catch (Exception ex)
            {
                throw new Exception("AD: CareTeamCommand Execute::" + ex.Message, ex.InnerException);
            }
        }
Exemple #2
0
        /// <summary>
        /// Deserialize JSON into a FHIR CareTeam
        /// </summary>
        public static void DeserializeJson(this CareTeam current, ref Utf8JsonReader reader, JsonSerializerOptions options)
        {
            string propertyName;

            while (reader.Read())
            {
                if (reader.TokenType == JsonTokenType.EndObject)
                {
                    return;
                }

                if (reader.TokenType == JsonTokenType.PropertyName)
                {
                    propertyName = reader.GetString();
                    if (Hl7.Fhir.Serialization.FhirSerializerOptions.Debug)
                    {
                        Console.WriteLine($"CareTeam >>> CareTeam.{propertyName}, depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                    }
                    reader.Read();
                    current.DeserializeJsonProperty(ref reader, options, propertyName);
                }
            }

            throw new JsonException($"CareTeam: invalid state! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
        }
        public CohortRuleResponse Run(CareTeam careTeam, CohortRuleCheckData data)
        {
            var response = new CohortRuleResponse();

            if (careTeam == null)
            {
                throw new ArgumentNullException("careTeam");
            }

            try
            {
                var activeCorePCM = _cohortRuleUtil.GetCareTeamActiveCorePCM(careTeam);

                if (activeCorePCM != null)
                {
                    //We need to add Active Core PCM from the CohortPatientView for the referenced individual
                    if (!data.UsersContactIds.IsNullOrEmpty())
                    {
                        _contactEndpointUtil.AddPCMToCohortPatientView(data.PatientId, activeCorePCM.ContactId, data.Version, data.ContractNumber, data.UserId, data.UsersContactIds.Contains(activeCorePCM.ContactId));
                    }
                }

                response.IsSuccessful = true;
            }
            catch (Exception ex)
            {
                response.IsSuccessful = false;
                response.ErrorCode    = "UnAssignedPCMRule.Cohort.Error";
                response.Message      = ex.Message;

                _logger.Log(ex);
            }
            return(response);
        }
Exemple #4
0
        public CohortRuleResponse Run(CareTeam careTeam, CohortRuleCheckData data)
        {
            var response = new CohortRuleResponse();

            try
            {
                if (careTeam == null)
                {
                    throw new ArgumentNullException("careTeam");
                }

                //Check if any of the members have active core PCM role.
                if (!_cohortRuleUtil.CheckIfCareTeamHasActiveCorePCM(careTeam))
                {
                    //Add to UnAssigned PCM.
                    var isSuccessful = _contactEndpointUtil.RemovePCMCohortPatientView(data.PatientId, data.Version, data.ContractNumber, data.UserId);

                    response.IsSuccessful = isSuccessful;
                }
            }
            catch (Exception ex)
            {
                response.IsSuccessful = false;
                response.ErrorCode    = "UnAssignedPCMRule.Cohort.Error";
                response.Message      = ex.Message;

                _logger.Log(ex);
            }

            return(response);
        }
Exemple #5
0
        private void ApplyCohortRules(CohortRuleCheckData cohortRuleCheckData)
        {
            CareTeam careTeam     = null;
            var      careTeamData = EndpointUtil.GetCareTeam(new GetCareTeamRequest
            {
                ContactId      = cohortRuleCheckData.ContactId,
                ContractNumber = cohortRuleCheckData.ContractNumber,
                UserId         = cohortRuleCheckData.UserId
            });

            if (careTeamData == null)
            {
                return;
            }
            careTeam = Mapper.Map <CareTeam>(careTeamData);
            var userList = GetAllUsersIds(cohortRuleCheckData.ContractNumber, cohortRuleCheckData.UserId, cohortRuleCheckData.Version);

            cohortRuleCheckData.UsersContactIds = userList;
            var rules = CareMemberCohortRuleFactory.GenerateEngageCareMemberCohortRules();

            foreach (var rule in rules)
            {
                rule.Run(careTeam, cohortRuleCheckData);
            }
        }
        public async Task <IHttpActionResult> GetCareTeam(Guid id)
        {
            CareTeam careTeam = await db.CareTeam.FindAsync(id);

            if (careTeam == null)
            {
                return(NotFound());
            }

            var roles = await db.Roles.ToDictionaryAsync(r => r.Id);

            return(Ok(ToDto.CareTeamToDto(careTeam, roles)));
        }
        public async Task <IHttpActionResult> DeleteCareTeam(Guid id)
        {
            CareTeam careTeam = await db.CareTeam.FindAsync(id);

            if (careTeam == null)
            {
                return(NotFound());
            }

            db.CareTeam.Remove(careTeam);
            await db.SaveChangesAsync();

            return(Ok(careTeam));
        }
Exemple #8
0
        public Member GetCareTeamActiveCorePCM(CareTeam team)
        {
            Member res = null;

            if (team.Members.IsNullOrEmpty())
            {
                return(res);
            }

            res = team.Members.FirstOrDefault(c =>
                                              c.StatusId == (int)CareTeamMemberStatus.Active && c.Core == true &&
                                              c.RoleId == Constants.PCMRoleId);


            return(res);
        }
Exemple #9
0
        public bool CheckIfCareTeamHasActiveCorePCM(CareTeam team)
        {
            var hasPCM = false;

            if (team.Members.IsNullOrEmpty())
            {
                return(false);
            }

            hasPCM = team.Members.Any(c =>
                                      c.StatusId == (int)CareTeamMemberStatus.Active && c.Core == true &&
                                      c.RoleId == Constants.PCMRoleId);


            return(hasPCM);
        }
Exemple #10
0
        public CareTeam GetCareTeam(GetCareTeamRequest request)
        {
            CareTeam careTeam = null;

            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (string.IsNullOrEmpty(request.ContactId))
            {
                throw new ArgumentNullException("request.ContactId");
            }
            try
            {
                CareTeamData careTeamData = EndpointUtil.GetCareTeam(request);
                if (careTeamData != null)
                {
                    careTeam = Mapper.Map <CareTeam>(careTeamData);
                    #region Populate Contact object for each care team member.
                    if (careTeam.Members != null && careTeam.Members.Count > 0)
                    {
                        List <string>      contactIds   = careTeam.Members.Select(a => a.ContactId).ToList();
                        List <ContactData> contactsData = EndpointUtil.GetContactsByContactIds(contactIds, request.Version, request.ContractNumber, request.UserId);
                        if (contactsData != null)
                        {
                            foreach (var member in careTeam.Members)
                            {
                                ContactData data = contactsData.FirstOrDefault(c => c.Id == member.ContactId);
                                if (data == null)
                                {
                                    throw new ApplicationException(string.Format("Contact card for a care team member with contact id = {0} was not found", member.ContactId));
                                }
                                else
                                {
                                    member.Contact = Mapper.Map <Contact>(data);
                                }
                            }
                        }
                    }
                    #endregion
                }
                return(careTeam);
            }
            catch (Exception ex) { throw ex; }
        }
        public async Task <IHttpActionResult> UpdateTeam(UpdateTeamBindingModel model)
        {
            CareTeam careTeam = await db.CareTeam.FindAsync(model.TeamId);

            if (careTeam == null)
            {
                return(NotFound());
            }
            careTeam.Providers.Clear();
            foreach (var providerId in model.ProviderIds)
            {
                var provider = await userManager.FindByIdAsync(providerId);

                if (provider == null)
                {
                    return(NotFound());
                }

                if (!careTeam.Providers.Contains(provider))
                {
                    careTeam.Providers.Add(provider);
                }
            }
            careTeam.Supporters.Clear();
            foreach (var supporterId in model.SupporterIds)
            {
                var supporter = await userManager.FindByIdAsync(supporterId);

                if (supporter == null)
                {
                    return(NotFound());
                }

                if (!careTeam.Supporters.Contains(supporter))
                {
                    careTeam.Supporters.Add(supporter);
                }
            }

            careTeam.Name = model.TeamName;

            await db.SaveChangesAsync();

            return(Ok());
        }
Exemple #12
0
        public static CareTeamDto CareTeamToDto(CareTeam careTeam, Dictionary <string, IdentityRole> roles = null)
        {
            var careTeamDto = new CareTeamDto();

            careTeamDto.InjectFrom(careTeam);
            careTeamDto.Patient    = UserToDto(careTeam.Patient);
            careTeamDto.Providers  = new List <UserDto>();
            careTeamDto.Supporters = new List <UserDto>();

            foreach (var provider in careTeam.Providers)
            {
                careTeamDto.Providers.Add(UserToDto(provider));
            }

            foreach (var supporter in careTeam.Supporters)
            {
                careTeamDto.Supporters.Add(UserToDto(supporter));
            }
            return(careTeamDto);
        }
Exemple #13
0
        public bool HasMultipleActiveCorePCP(CareTeam careTeam)
        {
            bool res = false;

            if (careTeam == null)
            {
                return(false);
            }
            var activeCorePCMs =
                careTeam.Members.Where(
                    c =>
                    c.RoleId == Constants.PCPRoleId && c.Core == true &&
                    c.StatusId == (int)CareTeamMemberStatus.Active).ToList();

            if (!activeCorePCMs.IsNullOrEmpty() && activeCorePCMs.Count() > 1)
            {
                res = true;
            }

            return(res);
        }
Exemple #14
0
        public bool ActiveCorePcmIsUser(CareTeam team, List <string> usersContactIds)
        {
            bool res = false;

            if (team.Members.IsNullOrEmpty() || usersContactIds == null)
            {
                return(res);
            }

            var activeCorePcm = team.Members.FirstOrDefault(c =>
                                                            c.StatusId == (int)CareTeamMemberStatus.Active && c.Core == true &&
                                                            c.RoleId == Constants.PCMRoleId);

            if (activeCorePcm == null)
            {
                return(res);
            }

            res = usersContactIds.Contains(activeCorePcm.ContactId);
            return(res);
        }
Exemple #15
0
        public CohortRuleResponse Run(CareTeam careTeam, CohortRuleCheckData data)
        {
            var response = new CohortRuleResponse();

            try
            {
                if (careTeam == null)
                {
                    throw new ArgumentNullException("careTeam");
                }

                //For each member in the careteam that is a user, add an ATO cohort for the referenced individual
                var contactIdsToAdd = new List <string>();
                foreach (var member in careTeam.Members)
                {
                    if (member.StatusId == (int)CareTeamMemberStatus.Active)
                    {
                        if (data.UsersContactIds.Contains(member.ContactId))
                        {
                            contactIdsToAdd.Add(member.ContactId);
                        }
                    }
                }

                _contactEndpointUtil.AssignContactsToCohortPatientView(data.PatientId, contactIdsToAdd.Distinct().ToList(), data.Version, data.ContractNumber, data.UserId);
                response.IsSuccessful = true;
            }
            catch (Exception ex)
            {
                response.IsSuccessful = false;
                response.ErrorCode    = "AssignedToMeRule.Cohort.Error";
                response.Message      = ex.Message;

                _logger.Log(ex);
            }

            return(response);
        }
Exemple #16
0
        public AddCareTeamMemberResponse AddCareTeamMember(AddCareTeamMemberRequest request)
        {
            var response = new AddCareTeamMemberResponse();

            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            ValidateCareTeamMemberFields(request.CareTeamMember);

            var careTeamData = EndpointUtil.GetCareTeam(new GetCareTeamRequest {
                ContactId = request.ContactId, ContractNumber = request.ContractNumber, UserId = request.UserId, Version = request.Version
            });

            if (careTeamData == null)
            {
                throw new ApplicationException(string.Format("No care team exists for contact  {0}", request.ContactId));
            }

            var members = careTeamData.Members;

            if (!members.IsNullOrEmpty())
            {
                var mappedMembers = members.Select(Mapper.Map <Member>).ToList();
                mappedMembers.Add(request.CareTeamMember);

                var careTeam = new CareTeam {
                    Members = mappedMembers, ContactId = request.ContactId, Id = careTeamData.Id
                };

                if (CohortRuleUtil.HasMultipleActiveCorePCM(careTeam))
                {
                    throw new ApplicationException("The Care team cannot have multiple Active, Core PCMs");
                }

                if (CohortRuleUtil.HasMultipleActiveCorePCP(careTeam))
                {
                    throw new ApplicationException("The Care team cannot have multiple Active, Core PCPs");
                }
            }

            var contact = GetContactByContactId(new GetContactByContactIdRequest
            {
                ContractNumber = request.ContractNumber,
                ContactId      = request.ContactId,
                UserId         = request.UserId,
                Version        = request.Version
            });

            if (contact == null)
            {
                throw new ApplicationException(string.Format("Contact with id: {0} does not exist", request.ContactId));
            }

            var cohortRuleCheckData = new CohortRuleCheckData()
            {
                ContactId      = request.ContactId,
                ContractNumber = request.ContractNumber,
                UserId         = request.UserId,
                PatientId      = contact.PatientId
            };

            try
            {
                var domainResponse = EndpointUtil.AddCareTeamMember(request);
                if (domainResponse != null)
                {
                    response.Id = domainResponse.Id;
                    CohortRules.EnqueueCohorRuleCheck(cohortRuleCheckData);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("AD:UpdateCareTeamMember()::" + ex.Message, ex.InnerException);
            }

            return(response);
        }
Exemple #17
0
        /// <summary>
        /// Serialize a FHIR CareTeam into JSON
        /// </summary>
        public static void SerializeJson(this CareTeam current, Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true)
        {
            if (includeStartObject)
            {
                writer.WriteStartObject();
            }
            writer.WriteString("resourceType", "CareTeam");
            // Complex: CareTeam, Export: CareTeam, Base: DomainResource (DomainResource)
            ((Hl7.Fhir.Model.DomainResource)current).SerializeJson(writer, options, false);

            if ((current.Identifier != null) && (current.Identifier.Count != 0))
            {
                writer.WritePropertyName("identifier");
                writer.WriteStartArray();
                foreach (Identifier val in current.Identifier)
                {
                    val.SerializeJson(writer, options, true);
                }
                writer.WriteEndArray();
            }

            if (current.StatusElement != null)
            {
                if (current.StatusElement.Value != null)
                {
                    writer.WriteString("status", Hl7.Fhir.Utility.EnumUtility.GetLiteral(current.StatusElement.Value));
                }
                if (current.StatusElement.HasExtensions() || (!string.IsNullOrEmpty(current.StatusElement.ElementId)))
                {
                    JsonStreamUtilities.SerializeExtensionList(writer, options, "_status", false, current.StatusElement.Extension, current.StatusElement.ElementId);
                }
            }

            if ((current.Category != null) && (current.Category.Count != 0))
            {
                writer.WritePropertyName("category");
                writer.WriteStartArray();
                foreach (CodeableConcept val in current.Category)
                {
                    val.SerializeJson(writer, options, true);
                }
                writer.WriteEndArray();
            }

            if (current.NameElement != null)
            {
                if (!string.IsNullOrEmpty(current.NameElement.Value))
                {
                    writer.WriteString("name", current.NameElement.Value);
                }
                if (current.NameElement.HasExtensions() || (!string.IsNullOrEmpty(current.NameElement.ElementId)))
                {
                    JsonStreamUtilities.SerializeExtensionList(writer, options, "_name", false, current.NameElement.Extension, current.NameElement.ElementId);
                }
            }

            if (current.Subject != null)
            {
                writer.WritePropertyName("subject");
                current.Subject.SerializeJson(writer, options);
            }

            if (current.Encounter != null)
            {
                writer.WritePropertyName("encounter");
                current.Encounter.SerializeJson(writer, options);
            }

            if (current.Period != null)
            {
                writer.WritePropertyName("period");
                current.Period.SerializeJson(writer, options);
            }

            if ((current.Participant != null) && (current.Participant.Count != 0))
            {
                writer.WritePropertyName("participant");
                writer.WriteStartArray();
                foreach (CareTeam.ParticipantComponent val in current.Participant)
                {
                    val.SerializeJson(writer, options, true);
                }
                writer.WriteEndArray();
            }

            if ((current.ReasonCode != null) && (current.ReasonCode.Count != 0))
            {
                writer.WritePropertyName("reasonCode");
                writer.WriteStartArray();
                foreach (CodeableConcept val in current.ReasonCode)
                {
                    val.SerializeJson(writer, options, true);
                }
                writer.WriteEndArray();
            }

            if ((current.ReasonReference != null) && (current.ReasonReference.Count != 0))
            {
                writer.WritePropertyName("reasonReference");
                writer.WriteStartArray();
                foreach (ResourceReference val in current.ReasonReference)
                {
                    val.SerializeJson(writer, options, true);
                }
                writer.WriteEndArray();
            }

            if ((current.ManagingOrganization != null) && (current.ManagingOrganization.Count != 0))
            {
                writer.WritePropertyName("managingOrganization");
                writer.WriteStartArray();
                foreach (ResourceReference val in current.ManagingOrganization)
                {
                    val.SerializeJson(writer, options, true);
                }
                writer.WriteEndArray();
            }

            if ((current.Telecom != null) && (current.Telecom.Count != 0))
            {
                writer.WritePropertyName("telecom");
                writer.WriteStartArray();
                foreach (ContactPoint val in current.Telecom)
                {
                    val.SerializeJson(writer, options, true);
                }
                writer.WriteEndArray();
            }

            if ((current.Note != null) && (current.Note.Count != 0))
            {
                writer.WritePropertyName("note");
                writer.WriteStartArray();
                foreach (Annotation val in current.Note)
                {
                    val.SerializeJson(writer, options, true);
                }
                writer.WriteEndArray();
            }

            if (includeStartObject)
            {
                writer.WriteEndObject();
            }
        }
Exemple #18
0
        /// <summary>
        /// Deserialize JSON into a FHIR CareTeam
        /// </summary>
        public static void DeserializeJsonProperty(this CareTeam current, ref Utf8JsonReader reader, JsonSerializerOptions options, string propertyName)
        {
            switch (propertyName)
            {
            case "identifier":
                if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
                {
                    throw new JsonException($"CareTeam error reading 'identifier' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                }

                current.Identifier = new List <Identifier>();

                while (reader.TokenType != JsonTokenType.EndArray)
                {
                    Hl7.Fhir.Model.Identifier v_Identifier = new Hl7.Fhir.Model.Identifier();
                    v_Identifier.DeserializeJson(ref reader, options);
                    current.Identifier.Add(v_Identifier);

                    if (!reader.Read())
                    {
                        throw new JsonException($"CareTeam error reading 'identifier' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                    }
                    if (reader.TokenType == JsonTokenType.EndObject)
                    {
                        reader.Read();
                    }
                }

                if (current.Identifier.Count == 0)
                {
                    current.Identifier = null;
                }
                break;

            case "status":
                if (reader.TokenType == JsonTokenType.Null)
                {
                    current.StatusElement = new Code <Hl7.Fhir.Model.CareTeam.CareTeamStatus>();
                    reader.Skip();
                }
                else
                {
                    current.StatusElement = new Code <Hl7.Fhir.Model.CareTeam.CareTeamStatus>(Hl7.Fhir.Utility.EnumUtility.ParseLiteral <Hl7.Fhir.Model.CareTeam.CareTeamStatus>(reader.GetString()));
                }
                break;

            case "_status":
                if (current.StatusElement == null)
                {
                    current.StatusElement = new Code <Hl7.Fhir.Model.CareTeam.CareTeamStatus>();
                }
                ((Hl7.Fhir.Model.Element)current.StatusElement).DeserializeJson(ref reader, options);
                break;

            case "category":
                if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
                {
                    throw new JsonException($"CareTeam error reading 'category' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                }

                current.Category = new List <CodeableConcept>();

                while (reader.TokenType != JsonTokenType.EndArray)
                {
                    Hl7.Fhir.Model.CodeableConcept v_Category = new Hl7.Fhir.Model.CodeableConcept();
                    v_Category.DeserializeJson(ref reader, options);
                    current.Category.Add(v_Category);

                    if (!reader.Read())
                    {
                        throw new JsonException($"CareTeam error reading 'category' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                    }
                    if (reader.TokenType == JsonTokenType.EndObject)
                    {
                        reader.Read();
                    }
                }

                if (current.Category.Count == 0)
                {
                    current.Category = null;
                }
                break;

            case "name":
                if (reader.TokenType == JsonTokenType.Null)
                {
                    current.NameElement = new FhirString();
                    reader.Skip();
                }
                else
                {
                    current.NameElement = new FhirString(reader.GetString());
                }
                break;

            case "_name":
                if (current.NameElement == null)
                {
                    current.NameElement = new FhirString();
                }
                ((Hl7.Fhir.Model.Element)current.NameElement).DeserializeJson(ref reader, options);
                break;

            case "subject":
                current.Subject = new Hl7.Fhir.Model.ResourceReference();
                ((Hl7.Fhir.Model.ResourceReference)current.Subject).DeserializeJson(ref reader, options);
                break;

            case "encounter":
                current.Encounter = new Hl7.Fhir.Model.ResourceReference();
                ((Hl7.Fhir.Model.ResourceReference)current.Encounter).DeserializeJson(ref reader, options);
                break;

            case "period":
                current.Period = new Hl7.Fhir.Model.Period();
                ((Hl7.Fhir.Model.Period)current.Period).DeserializeJson(ref reader, options);
                break;

            case "participant":
                if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
                {
                    throw new JsonException($"CareTeam error reading 'participant' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                }

                current.Participant = new List <CareTeam.ParticipantComponent>();

                while (reader.TokenType != JsonTokenType.EndArray)
                {
                    Hl7.Fhir.Model.CareTeam.ParticipantComponent v_Participant = new Hl7.Fhir.Model.CareTeam.ParticipantComponent();
                    v_Participant.DeserializeJson(ref reader, options);
                    current.Participant.Add(v_Participant);

                    if (!reader.Read())
                    {
                        throw new JsonException($"CareTeam error reading 'participant' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                    }
                    if (reader.TokenType == JsonTokenType.EndObject)
                    {
                        reader.Read();
                    }
                }

                if (current.Participant.Count == 0)
                {
                    current.Participant = null;
                }
                break;

            case "reasonCode":
                if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
                {
                    throw new JsonException($"CareTeam error reading 'reasonCode' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                }

                current.ReasonCode = new List <CodeableConcept>();

                while (reader.TokenType != JsonTokenType.EndArray)
                {
                    Hl7.Fhir.Model.CodeableConcept v_ReasonCode = new Hl7.Fhir.Model.CodeableConcept();
                    v_ReasonCode.DeserializeJson(ref reader, options);
                    current.ReasonCode.Add(v_ReasonCode);

                    if (!reader.Read())
                    {
                        throw new JsonException($"CareTeam error reading 'reasonCode' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                    }
                    if (reader.TokenType == JsonTokenType.EndObject)
                    {
                        reader.Read();
                    }
                }

                if (current.ReasonCode.Count == 0)
                {
                    current.ReasonCode = null;
                }
                break;

            case "reasonReference":
                if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
                {
                    throw new JsonException($"CareTeam error reading 'reasonReference' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                }

                current.ReasonReference = new List <ResourceReference>();

                while (reader.TokenType != JsonTokenType.EndArray)
                {
                    Hl7.Fhir.Model.ResourceReference v_ReasonReference = new Hl7.Fhir.Model.ResourceReference();
                    v_ReasonReference.DeserializeJson(ref reader, options);
                    current.ReasonReference.Add(v_ReasonReference);

                    if (!reader.Read())
                    {
                        throw new JsonException($"CareTeam error reading 'reasonReference' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                    }
                    if (reader.TokenType == JsonTokenType.EndObject)
                    {
                        reader.Read();
                    }
                }

                if (current.ReasonReference.Count == 0)
                {
                    current.ReasonReference = null;
                }
                break;

            case "managingOrganization":
                if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
                {
                    throw new JsonException($"CareTeam error reading 'managingOrganization' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                }

                current.ManagingOrganization = new List <ResourceReference>();

                while (reader.TokenType != JsonTokenType.EndArray)
                {
                    Hl7.Fhir.Model.ResourceReference v_ManagingOrganization = new Hl7.Fhir.Model.ResourceReference();
                    v_ManagingOrganization.DeserializeJson(ref reader, options);
                    current.ManagingOrganization.Add(v_ManagingOrganization);

                    if (!reader.Read())
                    {
                        throw new JsonException($"CareTeam error reading 'managingOrganization' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                    }
                    if (reader.TokenType == JsonTokenType.EndObject)
                    {
                        reader.Read();
                    }
                }

                if (current.ManagingOrganization.Count == 0)
                {
                    current.ManagingOrganization = null;
                }
                break;

            case "telecom":
                if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
                {
                    throw new JsonException($"CareTeam error reading 'telecom' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                }

                current.Telecom = new List <ContactPoint>();

                while (reader.TokenType != JsonTokenType.EndArray)
                {
                    Hl7.Fhir.Model.ContactPoint v_Telecom = new Hl7.Fhir.Model.ContactPoint();
                    v_Telecom.DeserializeJson(ref reader, options);
                    current.Telecom.Add(v_Telecom);

                    if (!reader.Read())
                    {
                        throw new JsonException($"CareTeam error reading 'telecom' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                    }
                    if (reader.TokenType == JsonTokenType.EndObject)
                    {
                        reader.Read();
                    }
                }

                if (current.Telecom.Count == 0)
                {
                    current.Telecom = null;
                }
                break;

            case "note":
                if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
                {
                    throw new JsonException($"CareTeam error reading 'note' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                }

                current.Note = new List <Annotation>();

                while (reader.TokenType != JsonTokenType.EndArray)
                {
                    Hl7.Fhir.Model.Annotation v_Note = new Hl7.Fhir.Model.Annotation();
                    v_Note.DeserializeJson(ref reader, options);
                    current.Note.Add(v_Note);

                    if (!reader.Read())
                    {
                        throw new JsonException($"CareTeam error reading 'note' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                    }
                    if (reader.TokenType == JsonTokenType.EndObject)
                    {
                        reader.Read();
                    }
                }

                if (current.Note.Count == 0)
                {
                    current.Note = null;
                }
                break;

            // Complex: CareTeam, Export: CareTeam, Base: DomainResource
            default:
                ((Hl7.Fhir.Model.DomainResource)current).DeserializeJsonProperty(ref reader, options, propertyName);
                break;
            }
        }
Exemple #19
0
        public static Bundle getBundle(string basePath)
        {
            Bundle bdl = new Bundle();

            bdl.Type = Bundle.BundleType.Document;

            // A document must have an identifier with a system and a value () type = 'document' implies (identifier.system.exists() and identifier.value.exists())

            bdl.Identifier = new Identifier()
            {
                System = "urn:ietf:rfc:3986",
                Value  = FhirUtil.createUUID()
            };

            //Composition for Discharge Summary
            Composition c = new Composition();

            //B.2 患者基本情報
            // TODO 退院時サマリー V1.41 B.2 患者基本情報のproviderOrganizationの意図を確認 B.8 受診、入院時情報に入院した
            //医療機関の記述が書かれているならば、ここの医療機関はどういう位置づけのもの? とりあえず、managingOrganizationにいれておくが。
            Patient patient = null;

            if (true)
            {
                //Patientリソースを自前で生成する場合
                patient = PatientUtil.create();
            }
            else
            {
                //Patientリソースをサーバから取ってくる場合
                #pragma warning disable 0162
                patient = PatientUtil.get();
            }

            Practitioner practitioner = PractitionerUtil.create();
            Organization organization = OrganizationUtil.create();

            patient.ManagingOrganization = new ResourceReference()
            {
                Reference = organization.Id
            };


            //Compositionの作成

            c.Id     = FhirUtil.createUUID();         //まだFHIRサーバにあげられていないから,一時的なUUIDを生成してリソースIDとしてセットする
            c.Status = CompositionStatus.Preliminary; //最終版は CompositionStatus.Final
            c.Type   = new CodeableConcept()
            {
                Text   = "Discharge Summary", //[疑問]Codable Concept内のTextと、Coding内のDisplayとの違いは。Lead Term的な表示?
                Coding = new List <Coding>()
                {
                    new Coding()
                    {
                        Display = "Discharge Summary",
                        System  = "http://loinc.org",
                        Code    = "18842-5",
                    }
                }
            };

            c.Date   = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzzz");
            c.Author = new List <ResourceReference>()
            {
                new ResourceReference()
                {
                    Reference = practitioner.Id
                }
            };

            c.Subject = new ResourceReference()
            {
                Reference = patient.Id
            };

            c.Title = "退院時サマリー"; //タイトルはこれでいいのかな。

            //B.3 承認者

            var attester = new Composition.AttesterComponent();

            var code = new Code <Composition.CompositionAttestationMode>();
            code.Value = Composition.CompositionAttestationMode.Legal;
            attester.ModeElement.Add(code);

            attester.Party = new ResourceReference()
            {
                Reference = practitioner.Id
            };
            attester.Time = "20140620";

            c.Attester.Add(attester);

            //B.4 退院時サマリー記載者

            var author = new Practitioner();
            author.Id = FhirUtil.createUUID();

            var authorName = new HumanName().WithGiven("太郎").AndFamily("本日");
            authorName.Use = HumanName.NameUse.Official;
            authorName.AddExtension("http://hl7.org/fhir/StructureDefinition/iso21090-EN-representation", new FhirString("IDE"));
            author.Name.Add(authorName);

            c.Author.Add(new ResourceReference()
            {
                Reference = author.Id
            });

            //B.5 原本管理者

            c.Custodian = new ResourceReference()
            {
                Reference = organization.Id
            };

            //B.6 関係者 保険者 何故退院サマリーに保険者の情報を入れているのかな?
            //TODO 未実装


            //sections

            //B.7 主治医
            var section_careteam = new Composition.SectionComponent();
            section_careteam.Title = "careteam";

            var careteam = new CareTeam();
            careteam.Id = FhirUtil.createUUID();

            var attendingPhysician = new Practitioner();
            attendingPhysician.Id = FhirUtil.createUUID();

            var attendingPhysicianName = new HumanName().WithGiven("二郎").AndFamily("日本");
            attendingPhysicianName.Use = HumanName.NameUse.Official;
            attendingPhysicianName.AddExtension("http://hl7.org/fhir/StructureDefinition/iso21090-EN-representation", new FhirString("IDE"));
            attendingPhysician.Name.Add(attendingPhysicianName);

            //医師の診療科はPracitionerRole/speciality + PracticeSettingCodeValueSetで表現する.
            //TODO: 膠原病内科は、Specilityのprefered ValueSetの中にはなかった。日本の診療科に関するValueSetを作る必要がある。
            var attendingPractitionerRole = new PractitionerRole();

            attendingPractitionerRole.Id           = FhirUtil.createUUID();
            attendingPractitionerRole.Practitioner = new ResourceReference()
            {
                Reference = attendingPhysician.Id
            };
            attendingPractitionerRole.Code.Add(new CodeableConcept("http://hl7.org/fhir/ValueSet/participant-role", "394733009", "Attending physician"));
            attendingPractitionerRole.Specialty.Add(new CodeableConcept("http://hl7.org/fhir/ValueSet/c80-practice-codes", "405279007", "Medical specialty--OTHER--NOT LISTED"));

            var participant = new CareTeam.ParticipantComponent();
            participant.Member = new ResourceReference()
            {
                Reference = attendingPractitionerRole.Id
            };

            careteam.Participant.Add(participant);


            section_careteam.Entry.Add(new ResourceReference()
            {
                Reference = careteam.Id
            });
            c.Section.Add(section_careteam);


            //B.8 受診、入院情報
            //B.12 本文 (Entry部) 退院時サマリーV1.41の例では入院時診断を本文に書くような形に
            //なっているが、FHIRではadmissionDetailセクション中のEncounterで記載するのが自然だろう。

            var section_admissionDetail = new Composition.SectionComponent();
            section_admissionDetail.Title = "admissionDetail";

            var encounter = new Encounter();
            encounter.Id = FhirUtil.createUUID();

            encounter.Period = new Period()
            {
                Start = "20140328", End = "20140404"
            };

            var hospitalization = new Encounter.HospitalizationComponent();
            hospitalization.DischargeDisposition = new CodeableConcept("\thttp://hl7.org/fhir/discharge-disposition", "01", "Discharged to home care or self care (routine discharge)");

            encounter.Hospitalization = hospitalization;

            var locationComponent = new Encounter.LocationComponent();
            var location          = new Location()
            {
                Id   = FhirUtil.createUUID(),
                Name = "○○クリニック",
                Type = new CodeableConcept("http://terminology.hl7.org/ValueSet/v3-ServiceDeliveryLocationRoleType", "COAG", "Coagulation clinic")
            };

            locationComponent.Location = new ResourceReference()
            {
                Reference = location.Id
            };

            section_admissionDetail.Entry.Add(new ResourceReference()
            {
                Reference = encounter.Id
            });



            var diagnosisAtAdmission = new Condition()
            {
                Code = new CodeableConcept("http://hl7.org/fhir/ValueSet/icd-10", "N801", "右卵巣嚢腫")
            };
            diagnosisAtAdmission.Id = FhirUtil.createUUID();

            var diagnosisComponentAtAdmission = new Encounter.DiagnosisComponent()
            {
                Condition = new ResourceReference()
                {
                    Reference = diagnosisAtAdmission.Id
                },
                Role = new CodeableConcept("http://hl7.org/fhir/ValueSet/diagnosis-role", "AD", "Admission diagnosis")
            };

            var encounterAtAdmission = new Encounter();
            encounterAtAdmission.Id = FhirUtil.createUUID();
            encounterAtAdmission.Diagnosis.Add(diagnosisComponentAtAdmission);
            section_admissionDetail.Entry.Add(new ResourceReference()
            {
                Reference = encounterAtAdmission.Id
            });


            c.Section.Add(section_admissionDetail);

            //B.9情報提供者

            var section_informant = new Composition.SectionComponent();
            section_informant.Title = "informant";

            var informant = new RelatedPerson();
            informant.Id = FhirUtil.createUUID();

            var informantName = new HumanName().WithGiven("藤三郎").AndFamily("東京");
            informantName.Use = HumanName.NameUse.Official;
            informantName.AddExtension("http://hl7.org/fhir/StructureDefinition/iso21090-EN-representation", new FhirString("IDE"));
            informant.Name.Add(informantName);
            informant.Patient = new ResourceReference()
            {
                Reference = patient.Id
            };
            informant.Relationship = new CodeableConcept("http://hl7.org/fhir/ValueSet/relatedperson-relationshiptype", "FTH", "father");

            informant.Address.Add(new Address()
            {
                Line       = new string[] { "新宿区神楽坂一丁目50番地" },
                State      = "東京都",
                PostalCode = "01803",
                Country    = "日本"
            });

            informant.Telecom.Add(new ContactPoint()
            {
                System = ContactPoint.ContactPointSystem.Phone,
                Use    = ContactPoint.ContactPointUse.Work,
                Value  = "tel:(03)3555-1212"
            });


            section_informant.Entry.Add(new ResourceReference()
            {
                Reference = informant.Id
            });
            c.Section.Add(section_informant);


            // B.10 本文
            // B.10.1 本文記述

            var section_clinicalSummary = new Composition.SectionComponent();
            section_clinicalSummary.Title = "来院理由";

            section_clinicalSummary.Code = new CodeableConcept("http://loinc.org", "29299-5", "Reason for visit Narrative");

            var dischargeSummaryNarrative = new Narrative();
            dischargeSummaryNarrative.Status = Narrative.NarrativeStatus.Additional;
            dischargeSummaryNarrative.Div    = @"
<div xmlns=""http://www.w3.org/1999/xhtml"">\n\n
<p>平成19年喘息と診断を受けた。平成20年7月喘息の急性増悪にて当院呼吸器内科入院。退院後HL7医院にてFollowされていた</p>
<p>平成21年10月20日頃より右足首にじんじん感が出現。左足首、両手指にも認めるようになった。同時に37℃台の熱発出現しWBC28000、Eosi58%と上昇していた</p>
<p>このとき尿路感染症が疑われセフメタゾン投与されるも改善せず。WBC31500、Eosi64%と上昇、しびれ感の増悪認めた。またHb 7.3 Ht 20.0と貧血を認めた</p>
<p>膠原病、特にChuge-stress-syndoromeが疑われ平成21年11月8日当院膠原病内科入院となった</p>
</div>
            ";

            section_clinicalSummary.Text = dischargeSummaryNarrative;
            c.Section.Add(section_clinicalSummary);

            //B.10.3 観察・検査等
            //section-observations

            var section_observations = new Composition.SectionComponent();
            section_observations.Title = "observations";

            var obs = new List <Observation>()
            {
                FhirUtil.createLOINCObservation(patient, "8302-2", "身長", new Quantity()
                {
                    Value = (decimal)2.004,
                    Unit  = "m"
                }),
                FhirUtil.createLOINCObservation(patient, "8302-2", "身長", new Quantity()
                {
                    Value = (decimal)2.004,
                    Unit  = "m"
                }),
                //Component Resultsの例 血圧- 拡張期血圧、収縮期血圧のコンポーネントを含む。
                new Observation()
                {
                    Id      = FhirUtil.createUUID(),
                    Subject = new ResourceReference()
                    {
                        Reference = patient.Id
                    },
                    Status = ObservationStatus.Final,
                    Code   = new CodeableConcept()
                    {
                        Text   = "血圧",
                        Coding = new List <Coding>()
                        {
                            new Coding()
                            {
                                System  = "http://loinc.org",
                                Code    = "18684-1",
                                Display = "血圧"
                            }
                        }
                    },
                    Component = new List <Observation.ComponentComponent>()
                    {
                        new Observation.ComponentComponent()
                        {
                            Code = new CodeableConcept()
                            {
                                Text   = "収縮期血圧血圧",
                                Coding = new List <Coding>()
                                {
                                    new Coding()
                                    {
                                        System  = "http://loinc.org",
                                        Code    = "8480-6",
                                        Display = "収縮期血圧"
                                    }
                                }
                            },
                            Value = new Quantity()
                            {
                                Value = (decimal)120,
                                Unit  = "mm[Hg]"
                            }
                        },
                        new Observation.ComponentComponent()
                        {
                            Code = new CodeableConcept()
                            {
                                Text   = "拡張期血圧",
                                Coding = new List <Coding>()
                                {
                                    new Coding()
                                    {
                                        System  = "http://loinc.org",
                                        Code    = "8462-4",
                                        Display = "拡張期血圧"
                                    }
                                }
                            },
                            Value = new Quantity()
                            {
                                Value = (decimal)100,
                                Unit  = "mm[Hg]"
                            }
                        },
                    }
                }
            };


            foreach (var res in obs)
            {
                section_observations.Entry.Add(new ResourceReference()
                {
                    Reference = res.Id
                });
            }

            c.Section.Add(section_observations);


            //B.10.4 キー画像
            //section-medicalImages


            var mediaPath = basePath + "/../../resource/Hydrocephalus_(cropped).jpg";
            var media     = new Media();
            media.Id      = FhirUtil.createUUID();
            media.Type    = Media.DigitalMediaType.Photo;
            media.Content = FhirUtil.CreateAttachmentFromFile(mediaPath);

            /* R3ではImagingStudyに入れられるのはDICOM画像だけみたい。 R4ではreasonReferenceでMediaも参照できる。
             * とりあえずDSTU3ではMediaリソースをmedicalImagesセクションにセットする。
             * var imagingStudy = new ImagingStudy();
             * imagingStudy.Id = FhirUtil.getUUID(); //まだFHIRサーバにあげられていないから,一時的なUUIDを生成してリソースIDとしてセットする
             * imagingStudy.re
             */

            var section_medicalImages = new Composition.SectionComponent();
            section_medicalImages.Title = "medicalImages";
            //TODO: sectionのcodeは?
            section_medicalImages.Entry.Add(new ResourceReference()
            {
                Reference = media.Id
            });
            c.Section.Add(section_medicalImages);


            //Bundleの構築

            //Bundleの構成要素
            //Bunbdleの一番最初はCompostion Resourceであること。
            List <Resource> bdl_entries = new List <Resource> {
                c, patient, organization, practitioner, author, careteam, encounter, encounterAtAdmission,
                diagnosisAtAdmission, location, informant, media, attendingPhysician, attendingPractitionerRole
            };
            bdl_entries.AddRange(obs);


            foreach (Resource res in bdl_entries)
            {
                var entry = new Bundle.EntryComponent();
                //entry.FullUrl = res.ResourceBase.ToString()+res.ResourceType.ToString() + res.Id;
                entry.FullUrl  = res.Id;
                entry.Resource = res;
                bdl.Entry.Add(entry);
            }

            return(bdl);
        }
        public async Task <IHttpActionResult> PostCareTeam(CareTeamBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var patient = await userManager.FindByIdAsync(model.PatientId);

            if (patient == null)
            {
                return(NotFound());
            }

            List <ApplicationUser> providers = new List <ApplicationUser>();

            foreach (string ProviderId in model.ProviderIds)
            {
                var provider = await userManager.FindByIdAsync(ProviderId);

                if (provider == null)
                {
                    return(NotFound());
                }
                providers.Add(provider);
            }

            List <ApplicationUser> supporters = new List <ApplicationUser>();

            foreach (string SupporterId in model.SupporterIds)
            {
                var supporter = await userManager.FindByIdAsync(SupporterId);

                if (supporter == null)
                {
                    return(NotFound());
                }
                supporters.Add(supporter);
            }

            var careTeam = new CareTeam()
            {
                Id         = Guid.NewGuid(),
                Name       = model.Name,
                Active     = false,
                Providers  = providers,
                Supporters = supporters,
                Patient    = patient
            };

            db.CareTeam.Add(careTeam);
            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (CareTeamExists(careTeam.Id))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            return(Created("CareTeams/" + careTeam.Id, ToDto.CareTeamToDto(careTeam)));
        }