def map(self):
    try:
      id_value = sha256(self.data['concat_elements'].encode('utf-8')).hexdigest()

      lufu_diagnostic_report = diagnosticreport.DiagnosticReport();
      lufu_diagnostic_report.id = id_value
      lufu_diagnostic_report_identifier = self.data['untersuchung_id']
      lufu_diagnostic_report.identifier = [identifier.Identifier({"use": "official",
                                                                  "system": self.systems['lufu_obs_id'],
                                                                  "value": str(lufu_diagnostic_report_identifier)})]
      dt_string = self.data['untersuchungsdatum']+" "+self.data['untersuchungsuhrzeit']
      lufu_report_dt = datetime.strftime(datetime.strptime(dt_string, "%Y-%m-%d %H:%M:%S"), '%Y-%m-%dT%H:%M:%S')
      lufu_diagnostic_report_date = fhirdate.FHIRDate(lufu_report_dt)

      lufu_diagnostic_report.effectiveDateTime = lufu_diagnostic_report_date

      ref = {"reference": f"Patient/{self.data['patient_psn']}"}
      lufu_diagnostic_report.subject = fhirreference.FHIRReference(jsondict=ref)
      ref = {"reference": f"Encounter/{self.data['encounter_psn']}"}
      lufu_diagnostic_report.encounter = fhirreference.FHIRReference(jsondict=ref)

      rep_code_system_cc = codeableconcept.CodeableConcept()
      rep_code_system_cc.coding = [coding.Coding({"system": "https://www.dimdi.de/static/de/klassifikationen/ops",
                     "code": "1-71",
                     "display": "Pneumologische Funktionsuntersuchunge"})]

      rep_status = 'final'
      lufu_diagnostic_report.code = rep_code_system_cc
      lufu_diagnostic_report.status = rep_status
      conclusion_str = ""
      if self.data['beurteilung'] is not None and self.data['beurteilung'] != "":
        conclusion_str = conclusion_str + "Beurteilung: "+self.data['beurteilung']
      if self.data['anmerkung'] is not None and self.data['anmerkung'] != "":
        conclusion_str = conclusion_str + "|\n Anmerkung: "+self.data['anmerkung']
      if self.data['empfehlung'] is not None and self.data['empfehlung'] != "":
        conclusion_str = conclusion_str + " |\n Empfehlung: "+self.data['empfehlung']

      lufu_diagnostic_report.conclusion = conclusion_str

      return lufu_diagnostic_report
    except KeyError as exc:
      self.logger.error(f"In {__name__}: Key {exc} not found in dictionary")
      raise
    except Exception as exc:
      self.logger.error(f"In {__name__}: Error occurred in mapping ({exc})")
      raise
