Exemple #1
0
        //PV1|1|O|Ward1^RoomE8^Bed10^ADHAHOSP&2.16.840.1.113883.19.5&ISO||||ABCB^AttendingOmar^Muhammad^^^Dr^^^SUPER-LIS~123456^AttendingOmar^Muhammad^^^Dr^^^ADHAHOSP~2304227F^AttendingOmar^Muhammad^^^Dr^^^AUSHICPR|HIJK^ReferringWilliams^Simon^^^Dr^^^SUPER-LIS~858595^ReferringWilliams^Simon^^^Dr^^^ADHAHOSP~2929016F^ReferringWilliams^Simon^^^Dr^^^AUSHICPR
        public static ISegment GetPV1(string patientClassCode, Spia.PathologyReportModel.Model.Provider referringProvider, string performingLabNataSiteNumber)
        {
            ISegment PV1 = Creator.Segment("PV1");

            PV1.Field(1).AsString = "1";
            PV1.Field(2).AsString = patientClassCode;

            //IField PatientLocation = Creator.Field();
            //PatientLocation.Component(1).AsString = "Ward1";
            //PatientLocation.Component(2).AsString = "RoomE8";
            //PatientLocation.Component(3).AsString = "Bed10";
            //PatientLocation.Component(4).SubComponent(1).AsString = "ADHAHOSP";
            //PatientLocation.Component(5).SubComponent(2).AsString = "2.16.840.1.113883.19.5";
            //PatientLocation.Component(5).SubComponent(3).AsString = "ISO";
            //PV1.Element(3).Add(PatientLocation);


            foreach (var Id in referringProvider.IdentifierList)
            {
                var    IdentiferTypeInfo = HL7v2IdentifierSupport.GetIdentiferCode(Id, $"NATA{performingLabNataSiteNumber}");
                IField Field             = Creator.Field();
                Field.Component(1).AsString  = IdentiferTypeInfo.Value;
                Field.Component(2).AsString  = referringProvider.Name.Family;
                Field.Component(3).AsString  = referringProvider.Name.Given ?? "";
                Field.Component(6).AsString  = referringProvider.Name.Title ?? "";
                Field.Component(9).AsString  = IdentiferTypeInfo.AssigingAuthority;
                Field.Component(10).AsString = "L";
                Field.Component(13).AsString = IdentiferTypeInfo.TypeCode ?? "";

                //PV1-8: Definition: This field contains the referring physician information. Multiple names and identifiers for the same
                //physician may be sent. The field sequences are not used to indicate multiple referring doctors. The legal name must be sent
                //in the first sequence. If the legal name is not sent, then a repeat delimiter must be sent in the first sequence. Depending on
                //local agreements, either the ID or the name may be absent from this field. Refer to User-defined Table 0010 - Physician ID for suggested values
                PV1.Element(8).Add(Field);

                //https://confluence.hl7australia.com/display/OOADRM20181/2+Patient+Administration+for+Pathology#id-2PatientAdministrationforPathology-PV1-92.2.2.9PV1-9Consultingdoctor(XCN)00139
                //PV1-9: In the Australian setting this field is used to identify the target provider for this message.
                //A location specific ID is used and the field should not repeat as each message is unique for the target provider.
                //Where available the Medicare provider number is used as this provides for a location specific identifier. Messages
                //should be routed based on this field and only the first repeat is used.
                if (Id.Type == PathologyReportModel.Model.IdentifierType.MedicareProviderNumber)
                {
                    PV1.Element(9).Add(Field.Clone());
                }
            }

            return(PV1);
        }
