public List <PhrData> GetPatientData(PatientIdentifier p)
        {
            var retList = new List <PhrData>();

            foreach (var configurator in _availableConfigurators)
            {
                var configuration = configurator.GetConfiguration();
                foreach (var phrSource in _availablePhrs)
                {
                    if (phrSource.Source == null)
                    {
                        continue;
                    }
                    if (configuration.Sources.Select(s => s.InternalId).Contains(phrSource.Source.InternalId)) //not the best thing, but at this stage it will do...
                    {
                        var phrdata = phrSource.GetData(p, configuration);
                        if (phrdata == null)
                        {
                            // no data to add and/or process.
                            continue;
                        }
                        // filter
                        List <DataUnit> filteredData = new List <DataUnit>();
                        filteredData.AddRange(phrdata.Data.Where(pd => configuration.DesiredData.Select(s => s.OntologicName).Contains(pd.OntologicName)));
                        phrdata.Data = filteredData;
                        retList.Add(phrdata);
                    }
                }
            }
            return(retList);
        }
Exemple #2
0
        public PatientIdentifier SavePatientIdentifier(PatientIdentifier pi)
        {
            SqlServerConnection conn = new SqlServerConnection();

            pi.Id = conn.SqlServerUpdate("DECLARE @idnt INT=" + pi.Id + ", @default BIT='" + pi.Default + "', @patient INT=" + pi.Patient.Id + ", @type INT=" + pi.Type.Id + ", @identifier NVARCHAR(250)='" + pi.Identifier + "', @user INT=" + pi.AddedBy.Id + ", @notes NVARCHAR(MAX)='" + pi.Notes + "'; IF NOT EXISTS (SELECT pi_idnt FROM PatientIdentifier WHERE pi_idnt=@idnt) BEGIN INSERT INTO PatientIdentifier(pi_default, pi_patient, pi_type, pi_identifier, pi_added_by, pi_notes) output INSERTED.pi_idnt VALUES (@default, @patient, @type, @identifier, @user, @notes) END ELSE BEGIN UPDATE PatientIdentifier SET pi_default=@default, pi_type=@type, pi_identifier=@identifier, pi_notes=@notes output INSERTED.pi_idnt WHERE pi_idnt=@idnt END");

            return(pi);
        }
Exemple #3
0
        public CompositeIdentifierDetail CreateMrnDetail(PatientIdentifier mrn)
        {
            if (mrn == null)
            {
                return(new CompositeIdentifierDetail());
            }

            return(new CompositeIdentifierDetail(
                       mrn.Id,
                       EnumUtils.GetEnumValueInfo(mrn.AssigningAuthority)));
        }
        public string GetUserName(PatientIdentifier p)
        {
            if (authMap == null)
            {
                LoadAuthTokens();
            }
            if (this.authMap.ContainsKey(p.InternalId.ToString()))
            {
                return(((CarreAuthToken)authMap[p.InternalId.ToString()]).Username);
            }

            return(null);
        }
        //[ExpectedException(typeof(HealthServiceAccessDeniedException))]
        public void TestRumRun()
        {
            var rum     = new Rum(true);
            var patient = new PatientIdentifier()
            {
                InternalId = new Guid(PGuid)
            };
            var patData = rum.GetPatientData(patient);

            Assert.IsTrue(patData.FindAll(p => p.Patient.InternalId == patient.InternalId).Count == 1, "There are no entries for test patient, why?");
            Assert.IsTrue(patData.FindAll(p => p.Data.FindAll(d => d.OntologicName == "rdf:TestEntry").Count > 0).Count == 1, "PhrPluginEmpty should have been returned DataUnit with a TestEntry.");
            Assert.IsTrue(patData.FindAll(p => p.Data.FindAll(d => d.OntologicName == "rdf:DifferentTestEntry").Count > 0).Count == 0, "DifferentTestEntry should have been filtered out by RUMs' config.");
        }
        public CarreAuthToken GetAuthToken(PatientIdentifier p)
        {
            CarreAuthToken t = new CarreAuthToken();

            if (authMap == null)
            {
                LoadAuthTokens();
            }
            if (this.authMap.ContainsKey(p.InternalId.ToString()))
            {
                return((CarreAuthToken)authMap[p.InternalId.ToString()]);
            }

            return(null);
        }