Esempio n. 2
0
    def map(self):
        try:
            obs_status = "preliminary"
            obs_meta = meta.Meta()
            obs_meta.source = "#sap-ish"

            start_dt = None
            end_dt = None
            if not pd.isna(self.data['admission_dt']):
                start_dt = fhirdate.FHIRDate(
                    datetime.strftime(self.data['admission_dt'],
                                      '%Y-%m-%dT%H:%M:%S'))
                if not pd.isna(self.data['discharge_dt']):
                    end_dt = fhirdate.FHIRDate(
                        datetime.strftime(self.data['discharge_dt'],
                                          '%Y-%m-%dT%H:%M:%S'))
                    obs_status = "final"
            obs_period = period.Period()
            obs_period.start = start_dt
            obs_period.end = end_dt

            id_value = f"{self.data['encounter_psn']}-dia"
            dialysis_observation = miracum_observation.Observation()
            dialysis_observation.id = id_value
            dialysis_sys = self.systems['p21obs_id']
            dialysis_observation.identifier = [
                identifier.Identifier({
                    "system": dialysis_sys,
                    "value": id_value
                })
            ]
            ref = {"reference": f"Encounter/{self.data['encounter_psn']}"}
            dialysis_observation.encounter = fhirreference.FHIRReference(
                jsondict=ref)
            ref = {"reference": f"Patient/{self.data['patient_psn']}"}
            dialysis_observation.subject = fhirreference.FHIRReference(
                jsondict=ref)

            dialysis_code = miracum_codeableconcept.CodeableConcept()
            obs_code_sys = "https://miracum.org/fhir/CodeSystem/core/observations"
            dialysis_code.text = "Intercurrent dialysis"
            dialysis_code.coding = [
                miracum_coding.Coding({
                    "system": obs_code_sys,
                    "code": "intercurrent-dialysis",
                    "display": "Intercurrent dialysis"
                })
            ]
            dialysis_observation.code = dialysis_code
            dialysis_observation.valueInteger = self.data['dialysis_hours']

            dialysis_observation.status = obs_status
            dialysis_observation.effectivePeriod = obs_period
            dialysis_observation.meta = obs_meta

            id_value = f"{self.data['encounter_psn']}-icu"
            icu_observation = miracum_observation.Observation()
            icu_observation.id = id_value
            icu_sys = self.systems['p21obs_id']
            icu_observation.identifier = [
                identifier.Identifier({
                    "system": icu_sys,
                    "value": id_value
                })
            ]
            ref = {"reference": f"Encounter/{self.data['encounter_psn']}"}
            icu_observation.encounter = fhirreference.FHIRReference(
                jsondict=ref)
            ref = {"reference": f"Patient/{self.data['patient_psn']}"}
            icu_observation.subject = fhirreference.FHIRReference(jsondict=ref)

            icu_code = miracum_codeableconcept.CodeableConcept()
            icu_code.text = "Days in intensive care unit"
            icu_code.coding = [
                miracum_coding.Coding({
                    "system": 'http://loinc.org',
                    "code": "74200-7",
                    "display": "Days in intensive care unit",
                    "version": "2.46"
                })
            ]
            icu_observation.code = icu_code
            if self.data['icu_days']:
                icu_observation.valueQuantity = miracum_quantity.Quantity({
                    "value":
                    self.data['icu_days'],
                    "unit":
                    "d",
                    "system":
                    "http://unitsofmeasure.org",
                    "code":
                    "d"
                })
            icu_observation.status = obs_status
            icu_observation.effectivePeriod = obs_period
            icu_observation.meta = obs_meta

            return [dialysis_observation, icu_observation]
        except KeyError as exc:
            self.logger.error(
                f"In {__name__}: Key {exc} not found in dictionary")
            raise
        except FHIRValidationError:
            raise
    def map(self):
        try:
            obs_status = "preliminary"
            obs_meta = meta.Meta()
            obs_meta.source = "#sap-ish"

            start_dt = None
            end_dt = None
            if not pd.isna(self.data['admission_dt']):
                start_dt = fhirdate.FHIRDate(
                    datetime.strftime(self.data['admission_dt'],
                                      '%Y-%m-%dT%H:%M:%S'))
                if not pd.isna(self.data['discharge_dt']):
                    end_dt = fhirdate.FHIRDate(
                        datetime.strftime(self.data['discharge_dt'],
                                          '%Y-%m-%dT%H:%M:%S'))
                    obs_status = "final"
            obs_period = period.Period()
            obs_period.start = start_dt
            obs_period.end = end_dt

            id_value = f"{self.data['encounter_psn']}-vent"
            vent_observation = miracum_observation.Observation()
            vent_observation.id = id_value
            vent_observation.identifier = [
                identifier.Identifier({
                    "system": self.systems['p21obs_id'],
                    "value": id_value
                })
            ]

            ref = {"reference": f"Encounter/{self.data['encounter_psn']}"}
            vent_observation.encounter = fhirreference.FHIRReference(
                jsondict=ref)
            ref = {"reference": f"Patient/{self.data['patient_psn']}"}
            vent_observation.subject = fhirreference.FHIRReference(
                jsondict=ref)

            ventilation_code = miracum_codeableconcept.CodeableConcept()
            ventilation_code.text = "Days on Ventilator"
            ventilation_code.coding = [
                miracum_coding.Coding({
                    "system": "http://loinc.org",
                    "code": "74201-5",
                    "display": "Days on Ventilator"
                })
            ]
            vent_observation.code = ventilation_code
            if self.data['vent_days']:
                vent_observation.valueQuantity = miracum_quantity.Quantity({
                    "value":
                    self.data['vent_days'],
                    "unit":
                    "d",
                    "system":
                    "http://unitsofmeasure.org",
                    "code":
                    "d"
                })
            vent_observation.status = obs_status
            vent_observation.effectivePeriod = obs_period
            vent_observation.meta = obs_meta

            return vent_observation

        except KeyError as exc:
            self.logger.error(
                f"In {__name__}: Key {exc} not found in dictionary")
            raise
        except FHIRValidationError:
            raise