Exemple #2
0
        public void Process(Spia.PathologyReportModel.Model.PathologyReport Report, string CdaOutputDirectory, string PdfDirectory, byte[] LogoBytes = null)
        {
            var pathologyResultReport = PathologyResultReport.CreatePathologyResultReport();

            // Include Logo
            if (LogoBytes != null)
            {
                pathologyResultReport.IncludeLogo = true;
                pathologyResultReport.LogoByte    = LogoBytes;
            }
            else
            {
                pathologyResultReport.IncludeLogo = false;
            }


            // Set Creation Time
            DateTimeOffset DocumentCreationDateTime = Report.GetOldestReportReleaseDateTime();

            pathologyResultReport.DocumentCreationTime = new ISO8601DateTime(DocumentCreationDateTime.DateTime, ISO8601DateTime.Precision.Second, DocumentCreationDateTime.Offset);


            #region Setup and populate the CDA context model

            // Setup and populate the CDA context model
            var cdaContext = PathologyResultReport.CreateCDAContext();
            // Document Id
            cdaContext.DocumentId = BaseCDAModel.CreateIdentifier(BaseCDAModel.CreateOid(), null);
            // Set Id
            cdaContext.SetId = BaseCDAModel.CreateIdentifier(BaseCDAModel.CreateGuid(), null);

            // CDA Context Version , this needs to increment for each correction to the first report instance
            cdaContext.Version = "1";
            // Custodian
            cdaContext.Custodian = BaseCDAModel.CreateCustodian();

            //custodian/assignedCustodian
            cdaContext.Custodian.Participant = BaseCDAModel.CreateParticipantCustodian();;

            // custodian/assignedCustodian/representedCustodianOrganization
            cdaContext.Custodian.Participant.Organisation = BaseCDAModel.CreateOrganisationName();

            // custodian/assignedCustodian/representedCustodianOrganization/<Entity Identifier>
            cdaContext.Custodian.Participant.Organisation.Identifiers = new List <Identifier>
            {
                BaseCDAModel.CreateHealthIdentifier(HealthIdentifierType.HPIO, Report.PerformingLaboratory.Hpio.Replace(" ", string.Empty))
            };

            // custodian/assignedCustodian/representedCustodianOrganization/name
            cdaContext.Custodian.Participant.Organisation.Name = Report.PerformingLaboratory.FacilityName;

            ElectronicCommunicationDetail PerformingPathologyLabComms = BaseCDAModel.CreateElectronicCommunicationDetail(
                Report.PerformingLaboratory.BusinessPhoneNumber,
                ElectronicCommunicationMedium.Telephone,
                ElectronicCommunicationUsage.WorkPlace);

            // custodian/assignedCustodian/representedCustodianOrganization/<Address>
            cdaContext.Custodian.Participant.Address = GetCdaAddress(Report.PerformingLaboratory.Address);

            // custodian/assignedCustodian/representedCustodianOrganization/<Electronic Communication Detail>
            cdaContext.Custodian.Participant.ElectronicCommunicationDetail = PerformingPathologyLabComms;


            // Legal Authenticator
            cdaContext.LegalAuthenticator = BaseCDAModel.CreateLegalAuthenticator();
            // LegalAuthenticator/assignedEntity
            cdaContext.LegalAuthenticator.Participant = BaseCDAModel.CreateParticipantForLegalAuthenticator();

            // LegalAuthenticator/assignedEntity/assignedPerson
            cdaContext.LegalAuthenticator.Participant.Person = BaseCDAModel.CreatePerson();

            DateTimeOffset OldestReportReleaseDate = Report.GetOldestReportReleaseDateTime();
            // LegalAuthenticator/time/@value
            cdaContext.LegalAuthenticator.Participant.DateTimeAuthenticated = new ISO8601DateTime(OldestReportReleaseDate.DateTime, ISO8601DateTime.Precision.Second, OldestReportReleaseDate.Offset);


            Spia.PathologyReportModel.Model.Provider FirstReportingPathologist = Report.ReportList.First().ReportingPathologist;

            //LegalAuthenticator/assignedEntity/assignedPerson/<Person Name>
            var ReportingPathologistName = BaseCDAModel.CreatePersonName();
            if (FirstReportingPathologist.Name.Given is object)
            {
                ReportingPathologistName.GivenNames = new List <string> {
                    FirstReportingPathologist.Name.Given
                };
            }

            ReportingPathologistName.FamilyName = FirstReportingPathologist.Name.Family;
            if (FirstReportingPathologist.Name.Title is object)
            {
                ReportingPathologistName.Titles = new List <string> {
                    FirstReportingPathologist.Name.Title
                };
            }

            ReportingPathologistName.NameUsages = new List <NameUsage> {
                NameUsage.Legal
            };

            cdaContext.LegalAuthenticator.Participant.Person.PersonNames = new List <Nehta.VendorLibrary.CDA.IPersonName> {
                ReportingPathologistName
            };

            // LegalAuthenticator/assignedEntity/<Entity Identifier>
            cdaContext.LegalAuthenticator.Participant.Person.Identifiers = new List <Identifier>
            {
                BaseCDAModel.CreateHealthIdentifier(HealthIdentifierType.HPII, FirstReportingPathologist.IdentifierList.SingleOrDefault(x => x.Type == PathologyReportModel.Model.IdentifierType.HPII).Value.Replace(" ", ""))
            };

            // LegalAuthenticator/assignedEntity/code
            cdaContext.LegalAuthenticator.Role = BaseCDAModel.CreateRole(Occupation.Pathologist, Nehta.VendorLibrary.CDA.Generator.Enums.CodingSystem.ANZSCORevision1);

            cdaContext.LegalAuthenticator.Participant.Addresses = new List <IAddress>()
            {
                GetCdaAddress(Report.PerformingLaboratory.Address)
            };

            // LegalAuthenticator/assignedEntity/<Electronic Communication Detail>
            cdaContext.LegalAuthenticator.Participant.ElectronicCommunicationDetails = new List <ElectronicCommunicationDetail> {
                PerformingPathologyLabComms
            };

            // LegalAuthenticator/assignedEntity/representedOrganization
            cdaContext.LegalAuthenticator.Participant.Organisation = BaseCDAModel.CreateOrganisationName();

            // LegalAuthenticator/assignedEntity/representedOrganization/name
            cdaContext.LegalAuthenticator.Participant.Organisation.Name = Report.PerformingLaboratory.FacilityName;

            // LegalAuthenticator/assignedEntity/representedOrganization/<Entity Identifier>
            cdaContext.LegalAuthenticator.Participant.Organisation.Identifiers = new List <Identifier>();

            var CodableConceptNataSiteNumber = BaseCDAModel.CreateCodableText();
            CodableConceptNataSiteNumber.Code           = "XX";
            CodableConceptNataSiteNumber.CodeSystemName = "Identifier Type (HL7)";
            CodableConceptNataSiteNumber.CodeSystemCode = "2.16.840.1.113883.12.203";
            CodableConceptNataSiteNumber.DisplayName    = "Organization identifier";

            var NataSiteNumber = BaseCDAModel.CreateIdentifier("1.2.36.1.2001.1005.74", Report.PerformingLaboratory.NataSiteNumber);
            NataSiteNumber.Code = CodableConceptNataSiteNumber;
            NataSiteNumber.AssigningGeographicArea = "National Identifier";
            NataSiteNumber.AssigningAuthorityName  = "NATA Site Number";
            cdaContext.LegalAuthenticator.Participant.Organisation.Identifiers.Add(NataSiteNumber);

            //cdaContext.LegalAuthenticator.Participant.Organisation.Identifiers.Add(BaseCDAModel.CreateIdentifier("NATA", Nehta.VendorLibrary.CDA.Generator.Enums.HealthcareIdentifierGeographicArea.NationalIdentifier, PerformingPathologyLab.NataSiteNumber, "1.2.36.1.2001.1005.12", BaseCDAModel.CreateCodableText("AUSNATA", Nehta.VendorLibrary.CDA.Generator.Enums.CodingSystem.HL7IdentifierType, "National Association of Testing Authorities (NATA) Site Number")));
            cdaContext.LegalAuthenticator.Participant.Organisation.Identifiers.Add(BaseCDAModel.CreateHealthIdentifier(HealthIdentifierType.HPIO, Report.PerformingLaboratory.Hpio.Replace(" ", "")));

            pathologyResultReport.CDAContext = cdaContext;

            #endregion

            #region Setup and Populate the SCS Context model

            pathologyResultReport.SCSContext = PathologyResultReport.CreateSCSContext();

            // Author Health Care Provider
            pathologyResultReport.SCSContext.Author = BaseCDAModel.CreateAuthorHealthcareProvider();

            // Document Author > Participant
            pathologyResultReport.SCSContext.Author.Participant = BaseCDAModel.CreateParticipantForAuthorHealthcareProvider();

            pathologyResultReport.SCSContext.Author.AuthorParticipationPeriodOrDateTimeAuthored = BaseCDAModel.CreateParticipationPeriod(new ISO8601DateTime(OldestReportReleaseDate.DateTime, ISO8601DateTime.Precision.Second, OldestReportReleaseDate.Offset));

            // Document Author > Role = AddressPurpose.Residential
            pathologyResultReport.SCSContext.Author.Role = BaseCDAModel.CreateRole(Occupation.Pathologist, Nehta.VendorLibrary.CDA.Generator.Enums.CodingSystem.ANZSCORevision1);

            // Document Author > Participant > Person or Organisation or Device > Person > Person Name (Note: 1..* in ACI)
            pathologyResultReport.SCSContext.Author.Participant.Person             = BaseCDAModel.CreatePersonHealthcareProvider();
            pathologyResultReport.SCSContext.Author.Participant.Person.PersonNames = new List <IPersonName> {
                ReportingPathologistName
            };

            //person.PersonNames = new List<IPersonName> { ReportingPathologistName };
            //if (!mandatoryOnly)
            //{
            //  // Not providing a family name will insert a nullflavor of 'NI'
            //  name.FamilyName = "Doctor family name";
            //}

            pathologyResultReport.SCSContext.Author.Participant.Person.Identifiers              = cdaContext.LegalAuthenticator.Participant.Person.Identifiers;
            pathologyResultReport.SCSContext.Author.Participant.Person.Organisation             = BaseCDAModel.CreateEmploymentOrganisation();
            pathologyResultReport.SCSContext.Author.Participant.Person.Organisation.Name        = Report.PerformingLaboratory.FacilityName;
            pathologyResultReport.SCSContext.Author.Participant.Person.Organisation.Identifiers = new List <Identifier>()
            {
                BaseCDAModel.CreateHealthIdentifier(HealthIdentifierType.HPIO, Report.PerformingLaboratory.Hpio.Replace(" ", ""))
            };
            pathologyResultReport.SCSContext.Author.Participant.ElectronicCommunicationDetails = new List <ElectronicCommunicationDetail>()
            {
                PerformingPathologyLabComms
            };


            // Document Author > Participant > Addresses
            pathologyResultReport.SCSContext.Author.Participant.Addresses = new List <IAddress>
            {
                GetCdaAddress(Report.PerformingLaboratory.Address)
            };

            // Document Author > Participant > Address (Note: optional in ACI)
            pathologyResultReport.SCSContext.Author.Participant.Person.Organisation.Addresses = new List <IAddress>
            {
                GetCdaAddress(Report.PerformingLaboratory.Address)
            };

            pathologyResultReport.SCSContext.Author.Participant.Person.Organisation.Name      = Report.PerformingLaboratory.FacilityName;
            pathologyResultReport.SCSContext.Author.Participant.Person.Organisation.NameUsage = OrganisationNameUsage.BusinessName;

            //pathologyResultReport.SCSContext.Author.Participant.Person.Organisation.Department = "Some department service provider";
            //pathologyResultReport.SCSContext.Author.Participant.Person.Organisation.EmploymentType = BaseCDAModel.CreateCodableText(null, null, null, "Casual", null);
            pathologyResultReport.SCSContext.Author.Participant.Person.Organisation.Occupation = BaseCDAModel.CreateRole(Occupation.Pathologist, Nehta.VendorLibrary.CDA.Generator.Enums.CodingSystem.ANZSCORevision1);
            //pathologyResultReport.SCSContext.Author.Participant.Person.Organisation.PositionInOrganisation = BaseCDAModel.CreateCodableText(null, null, null, "Manager", null);

            pathologyResultReport.SCSContext.Author.Participant.Person.Organisation.ElectronicCommunicationDetails = new List <ElectronicCommunicationDetail>
            {
                PerformingPathologyLabComms
            };


            // The Reporting Pathologist
            pathologyResultReport.SCSContext.ReportingPathologist = PathologyResultReport.CreateReportingPathologist();

            // Document reportingPathologist > Participant
            pathologyResultReport.SCSContext.ReportingPathologist.Participant = PathologyResultReport.CreateParticipantForReportingPathologist();

            pathologyResultReport.SCSContext.ReportingPathologist.Participant.Person             = BaseCDAModel.CreatePersonWithOrganisation();
            pathologyResultReport.SCSContext.ReportingPathologist.Participant.Person.PersonNames = new List <IPersonName> {
                ReportingPathologistName
            };

            // Participation Period
            pathologyResultReport.SCSContext.ReportingPathologist.ParticipationEndTime = new ISO8601DateTime(OldestReportReleaseDate.DateTime, ISO8601DateTime.Precision.Second, OldestReportReleaseDate.Offset);

            // Document reportingPathologist > Role
            pathologyResultReport.SCSContext.ReportingPathologist.Role = PathologyResultReport.CreateRole(Occupation.Pathologist);

            // Document reportingPathologist > Participant > Address
            pathologyResultReport.SCSContext.ReportingPathologist.Participant.Addresses = new List <IAddress>()
            {
                GetCdaAddress(Report.PerformingLaboratory.Address)
            };

            pathologyResultReport.SCSContext.ReportingPathologist.Participant.ElectronicCommunicationDetails = new List <ElectronicCommunicationDetail> {
                PerformingPathologyLabComms
            };
            pathologyResultReport.SCSContext.ReportingPathologist.Participant.Person = pathologyResultReport.SCSContext.Author.Participant.Person;


            // Order Details
            pathologyResultReport.SCSContext.OrderDetails = DiagnosticImagingReport.CreateOrderDetails();

            // Requester Order Identifier
            //pathologyResultReport.SCSContext.OrderDetails.RequesterOrderIdentifier = BaseCDAModel.CreateIdentifier("1.2.36.1.2001.1005.52.8003620833333789", "10523479");

            // Requester
            pathologyResultReport.SCSContext.OrderDetails.Requester = BaseCDAModel.CreateRequester();

            pathologyResultReport.SCSContext.OrderDetails.Requester.ParticipationEndTime = new ISO8601DateTime(Report.Request.RequestedDate.DateTime, ISO8601DateTime.Precision.Day, Report.Request.RequestedDate.Offset);
            // Document Requester> Role
            pathologyResultReport.SCSContext.OrderDetails.Requester.Role = BaseCDAModel.CreateRole(Occupation.GeneralMedicalPractitioner, Nehta.VendorLibrary.CDA.Generator.Enums.CodingSystem.ANZSCORevision1);

            pathologyResultReport.SCSContext.OrderDetails.Requester.Participant        = BaseCDAModel.CreateParticipantForRequester();
            pathologyResultReport.SCSContext.OrderDetails.Requester.Participant.Person = BaseCDAModel.CreatePersonWithOrganisation();
            // Participation Period


            var RequestingDoctorName = BaseCDAModel.CreatePersonName();
            RequestingDoctorName.FamilyName = Report.Request.RequestingProvider.Name.Family;
            if (Report.Request.RequestingProvider.Name.Given is object)
            {
                RequestingDoctorName.GivenNames = new List <string>()
                {
                    Report.Request.RequestingProvider.Name.Given
                };
            }
            pathologyResultReport.SCSContext.OrderDetails.Requester.Participant.Person.PersonNames = new List <IPersonName>()
            {
                RequestingDoctorName
            };


            pathologyResultReport.SCSContext.OrderDetails.Requester.Participant.Person.Identifiers = new List <Identifier>();

            ///Get Requester HPI-I
            var RequesterHpii = Report.Request.RequestingProvider.IdentifierList.SingleOrDefault(x => x.Type == PathologyReportModel.Model.IdentifierType.HPII);
            if (RequesterHpii is object)
            {
                pathologyResultReport.SCSContext.OrderDetails.Requester.Participant.Person.Identifiers.Add(BaseCDAModel.CreateHealthIdentifier(HealthIdentifierType.HPII, RequesterHpii.Value.Replace(" ", "")));
            }

            ///Get Requester Medicare Provider Number
            var RequesterMedicareProvidernumber = Report.Request.RequestingProvider.IdentifierList.SingleOrDefault(x => x.Type == PathologyReportModel.Model.IdentifierType.MedicareProviderNumber);
            if (RequesterMedicareProvidernumber is object)
            {
                var MedicareProvidernumberIdentifier = BaseCDAModel.CreateIdentifier("Medicare", Nehta.VendorLibrary.CDA.Generator.Enums.HealthcareIdentifierGeographicArea.NationalIdentifier, RequesterMedicareProvidernumber.Value, "1.2.36.174030967.0.2", BaseCDAModel.CreateCodableText("AUSHICPR", Nehta.VendorLibrary.CDA.Generator.Enums.CodingSystem.HL7IdentifierType, "Medicare Provider Number"));
                pathologyResultReport.SCSContext.OrderDetails.Requester.Participant.Person.Identifiers.Add(MedicareProvidernumberIdentifier);
            }

            // Subject Of Care
            pathologyResultReport.SCSContext.SubjectOfCare                    = BaseCDAModel.CreateSubjectOfCare();
            pathologyResultReport.SCSContext.SubjectOfCare.Participant        = BaseCDAModel.CreateParticipantForSubjectOfCare();
            pathologyResultReport.SCSContext.SubjectOfCare.Participant.Person = BaseCDAModel.CreatePersonForSubjectOfCare();

            pathologyResultReport.SCSContext.SubjectOfCare.Participant.Person.PersonNames = new List <IPersonName>();
            pathologyResultReport.SCSContext.SubjectOfCare.Participant.Person.PersonNames.Add(GetCdaPatientName(Report.Patient.Name));

            pathologyResultReport.SCSContext.SubjectOfCare.Participant.Person.Gender = GetCdaGender(Report.Patient.Gender);

            pathologyResultReport.SCSContext.SubjectOfCare.Participant.Person.DateOfBirth = new ISO8601DateTime(Report.Patient.DateOfBirth, ISO8601DateTime.Precision.Day);

            pathologyResultReport.SCSContext.SubjectOfCare.Participant.Person.IndigenousStatus = IndigenousStatus.NeitherAboriginalNorTorresStraitIslanderOrigin;

            //Phone numbers
            if (Report.Patient.HomePhoneNumber is object)
            {
                if (pathologyResultReport.SCSContext.SubjectOfCare.Participant.ElectronicCommunicationDetails is null)
                {
                    pathologyResultReport.SCSContext.SubjectOfCare.Participant.ElectronicCommunicationDetails = new List <ElectronicCommunicationDetail>();
                }

                //Work out if it is a Mobile number
                ElectronicCommunicationMedium ElectronicCommunicationMedium = ElectronicCommunicationMedium.Telephone;
                if (Report.Patient.HomePhoneNumber.Replace(" ", "").StartsWith("04", StringComparison.CurrentCultureIgnoreCase) || Report.Patient.HomePhoneNumber.Replace(" ", "").StartsWith("+614", StringComparison.CurrentCultureIgnoreCase))
                {
                    ElectronicCommunicationMedium = ElectronicCommunicationMedium.Mobile;
                }
                pathologyResultReport.SCSContext.SubjectOfCare.Participant.ElectronicCommunicationDetails.Add(
                    BaseCDAModel.CreateElectronicCommunicationDetail(
                        Report.Patient.HomePhoneNumber,
                        ElectronicCommunicationMedium,
                        ElectronicCommunicationUsage.Home)
                    );
            }

            //Address
            pathologyResultReport.SCSContext.SubjectOfCare.Participant.Addresses = new List <IAddress>();
            foreach (var Address in Report.Patient.AddressList)
            {
                pathologyResultReport.SCSContext.SubjectOfCare.Participant.Addresses.Add(GetCdaAddress(Address));
            }

            pathologyResultReport.SCSContext.SubjectOfCare.Participant.Person.Identifiers = new List <Identifier>();

            var IhiNumber = Report.Patient.IdentifierList.SingleOrDefault(x => x.Type == PathologyReportModel.Model.IdentifierType.IHI);
            if (IhiNumber is object)
            {
                pathologyResultReport.SCSContext.SubjectOfCare.Participant.Person.Identifiers.Add(BaseCDAModel.CreateHealthIdentifier(HealthIdentifierType.IHI, IhiNumber.Value.Replace(" ", "")));
            }

            var MedicareNumber = Report.Patient.IdentifierList.SingleOrDefault(x => x.Type == PathologyReportModel.Model.IdentifierType.MedicareNumber);
            if (MedicareNumber is object)
            {
                //Medicare Number goes in Entitlements as it is not a true identifier legally
                var MedicareEntitlement = BaseCDAModel.CreateEntitlement();
                MedicareEntitlement.Id   = BaseCDAModel.CreateMedicareNumber(MedicareNumberType.MedicareCardNumber, MedicareNumber.Value.Replace(" ", ""));
                MedicareEntitlement.Type = EntitlementType.MedicareBenefits;
                //MedicareEntitlement.ValidityDuration = BaseCDAModel.CreateInterval(new ISO8601DateTime(DateTime.Now), new ISO8601DateTime(DateTime.Now));
                pathologyResultReport.SCSContext.SubjectOfCare.Participant.Entitlements = new List <Entitlement> {
                    MedicareEntitlement
                };
            }

            //var MrnNumber = this.Input.Message.Segment("PID").Element(3).RepeatList.SingleOrDefault(x => x.Component(5).AsString.Equals("MR", StringComparison.CurrentCultureIgnoreCase));
            //if (MrnNumber is object)
            //{
            //  pathologyResultReport.SCSContext.SubjectOfCare.Participant.Person.Identifiers.Add(BaseCDAModel.CreateMedicalRecordNumber(MrnNumber.Component(1).AsString, "We need a root OID for the MRN  Facility", MrnNumber.Component(4).AsString));
            //}
            #endregion

            #region Setup and populate the SCS Content model

            // Setup and populate the SCS Content model
            pathologyResultReport.SCSContent = PathologyResultReport.CreateSCSContent();

            // Pathology Test Result
            string ReportLinkName = string.Empty;
            pathologyResultReport.SCSContent.PathologyTestResult = new List <Nehta.VendorLibrary.CDA.SCSModel.Pathology.PathologyTestResult>();
            foreach (var Panel in Report.ReportList)
            {
                var TestResult = PathologyResultReport.CreatePathologyTestResult();
                pathologyResultReport.SCSContent.PathologyTestResult.Add(TestResult);

                // Please note optional field - Note: This field is only displayed in the Narrative
                TestResult.ReportingPathologistForTestResult = Report.ReportList.First().ReportingPathologist.Name.Title ?? "";
                TestResult.ReportingPathologistForTestResult = $"{TestResult.ReportingPathologistForTestResult} {Report.ReportList.First().ReportingPathologist.Name.Family.ToUpper()}";
                TestResult.ReportingPathologistForTestResult = $"{TestResult.ReportingPathologistForTestResult}, {Report.ReportList.First().ReportingPathologist.Name.Given ?? ""}";


                if (!string.IsNullOrWhiteSpace(Panel.ReportType.Local.Oid))
                {
                    TestResult.TestResultName                = BaseCDAModel.CreateCodableText();
                    TestResult.TestResultName.Code           = Panel.ReportType.Local.Term;
                    TestResult.TestResultName.DisplayName    = Panel.ReportType.Local.Description;
                    TestResult.TestResultName.CodeSystemCode = Panel.ReportType.Local.Oid;
                    TestResult.TestResultName.OriginalText   = Panel.ReportType.Local.Description;
                }
                else
                {
                    TestResult.TestResultName = BaseCDAModel.CreateCodableText();
                    TestResult.TestResultName.OriginalText = Panel.ReportType.Local.Description;
                }

                if (Panel.ReportType.Snomed is object)
                {
                    TestResult.TestResultName.Translations = new List <ICodableTranslation>();
                    TestResult.TestResultName.Translations.Add(BaseCDAModel.CreateCodableTranslation(Panel.ReportType.Snomed.Term, Nehta.VendorLibrary.CDA.Generator.Enums.CodingSystem.SNOMED, Panel.ReportType.Snomed.Description));
                }

                // Department Code
                TestResult.PathologyDiscipline = GetCdaDiagnosticService(Panel.Department);

                // ResultStatus
                TestResult.OverallTestResultStatus = GetCdaResultStatus(Panel.ReportStatus);

                // Test Specimen Detail
                TestResult.TestSpecimenDetail = PathologyResultReport.CreateTestSpecimenDetail();
                TestResult.TestSpecimenDetail.CollectionDateTime = new ISO8601DateTime(Panel.CollectionDateTime.DateTime, ISO8601DateTime.Precision.Minute, Panel.CollectionDateTime.Offset);
                TestResult.ObservationDateTime = TestResult.TestSpecimenDetail.CollectionDateTime;
            }

            // Related Document
            pathologyResultReport.SCSContent.RelatedDocument = PathologyResultReport.CreateRelatedDocument();
            System.IO.FileInfo PdfFileInfo = new System.IO.FileInfo(System.IO.Path.Combine(PdfDirectory, Report.PdfFileName));

            if (!PdfFileInfo.Exists)
            {
                throw new FieldAccessException($"Unable to locate PDF attachment file at path: {PdfFileInfo.FullName}");
            }

            if (!PdfFileInfo.Extension.EndsWith(".pdf", StringComparison.CurrentCultureIgnoreCase))
            {
                throw new FieldAccessException($"The report attachment file must be in a .pdf format.");
            }

            // Pathology PDF
            var AttachmentPdf = BaseCDAModel.CreateExternalData();
            AttachmentPdf.ExternalDataMediaType = Nehta.VendorLibrary.CDA.Generator.Enums.MediaType.PDF;

            //We have to move the PDF attachment file to a new place and then rename it to 'attachment.pdf' and then after
            //generating the CDA document we will delete at copy of the PDF.
            System.IO.FileInfo TempAttachmentFilePath = new System.IO.FileInfo(System.IO.Path.Combine(TempWorkingDirectoryPath.FullName, "attachment.pdf"));
            if (TempAttachmentFilePath.Exists)
            {
                TempAttachmentFilePath.Delete();
            }
            PdfFileInfo.CopyTo(TempAttachmentFilePath.FullName);
            AttachmentPdf.Path = TempAttachmentFilePath.FullName;
            pathologyResultReport.SCSContent.RelatedDocument.ExaminationResultRepresentation = AttachmentPdf;

            // Document Provenance
            pathologyResultReport.SCSContent.RelatedDocument.DocumentDetails = BaseCDAModel.CreateDocumentDetails();

            // Report Identifier
            pathologyResultReport.SCSContent.RelatedDocument.DocumentDetails.ReportIdentifier = BaseCDAModel.CreateIdentifier($"1.2.36.1.2001.1005.54.{Report.PerformingLaboratory.Hpio.Replace(" ", "")}", Report.ReportList.First().ReportId);

            // Report Date
            pathologyResultReport.SCSContent.RelatedDocument.DocumentDetails.ReportDate = new ISO8601DateTime(Report.GetOldestReportReleaseDateTime().DateTime, ISO8601DateTime.Precision.Second, Report.GetOldestReportReleaseDateTime().Offset);

            // Result Status
            pathologyResultReport.SCSContent.RelatedDocument.DocumentDetails.ReportStatus = GetCdaResultStatus(Report.GetRolledUpReportStatus());

            // Report Name
            if (Report.ReportList.Count == 1)
            {
                pathologyResultReport.SCSContent.RelatedDocument.DocumentDetails.ReportDescription = Report.ReportList[0].ReportType.Local.Description;
            }
            else
            {
                pathologyResultReport.SCSContent.RelatedDocument.DocumentDetails.ReportDescription = "Pathology Report";
            }


            #endregion


            XmlDocument xmlDoc;
            try
            {
                Nehta.VendorLibrary.CDA.Generator.CDAGenerator.NarrativeGenerator = new Nehta.VendorLibrary.CDA.Generator.CDANarrativeGenerator();

                //Pass the Event Summary model into the GeneratePathologyResultReport method
                xmlDoc = Nehta.VendorLibrary.CDA.Generator.CDAGenerator.GeneratePathologyResultReport(pathologyResultReport);

                System.IO.DirectoryInfo CdaOutputDirectoryInfo = new System.IO.DirectoryInfo(CdaOutputDirectory);
                System.IO.FileInfo      CdaFileInfo            = new System.IO.FileInfo(System.IO.Path.Combine(CdaOutputDirectoryInfo.FullName, Report.PdfFileName.Replace(".pdf", ".xml")));
                if (System.IO.File.Exists(CdaFileInfo.FullName))
                {
                    System.IO.File.Delete(CdaFileInfo.FullName);
                }

                using (var writer = XmlWriter.Create(CdaFileInfo.FullName, new XmlWriterSettings {
                    Indent = true
                }))
                {
                    xmlDoc.Save(writer);
                }
            }
            catch (Nehta.VendorLibrary.Common.ValidationException ex)
            {
                //Catch any validation exceptions
                var validationMessages = ex.GetMessagesString();
                throw new ApplicationException($"Error encountered in generating CDA document: {validationMessages}");
            }
            finally
            {
                TempAttachmentFilePath.Delete();
            }
        }