Exemple #7
0
        public List <PhrData> GetMockData()
        {
            PatientIdentifier patient1 = new PatientIdentifier()
            {
                InternalId = new Guid(guid)
            };

            SourceIdentifier source1 = new SourceIdentifier()
            {
                InternalId = new Guid("5c30ee9a-2e63-42c7-b418-ef4fe2f3e565"),
                SourceName = "vivaport"
            };


            List <PhrData> TestData = new List <PhrData>()
            {
                new PhrData()
                {
                    Patient = patient1,
                    Source  = source1,
                    Data    = new List <DataUnit>()
                    {
                        new DataUnit()
                        {
                            OntologicName = "test1",
                            Datetime      = DateTime.Now.Date.AddDays(-2), //overrides value-1
                            Identifier    = "identifier-1",
                            Name          = "name-1",
                            Value         = "value-1",
                            Source        = source1,
                            OntologicType = "string",
                        },
                        new DataUnit()
                        {
                            OntologicName = "test2",
                            Datetime      = DateTime.Now.Date.AddDays(-2),
                            Identifier    = "identifier-2",
                            Name          = "name-2",
                            Value         = "value-1-1",
                            Source        = source1,
                            OntologicType = "string",
                        }
                    }
                },
            };

            return(TestData);
        }
 public PhrData GetData(PatientIdentifier p, Configuration config)
 {
     return new PhrData()
     {
         Source = this.Source,
         Patient = p,
         Data = new List<DataUnit>()
         {
             new DataUnit()
             {
                 OntologicName = "rdf:TestEntry",
                 Name = "TestEntry"
             },
             new DataUnit()
             {
                 OntologicName = "rdf:DifferentTestEntry",
                 Name = "DifferentTestEntry"
             }
         }
     };
 }
 public PhrData GetData(PatientIdentifier p, Configuration config)
 {
     return(new PhrData()
     {
         Source = this.Source,
         Patient = p,
         Data = new List <DataUnit>()
         {
             new DataUnit()
             {
                 OntologicName = "rdf:TestEntry",
                 Name = "TestEntry"
             },
             new DataUnit()
             {
                 OntologicName = "rdf:DifferentTestEntry",
                 Name = "DifferentTestEntry"
             }
         }
     });
 }
 public List <StudiesSummaryModel> GetStudiesSummary([FromUri(Name = "")] PatientIdentifier patientIdentifier)
 {
     try
     {
         if (patientIdentifier != null)
         {
             if (patientIdentifier.FromDate == Convert.ToDateTime("1/1/0001 12:00:00 AM"))
             {
                 patientIdentifier.FromDate = SqlDateTime.MinValue.Value;
             }
             if (patientIdentifier.ToDate == Convert.ToDateTime("1/1/0001 12:00:00 AM"))
             {
                 patientIdentifier.ToDate = SqlDateTime.MaxValue.Value;
             }
             return(_repo.GetStudiesSummary(patientIdentifier.Id, patientIdentifier.Type.ToString(), patientIdentifier.FromDate, patientIdentifier.ToDate));
         }
         return(null);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
 public PatientDetailsModel GetDetails([FromUri(Name = "")] PatientIdentifier patientIdentifier)
 {
     try
     {
         if (patientIdentifier != null)
         {
             if (patientIdentifier.FromDate == Convert.ToDateTime("1/1/0001 12:00:00 AM"))
             {
                 patientIdentifier.FromDate = SqlDateTime.MinValue.Value;
             }
             if (patientIdentifier.ToDate == Convert.ToDateTime("1/1/0001 12:00:00 AM"))
             {
                 patientIdentifier.ToDate = SqlDateTime.MaxValue.Value;
             }
             return(_repo.GetPatientInformation(patientIdentifier.Id, patientIdentifier.Type.ToString(), patientIdentifier.FromDate, patientIdentifier.ToDate));
         }
         return(null);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Exemple #12
0
        private PatientIdentifier GetMrgPatientIdentifier(MRG mrg)
        {
            PatientIdentifier identifier = new PatientIdentifier();

            CX[] cxs = mrg.GetPriorPatientIdentifierList();

            foreach (var cx in cxs)
            {
                Identifier assignAuth = new Identifier(
                    cx.AssigningAuthority.NamespaceID.Value,
                    cx.AssigningAuthority.UniversalID.Value,
                    cx.AssigningAuthority.UniversalIDType.Value);
                Identifier assignFac = new Identifier(
                    cx.AssigningFacility.NamespaceID.Value,
                    cx.AssigningFacility.UniversalID.Value,
                    cx.AssigningFacility.UniversalIDType.Value);
                identifier.AssigningAuthority = assignAuth;
                identifier.AssigningFacility  = assignFac;
                identifier.Id = cx.ID.Value;
                identifier.IdentifierTypeCode = cx.IdentifierTypeCode.Value;
            }

            return(identifier);
        }
        /// <summary>
        /// Implementation of GetData method outlined in interface
        /// </summary>
        /// <param name="p">patient identifier</param>
        /// <param name="config">configuration parameters</param>
        /// <returns>PHR data</returns>
        public PhrData GetData(PatientIdentifier p, Configuration config)
        {
            PhrData retData = new PhrData();
            retData.Patient = p;
            retData.Source = this._sourceId;
            retData.Data = new List<DataUnit>();
            if (getPatientId(p.InternalId) == null)
            {
                return retData;
            }

            if (!Documents.ContainsKey(getPatientId(p.InternalId)))
            {
                return retData;
            }

            foreach (DataUnit du in config.DesiredData)
            {
                if (!this.DataMap.ContainsKey(du.OntologicName))
                {
                    continue;
                }

                foreach (XmlDocument x in (List<XmlDocument>)Documents[getPatientId(p.InternalId)])
                {
                    XDocument xd = XDocument.Parse(x.OuterXml);
                    var val = (IEnumerable)xd.XPathEvaluate(this.DataMap[du.OntologicName].ToString());
                    DateTime dt = new DateTime();
                    if (DateMap.ContainsKey(du.OntologicName))
                    {
                        var dateVal = (IEnumerable)xd.XPathEvaluate(this.DateMap[du.OntologicName].ToString());
                        if (dateVal.Cast<XText>().FirstOrDefault() != null)
                        {
                            var date = dateVal.Cast<XText>().FirstOrDefault().Value;
                            if (!DateTime.TryParse(date, out dt))
                            {
                                dt = DateTime.Parse("1900-01-01");
                            }
                        }
                        else
                        {
                            dt = DateTime.Parse("1900-01-01");
                        }
                    }
                    string type = "string";
                    if (TypeMap.ContainsKey(du.OntologicName))
                    {
                        type = TypeMap[du.OntologicName].ToString();
                    }
                    if (val.Cast<XText>().FirstOrDefault() == null) { continue; }
                    var value = val.Cast<XText>().FirstOrDefault().Value;
                    retData.Data.Add(new DataUnit() { OntologicName = du.OntologicName, Value = value, Name = du.Name, Identifier = this._sourceId.SourceName, Datetime = dt, OntologicType = type });
                }
            }
            return retData;
        }
Exemple #14
0
        public async Task <PatientIdentifier> EnrollPatient(string enrollmentNo, int patientId, int serviceAreaId, int createdBy, DateTime dateOfEnrollment)
        {
            using (var trans = _unitOfWork.Context.Database.BeginTransaction())
            {
                try
                {
                    var previouslyIdentifiers = await _unitOfWork.Repository <PatientIdentifier>().Get(y =>
                                                                                                       y.IdentifierValue == enrollmentNo && y.IdentifierTypeId == 8)
                                                .ToListAsync();

                    if (previouslyIdentifiers.Count > 0)
                    {
                        var exception = new Exception("No: " + enrollmentNo + " already exists");
                        throw exception;
                    }

                    var enrollmentVisitType = await _unitOfWork.Repository <LookupItemView>().Get(x => x.MasterName == "VisitType" && x.ItemName == "Enrollment").FirstOrDefaultAsync();

                    int?visitType          = enrollmentVisitType != null ? enrollmentVisitType.ItemId : 0;
                    var patientMasterVisit = new PatientMasterVisit()
                    {
                        PatientId  = patientId,
                        ServiceId  = serviceAreaId,
                        Start      = DateTime.Now,
                        End        = null,
                        Active     = false,
                        VisitDate  = DateTime.Now,
                        VisitType  = visitType,
                        Status     = 1,
                        CreateDate = DateTime.Now,
                        DeleteFlag = false,
                        CreatedBy  = createdBy
                    };

                    await _unitOfWork.Repository <PatientMasterVisit>().AddAsync(patientMasterVisit);

                    await _unitOfWork.SaveAsync();

                    var patientEnrollment = new PatientEnrollment()
                    {
                        PatientId          = patientId,
                        ServiceAreaId      = serviceAreaId,
                        EnrollmentDate     = dateOfEnrollment,
                        EnrollmentStatusId = 0,
                        TransferIn         = false,
                        CareEnded          = false,
                        DeleteFlag         = false,
                        CreatedBy          = createdBy,
                        CreateDate         = DateTime.Now
                    };

                    await _unitOfWork.Repository <PatientEnrollment>().AddAsync(patientEnrollment);

                    await _unitOfWork.SaveAsync();

                    var patientIdentifier = new PatientIdentifier()
                    {
                        PatientId           = patientId,
                        PatientEnrollmentId = patientEnrollment.Id,
                        IdentifierTypeId    = 8,
                        IdentifierValue     = enrollmentNo,
                        DeleteFlag          = false,
                        CreatedBy           = createdBy,
                        CreateDate          = DateTime.Now,
                        Active = true
                    };

                    await _unitOfWork.Repository <PatientIdentifier>().AddAsync(patientIdentifier);

                    await _unitOfWork.SaveAsync();

                    GetPatientDetails patientDetails = new GetPatientDetails(_unitOfWork);
                    LookupLogic       lookupLogic    = new LookupLogic(_unitOfWork);

                    var patientLookup = await patientDetails.GetPatientByPatientId(patientId);

                    if (patientLookup.Count > 0)
                    {
                        Facility facility = await _unitOfWork.Repository <Facility>().Get(x => x.DeleteFlag == 0).FirstOrDefaultAsync();

                        var referralId = await lookupLogic.GetDecodeIdByName("VCT", 17);

                        var maritalStatusId = await lookupLogic.GetDecodeIdByName(patientLookup[0].MaritalStatusName, 17);

                        var address      = patientLookup[0].PhysicalAddress == null ? " " : patientLookup[0].PhysicalAddress;
                        var phone        = patientLookup[0].MobileNumber == null ? " " : patientLookup[0].MobileNumber;
                        var dobPrecision = 0;
                        if (patientLookup[0].DobPrecision.HasValue)
                        {
                            var dobPrecisionValue = patientLookup[0].DobPrecision.Value;
                            dobPrecision = dobPrecisionValue ? 1 : 0;
                        }

                        var gender = 0;
                        if (patientLookup[0].Gender == "Male")
                        {
                            gender = 16;
                        }
                        else if (patientLookup[0].Gender == "Female")
                        {
                            gender = 17;
                        }

                        string dateOfBirth = string.Empty;
                        if (patientLookup[0].DateOfBirth.HasValue)
                        {
                            dateOfBirth = patientLookup[0].DateOfBirth.Value.ToString("yyyy-MM-dd");
                        }

                        StringBuilder sql = new StringBuilder();
                        sql.Append("exec pr_OpenDecryptedSession;");
                        sql.Append("Insert Into mst_Patient(FirstName, LastName, MiddleName, LocationID, PatientEnrollmentID, ReferredFrom, RegistrationDate, Sex, DOB, DobPrecision, MaritalStatus, Address, Phone, UserID, PosId, Status, DeleteFlag, CreateDate,MovedToPatientTable)");
                        sql.Append("Values(");
                        sql.Append($"ENCRYPTBYKEY(KEY_GUID('Key_CTC'),'{patientLookup[0].FirstName}'),");
                        sql.Append($"ENCRYPTBYKEY(KEY_GUID('Key_CTC'),'{patientLookup[0].LastName}'),");
                        sql.Append($"ENCRYPTBYKEY(KEY_GUID('Key_CTC'),'{patientLookup[0].MidName}'),");
                        sql.Append($"'{facility.FacilityID}',");
                        sql.Append("' ',");
                        sql.Append($"'{referralId}',");
                        sql.Append($"'{dateOfEnrollment.ToString("yyyy-MM-dd")}',");
                        sql.Append($"'{gender}',");
                        sql.Append($"'{dateOfBirth}',");
                        sql.Append($"'{dobPrecision}',");
                        sql.Append($"'{maritalStatusId}',");
                        sql.Append($"ENCRYPTBYKEY(KEY_GUID('Key_CTC'),'{address}'),");
                        sql.Append($"ENCRYPTBYKEY(KEY_GUID('Key_CTC'),'{phone}'),");
                        sql.Append($"'{createdBy}',");
                        sql.Append($"'{facility.PosID}',");
                        sql.Append("0,");
                        sql.Append("0,");
                        sql.Append($"'{dateOfEnrollment.ToString("yyyy-MM-dd")}',");
                        sql.Append("1");
                        sql.Append(");");

                        sql.Append("SELECT Ptn_Pk, CAST(DECRYPTBYKEY([FirstName]) AS VARCHAR(50)) AS FirstName, CAST(DECRYPTBYKEY([LastName]) AS VARCHAR(50)) AS LastName, LocationID FROM [dbo].[mst_Patient] WHERE [Ptn_Pk] = SCOPE_IDENTITY();");
                        sql.Append("exec [dbo].[pr_CloseDecryptedSession];");

                        var result = await _unitOfWork.Repository <MstPatient>().FromSql(sql.ToString());

                        StringBuilder sqlBuilder = new StringBuilder();
                        sqlBuilder.Append("Insert Into Lnk_PatientProgramStart(Ptn_pk, ModuleId, StartDate, UserID, CreateDate)");
                        sqlBuilder.Append("Values(");
                        sqlBuilder.Append($"'{result[0].Ptn_Pk}',");
                        sqlBuilder.Append("283,");
                        sqlBuilder.Append($"'{dateOfEnrollment.ToString("yyyy-MM-dd")}',");
                        sqlBuilder.Append($"'{createdBy}',");
                        sqlBuilder.Append($"'{dateOfEnrollment.ToString("yyyy-MM-dd")}'");
                        sqlBuilder.Append(");");

                        var insertResult = await _unitOfWork.Context.Database.ExecuteSqlCommandAsync(sqlBuilder.ToString());

                        StringBuilder sqlPatient = new StringBuilder();
                        sqlPatient.Append($"UPDATE Patient SET ptn_pk = '{result[0].Ptn_Pk}' WHERE Id = '{patientId}';");
                        var updateResult = await _unitOfWork.Context.Database.ExecuteSqlCommandAsync(sqlPatient.ToString());
                    }

                    trans.Commit();

                    return(patientIdentifier);
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    throw ex;
                }
            }
        }
        public void TestUnification()
        {
            var unificator = new Unificator();

            unificator.LoadUnificationRules("../../Fixtures/SourcePriorities.xml");

            PatientIdentifier patient1 = new PatientIdentifier()
            {
                InternalId = new Guid("5c30ee9a-2e63-42c7-b418-ef4fe2f3e565")
            };
            PatientIdentifier patient2 = new PatientIdentifier()
            {
                InternalId = new Guid("5c30ee9a-2e63-42c7-b418-ef4fe2f3e566")           // should be untouched
            };

            SourceIdentifier source1 = new SourceIdentifier()
            {
                InternalId = new Guid("5c30ee9a-2e63-42c7-b418-ef4fe2f3e565"),           // has priority 10
                SourceName = "FAKE"
            };
            SourceIdentifier source2 = new SourceIdentifier()
            {
                InternalId = new Guid("5c30ee9a-2e63-42c7-b418-ef4fe2f3e566"),           // has priority 20
                SourceName = "FAKE"
            };

            List <PhrData> TestData = new List <PhrData>()
            {
                new PhrData()
                {
                    Patient = patient1,
                    Source  = source1,
                    Data    = new List <DataUnit>()
                    {
                        new DataUnit()
                        {
                            OntologicName = "test1",
                            Datetime      = DateTime.Now.Date.AddDays(-2), //overrides value-1
                            Identifier    = "identifier-1",
                            Name          = "name-1",
                            Value         = "value-1"
                        },
                        new DataUnit()
                        {
                            OntologicName = "test2",
                            Datetime      = DateTime.Now.Date.AddDays(-2),
                            Identifier    = "identifier-2",
                            Name          = "name-2",
                            Value         = "value-1-1"
                        }
                    }
                },
                new PhrData()
                {
                    Patient = patient1,
                    Source  = source2, // priority of 20, should be overriden
                    Data    = new List <DataUnit>()
                    {
                        new DataUnit()
                        {
                            OntologicName = "test1",
                            Datetime      = DateTime.Now.Date.AddDays(-2),
                            Identifier    = "identifier-1",
                            Name          = "name-1",
                            Value         = "value-1-3"
                        },
                        new DataUnit()
                        {
                            OntologicName = "test2",
                            Datetime      = DateTime.Now.Date.AddDays(-1), //newer, should override
                            Identifier    = "identifier-2",
                            Name          = "name-2",
                            Value         = "value-1-4"
                        }
                    }
                },
                new PhrData()
                {
                    Patient = patient2,
                    Source  = source2,
                    Data    = new List <DataUnit>()
                    {
                        new DataUnit()
                        {
                            OntologicName = "test1",
                            Datetime      = DateTime.Now.AddDays(-2),
                            Identifier    = "identifier-1",
                            Name          = "name-1",
                            Value         = "value-1"
                        },
                        new DataUnit()
                        {
                            OntologicName = "test2",
                            Datetime      = DateTime.Now.AddDays(-1),
                            Identifier    = "identifier-2",
                            Name          = "name-2",
                            Value         = "value-1-1"
                        }
                    }
                },
            };

            List <PhrData> result = unificator.Unify(TestData);

            Assert.IsTrue(result.Exists(phd => phd.Patient == patient1), "patient1 should exist in list.");
            Assert.IsTrue(result.Exists(phd => phd.Patient == patient2), "patient2 should exist in list.");

            Assert.IsTrue(result.FindAll(phd => phd.Patient == patient1).Exists(pd => pd.Data.Exists(dat => dat.Name == "name-1")), "patient1 data missing");
            Assert.IsTrue(result.FindAll(phd => phd.Patient == patient1).Exists(pd => pd.Data.Exists(dat => dat.Name == "name-2")), "patient1 data missing");

            Assert.IsTrue(result.FindAll(phd => phd.Patient == patient2).Exists(pd => pd.Data.Exists(dat => dat.Name == "name-1")), "patient2 data missing");
            Assert.IsTrue(result.FindAll(phd => phd.Patient == patient2).Exists(pd => pd.Data.Exists(dat => dat.Name == "name-2")), "patient2 data missing");


            Assert.IsTrue(result.FindAll(phd => phd.Patient == patient2).Exists(pd => pd.Data.Exists(dat => dat.Name == "name-1" && dat.Value == "value-1")), "patient2 data touched!");
            Assert.IsTrue(result.FindAll(phd => phd.Patient == patient2).Exists(pd => pd.Data.Exists(dat => dat.Name == "name-2" && dat.Value == "value-1-1")), "patient2 data touched!");

            Assert.IsTrue(result.FindAll(phd => phd.Patient == patient1).FindAll(pd => pd.Data.Exists(dat => dat.Name == "name-1")).Count == 1);
            Assert.IsTrue(result.FindAll(phd => phd.Patient == patient1).FindAll(pd => pd.Data.Exists(dat => dat.Name == "name-2")).Count == 1);

            Assert.IsTrue(result.FindAll(phd => phd.Patient == patient1).Exists(pd => pd.Data.Exists(dat => dat.Name == "name-1" && dat.Value == "value-1")), "patient1 data identifier-1 is not value-1!");
            Assert.IsTrue(result.FindAll(phd => phd.Patient == patient1).Exists(pd => pd.Data.Exists(dat => dat.Name == "name-2" && dat.Value == "value-1-4")), "partient1 data name-2 is not value-1-4!");
        }
Exemple #16
0
			public IdentifierFacade(PatientIdentifier identifier)
			{
				_identifier = identifier;
			}
Exemple #17
0
        public async Task <Result <EnrollClientResponse> > Handle(EnrollClientCommand request, CancellationToken cancellationToken)
        {
            using (var trans = _unitOfWork.Context.Database.BeginTransaction())
            {
                try
                {
                    var patientMasterVisit = new PatientMasterVisit()
                    {
                        PatientId      = request.ClientEnrollment.PatientId,
                        ServiceId      = request.ClientEnrollment.ServiceAreaId,
                        Start          = DateTime.Now,
                        End            = null,
                        Active         = false,
                        VisitDate      = DateTime.Now,
                        VisitScheduled = 0,
                        VisitBy        = 108,
                        VisitType      = 1,
                        Status         = 1,
                        CreateDate     = DateTime.Now,
                        DeleteFlag     = false,
                        CreatedBy      = request.ClientEnrollment.CreatedBy
                    };

                    await _unitOfWork.Repository <PatientMasterVisit>().AddAsync(patientMasterVisit);

                    await _unitOfWork.SaveAsync();

                    var patientEnrollment = new PatientEnrollment()
                    {
                        PatientId          = request.ClientEnrollment.PatientId,
                        ServiceAreaId      = request.ClientEnrollment.ServiceAreaId,
                        EnrollmentDate     = request.ClientEnrollment.DateOfEnrollment,
                        EnrollmentStatusId = 0,
                        TransferIn         = false,
                        CareEnded          = false,
                        DeleteFlag         = false,
                        CreatedBy          = request.ClientEnrollment.CreatedBy,
                        CreateDate         = DateTime.Now
                    };

                    await _unitOfWork.Repository <PatientEnrollment>().AddAsync(patientEnrollment);

                    await _unitOfWork.SaveAsync();

                    var patientIdentifier = new PatientIdentifier()
                    {
                        PatientId           = request.ClientEnrollment.PatientId,
                        PatientEnrollmentId = patientEnrollment.Id,
                        IdentifierTypeId    = 8,
                        IdentifierValue     = request.ClientEnrollment.EnrollmentNo,
                        DeleteFlag          = false,
                        CreatedBy           = request.ClientEnrollment.CreatedBy,
                        CreateDate          = DateTime.Now,
                        Active = true
                    };

                    await _unitOfWork.Repository <PatientIdentifier>().AddAsync(patientIdentifier);

                    await _unitOfWork.SaveAsync();

                    trans.Commit();

                    return(Result <EnrollClientResponse> .Valid(new EnrollClientResponse
                    {
                        IdentifierValue = request.ClientEnrollment.EnrollmentNo,
                        IdentifierId = patientIdentifier.Id
                    }));
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    return(Result <EnrollClientResponse> .Invalid(ex.Message));
                }
            }
        }
Exemple #18
0
 public IdentifierFacade(PatientIdentifier identifier)
 {
     _identifier = identifier;
 }
Exemple #19
0
 private static void RemovePatientIdentifier(
     PatientIdentifierDto patientIdentifierDto, Patient patient, PatientIdentifier patientIdentifier)
 {
     patient.RemoveIdentifier(patientIdentifier);
 }
Exemple #20
0
 private void ChangePatientIdentifier(PatientIdentifierDto patientIdentifierDto, Patient patient, PatientIdentifier patientIdentifier)
 {
     RemovePatientIdentifier(patientIdentifierDto, patient, patientIdentifier);
     AddPatientIdentifier(patientIdentifierDto, patient);
 }
Exemple #21
0
        public byte[] ProcessMessage(byte[] request)
        {
            string msgIn = Encoding.UTF8.GetString(request);

            var parser = new PipeParser();

            IMessage  msg    = parser.Parse(msgIn, "2.3.1");
            HL7Header header = new HL7Header(msg);

            ACK reply = InitAcknowledgment(header);
            XdsPatientServiceImpl patientService = new XdsPatientServiceImpl();

            PID pid231;

            try
            {
                LogAdapter.Logger.Info(string.Format("Process HL7 event {0}", header.TriggerEvent));
                //Platform.Log(LogLevel.Info, "Process HL7 event {0}", header.TriggerEvent);
                switch (header.TriggerEvent)
                {
                case "A01":
                case "A04":
                case "A05":     // Insert Patient
                {
                    pid231 = (PID)msg.GetStructure("PID");
                    PatientIdentifier patientIdentifier = GetPatientIdentifier(pid231);
                    var patientInfo = new PatientInfo()
                    {
                        PatientIdent = patientIdentifier
                    };

                    //if (!PixRegistryConfigration.IsValidDomain(patient.AssigningAuthority))
                    //{
                    //    PopulateErr(reply.ERR, "PID", "1", "3", "204", "Unknown Key Identifier", "Domain don't accept.");
                    //    throw new HL7Exception("Unknown Key Identifier", ErrorCode.UnknownKeyIdentifier, ErrorSeverity.E);
                    //}

                    AnalyzePID(pid231, ref patientInfo);
                    patientService.CreatePatient(patientInfo);
                    break;
                }

                case "A08":     // Update Patient
                {
                    pid231 = (PID)msg.GetStructure("PID");
                    PatientIdentifier patientIdentifier = GetPatientIdentifier(pid231);
                    var patientInfo = new PatientInfo()
                    {
                        PatientIdent = patientIdentifier
                    };

                    //if (!PixRegistryConfigration.IsValidDomain(patient.AssigningAuthority))
                    //{
                    //    PopulateErr(reply.ERR, "PID", "1", "3", "204", "Unknown Key Identifier", "Domain don't accept.");
                    //    throw new HL7Exception("Unknown Key Identifier", ErrorCode.UnknownKeyIdentifier, ErrorSeverity.E);
                    //}

                    AnalyzePID(pid231, ref patientInfo);
                    patientService.UpdatePatient(patientInfo);
                    break;
                }

                //case "A40": // Merge Patient
                //    {
                //        ADT_A40_PATIENT allPatient = (ADT_A40_PATIENT)msg.GetStructure("PATIENT");
                //        PatientIdentifier patient = GetPatientIdentifier(allPatient.PID);
                //        PatientIdentifier mergePatient = GetMrgPatientIdentifier(allPatient.MRG);

                //        //if (!PixRegistryConfigration.IsValidDomain(patient.AssigningAuthority))
                //        //{
                //        //    PopulateErr(reply.ERR, "PID", "1", "3", "204", "Unknown Key Identifier", "Domain don't accept.");
                //        //    throw new HL7Exception("Unknown Key Identifier", ErrorCode.UnknownKeyIdentifier, ErrorSeverity.E);
                //        //}

                //        patientService.MergePatient(patient, mergePatient);
                //        break;
                //    }

                default:
                {
                    const string ErrorMsg =
                        "Unexpected request to XDS-Registry. Valid message type are ADT^A01, ADT^A04, ADT^A05, ADT^A08, ADT^A40";
                    LogAdapter.Logger.Error(ErrorMsg);
                    //Platform.Log(LogLevel.Warn, ErrorMsg);
                    throw new Exception(ErrorMsg);
                }
                }

                PopulateMSA(reply.MSA, "AA", header.MessageControlId);
            }
            catch (HL7Exception ex)
            {
                LogAdapter.Logger.TraceException(ex);
                //Platform.Log(LogLevel.Warn, ex);
                PopulateMSA(reply.MSA, "AE", header.MessageControlId);
            }
            catch (PatientDonotExistException ex)
            {
                LogAdapter.Logger.TraceException(ex);
                //Platform.Log(LogLevel.Warn, ex);
                PopulateMSA(reply.MSA, "AE", header.MessageControlId);
                PopulateErr(reply.ERR, "PID", "1", "3", "204", "Unknown Key Identifier", ex.Message);
            }
            catch (Exception ex)
            {
                LogAdapter.Logger.TraceException(ex);
                //Platform.Log(LogLevel.Warn, ex);
                PopulateMSA(reply.MSA, "AE", header.MessageControlId);
                PopulateErr(reply.ERR, string.Empty, string.Empty, string.Empty, "207", "Application internal error", ex.Message);
            }

            return(Encoding.UTF8.GetBytes(parser.Encode(reply)));
        }
        /// <summary>
        /// Implementation of GetData method outlined in interface
        /// </summary>
        /// <param name="p">patient identifier</param>
        /// <param name="config">configuration parameters</param>
        /// <returns>PHR data</returns>
        public PhrData GetData(PatientIdentifier p, Configuration config)
        {
            PhrData retData = new PhrData();

            retData.Patient = p;
            retData.Source  = this._sourceId;
            retData.Data    = new List <DataUnit>();
            if (getPatientId(p.InternalId) == null)
            {
                return(retData);
            }

            if (!Documents.ContainsKey(getPatientId(p.InternalId)))
            {
                return(retData);
            }

            foreach (DataUnit du in config.DesiredData)
            {
                if (!this.DataMap.ContainsKey(du.OntologicName))
                {
                    continue;
                }

                foreach (XmlDocument x in (List <XmlDocument>)Documents[getPatientId(p.InternalId)])
                {
                    XDocument xd  = XDocument.Parse(x.OuterXml);
                    var       val = (IEnumerable)xd.XPathEvaluate(this.DataMap[du.OntologicName].ToString());
                    DateTime  dt  = new DateTime();
                    if (DateMap.ContainsKey(du.OntologicName))
                    {
                        var dateVal = (IEnumerable)xd.XPathEvaluate(this.DateMap[du.OntologicName].ToString());
                        if (dateVal.Cast <XText>().FirstOrDefault() != null)
                        {
                            var date = dateVal.Cast <XText>().FirstOrDefault().Value;
                            if (!DateTime.TryParse(date, out dt))
                            {
                                dt = DateTime.Parse("1900-01-01");
                            }
                        }
                        else
                        {
                            dt = DateTime.Parse("1900-01-01");
                        }
                    }
                    string type = "string";
                    if (TypeMap.ContainsKey(du.OntologicName))
                    {
                        type = TypeMap[du.OntologicName].ToString();
                    }
                    if (val.Cast <XText>().FirstOrDefault() == null)
                    {
                        continue;
                    }
                    var value = val.Cast <XText>().FirstOrDefault().Value;
                    retData.Data.Add(new DataUnit()
                    {
                        OntologicName = du.OntologicName, Value = value, Name = du.Name, Identifier = this._sourceId.SourceName, Datetime = dt, OntologicType = type
                    });
                }
            }
            return(retData);
        }
Exemple #23
0
        public PhrData GetData(PatientIdentifier p, Configuration c)
        {
            var clientApp = HealthClientApplication.Create(_clientId, _masterId, _shellUri, _platformUri);

            if (clientApp.GetApplicationInfo() == null)
            {
                // Create a new client instance.
                clientApp.StartApplicationCreationProcess();
                return(null);
            }

            var ap = clientApp.ApplicationConnection.GetAuthorizedPeople().ToList();

            var pi = clientApp.ApplicationConnection.GetAuthorizedPeople().FirstOrDefault(k => k.PersonId == p.InternalId);

            if (pi == null)
            {
                clientApp.StartUserAuthorizationProcess();
                return(null);                // not authorized;
            }

            var authConnection = clientApp.CreateAuthorizedConnection(pi.PersonId);
            var access         = new HealthRecordAccessor(authConnection, authConnection.GetPersonInfo().GetSelfRecord().Id);

            var ret = new PhrData {
                Data = new List <DataUnit>(), Patient = p, Source = Source
            };

            ret.Data.Add(new DataUnit {
                Datetime = DateTime.UtcNow, Name = "Name", OntologicName = "rdf:Name", Value = pi.Name
            });
            var b = GetSingleValue <Basic>(Basic.TypeId, access);

            ret.Data.Add(new DataUnit {
                Datetime      = b.EffectiveDate,
                Name          = "Birth date",
                OntologicName = "rdf:BDate",
                Value         = b.BirthYear
            });
            var gender = b.Gender ?? Gender.Unknown;

            ret.Data.Add(new DataUnit {
                Datetime      = b.EffectiveDate,
                Name          = "Gender",
                OntologicName = "rdf:Gender",
                Value         = gender == Gender.Male ? "male" : gender == Gender.Female ? "female" : "unknown"
            });
            ret.Data.Add(new DataUnit {
                Datetime      = b.EffectiveDate,
                Name          = "Country",
                OntologicName = "rdf:Country",
                Value         = b.Country
            });
            var heights = GetValues <Height>(Height.TypeId, access);

            foreach (var h in heights)
            {
                ret.Data.Add(new DataUnit {
                    Datetime      = h.EffectiveDate,
                    Name          = "Height_meters",
                    OntologicName = "rdf:Height",
                    Value         = h.Value.Meters
                });
            }

            var weights = GetValues <Weight>(Weight.TypeId, access);

            foreach (var w in weights)
            {
                ret.Data.Add(new DataUnit {
                    Datetime      = w.EffectiveDate,
                    Name          = "weight_kg",
                    OntologicName = "rdf:Height",
                    Value         = w.Value.Kilograms
                });
            }


            return(ret);
        }