def mapLufuItems2Obs(self, param, items):

    sct_code = self.snomed_mapper.codeLookup(str(param))
    sct_display = self.snomed_mapper.displayLookup(str(sct_code))

    lufu_observation = observation.Observation()
    observation_unit = ''
    concat_string = self.data['concat_elements'] + param
    id_value = sha256(concat_string.encode('utf-8')).hexdigest()
    lufu_observation.id = id_value
    lufu_observation.identifier = [
        identifier.Identifier({
            "system": self.systems['lufu_obs_id'],
            "value": id_value
        })
    ]
    obs_actual_code = codeableconcept.CodeableConcept()
    obs_actual_code.coding = [
        coding.Coding({
            "system": "http://snomed.info/sct",
            "code": sct_code,
            "display": sct_display,
            "version": "0.1"
        })
    ]
    # obs category
    obs_type_sys = "http://terminology.hl7.org/CodeSystem/observation-category"
    code = 'exam'
    observation_cat = codeableconcept.CodeableConcept()
    observation_cat.coding = [
        coding.Coding({
            "system": obs_type_sys,
            "code": code
        })
    ]
    lufu_observation.category = [observation_cat]
    lufu_observation.code = obs_actual_code

    ref = {"reference": f"Encounter/{self.data['encounter_psn']}"}
    lufu_observation.encounter = fhirreference.FHIRReference(jsondict=ref)
    ref = {"reference": f"Patient/{self.data['patient_psn']}"}
    lufu_observation.subject = fhirreference.FHIRReference(jsondict=ref)

    if not pd.isna(self.data['untersuchungsdatum']) and not pd.isna(
            self.data['untersuchungsuhrzeit']):
        dt_string = self.data['untersuchungsdatum'] + " " + self.data[
            'untersuchungsuhrzeit']
        obs_datetime = datetime.strptime(dt_string, "%Y-%m-%d %H:%M:%S")
        obs_datetime.replace(tzinfo=timezone.utc)
        # collect_ts_fhir = datetime.strftime(obs_datetime.astimezone().isoformat(), '%Y-%m-%dT%H:%M:%S')
        lufu_observation.effectiveDateTime = fhirdate.FHIRDate(
            obs_datetime.astimezone().isoformat())

    components = []

    for item in items:
        if 'actual' in str(item):
            obs_component = observation.ObservationComponent()
            lufu_value = self.data[item]
            lookupParam = item
            if ("PRE" not in param) and ("POST" not in param):
                lookupParam = str(item).replace("PRE_", "")
            loinc_code = self.loinc_mapper.codeLookup(lookupParam)
            loinc_display = self.loinc_mapper.displayLookup(loinc_code)
            i2b2_code = self.i2b2_mapper.codeLookup(lookupParam)

            codings = []

            if loinc_code != 'No Code':
                codings.append(
                    coding.Coding({
                        "system": "http://loinc.org",
                        "code": loinc_code,
                        "display": loinc_display,
                        "version": "2.46"
                    }))
                mask = self.map_table[self.map_table['RELMA'] == loinc_code]
                observation_unit = mask['Unit'].values[0]
            if i2b2_code != 'No Code':
                codings.append(
                    coding.Coding({
                        "system": "http://mdr.miracum.org",
                        "code": i2b2_code,
                        "version": "0.01"
                    }))
                mask = self.map_table[self.map_table['I2B2 Basecode'] ==
                                      i2b2_code]
                observation_unit = mask['Unit'].values[0]

            if len(codings) > 0:
                obs_component_code = codeableconcept.CodeableConcept()
                obs_component_code.coding = codings
                obs_component.code = obs_component_code
                #obs_component.valueDateTime = fhirdate.FHIRDate(collect_ts_fhir)
                obs_component.valueQuantity = quantity.Quantity({
                    "value":
                    lufu_value,
                    "unit":
                    observation_unit,
                    "system":
                    "http://unitsofmeasure.org",
                    "code":
                    observation_unit
                })
                lufu_ref_value = self.data[str(item).replace(
                    'actual', 'target')]
                low_ref_value = quantity.Quantity({
                    "value": lufu_ref_value,
                    "unit": observation_unit,
                    "system": "http://unitsofmeasure.org",
                    "code": observation_unit
                })
                ref_range = ObservationReferenceRange()
                ref_range.low = low_ref_value
                ref_range.high = low_ref_value
                obs_component.referenceRange = [ref_range]

                components.append(obs_component)

    lufu_observation.component = components
    lufu_observation.status = "final"

    lufu_actual_meta = meta.Meta()
    lufu_actual_meta.source = "#lufu-cwd"
    lufu_observation.meta = lufu_actual_meta
    if len(lufu_observation.component) > 0:
        return lufu_observation
    else:
        return []
    def map(self):
        try:
            sub_encounter = mii_encounter_abfall.Encounter()
            id_value = sha256(
                self.data['concat_elements'].encode('utf-8')).hexdigest()

            sub_encounter.id = id_value
            sub_encounter.identifier = [
                identifier.Identifier({
                    "use": "usual",
                    "system": self.systems['subencounter_id'],
                    "value": id_value
                })
            ]
            sub_encounter.status = "in-progress"
            enc_class_system = "http://terminology.hl7.org/CodeSystem/v3-ActCode"
            sub_encounter.class_fhir = mii_coding.Coding({
                "system":
                enc_class_system,
                "code":
                "IMP",
                "display":
                "inpatient encounter"
            })
            ref = {"reference": f"Patient/{self.data['patient_psn']}"}
            sub_encounter.subject = fhirreference.FHIRReference(jsondict=ref)
            ref = {"reference": f"Encounter/{self.data['encounter_psn']}"}
            sub_encounter.partOf = fhirreference.FHIRReference(jsondict=ref)

            fab_code = self.data['dep_full_code']
            service_type = mii_codeableconcept.CodeableConcept()
            service_type_sys = "http://terminology.hl7.org/CodeSystem/service-type"
            service_type.coding = [
                mii_coding.Coding({
                    "system": service_type_sys,
                    "code": fab_code,
                    "display": self._dep_name_lookup(fab_code)
                })
            ]
            sub_encounter.serviceType = service_type

            enc_period = mii_period.Period()
            enc_period.start = fhirdate.FHIRDate(
                datetime.strftime(self.data['admission_dt'],
                                  '%Y-%m-%dT%H:%M:%S'))
            if not pd.isna(self.data['discharge_dt']):
                sub_encounter.status = "finished"
                enc_period.end = fhirdate.FHIRDate(
                    datetime.strftime(self.data['discharge_dt'],
                                      '%Y-%m-%dT%H:%M:%S'))
            sub_encounter.period = enc_period

            enc_meta = meta.Meta()
            enc_meta.source = "#sap-ish"
            sub_encounter.meta = enc_meta

            sub_encounter.location = []
            location_list = []
            added_res_loc = 0
            res_loc_invalid = 0
            for loc_name, loc_am_ts, loc_dc_ts in zip(
                    self.data['loc_name_set'], self.data['loc_am_ts_set'],
                    self.data['loc_dc_ts_set']):
                new_location = location.Location()
                id_value = sha256(loc_name.encode('utf-8')).hexdigest()
                new_location.id = id_value
                new_location.identifier = [
                    identifier.Identifier({
                        "use": "usual",
                        "system":
                        "https://diz.mii.de/fhir/CodeSystem/TestOrganisationAbteilungen",
                        "value": id_value
                    })
                ]
                new_location.name = loc_name

                loc = mii_encounter_abfall.EncounterLocation()
                loc.status = 'active'
                loc_period = mii_period.Period()
                loc_period.start = fhirdate.FHIRDate(
                    datetime.strftime(loc_am_ts, '%Y-%m-%dT%H:%M:%S'))
                if not pd.isna(loc_dc_ts):
                    loc.status = "completed"
                    loc_period.end = fhirdate.FHIRDate(
                        datetime.strftime(loc_dc_ts, '%Y-%m-%dT%H:%M:%S'))
                loc.period = loc_period
                ref = {"reference": f"Location/{id_value}"}
                loc.location = fhirreference.FHIRReference(jsondict=ref)
                try:
                    loc.as_json()
                    sub_encounter.location.append(loc)
                    location_list.append(new_location)
                    added_res_loc += 1
                except FHIRValidationError:
                    self.logger.warning(
                        "Validation error for created Location resource "
                        f"(id: {self.data['encounter_psn']})")
                    res_loc_invalid += 1

            return sub_encounter, location_list, added_res_loc, res_loc_invalid
        except KeyError as exc:
            self.logger.error(
                f"In {__name__}: Key {exc} not found in dictionary")
            raise
    def _map_dmpro2medi(self, encounter_ref, patient_ref):
        new_medication = []
        medication_stm = []
        mapping_row = self.ops_drug_mapping[self.ops_drug_mapping['ops_code']
                                            == self.data['ops_kode']]
        if not mapping_row.empty:
            drug_name = mapping_row['medication'].to_string(index=False)[1:]
            drug_atc = mapping_row['atc_code1'].to_string(index=False)[1:]
            dosage_text = mapping_row['text'].to_string(index=False)[1:]
            ucum_short = mapping_row['ucum_short'].to_string(index=False)[1:]
            ucum_full = mapping_row['ucum_full'].to_string(index=False)[1:]
            dosage_min = mapping_row['dosage_min'].to_string(index=False)[1:]
            dosage_max = mapping_row['dosage_max'].to_string(index=False)[1:]
            combi_product = mapping_row['medication_combi'].to_string(
                index=False)

            # generate medication statement resources
            new_medication = medication.Medication()
            id_value = str(self.data['encounter_psn']) + '_' + str(
                self.data['procedure_nr']) + '_med'
            #id_value = f"{drug_name}"
            #id_value = sha256(id_value.encode('utf-8')).hexdigest()
            new_medication.id = id_value
            new_medication.identifier = [
                identifier.Identifier({
                    "system": self.systems['med_id'],
                    "value": id_value
                })
            ]

            atc_cc = codeableconcept.CodeableConcept()
            atc_cc.coding = [
                coding.Coding({
                    "system": "http://fhir.de/CodeSystem/dimdi/atc",
                    "code": drug_atc,
                    "version": "ATC/DDD Version 2020",
                    "display": drug_name
                })
            ]
            new_medication.code = atc_cc
            new_medication.status = "active"
            med_meta = meta.Meta()
            med_meta.source = "#sap-ish"
            new_medication.meta = med_meta

            substances = [drug_name]
            if combi_product:
                substances = drug_name.split('-')

            ingredients = []
            if substances != ["UNKLAR"]:
                for substance in substances:
                    mapping_row2 = self.drug_unii_mapping[
                        self.drug_unii_mapping['Substanzangabe_aus_OPS-Code']
                        == substance]
                    substance_unii = mapping_row2[
                        'Substanz_fuer_Dosisberechnung_UNII-number'].to_string(
                            index=False)[1:]
                    substance_ask = mapping_row2[
                        'Substanz_fuer_Dosisberechnung_ASK-Nr'].to_string(
                            index=False)[1:]
                    substance_cas = mapping_row2[
                        'Substanz_fuer_Dosisberechnung_CAS-Nummer'].to_string(
                            index=False)[1:]

                    ingredient = medication.MedicationIngredient()
                    ingredient_cc = codeableconcept.CodeableConcept()
                    ingredient_cc.coding = [
                        coding.Coding({
                            "system": "http://fdasis.nlm.nih.gov",
                            "code": substance_unii,
                            "display": substance
                        })
                    ]
                    ingredient_cc.coding += [
                        coding.Coding({
                            "system": "http://fhir.de/CodeSystem/ask",
                            "code": substance_ask,
                            "display": substance
                        })
                    ]
                    ingredient_cc.coding += [
                        coding.Coding({
                            "system": "urn:oid:2.16.840.1.113883.6.61",
                            "code": substance_cas,
                            "display": substance
                        })
                    ]
                    ingredient.itemCodeableConcept = ingredient_cc
                    ingredients.append(ingredient)
            new_medication.ingredient = ingredients

            # generate medication statement resources
            id_value = str(self.data['encounter_psn']) + '_' + str(
                self.data['procedure_nr']) + '_med_stat'
            #id_value = f"{self.data['concat_elements']}-medication"
            #id_value = sha256(id_value.encode('utf-8')).hexdigest()

            medication_stm = medicationstatement.MedicationStatement()
            medication_stm.id = id_value
            medication_stm.identifier = [
                identifier.Identifier({
                    "system": self.systems['med_stm_id'],
                    "value": id_value
                })
            ]
            med_meta = meta.Meta()
            med_meta.source = "#sap-ish"
            medication_stm.meta = med_meta

            ref = {"reference": f"Medication/{new_medication.id}"}
            medication_ref = fhirreference.FHIRReference(jsondict=ref)
            medication_stm.medicationReference = medication_ref
            medication_stm.context = encounter_ref
            medication_stm.subject = patient_ref
            #medication_stm.partOf =

            medication_stm.status = "active"

            if not pd.isna(self.data['admission_dt']):
                med_period = period.Period()
                med_period.start = fhirdate.FHIRDate(
                    datetime.strftime(self.data['admission_dt'],
                                      '%Y-%m-%dT%H:%M:%S'))
                if not pd.isna(self.data['discharge_dt']):
                    med_period.end = fhirdate.FHIRDate(
                        datetime.strftime(self.data['discharge_dt'],
                                          '%Y-%m-%dT%H:%M:%S'))
                    medication_stm.status = "completed"
                medication_stm.effectivePeriod = med_period

            new_dosage = dosage.Dosage()
            new_dosage.text = dosage_text

            dose_range = range.Range()
            if dosage_min != "NaN":
                dose_range.low = quantity.Quantity({
                    "value":
                    float(dosage_min.replace(',', '.')),
                    "unit":
                    ucum_full,
                    "system":
                    "http://unitsofmeasure.org",
                    "code":
                    ucum_short
                })
            if dosage_max != "NaN":
                dose_range.high = quantity.Quantity({
                    "value":
                    float(dosage_max.replace(',', '.')),
                    "unit":
                    ucum_full,
                    "system":
                    "http://unitsofmeasure.org",
                    "code":
                    ucum_short
                })
            dose_rate = dosage.DosageDoseAndRate()
            dose_rate.doseRange = dose_range
            new_dosage.doseAndRate = [dose_rate]

            #method, route, site

            medication_stm.dosage = [new_dosage]
        return [new_medication, medication_stm]
    def map(self):
        try:
            new_medication = []
            medication_stm = []

            #id_value = sha256(self.data['concat_elements'].encode('utf-8')).hexdigest()
            id_value = str(self.data['encounter_psn']) + '_' + str(
                self.data['procedure_nr'])

            pat_procedure = mii_procedure.Procedure()
            pat_procedure.id = id_value
            pat_procedure.identifier = [
                identifier.Identifier({
                    "system": self.systems['prod_id'],
                    "value": id_value
                })
            ]
            pat_procedure.status = "completed"

            ref = {"reference": f"Encounter/{self.data['encounter_psn']}"}
            encounter_ref = fhirreference.FHIRReference(jsondict=ref)
            ref = {"reference": f"Patient/{self.data['patient_psn']}"}
            patient_ref = fhirreference.FHIRReference(jsondict=ref)

            pat_procedure.encounter = encounter_ref
            pat_procedure.subject = patient_ref

            category = mii_codeableconcept.CodeableConcept()
            category.coding = [
                mii_coding.Coding({
                    "system": "http://snomed.info/sct",
                    "code": "387713003"
                })
            ]
            pat_procedure.category = category

            procedure_code = mii_codeableconcept.CodeableConcept()
            procedure_code.coding = [
                mii_coding.Coding({
                    "system": "http://fhir.de/CodeSystem/dimdi/ops",
                    "code": self.data['ops_kode'],
                    "version": self.data['ops_version']
                })
            ]
            pat_procedure.code = procedure_code

            if self.data['ops_kode'][0] == '6':
                [new_medication, medication_stm
                 ] = self._map_dmpro2medi(encounter_ref, patient_ref)

            if not pd.isna(self.data['ops_datum']):
                ops_datum_fhir = datetime.strftime(self.data['ops_datum'],
                                                   '%Y-%m-%dT%H:%M:%S')
                pat_procedure.performedDateTime = fhirdate.FHIRDate(
                    ops_datum_fhir)

            if self.data['lokalisation']:
                pat_procedure.bodySite = []
                snomed_ver = "http://snomed.info/sct/900000000000207008/version/20200309"
                if self.data['lokalisation'] == 'L' or self.data[
                        'lokalisation'] == 'B':
                    left_body_part = mii_codeableconcept.CodeableConcept()
                    left_body_part.coding = [
                        mii_coding.Coding({
                            "system": "http://snomed.info/sct",
                            "code": "31156008",
                            "display": '''Structure of left half
                                                                of body (body structure)''',
                            "version": snomed_ver
                        })
                    ]
                    pat_procedure.bodySite.append(left_body_part)

                if self.data['lokalisation'] == 'R' or self.data[
                        'lokalisation'] == 'B':
                    right_body_part = mii_codeableconcept.CodeableConcept()
                    right_body_part.coding = [
                        mii_coding.Coding({
                            "system": "http://snomed.info/sct",
                            "code": "85421007",
                            "display": '''Structure of right half
                                                                 of body (body structure)''',
                            "version": snomed_ver
                        })
                    ]
                    pat_procedure.bodySite.append(right_body_part)

            pro_meta = meta.Meta()
            pro_meta.source = "#sap-ish"
            pat_procedure.meta = pro_meta

            return [pat_procedure, new_medication, medication_stm]
        except KeyError as exc:
            self.logger.error(
                f"In {__name__}: Key {exc} not found in dictionary")
            raise
    def map(self, lufu_section):
        try:
            ops_code = 'No OPS Code'
            ops_text = 'No OPS Code Text'

            if lufu_section == 'B':
                ops_code = '1-710'
                ops_text = self.procedure_mapper.codeLookup(ops_code)
            else:
                ops_code = '1-71'
                ops_text = self.procedure_mapper.codeLookup(ops_code)

            id_value = sha256(
                (str(lufu_section) +
                 self.data['concat_elements']).encode('utf-8')).hexdigest()

            lufu_procedure = procedure.Procedure()

            #lufu_procedure_system = ''
            lufu_procedure_identifier = id_value
            lufu_procedure.identifier = [
                identifier.Identifier({
                    "use": "official",
                    "system": self.systems['prod_id'],
                    "value": lufu_procedure_identifier
                })
            ]
            lufu_procedure.id = id_value

            lufu_procedure_identifier_perf_date = fhirdate.FHIRDate(
                datetime.strftime(
                    datetime.strptime(self.data['untersuchungsdatum'],
                                      '%d.%m.%Y %H:%M:%S'),
                    '%Y-%m-%dT%H:%M:%S'))

            lufu_procedure.performedDateTime = lufu_procedure_identifier_perf_date

            ref = {"reference": f"Patient/{self.data['patient_psn']}"}
            lufu_procedure.subject = fhirreference.FHIRReference(jsondict=ref)
            ref = {"reference": f"Encounter/{self.data['encounter_psn']}"}
            lufu_procedure.encounter = fhirreference.FHIRReference(
                jsondict=ref)

            rep_code_system_cc = codeableconcept.CodeableConcept()
            rep_code_system_cc.coding = [
                coding.Coding({
                    "system":
                    "https://www.dimdi.de/static/de/klassifikationen/ops",
                    "code": ops_code,
                    "display": ops_text
                })
            ]

            rep_status = 'completed'

            lufu_procedure.code = rep_code_system_cc
            lufu_procedure.status = rep_status

            return lufu_procedure
        except KeyError as exc:
            self.logger.error(
                f"In {__name__}: Key {exc} not found in dictionary")
            raise
        except Exception as exc:
            self.logger.error(
                f"In {__name__}: Error occurred in mapping ({exc})")
            raise
    def map(self):
        try:
            id_value = str(self.data['encounter_psn']) + '_' + str(
                self.data['diagnosis_nr'])
            #sha256(self.data['concat_elements'].encode('utf-8')).hexdigest()

            icd_condition = mii_condition.Condition()
            icd_condition.id = id_value
            icd_condition.identifier = [
                identifier.Identifier({
                    "system": self.systems['condition_id'],
                    "value": id_value
                })
            ]

            clinic_status = codeableconcept.CodeableConcept()
            clinic_status.coding = [
                coding.Coding({
                    "system":
                    "http://terminology.hl7.org/CodeSystem/condition-clinical",
                    "code": "active"
                })
            ]
            icd_condition.clinicalStatus = clinic_status

            full_code = self.data['code']
            if self.data['sec_code']:
                full_code = self.data['code'] + " " + self.data['sec_code']
            condition_coding = mii_coding.Coding()
            condition_coding.system = "http://fhir.de/CodeSystem/dimdi/icd-10-gm"
            condition_coding.code = full_code
            condition_coding.version = self.data['code_ver']

            if self.data['sec_code']:
                main_cross_ext = extension.Extension()
                main_cross_ext.url = "http://fhir.de/StructureDefinition/icd-10-gm-haupt-kreuz"
                main_cross_ext.valueCoding = coding.Coding({
                    "system":
                    condition_coding.system,
                    "version":
                    self.data['code_ver'],
                    "code":
                    re.sub(r"[+†]", "", self.data['code'])
                })
                condition_coding.extension = [main_cross_ext]

                if '!' in self.data['sec_code']:
                    excl_ext = extension.Extension()
                    excl_ext.url = "http://fhir.de/StructureDefinition/icd-10-gm-ausrufezeichen"
                    excl_ext.valueCoding = coding.Coding({
                        "system":
                        condition_coding.system,
                        "version":
                        self.data['code_ver'],
                        "code":
                        re.sub(r"!", "", self.data['sec_code'])
                    })
                    condition_coding.extension.append(excl_ext)

                if '*' in self.data['sec_code']:
                    star_ext = extension.Extension()
                    star_ext.url = "http://fhir.de/StructureDefinition/icd-10-gm-stern"
                    star_ext.valueCoding = coding.Coding({
                        "system":
                        condition_coding.system,
                        "version":
                        self.data['code_ver'],
                        "code":
                        re.sub(r"\*", "", self.data['sec_code'])
                    })
                    condition_coding.extension.append(star_ext)

            condition_code = mii_codeableconcept.CodeableConcept()
            condition_code.coding = [condition_coding]
            icd_condition.code = condition_code

            # todo: what value of the data mart should be mapped?
            icd_condition.onsetString = '2002-01-01'

            ref = {"reference": f"Encounter/{self.data['encounter_psn']}"}
            icd_condition.encounter = fhirreference.FHIRReference(jsondict=ref)
            ref = {"reference": f"Patient/{self.data['patient_psn']}"}
            icd_condition.subject = fhirreference.FHIRReference(jsondict=ref)

            if not pd.isna(self.data['admission_dt']):
                icd_condition.recordedDate = fhirdate.FHIRDate(
                    datetime.strftime(self.data['admission_dt'],
                                      '%Y-%m-%dT%H:%M:%S'))

            if self.data['loc']:
                icd_condition.bodySite = []
                if self.data['loc'] == "L" or self.data['loc'] == "B":
                    left_body_part = mii_codeableconcept.CodeableConcept()
                    icd_loc_sys = "http://fhir.de/CodeSystem/kbv/s_icd_seitenlokalisation"
                    left_body_part.coding = [
                        mii_coding.Coding({
                            "system": icd_loc_sys,
                            "code": "L",
                            "display": "links"
                        })
                    ]
                    icd_condition.bodySite.append(left_body_part)

                if self.data['loc'] == "R" or self.data['loc'] == "B":
                    right_body_part = mii_codeableconcept.CodeableConcept()
                    icd_loc_sys = "http://fhir.de/CodeSystem/kbv/s_icd_seitenlokalisation"
                    right_body_part.coding = [
                        mii_coding.Coding({
                            "system": icd_loc_sys,
                            "code": "R",
                            "display": "rechts"
                        })
                    ]
                    icd_condition.bodySite.append(right_body_part)

            rank = 2
            if self.data['diag_type'] == 1:
                rank = 1

            icd_meta = meta.Meta()
            icd_meta.source = "#sap-ish"
            icd_condition.meta = icd_meta

            return [icd_condition, rank]

        except KeyError as exc:
            self.logger.error(
                f"In {__name__}: Key {exc} not found in dictionary")
            raise