CDA to FHIR Maps
0.1.0 - ci-build Italy flag

CDA to FHIR Maps, published by HL7 Italy. This guide is not an authorized publication; it is the continuous build for version 0.1.0 built by the FHIR (HL7® FHIR® Standard) CI Build. This version is based on the current content of https://github.com/hl7-it/cda2fhir/ and changes regularly. See the Directory of published versions

StructureMap: CDA to FHIR - LDO

Official URL: http://hl7.it/fhir/cda2fhir/StructureMap/cda2fhirLdo Version: 0.1.0
Draft as of 2024-09-15 Computable Name: cda2fhirLdo
map "http://hl7.it/fhir/cda2fhir/StructureMap/cda2fhirLdo" = "cda2fhirLdo"

uses "http://hl7.org/fhir/cda/StructureDefinition/ClinicalDocument" alias ClinicalDocument as source
uses "http://hl7.org/fhir/cda/StructureDefinition/AssignedAuthor" alias AssignedAuthor as queried
uses "http://hl7.org/fhir/cda/StructureDefinition/AssignedEntity" alias AssignedEntity as queried
uses "http://hl7.org/fhir/cda/StructureDefinition/AssociatedEntity" alias AssociatedEntity as queried
uses "http://hl7.org/fhir/cda/StructureDefinition/CustodianOrganization" alias CustodianOrganization as queried
uses "http://hl7.org/fhir/cda/StructureDefinition/OrganizationPartOf" alias OrganizationPartOf as queried
uses "http://hl7.org/fhir/cda/StructureDefinition/Organization" alias rapresentedOrganization as queried
uses "http://hl7.org/fhir/cda/StructureDefinition/Section" alias Section as queried
uses "http://hl7.org/fhir/cda/StructureDefinition/PatientRole" alias PatientRole as queried
uses "http://hl7.org/fhir/cda/StructureDefinition/AD" alias AD as source
uses "http://hl7.org/fhir/StructureDefinition/Bundle" alias Bundle as target
uses "http://hl7.org/fhir/StructureDefinition/Composition" alias Composition as produced
uses "http://hl7.org/fhir/StructureDefinition/Patient" alias Patient as produced
uses "http://hl7.org/fhir/StructureDefinition/Encounter" alias Encounter as produced
uses "http://hl7.org/fhir/StructureDefinition/Person" alias Patient as produced
uses "http://hl7.org/fhir/StructureDefinition/Practitioner" alias Practitioner as produced
uses "http://hl7.org/fhir/StructureDefinition/Organization" alias Organization as produced
uses "http://hl7.org/fhir/cda/StructureDefinition/Act" alias Act as produced
uses "http://hl7.org/fhir/cda/StructureDefinition/IVL-PQ" alias IVL_PQ as source
uses "http://hl7.org/fhir/cda/StructureDefinition/PQ" alias PQ as source
uses "http://hl7.org/fhir/StructureDefinition/SimpleQuantity" alias SimpleQuantity as target

imports "http://hl7.it/fhir/cda2fhir/StructureMap/cda2fhirDataTypes"
imports "http://hl7.it/fhir/cda2fhir/StructureMap/cda2fhirHeader"

group CdaToBundle(source cda : ClinicalDocument, target bundle : Bundle) {
  cda ->  bundle.entry as e,  e.request = create('BackboneElement') as request,  request.method = 'POST',  e.resource = create('Composition') as composition,  composition.id = uuid() as uuid1,  e.fullUrl = append('https://example/Composition/', uuid1),  request.url = 'Composition',  bundle.entry as e2,  e2.request = create('BackboneElement') as requestPAT,  requestPAT.method = 'PUT',  e2.resource = create('Patient') as patient,  patient.id = uuid() as uuid2,  e2.fullUrl = append('https://example/Patient/', uuid2),  bundle.entry as e3,  e3.request = create('BackboneElement') as request,  request.method = 'POST',  e3.resource = create('Encounter') as encounter,  encounter.id = uuid() as uuid3,  e3.fullUrl = append('https://example/Encounter/', uuid3),  request.url = 'Encounter',  bundle.entry as e5,  e5.request = create('BackboneElement') as request,  request.method = 'POST',  e5.resource = create('DocumentReference') as DocumentReference,  DocumentReference.id = uuid() as uuid5,  e5.fullUrl = append('https://example/DocumentReference/', uuid5),  request.url = 'DocumentReference' then {
    cda then ClinicalDocumentToBundle(cda, patient, composition, encounter, bundle, DocumentReference) "cdatobundle";
    cda.recordTarget as recordTarget then {
      recordTarget.patientRole as patient then {
        patient.id as id -> patient.identifier as identifier then {
          id.root as r -> identifier.system = translate(r, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri') "root1";
          id.extension as ext -> identifier.value = ext;
          id.assigningAuthorityName as s ->  identifier.assigner as a,  a.display = s;
        } "record";
        patient.id as id where (root = '2.16.840.1.113883.2.9.4.3.2') or (root = '2.16.840.1.113883.2.9.4.3.7') or (root = '2.16.840.1.113883.2.9.4.3.3') or (root = '2.16.840.1.113883.2.9.4.3.17') or (root = '2.16.840.1.113883.2.9.4.3.18') or (root = '2.16.840.1.113883.2.9.2.10.4.1.1') or (root = '2.16.840.1.113883.2.9.2.20.4.1.1') or (root = '2.16.840.1.113883.2.9.2.30.4.1.1') or (root = '2.16.840.1.113883.2.9.2.41.4.1.1') or (root = '2.16.840.1.113883.2.9.2.42.4.1.1') or (root = '2.16.840.1.113883.2.9.2.50.4.1.1') or (root = '2.16.840.1.113883.2.9.2.60.4.1.1') or (root = '2.16.840.1.113883.2.9.2.70.4.1.1') or (root = '2.16.840.1.113883.2.9.2.80.4.1.1') or (root = '2.16.840.1.113883.2.9.2.90.4.1.1') or (root = '2.16.840.1.113883.2.9.2.100.4.1.1') or (root = '2.16.840.1.113883.2.9.2.110.4.1.1') or (root = '2.16.840.1.113883.2.9.2.120.4.1.1') or (root = '2.16.840.1.113883.2.9.2.130.4.1.1') or (root = '2.16.840.1.113883.2.9.2.140.4.1.1') or (root = '2.16.840.1.113883.2.9.2.150.4.1.1') or (root = '2.16.840.1.113883.2.9.2.160.4.1.1') or (root = '2.16.840.1.113883.2.9.2.170.4.1.1') or (root = '2.16.840.1.113883.2.9.2.180.4.1.1') or (root = '2.16.840.1.113883.2.9.2.190.4.1.1') or (root = '2.16.840.1.113883.2.9.2.200.4.1.1') or (root = '2.16.840.1.113883.2.9.2.10.4.1') or (root = '2.16.840.1.113883.2.9.2.20.4.1') or (root = '2.16.840.1.113883.2.9.2.30.4.1') or (root = '2.16.840.1.113883.2.9.2.41.4.1') or (root = '2.16.840.1.113883.2.9.2.42.4.1') or (root = '2.16.840.1.113883.2.9.2.50.4.1') or (root = '2.16.840.1.113883.2.9.2.60.4.1') or (root = '2.16.840.1.113883.2.9.2.70.4.1') or (root = '2.16.840.1.113883.2.9.2.80.4.1') or (root = '2.16.840.1.113883.2.9.2.90.4.1') or (root = '2.16.840.1.113883.2.9.2.100.4.1') or (root = '2.16.840.1.113883.2.9.2.110.4.1') or (root = '2.16.840.1.113883.2.9.2.120.4.1') or (root = '2.16.840.1.113883.2.9.2.130.4.1') or (root = '2.16.840.1.113883.2.9.2.140.4.1') or (root = '2.16.840.1.113883.2.9.2.150.4.1') or (root = '2.16.840.1.113883.2.9.2.160.4.1') or (root = '2.16.840.1.113883.2.9.2.170.4.1') or (root = '2.16.840.1.113883.2.9.2.180.4.1') or (root = '2.16.840.1.113883.2.9.2.190.4.1') or (root = '2.16.840.1.113883.2.9.2.200.4.1') or (root = '2.16.840.1.113883.2.9.4.3.15') then {
          id.extension as ext -> requestPAT.url = append('Patient?identifier=', ext) "UUID";
        } "ext";
      } "recPat";
    } "patient";
  } "ClinicalDocumentToBody";
}

group ClinicalDocumentToBundle(source cda : ClinicalDocument, target patient : Patient, target composition : Composition, target encounter : Encounter, target bundle : Bundle, target DocumentReference : DocumentReference) {
  cda -> bundle.id = uuid() "id";
  cda.id -> bundle.identifier "identifier";
  cda -> bundle.type = 'transaction' "type";
  cda -> bundle.timestamp = (timestamp.now()) "date";
  cda then ClinicalDocumentComposition(cda, composition, patient, encounter, bundle, DocumentReference) "composition";
  cda.component as component then {
    component.structuredBody as body then {
      body.component as component then {
        // discretizzi il primo livello di component
        component.section as srcSection then {
          srcSection.code where (code = '46241-6') -> composition.section as tgtSection then ClinicalDocumentSectionMotivoRicovero(cda, srcSection, patient, tgtSection, bundle, encounter) "motivoRicovero";
          srcSection.code where (code = '47039-3') -> composition.section as tgtSection then ClinicalDocumentSectionInquadramentoClinico(cda, srcSection, patient, tgtSection, bundle, encounter) "inquadramentoClinico";
          srcSection.code where (code = '8648-8') -> composition.section as tgtSection then ClinicalDocumentSectionDecorsoOspedaliero(cda, srcSection, patient, tgtSection, bundle, encounter) "DecorsoOspedaliero";
          srcSection.code where (code = '55109-3') -> composition.section as tgtSection then ClinicalDocumentSectionComplicanze(cda, srcSection, patient, tgtSection, bundle, encounter) "Complicazioni";
          srcSection.code where (code = '11493-4') -> composition.section as tgtSection then ClinicalDocumentSectionRiscontri(cda, srcSection, patient, tgtSection, bundle, encounter) "HospitalDischargeStudiesSummary";
          srcSection.code where (code = '34104-0') -> composition.section as tgtSection then ClinicalDocumentSectionConsulenza(cda, srcSection, patient, tgtSection, bundle, encounter) "HospitalDischargeStudiesSummary";
          srcSection.code where (code = '30954-2') -> composition.section as tgtSection then ClinicalDocumentSectionEsamiEseguitiRicovero(cda, srcSection, patient, tgtSection, bundle, encounter) "EsamiEseguitiDuranteilRicovero";
          srcSection.code where (code = '47519-4') -> composition.section as tgtSection then ClinicalDocumentSectionProcedureEseguiteRicovero(cda, srcSection, patient, tgtSection, bundle, encounter) "HistoryOfProceduresDocument";
          srcSection.code where (code = '48765-2') -> composition.section as tgtSection then ClinicalDocumentSectionAllergie(cda, srcSection, patient, tgtSection, bundle, encounter) "EsamiEseguitiDuranteIlRicovero";
          srcSection.code where (code = '10160-0') -> composition.section as tgtSection then ClinicalDocumentSectionTerapiaFarmacologicaDuranteRicovero(cda, srcSection, patient, tgtSection, bundle, encounter) "TerapiaFarmacologicaAllaDimissione";
          srcSection.code where (code = '11535-2') -> composition.section as tgtSection then ClinicalDocumentSectionDiagnosiDimissione(cda, srcSection, patient, tgtSection, bundle, encounter) "DiagnosiDiDimissione";
          srcSection.code where (code = '18776-5') -> composition.section as tgtSection then ClinicalDocumentSectionIstruzioniFollowUp(cda, srcSection, patient, tgtSection, bundle, encounter) "DiagnosiDiDimissione";
          srcSection.code where (code = '10183-2') -> composition.section as tgtSection then ClinicalDocumentSectionTerapiaDimissione(cda, srcSection, patient, tgtSection, bundle, encounter) "TerapiaFarmacologicaAllaDimissione";
        };
      };
    } "body";
  };
}

// -------------------------------------------------------------------------------------------------------------------
group ClinicalDocumentSectionMotivoRicovero(source cda : ClinicalDocument, source src : Section, target patient : Patient, target tgt, target bundle : Bundle, target enc : Encounter) {
  src.title as t -> tgt.title = (t.dataString);
  src.code -> tgt.code;
  src where src.entry.exists() then {
    src.text as cdaText -> tgt.text as fhirText then {
      cdaText -> fhirText.status = 'generated' "narrativeStatus";
      cdaText as t -> fhirText.div = t "narrativeText";
    } "cdaText";
  } "cText";
  src.entry as entry1 ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('Observation') as observation,  observation.id = uuid() as uuid1,  e1.fullUrl = append('https://example/Observation/', uuid1),  request.url = 'Observation',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %observation.id) then {
    entry1.observation as obs then Observation(obs, patient, enc, observation, bundle) "act";
  };
  src where src.entry.exists().not() then {
    src.text as cdaText ->  bundle.entry as e8,  e8.request = create('BackboneElement') as request,  request.method = 'POST',  e8.resource = create('Observation') as Observation,  Observation.id = uuid() as uuid8,  e8.fullUrl = append('https://example/Observation/', uuid8),  request.url = 'Observation',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %Observation.id) then {
      src ->  Observation.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
      src ->  Observation.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %enc.id) "reference";
      src.code -> Observation.code;
      src where observation.statusCode.exists().not() then {
        src -> Observation.status = 'final' "status";
      } "statuscode";
      cdaText -> Observation.note as note then {
        cdaText as t -> note.text = t "reference";
      } "reference";
    } "cdaText";
  } "where";
}

group ClinicalDocumentSectionInquadramentoClinico(source cda : ClinicalDocument, source src : Section, target patient : Patient, target tgt, target bundle : Bundle, target enc : Encounter) {
  src.title as t -> tgt.title = (t.dataString);
  src.code -> tgt.code;
  src.text as cdaText ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('Observation') as observation,  observation.id = uuid() as uuid1,  e1.fullUrl = append('https://example/Observation/', uuid1),  request.url = 'Observation',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %observation.id),  tgt.text as fhirText then {
    cdaText ->  observation.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
    cdaText ->  observation.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %enc.id) "reference";
    cdaText -> fhirText.status = 'generated' "narrativeStatus";
    cdaText as t -> fhirText.div = t "narrativeText";
    src.code -> observation.code;
    src where observation.statusCode.exists().not() then {
      src -> observation.status = 'final' "status";
    } "statuscode";
    cdaText -> observation.note as note then {
      cdaText as t -> note.text = t "reference";
    } "reference";
  } "cdaText";
  src.component as component then {
    component.section as section2 then {
      // ANAMNESI
      section2 -> tgt.section as sec2 then {
        section2.code where (code = '11329-0') -> sec2.code;
        section2.title as t -> sec2.title = (t.dataString);
        // section2.code -> sec2.code;
        src where src.entry.exists() then {
          section2.text as cdaText -> sec2.text as fhirText then {
            cdaText -> fhirText.status = 'generated' "narrativeStatus";
            cdaText as t -> fhirText.div = t "narrativeText";
          } "cdaText";
        } "exist";
        src where src.entry.exists().not() then {
          section2.text as cdaText ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('Observation') as condition,  condition.id = uuid() as uuid1,  e1.fullUrl = append('https://example/Observation/', uuid1),  request.url = 'Observation',  sec2.entry = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %condition.id) then {
            section2.code -> condition.code;
            src where condition.statusCode.exists().not() then {
              src -> condition.status = 'final' "status";
            } "statuscode";
            cdaText -> condition.note as note then {
              cdaText ->  condition.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
              cdaText ->  condition.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %enc.id) "reference";
              cdaText as t -> note.text = t "reference";
            } "reference";
          } "cdaText";
        } "where";
        section2.entry as entry1 then {
          entry1.observation as obs then {
            // EntryRelationship per il Problem
            obs.code where (code = '75326-9') then {
              obs ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('Condition') as condition,  condition.id = uuid() as uuid1,  e1.fullUrl = append('https://example/Condition/', uuid1),  request.url = 'Condition',  sec2.entry = create('Reference') as reference,  reference.reference = ('https://example/Condition/' + %condition.id) then {
                obs.code -> condition.category;
                obs ->  condition.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
                obs ->  condition.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %enc.id) "reference";
                obs.statusCode as status where (code = 'completed') -> condition.verificationStatus as status2 then {
                  status -> status2.coding as status3 then {
                    status -> status3.code = 'confirmed' "finald";
                    status -> status3.system = 'http://terminology.hl7.org/CodeSystem/condition-ver-status' "system";
                  } "st3";
                } "status";
                obs.effectiveTime as effective1 then {
                  effective1 where effective1.low.exists() or effective1.high.exists() then {
                    effective1 -> condition.onset = create('Period') as periodonset then IVLTSPeriod(effective1, periodonset) "onsetperiod";
                  } "ef";
                } "effectivetime1";
                obs.value : CD as val then {
                  val -> condition.code = create('CodeableConcept') as ce then {
                    val.originalText -> ce.text;
                    val -> ce.coding as coding then {
                      val.code as code -> coding.code = cast(code, 'string');
                      val.codeSystem as system -> coding.system = translate(system, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri');
                      val.displayName as display -> coding.display = cast(display, 'string');
                    } "coding";
                  } "Ce";
                } "Value";
                obs.entryRelationship as entriRel then {
                  entriRel -> condition.evidence = create('BackboneElement') as evidence then {
                    entriRel.observation as observation2 then {
                      observation2.code as code then {
                        code.code where (code.code = '89261-2') then {
                          obs ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('Observation') as observation,  observation.id = uuid() as uuid1,  e1.fullUrl = append('https://example/Observation/', uuid1),  request.url = 'Observation' then {
                            entriRel ->  evidence.detail = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %observation.id) "ref";
                            observation2.code -> observation.code;
                            observation2 where observation.statusCode.exists().not() then {
                              observation2 -> observation.status = 'final' "status";
                            } "statuscode";
                            observation2.text as text -> observation.note = create('Annotation') as note then {
                              text.reference as ref -> note.text = (ref.value) "val";
                            } "Annontation";
                            obs ->  observation.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
                            obs ->  observation.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %enc.id) "reference";
                            observation2.statusCode as statusc where (code = 'completed') -> ob.status = 'final';
                            observation2.statusCode as statusc where (code = 'active') -> ob.status = 'registered';
                            observation2.statusCode as statusc where (code = 'aborted') -> ob.status = 'cancelled';
                            observation2.statusCode as statusc where (code = 'suspended') -> ob.status = 'partial';
                            observation2.value : INT as int -> ob.value = (int.value);
                            observation2.value : BL as boolean -> ob.value = (boolean.value) "boolean";
                            observation2.value : CD as val then {
                              val -> ob.value = create('CodeableConcept') as ce then {
                                val.originalText as originalText then {
                                  originalText.reference as reference -> ce.text = reference;
                                } "originltext";
                                val -> ce.coding as coding then {
                                  val.code as code -> coding.code = cast(code, 'string');
                                  val.codeSystem as system -> coding.system = translate(system, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri');
                                  val.displayName as display -> coding.display = cast(display, 'string');
                                  val.codeSystemVersion as version -> coding.version = cast(version, 'string');
                                } "code";
                                val.translation as translation -> ce.coding as coding then {
                                  translation.code as code -> coding.code = cast(code, 'string');
                                  translation.codeSystem as system -> coding.system = translate(system, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri');
                                  translation.displayName as display -> coding.display = cast(display, 'string');
                                  translation.codeSystemVersion as version -> coding.version = cast(version, 'string');
                                  translation.qualifier as qualifier then {
                                    qualifier.value as value -> ce.coding as coding then {
                                      value.code as code -> coding.code = cast(code, 'string');
                                      value.codeSystem as system -> coding.system = translate(system, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri');
                                      value.displayName as display -> coding.display = cast(display, 'string');
                                      value.codeSystemVersion as version -> coding.version = cast(version, 'string');
                                    };
                                  };
                                };
                              } "coding";
                            } "val";
                            observation2.value : PQ as val then {
                              val -> ob.value = create('Quantity') as quantity then {
                                val.value as value -> quantity.value = value;
                                val.unit as unit -> quantity.unit = unit;
                              } "quantity";
                            } "valueQuantity";
                            observation2.value : ST as value ->  ob.value = create('string'),  ob.value = (value.dataString);
                            observation2.value : CE as val then {
                              val -> observation.value = create('CodeableConcept') as ce then {
                                val.originalText -> ce.text;
                                val -> ce.coding as coding then {
                                  val.code as code -> coding.code = cast(code, 'string');
                                  val.codeSystem as system -> coding.system = translate(system, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri');
                                  val.displayName as display -> coding.display = cast(display, 'string');
                                } "coding";
                              } "Ce";
                            } "Value";
                          } "obser";
                        } "whereDecorsoClinico";
                      };
                    } "Observation2";
                  } "evidence";
                } "EntryRelationship1";
                obs.entryRelationship as entriRel then {
                  entriRel.observation as observation2 then {
                    observation2.code as code then {
                      code.code where (code.code = '33999-4') then {
                        observation2 -> condition.clinicalStatus = create('CodeableConcept') as status then {
                          observation2.text as text then {
                            text.reference as refstat -> status.text = (refstat.value) "statref";
                          } "textstat";
                          observation2 -> status.coding = create('Coding') as coding then {
                            observation2.value as value then {
                              value.code where (value.code = 'LA16666-2') -> coding.code = 'active' "active";
                              value.code where (value.code = 'LA18632-2') -> coding.code = 'inactive' "inactive";
                              value.codeSystem as system -> coding.system = 'http://terminology.hl7.org/CodeSystem/condition-clinical' "system";
                              value.displayName as display -> coding.display = cast(display, 'string');
                            } "value1";
                          } "coding";
                        } "code";
                      } "whereDecorsoClinico";
                    } "codestatus";
                  } "observationstatus";
                } "entryrelationshipstatus";
              } "whereEntryPatologicaProssima";
            } "observationcondition";
          } "entry";
        } "subsection1";
        // ESAME PBIETTIVO
        section2.code where (code = '29545-1') then ClinicalDocumentSottoSectionOBS(section2, sec2, bundle, enc, patient) "esameObiettivo";
        // TETAPIA FARMACOLOGICA
        section2.code where (code = '42346-7') then ClinicalDocumentSottoSectionMS(section2, sec2, bundle, patient, enc) "TerapiaFarmacologicaAllIngresso";
      } "sec2fhir";
    } "componentSec";
  };
}

group ClinicalDocumentSectionDecorsoOspedaliero(source cda : ClinicalDocument, source src : Section, target patient : Patient, target tgt, target bundle : Bundle, target enc : Encounter) {
  src.title as t -> tgt.title = (t.dataString);
  src.code -> tgt.code;
  src.text as cdaText ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('Observation') as observation,  observation.id = uuid() as uuid1,  e1.fullUrl = append('https://example/Observation/', uuid1),  request.url = 'Observation',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %observation.id),  tgt.text as fhirText then {
    cdaText -> fhirText.status = 'generated' "narrativeStatus";
    cdaText as t -> fhirText.div = t "narrativeText";
    src.code -> observation.code;
    src where observation.statusCode.exists().not() then {
      src -> observation.status = 'final' "status";
    } "statuscode";
    src ->  observation.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
    src ->  observation.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %enc.id) "reference";
    cdaText -> observation.note as note then {
      cdaText as t -> note.text = t "reference";
    } "reference";
  } "cdaText";
  src.component as component then {
    component.section as section2 then {
      src then ClinicalDocumentSottoSectionOBS(section2, tgt, bundle, enc, patient) "Decorso";
    } "1";
  } "2";
}

group ClinicalDocumentSectionComplicanze(source cda : ClinicalDocument, source src : Section, target patient : Patient, target tgt, target bundle : Bundle, target enc : Encounter) {
  src.title as t -> tgt.title = (t.dataString);
  src.code -> tgt.code;
  src where src.entry.exists() then {
    src.text as cdaText -> tgt.text as fhirText then {
      cdaText -> fhirText.status = 'generated' "narrativeStatus";
      cdaText as t -> fhirText.div = t "narrativeText";
    } "cdaText";
  } "exist";
  src where src.entry.exists().not() then {
    src.text as cdaText ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('Observation') as observation,  observation.id = uuid() as uuid1,  e1.fullUrl = append('https://example/Observation/', uuid1),  request.url = 'Observation',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %observation.id) then {
      src ->  observation.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
      src ->  observation.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %enc.id) "reference";
      src.code -> observation.code;
      src where observation.statusCode.exists().not() then {
        src -> observation.status = 'final' "status";
      } "statuscode";
      cdaText -> observation.note as note then {
        cdaText as t -> note.text = t "reference";
      } "reference";
    } "cdaText";
  } "where";
  src.entry as entry1 ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('Observation') as observation,  observation.id = uuid() as uuid1,  e1.fullUrl = append('https://example/Observation/', uuid1),  request.url = 'Observation',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %observation.id) then {
    entry1.observation as obs then Observation(obs, patient, enc, observation, bundle) "act";
  };
}

group ClinicalDocumentSectionRiscontri(source cda : ClinicalDocument, source src : Section, target patient : Patient, target tgt, target bundle : Bundle, target enc : Encounter) {
  src.title as t -> tgt.title = (t.dataString);
  src.code -> tgt.code;
  src.text as cdaText ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('Observation') as observation,  observation.id = uuid() as uuid1,  e1.fullUrl = append('https://example/Observation/', uuid1),  request.url = 'Observation',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %observation.id),  tgt.text as fhirText then {
    cdaText -> fhirText.status = 'generated' "narrativeStatus";
    cdaText as t -> fhirText.div = t "narrativeText";
    src.code -> observation.code;
    src where observation.statusCode.exists().not() then {
      src -> observation.status = 'final' "status";
    } "statuscode";
    src ->  observation.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
    src ->  observation.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %enc.id) "reference";
    cdaText -> observation.note as note then {
      cdaText as t -> note.text = t "reference";
    } "reference";
  } "cdaText";
  src.component as component then {
    component.section as section2 then {
      src then ClinicalDocumentSottoSectionOBS(section2, tgt, bundle, enc, patient) "Decorso";
    } "1";
  } "2";
}

group ClinicalDocumentSectionConsulenza(source cda : ClinicalDocument, source src : Section, target patient : Patient, target tgt, target bundle : Bundle, target enc : Encounter) {
  src.title as t -> tgt.title = (t.dataString);
  src.code -> tgt.code;
  src where src.entry.exists() then {
    src.text as cdaText -> tgt.text as fhirText then {
      cdaText -> fhirText.status = 'generated' "narrativeStatus";
      cdaText as t -> fhirText.div = t "narrativeText";
    } "cdaText";
  } "exist";
  src where src.entry.exists().not() then {
    src.text as cdaText ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('Observation') as observation,  observation.id = uuid() as uuid1,  e1.fullUrl = append('https://example/Observation/', uuid1),  request.url = 'Observation',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %observation.id) then {
      src ->  observation.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
      src ->  observation.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %enc.id) "reference";
      src.code -> observation.code;
      src where observation.statusCode.exists().not() then {
        src -> observation.status = 'final' "status";
      } "statuscode";
      cdaText -> observation.note as note then {
        cdaText as t -> note.text = t "reference";
      } "reference";
    } "cdaText";
  } "where";
  src.entry as entry1 ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('Observation') as observation,  observation.id = uuid() as uuid1,  e1.fullUrl = append('https://example/Observation/', uuid1),  request.url = 'Observation',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %observation.id) then {
    entry1.observation as obs then ObservationConsulenza(obs, patient, enc, observation, bundle) "act";
  };
}

group ClinicalDocumentSectionEsamiEseguitiRicovero(source cda : ClinicalDocument, source src : Section, target patient : Patient, target tgt, target bundle : Bundle, target enc : Encounter) {
  src.title as t -> tgt.title = (t.dataString);
  src.code -> tgt.code;
  src where src.entry.exists() then {
    src.text as cdaText -> tgt.text as fhirText then {
      cdaText -> fhirText.status = 'generated' "narrativeStatus";
      cdaText as t -> fhirText.div = t "narrativeText";
    } "cdaText";
  } "exists";
  src where src.entry.exists().not() then {
    src.text as cdaText ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('Observation') as observation,  observation.id = uuid() as uuid1,  e1.fullUrl = append('https://example/Observation/', uuid1),  request.url = 'Observation',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %observation.id) then {
      src ->  observation.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
      src ->  observation.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %enc.id) "reference";
      src.code -> observation.code;
      src where observation.statusCode.exists().not() then {
        src -> observation.status = 'final' "status";
      } "statuscode";
      cdaText -> observation.note as note then {
        cdaText as t -> note.text = t "reference";
      } "reference";
    } "cdaText";
  } "where";
  src.entry as entry1 ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('Observation') as observation,  observation.id = uuid() as uuid1,  e1.fullUrl = append('https://example/Observation/', uuid1),  request.url = 'Observation',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %observation.id) then {
    entry1.observation as obs then ObservationEsamiDuranteRicovero(obs, patient, enc, observation, bundle) "act";
  };
}

group ClinicalDocumentSectionProcedureEseguiteRicovero(source cda : ClinicalDocument, source src : Section, target patient : Patient, target tgt, target bundle : Bundle, target enc : Encounter) {
  src.title as t -> tgt.title = (t.dataString);
  src.code -> tgt.code;
  src where src.entry.exists() then {
    src.text as cdaText -> tgt.text as fhirText then {
      cdaText -> fhirText.status = 'generated' "narrativeStatus";
      cdaText as t -> fhirText.div = t "narrativeText";
    } "cdaText";
  } "exists";
  src where src.entry.exists().not() then {
    src.text as cdaText ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('Procedure') as procedure,  procedure.id = uuid() as uuid1,  e1.fullUrl = append('https://example/Procedure/', uuid1),  request.url = 'Procedure',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Procedure/' + %procedure.id) then {
      src ->  procedure.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
      src ->  procedure.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %enc.id) "reference";
      src -> procedure.status = 'unknown' "statuscode";
      cdaText -> procedure.note as note then {
        cdaText as t -> note.text = t "reference";
      } "reference";
    } "cdaText";
  } "where";
  src.entry as entry1 ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('Procedure') as procedure,  procedure.id = uuid() as uuid1,  e1.fullUrl = append('https://example/Procedure/', uuid1),  request.url = 'Procedure',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Procedure/' + %procedure.id) then {
    src ->  procedure.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
    src ->  procedure.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %enc.id) "reference";
    entry1.procedure as proceduresrc then {
      proceduresrc.code -> procedure.code;
      proceduresrc.text as txt -> procedure.note as note then {
        txt.reference as ref -> note.text = (ref.value);
      };
      proceduresrc where proc.statusCode.exists().not() then {
        proceduresrc -> procedure.status = 'unknown' "statuscode";
      } "status";
      proceduresrc.statusCode as statusc where (code = 'completed') -> procedure.status = 'completed';
      proceduresrc.statusCode as statusc where (code = 'active') -> procedure.status = 'in-progress';
      proceduresrc.statusCode as statusc where (code = 'aborted') -> procedure.status = 'stopped';
      proceduresrc.statusCode as statusc where (code = 'suspended') -> procedure.status = 'on-hold';
      proceduresrc.statusCode as statusc where (code = 'cancelled') -> procedure.status = 'not-done';
      proceduresrc.statusCode as statusc where (code = 'held') -> procedure.status = 'on-hold';
      proceduresrc.statusCode as statusc where (code = 'new') -> procedure.status = 'preparation';
      proceduresrc.statusCode as statusc where (code = 'obsolete') -> procedure.status = 'entered-in-error';
      proceduresrc.statusCode as statusc where (code = 'nullified') -> procedure.status = 'unknown';
      proceduresrc.effectiveTime as efft -> procedure.performed = create('Period') as period then IVLTSPeriod(efft, period);
      proceduresrc.entryRelationship as entriRel ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('Observation') as observation,  observation.id = uuid() as uuid1,  e1.fullUrl = append('https://example/Observation/', uuid1),  request.url = 'Observation',  procedure.reasonReference = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %observation.id) then {
        entriRel ->  observation.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
        entriRel ->  observation.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %enc.id) "reference";
        entriRel.observation as obs then {
          obs.code -> observation.code;
          obs where observation.statusCode.exists().not() then {
            obs -> observation.status = 'final' "status";
          } "statuscode";
        } "ObservationValue";
      } "Observation";
    } "Procedure";
  } "Entry";
}

group ClinicalDocumentSectionAllergie(source cda : ClinicalDocument, source src : Section, target patient : Patient, target tgt, target bundle : Bundle, target enc : Encounter) {
  src.title as t -> tgt.title = (t.dataString);
  src.code -> tgt.code;
  src where src.entry.exists() then {
    src.text as cdaText -> tgt.text as fhirText then {
      cdaText -> fhirText.status = 'generated' "narrativeStatus";
      cdaText as t -> fhirText.div = t "narrativeText";
    } "cdaText";
  } "exists";
  src where src.entry.exists().not() then {
    src.text as cdaText ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('AllergyIntolerance') as allergy,  allergy.id = uuid() as uuid1,  e1.fullUrl = append('https://example/AllergyIntolerance/', uuid1),  request.url = 'AllergyIntolerance',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/AllergyIntolerance/' + %allergy.id) then {
      src ->  allergy.patient = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
      src ->  allergy.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %enc.id) "reference";
      src -> allergy.clinicalStatus = create('CodeableConcept') as status then {
        src -> status.text = 'string' "text";
        src -> status.coding = create('Coding') as coding then {
          src -> coding.code = 'active' "active";
          src -> coding.system = 'http://terminology.hl7.org/CodeSystem/allergyintolerance-clinical' "system";
        } "coding";
      } "allergy";
      src.code -> allergy.code;
      cdaText -> allergy.note as note then {
        cdaText as t -> note.text = t "reference";
      } "reference";
    } "cdaText";
  } "where";
  src.entry as entry1 ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('AllergyIntolerance') as allergy,  allergy.id = uuid() as uuid1,  e1.fullUrl = append('https://example/AllergyIntolerance/', uuid1),  request.url = 'AllergyIntolerance',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/AllergyIntolerance/' + %allergy.id) then {
    src ->  allergy.patient = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
    src ->  allergy.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %enc.id) "reference";
    entry1.act as actallint then {
      actallint.effectiveTime as eff -> allergy.onset = create('Period') as per then IVLTSPeriod(eff, per);
      actallint.entryRelationship as entryact then {
        entryact.observation as entryobs then {
          entryobs.value as code then {
            code.code as code1 -> allergy.type = translate(code1, '#AllergyTypeMap', 'code') "type";
            code.code as code2 -> allergy.category = translate(code2, '#AllergyCategoryMap', 'code') "category";
          } "code";
          entryobs.participant as partic then {
            partic.participantRole as pratRole then {
              pratRole.playingEntity as pratent then {
                pratent -> allergy.reaction = create('BackboneElement') as reaction then {
                  pratent.code -> reaction.substance "subs";
                  entryobs.entryRelationship as entryobs1 where (typeCode = 'MFST') then {
                    entryobs1.observation as entobs then {
                      entobs.effectiveTime as eff then {
                        eff.low as l -> reaction.onset = create('dateTime') as start then TSDateTime(l, start) "val";
                      } "eff";
                      entobs.value -> reaction.manifestation "manifest";
                    } "observ";
                  } "entry";
                } "cod";
              } "react";
            } "pratentit";
          } "PratRole";
          entryobs.entryRelationship as entryobs2 then {
            entryobs2.observation as entobs then {
              entobs.code as code where (code = 'SEV') then {
                entobs.value as value then {
                  value.code where (value.code = 'M') -> allergy.criticality = 'unable-to-assess' "active";
                  value.code where (value.code = 'L') -> allergy.criticality = 'low' "active";
                  value.code where (value.code = 'H') -> allergy.criticality = 'high' "active";
                } "entobs";
              } "sev";
            } "severity";
          } "observ";
          entryobs.entryRelationship as entryobs3 then {
            entryobs3.observation as entobs then {
              entobs.code as code where (code = '33999-4') then {
                entobs -> allergy.clinicalStatus = create('CodeableConcept') as status then {
                  entobs -> status.coding = create('Coding') as coding then {
                    entobs.value as value then {
                      value.code where (value.code = 'LA16666-2') -> coding.code = 'active' "active";
                      value.code where (value.code = 'LA18632-2') -> coding.code = 'inactive' "active";
                      value.codeSystem as system -> coding.system = 'http://terminology.hl7.org/CodeSystem/allergyintolerance-clinical' "system";
                      value.displayName as display -> coding.display = cast(display, 'string');
                    } "value1";
                  } "coding";
                } "clinicalStatus";
              } "stat";
            } "obobs3serv";
          } "entry3";
          entryobs.entryRelationship as entryobs4 then {
            entryobs4.act as entact then {
              entact.text as actext then {
                actext.reference as reftxt -> allergy.note = create('BackboneElement') as note then {
                  reftxt as ref -> note.text = (ref.value) "notxt";
                } "notetxt";
              } "txtact";
            } "obobs4serv";
          } "entry4";
        } "partic";
      };
    };
  } "allergy";
}

group ClinicalDocumentSectionDiagnosiDimissione(source cda : ClinicalDocument, source src : Section, target patient : Patient, target tgt, target bundle : Bundle, target enc : Encounter) {
  src.title as t -> tgt.title = (t.dataString);
  src.code -> tgt.code;
  src where src.entry.exists() then {
    src.text as cdaText -> tgt.text as fhirText then {
      cdaText -> fhirText.status = 'generated' "narrativeStatus";
      cdaText as t -> fhirText.div = t "narrativeText";
    } "cdaText";
  } "exists";
  src where src.entry.exists().not() then {
    src.text as cdaText ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('Observation') as observation,  observation.id = uuid() as uuid1,  e1.fullUrl = append('https://example/Observation/', uuid1),  request.url = 'Observation',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %observation.id) then {
      src ->  observation.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
      src ->  observation.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %enc.id) "reference";
      src.code -> observation.code;
      src where observation.statusCode.exists().not() then {
        src -> observation.status = 'final' "status";
      } "statuscode";
      cdaText -> observation.note as note then {
        cdaText as t -> note.text = t "reference";
      } "reference";
    } "cdaText";
  } "where";
  src.entry as entry1 ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('Observation') as observation,  observation.id = uuid() as uuid1,  e1.fullUrl = append('https://example/Observation/', uuid1),  request.url = 'Observation',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %observation.id) then {
    entry1.observation as obs then Observation(obs, patient, enc, observation, bundle) "act";
  };
}

group ClinicalDocumentSectionIstruzioniFollowUp(source cda : ClinicalDocument, source src : Section, target patient : Patient, target tgt, target bundle : Bundle, target enc : Encounter) {
  src.title as t -> tgt.title = (t.dataString);
  src.code -> tgt.code;
  src.text as cdaText -> tgt.text as fhirText then {
    cdaText -> fhirText.status = 'generated' "narrativeStatus";
    cdaText as t -> fhirText.div = t "narrativeText";
  } "cdaText";
  src.text as cdaText ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('CarePlan') as carePlan,  carePlan.id = uuid() as uuid1,  e1.fullUrl = append('https://example/CarePlan/', uuid1),  request.url = 'CarePlan',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/CarePlan/' + %carePlan.id) then {
    cdaText -> carePlan.note as note then {
      cdaText as t -> note.text = t "reference";
    } "reference";
    src ->  carePlan.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
    src ->  carePlan.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %enc.id) "reference";
    src -> carePlan.status = 'active' "status";
    src -> carePlan.intent = 'order' "intent";
  } "entry";
}

group ClinicalDocumentSectionTerapiaFarmacologicaDuranteRicovero(source cda : ClinicalDocument, source src : Section, target patient : Patient, target tgt, target bundle : Bundle, target enc : Encounter) {
  src.title as t -> tgt.title = (t.dataString);
  src.code -> tgt.code;
  src where src.entry.exists() then {
    src.text as cdaText -> tgt.text as fhirText then {
      cdaText -> fhirText.status = 'generated' "narrativeStatus";
      cdaText as t -> fhirText.div = t "narrativeText";
    } "cdaText";
  } "exists";
  src where src.entry.exists().not() then {
    src.text as cdaText ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('MedicationAdministration') as medicationAdm,  medicationAdm.id = uuid() as uuid1,  e1.fullUrl = append('https://example/MedicationAdministration/', uuid1),  request.url = 'MedicationAdministration',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/MedicationAdministration/' + %medicationAdm.id) then {
      cdaText ->  medicationAdm.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
      cdaText ->  medicationAdm.context = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %enc.id) "reference";
      cdaText -> medicationAdm.medication = create('CodeableConcept') as codecon then {
        cdaText -> codecon.text = 'string' "text";
      } "code";
      src -> medicationAdm.effective = create('Period') as period then {
        src -> period.start = (start.now()) "low";
        src -> period.end = (end.now()) "high";
      } "Period";
      src where sub.statusCode.exists().not() then {
        src -> medicationAdm.status = 'completed' "status";
      } "statuscode";
      cdaText -> medicationAdm.note as note then {
        cdaText as t -> note.text = t "reference";
      } "reference";
    } "cdaText";
  } "where";
  src.entry as entry1 ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('MedicationAdministration') as medicationAdm,  medicationAdm.id = uuid() as uuid1,  e1.fullUrl = append('https://example/MedicationAdministration/', uuid1),  request.url = 'MedicationAdministration',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/MedicationAdministration/' + %medicationAdm.id) then {
    entry1 ->  medicationAdm.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
    entry1 ->  medicationAdm.context = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %enc.id) "reference";
    entry1.substanceAdministration as sa then {
      sa.text as tx -> medicationAdm.note as note then {
        sa.performer as performer ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'PUT',  e1.resource = create('Practitioner') as practitioner then {
          performer.time as ti -> note.time = (ti.value);
          performer.assignedEntity as assEnty then {
            assEnty -> practitioner.meta as meta then {
              assEnty -> meta.tag = create('Coding') as coding then {
                assEnty -> coding.system = 'http://algoritmodiscoring' "system";
                assEnty -> coding.code = 'ClinicalDocument/body/TerapiaFarmacologicaRicovero/performer' "code";
              } "coding";
            } "meta";
            assEnty.id as id -> practitioner.identifier as identifier then {
              id.root as r -> identifier.system = translate(r, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri') "root1";
              id.extension as ext -> identifier.value = ext;
              id.assigningAuthorityName as s ->  identifier.assigner as a,  a.display = s;
              id.root as r then {
                id.extension as ext ->  practitioner.id = (r + '-' + ext) as uuid2,  e1.fullUrl = append('https://example/Practitioner/', uuid2),  request.url = 'Practitioner',  medicationAdm.performer as perf,  perf.actor = create('Reference') as reference,  reference.reference = ('https://example/Practitioner/' + %practitioner.id) "aut";
              } "r";
            } "identifier";
            assEnty.id as id where (root = '2.16.840.1.113883.2.9.4.3.2') then {
              id.extension as ext -> request.url = append('Practitioner?identifier=', ext) "UUID";
            } "2";
            assEnty.id as id where (root != '2.16.840.1.113883.2.9.4.3.2') then {
              id.extension as ext -> request.url = append('Practitioner?identifier=', ext) "UUID";
            } "diverso";
            assEnty.assignedPerson as assi then {
              assi.name -> practitioner.name;
            } "assi";
          } "assEntity";
        } "perf";
        tx.reference as ref -> note.text = (ref.value);
      } "tx";
      sa.statusCode as st -> medicationAdm.status = (st.code);
      sa.effectiveTime as eff -> medicationAdm.effective = create('Period') as period then IVLTSPeriod(eff, period) "period";
      sa -> medicationAdm.dosage as dos then {
        sa.routeCode -> dos.route;
      } "dos";
      sa -> medicationAdm.dosage as dos then {
        sa.approachSiteCode -> dos.site;
      } "dos";
      sa.doseQuantity as doseQuant ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('MedicationRequest') as medicationRq,  medicationRq.id = uuid() as uuid1,  e1.fullUrl = append('https://example/MedicationRequest/', uuid1),  request.url = 'MedicationRequest',  medicationAdm.request = create('Reference') as reference,  reference.reference = ('https://example/MedicationRequest/' + %medicationRq.id) then {
        doseQuant -> medicationRq.dosageInstruction = create('Dosage') as dosageInstruction then {
          doseQuant.originalText as ot then {
            ot.reference -> dosageInstruction.text;
          } "ot";
          doseQuant -> dosageInstruction.doseAndRate as dosageRate then {
            doseQuant -> dosageRate.dose = create('Range') as d then {
              doseQuant -> d.low = create('SimpleQuantity') as l then {
                doseQuant.low as lo -> l.value = (lo.value);
                doseQuant.low as lo -> l.unit = (lo.unit);
              } "low";
              doseQuant -> d.high = create('SimpleQuantity') as h then {
                doseQuant.high as hi -> h.value = (hi.value);
                doseQuant.high as hi -> h.unit = (hi.unit);
              } "low";
            } "d";
          } "dosageRate";
        } "Dosage";
        sa ->  medicationRq.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
        sa ->  medicationRq.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %enc.id) "reference";
        sa -> medicationRq.status = 'active' "status";
        sa -> medicationRq.intent = 'order' "intent";
        sa.rateQuantity as rateQuantity -> medicationRq.dosageInstruction = create('Dosage') as dosageInstruction1 then {
          rateQuantity.originalText as ot then {
            ot.reference -> dosageInstruction1.text;
          } "ot";
          rateQuantity -> dosageInstruction1.doseAndRate as dosageRate then {
            rateQuantity -> dosageRate.rate = create('Range') as d then {
              rateQuantity -> d.low = create('SimpleQuantity') as l then {
                rateQuantity.low as lo -> l.value = (lo.value);
                rateQuantity.low as lo -> l.unit = (lo.unit);
              } "low";
              rateQuantity -> d.high = create('SimpleQuantity') as h then {
                rateQuantity.high as hi -> h.value = (hi.value);
                rateQuantity.high as hi -> h.unit = (hi.unit);
              } "low";
            } "d";
          } "dosageRate";
        } "Dosage";
        sa ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('Medication') as medication,  medication.id = uuid() as uuid1,  e1.fullUrl = append('https://example/Medication/', uuid1),  request.url = 'Medication',  medicationAdm.medication = create('Reference') as reference,  reference.reference = ('https://example/Medication/' + %medication.id) then {
          sa ->  medicationRq.medication = create('Reference') as reference,  reference.reference = ('https://example/Medication/' + %medication.id) "reference";
          sa.administrationUnitCode -> medication.form;
          sa.consumable as consumable then {
            consumable.manufacturedProduct as manufac then {
              manufac.manufacturedMaterial as manuprod then {
                manuprod.code -> medication.code;
              } "manufactproduct";
            } "manufac";
          };
          sa.entryRelationship as entryRR then {
            entryRR.observation as observation then {
              observation.code where displayName = 'Grammatura' -> medication.ingredient as ingredient then {
                sa.consumable as consumable then {
                  consumable.manufacturedProduct as manufacturedProduct then {
                    manufacturedProduct.manufacturedMaterial as manufacturedMaterial then {
                      manufacturedMaterial.code as code -> ingredient.item = create('CodeableConcept') as value then CECodeableConcept(code, value) "CE";
                    } "material";
                  } "product";
                };
                observation.value as value -> ingredient.strength as strength then {
                  value -> strength.numerator as numerator then {
                    value -> numerator.value = (value.value) "valueN";
                  } "numerator";
                  value -> strength.denominator as denominator then {
                    value -> denominator.value = 1 "valueD";
                  } "denominator";
                } "strenght";
              } "ingredient";
              observation.code where displayName = 'Quantità nella Confezione' then {
                observation.value as value -> medication.amount as amount then {
                  value -> amount.numerator as numerator then {
                    value -> numerator.value = (value.value) "valueN";
                  } "numerator";
                  value -> amount.denominator as denominator then {
                    value -> denominator.value = 1 "valueD";
                  } "denominator";
                } "amount";
              } "quantita";
            } "obs";
          } "entryRr";
        } "medication";
        sa.entryRelationship as entryRelationship then {
          entryRelationship.supply as sup -> medicationRq.dispenseRequest as dispreq then {
            sup -> dispreq.quantity = create('SimpleQuantity') as quantity then {
              sup.quantity as q -> quantity.value = (q.value);
            } "quantity";
          } "sub";
        } "entryR";
        sa.participant as participant then {
          participant.time as t -> medicationRq.authoredOn = (t.value);
          participant.participantRole as participantR ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'PUT',  e1.resource = create('Practitioner') as practitioner then {
            participantR -> practitioner.meta as meta then {
              participantR -> meta.tag = create('Coding') as coding then {
                participantR -> coding.system = 'http://algoritmodiscoring' "system";
                participantR -> coding.code = 'ClinicalDocument/body/TerapiaFarmacologicaRicovero/participant' "code";
              } "coding";
            } "meta";
            participantR.id as id -> practitioner.identifier as identifier then {
              id.root as r -> identifier.system = translate(r, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri') "root1";
              id.extension as ext -> identifier.value = ext;
              id.assigningAuthorityName as s ->  identifier.assigner as a,  a.display = s;
              id.root as r then {
                id.extension as ext ->  practitioner.id = (r + '-' + ext) as uuid2,  e1.fullUrl = append('https://example/Practitioner/', uuid2),  request.url = append('Practitioner/', uuid1),  medicationRq.requester = create('Reference') as reference,  reference.reference = ('https://example/Practitioner/' + %practitioner.id) "aut";
              } "r";
            } "identifier";
            participantR.id as id where (root = '2.16.840.1.113883.2.9.4.3.2') then {
              id.extension as ext -> request.url = append('Practitioner?identifier=', ext) "UUID";
            } "2";
            participantR.playingEntity as assi then {
              assi.name -> practitioner.name;
            } "assi";
          } "perf";
          sa.effectiveTime : EIVL as eff -> medicationRq.dosageInstruction = create('Dosage') as dosage then {
            eff -> dosage.timing = create('Timing') as timing then {
              eff -> timing.repeat as rep then {
                eff.event as ev -> rep.where = (ev.code);
              } "rep";
            } "timing";
          } "period";
          sa.effectiveTime : TS as eff ->  medicationRq.dosageInstruction = create('Dosage') as dosage,  dosage.timing = create('Timing') as timing,  timing.event = (eff.value) "tim";
          sa.effectiveTime : PIVL_TS as eff -> medicationAdm.dosage = create('BackboneElement') as dosage then {
            eff -> dosage.rate = create('Ratio') as ratio then {
              eff -> ratio.numerator = create('Quantity') as quan then {
                eff.period as per -> quan.value = (per.value);
                eff.period as per -> quan.unit = (per.unit);
              } "quanti";
              eff -> ratio.denominator = create('Quantity') as quan then {
                eff.period -> quan.value = '1';
                eff.period as per -> quan.unit = (per.unit);
              } "quanti";
            } "ratio";
          } "eff";
        } "Medicationrequest";
      } "sa";
    } "entry";
  } "sa";
}

group ClinicalDocumentSottoSectionOBS(source src : Section, target tgt, target bundle : Bundle, target enc : Encounter, target patient : Patient) {
  src.title as t -> tgt.title = (t.dataString);
  src.code -> tgt.code;
  src.text as cdaText ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('Observation') as observation,  observation.id = uuid() as uuid1,  e1.fullUrl = append('https://example/Observation/', uuid1),  request.url = 'Observation',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %observation.id),  tgt.text as fhirText then {
    cdaText -> fhirText.status = 'generated' "narrativeStatus";
    cdaText as t -> fhirText.div = t "narrativeText";
    src.code -> observation.code;
    src ->  observation.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
    src ->  observation.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %enc.id) "reference";
    src where observation.statusCode.exists().not() then {
      src -> observation.status = 'final' "status";
    } "statuscode";
    cdaText -> observation.note as note then {
      cdaText as t -> note.text = t "reference";
    } "reference";
  } "cdaText";
}

group ClinicalDocumentSottoSectionMS(source src : Section, target tgt, target bundle : Bundle, target patient : Patient, target enc : Encounter) {
  src.title as t -> tgt.title = (t.dataString);
  src.code -> tgt.code;
  src.text as cdaText ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('MedicationStatement') as Medicationstatement,  Medicationstatement.id = uuid() as uuid1,  e1.fullUrl = append('https://example/MedicationStatement/', uuid1),  request.url = 'MedicationStatement',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/MedicationStatement/' + %Medicationstatement.id),  tgt.text as fhirText then {
    cdaText -> Medicationstatement.note as note then {
      cdaText as t -> note.text = t "reference";
      cdaText as t ->  Medicationstatement.medication = create('CodeableConcept') as medication,  medication.text = t "text";
    } "reference";
    src ->  Medicationstatement.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
    src -> Medicationstatement.status = 'unknown' "status";
  } "cdaText";
}

group Observation(source obs : Observation, target patient : Patient, target encounter : Encounter, target ob : Observation, target bundle : Bundle) {
  obs ->  ob.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
  obs ->  ob.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %encounter.id) "reference";
  obs.code -> ob.code;
  obs.statusCode as statusc where (code = 'completed') -> ob.status = 'final';
  obs.statusCode as statusc where (code = 'active') -> ob.status = 'registered';
  obs.statusCode as statusc where (code = 'aborted') -> ob.status = 'cancelled';
  obs.statusCode as statusc where (code = 'suspended') -> ob.status = 'partial';
  obs where obs.statusCode.exists().not() then {
    obs -> ob.status = 'final' "status";
  } "statuscode";
  obs.effectiveTime as effectiveTime -> ob.effective = create('dateTime') as value then TSDateTime(effectiveTime, value) "value2";
  obs where effectiveTime.low.exists() or effectiveTime.high.exists() then {
    obs.effectiveTime as eff -> ob.effective = create('Period') as period then IVLTSPeriod(eff, period) "value3";
  } "where";
  obs.value : INT as int -> ob.value = (int.value);
  obs.value : BL as boolean -> ob.value = (boolean.value) "boolean";
  obs.value : CD as val then {
    val -> ob.value = create('CodeableConcept') as ce then {
      val.originalText -> ce.text;
      val -> ce.coding as coding then {
        val.code as code -> coding.code = cast(code, 'string');
        val.codeSystem as system -> coding.system = translate(system, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri');
        val.displayName as display -> coding.display = cast(display, 'string');
      } "code";
      val.translation as translation -> ce.coding as coding then {
        translation.code as code -> coding.code = cast(code, 'string');
        translation.codeSystem as system -> coding.system = translate(system, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri');
        translation.displayName as display -> coding.display = cast(display, 'string');
        translation.qualifier as qualifier then {
          qualifier.value as value -> ce.coding as coding then {
            value.code as code -> coding.code = cast(code, 'string');
            value.codeSystem as system -> coding.system = translate(system, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri');
            value.displayName as display -> coding.display = cast(display, 'string');
          };
        };
      };
    } "coding";
  } "val";
  obs.value : CE as val then {
    val -> ob.value = create('CodeableConcept') as ce then {
      val.originalText -> ce.text;
      val -> ce.coding as coding then {
        val.code as code -> coding.code = cast(code, 'string');
        val.codeSystem as system -> coding.system = translate(system, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri');
        val.displayName as display -> coding.display = cast(display, 'string');
      } "code";
      val.translation as translation -> ce.coding as coding then {
        translation.code as code -> coding.code = cast(code, 'string');
        translation.codeSystem as system -> coding.system = translate(system, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri');
        translation.displayName as display -> coding.display = cast(display, 'string');
        translation.qualifier as qualifier then {
          qualifier.value as value -> ce.coding as coding then {
            value.code as code -> coding.code = cast(code, 'string');
            value.codeSystem as system -> coding.system = translate(system, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri');
            value.displayName as display -> coding.display = cast(display, 'string');
          };
        };
      };
    } "coding";
  } "val";
  obs.value : PQ as val then {
    val -> ob.value = create('Quantity') as quantity then {
      val.value as value -> quantity.value = value;
      val.unit as unit -> quantity.unit = unit;
    } "quantity";
  } "valueQuantity";
  obs.value : ST as value ->  ob.value = create('string'),  ob.value = (value.dataString);
  obs.interpretationCode -> ob.interpretation;
  obs.methodCode -> ob.method;
  obs.referenceRange as refRange -> ob.referenceRange = create('BackboneElement') as ref then {
    refRange.observationRange as obsRange -> ref.low = create('SimpleQuantity') as Low then {
      obsRange.value : IVL_PQ as v then {
        v.low as l1 then {
          l1.value as decValue -> Low.value = decValue;
          l1.unit as Unit -> Low.unit = Unit;
        } "decValue";
      } "IVLPQ";
    } "obsRange";
  } "refRange";
}

group ObservationConsulenza(source obs : Observation, target patient : Patient, target encounter : Encounter, target ob : Observation, target bundle : Bundle) {
  obs ->  ob.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
  obs ->  ob.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %encounter.id) "reference";
  obs.code -> ob.code;
  obs.statusCode as statusc where (code = 'completed') -> ob.status = 'final';
  obs.statusCode as statusc where (code = 'active') -> ob.status = 'registered';
  obs.statusCode as statusc where (code = 'aborted') -> ob.status = 'cancelled';
  obs.statusCode as statusc where (code = 'suspended') -> ob.status = 'partial';
  obs where obs.statusCode.exists().not() then {
    obs -> ob.status = 'final' "status";
  } "statuscode";
  obs.effectiveTime as effectiveTime -> ob.effective = create('dateTime') as value then TSDateTime(effectiveTime, value) "value2c";
  obs where effectiveTime.low.exists() or effectiveTime.high.exists() then {
    obs.effectiveTime as eff -> ob.effective = create('Period') as period then IVLTSPeriod(eff, period) "value3c";
  } "where";
  obs.value : INT as int -> ob.value = (int.value);
  obs.value : BL as boolean -> ob.value = (boolean.value) "boolean";
  obs.value : CE as val then {
    val -> ob.value = create('CodeableConcept') as ce then {
      val.originalText as originalText then {
        originalText.reference as reference -> ce.text = reference;
      } "originltext";
      val -> ce.coding as coding then {
        val.code as code -> coding.code = cast(code, 'string');
        val.codeSystem as system -> coding.system = translate(system, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri');
        val.displayName as display -> coding.display = cast(display, 'string');
        val.codeSystemVersion as version -> coding.version = cast(version, 'string');
      } "code";
      val.translation as translation -> ce.coding as coding then {
        translation.code as code -> coding.code = cast(code, 'string');
        translation.codeSystem as system -> coding.system = translate(system, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri');
        translation.displayName as display -> coding.display = cast(display, 'string');
        translation.codeSystemVersion as version -> coding.version = cast(version, 'string');
        translation.qualifier as qualifier then {
          qualifier.value as value -> ce.coding as coding then {
            value.code as code -> coding.code = cast(code, 'string');
            value.codeSystem as system -> coding.system = translate(system, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri');
            value.displayName as display -> coding.display = cast(display, 'string');
            value.codeSystemVersion as version -> coding.version = cast(version, 'string');
          };
        };
      };
    } "coding";
  } "val";
  obs.value : CD as val then {
    val -> ob.value = create('CodeableConcept') as ce then {
      val.originalText -> ce.text;
      val -> ce.coding as coding then {
        val.code as code -> coding.code = cast(code, 'string');
        val.codeSystem as system -> coding.system = translate(system, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri');
        val.displayName as display -> coding.display = cast(display, 'string');
      } "code";
      val.translation as translation -> ce.coding as coding then {
        translation.code as code -> coding.code = cast(code, 'string');
        translation.codeSystem as system -> coding.system = translate(system, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri');
        translation.displayName as display -> coding.display = cast(display, 'string');
        translation.qualifier as qualifier then {
          qualifier.value as value -> ce.coding as coding then {
            value.code as code -> coding.code = cast(code, 'string');
            value.codeSystem as system -> coding.system = translate(system, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri');
            value.displayName as display -> coding.display = cast(display, 'string');
          };
        };
      };
    } "coding";
  } "val";
  obs.value : PQ as val then {
    val -> ob.value = create('Quantity') as quantity then {
      val.value as value -> quantity.value = value;
      val.unit as unit -> quantity.unit = unit;
    } "quantity";
  } "valueQuantity";
  obs.value : ST as value ->  ob.value = create('string'),  ob.value = (value.dataString);
  obs ->  ob.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
  obs ->  ob.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %encounter.id) "reference";
  obs.interpretationCode -> ob.interpretation;
  obs.methodCode -> ob.method;
  obs.referenceRange as refRange -> ob.referenceRange = create('BackboneElement') as ref then {
    refRange.observationRange as obsRange -> ref.low = create('SimpleQuantity') as Low then {
      obsRange.value : IVL_PQ as v then {
        v.low as l1 then {
          l1.value as decValue -> Low.value = decValue;
          l1.unit as Unit -> Low.unit = Unit;
        } "decValue";
      } "IVLPQ";
    } "obsRange";
  } "refRange";
  obs.performer as performer ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'PUT',  e1.resource = create('Practitioner') as practitioner,  practitioner.id = uuid() as uuid1 then {
    performer.assignedEntity as assEntity then {
      assEntity -> practitioner.meta as meta then {
        assEntity -> meta.tag = create('Coding') as coding then {
          assEntity -> coding.system = 'http://algoritmodiscoring' "system";
          assEntity -> coding.code = 'ClinicalDocument/body/Consulenza/performer' "code";
        } "coding";
      } "meta";
      assEntity.id as id -> practitioner.identifier as identifier then {
        id.root as r -> identifier.system = translate(r, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri') "root1";
        id.extension as ext -> identifier.value = ext;
        id.assigningAuthorityName as s ->  identifier.assigner as a,  a.display = s;
        id.root as r then {
          id.extension as ext ->  practitioner.id = (r + '-' + ext) as uuid2,  e1.fullUrl = append('https://example/Practitioner/', uuid2),  ob.performer = create('Reference') as reference,  reference.reference = ('https://example/Practitioner/' + %practitioner.id) "aut";
        } "r";
      } "identifier";
      assEntity.id as id where (root = '2.16.840.1.113883.2.9.4.3.2') then {
        id.extension as ext -> request.url = append('Practitioner?identifier=', ext) "UUID";
      } "2";
      assEntity.assignedPerson as assi then {
        assi.name -> practitioner.name;
      } "assi";
    } "assEntity";
  } "perf";
  obs.participant as participant ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('ServiceRequest') as serviceRequest,  serviceRequest.id = uuid() as uuid1,  e1.fullUrl = append('https://example/ServiceRequest/', uuid1),  request.url = 'ServiceRequest',  ob.basedOn = create('Reference') as reference,  reference.reference = ('https://example/ServiceRequest/' + %serviceRequest.id) then {
    participant.time as t -> serviceRequest.authoredOn = (t.value);
    obs ->  serviceRequest.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
    obs ->  serviceRequest.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %encounter.id) "reference";
    obs -> serviceRequest.status = 'active' "status";
    obs -> serviceRequest.intent = 'order' "intent";
    participant.participantRole as participantRole ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'PUT',  e1.resource = create('Practitioner') as practitioner then {
      participantRole -> practitioner.meta as meta then {
        participantRole -> meta.tag = create('Coding') as coding then {
          participantRole -> coding.system = 'http://algoritmodiscoring' "system";
          participantRole -> coding.code = 'ClinicalDocument/body/Consulenza/participant' "code";
        } "coding";
      } "meta";
      participantRole.id as id -> practitioner.identifier as identifier then {
        id.root as r -> identifier.system = translate(r, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri') "root1";
        id.extension as ext -> identifier.value = ext;
        id.assigningAuthorityName as s ->  identifier.assigner as a,  a.display = s;
        id.root as r then {
          id.extension as ext ->  practitioner.id = (r + '-' + ext) as uuid3,  e1.fullUrl = append('https://example/Practitioner/', uuid3),  serviceRequest.performer = create('Reference') as reference,  reference.reference = ('https://example/Practitioner/' + %practitioner.id) "aut";
        } "r";
      } "identifier";
      participantRole.id as id where (root = '2.16.840.1.113883.2.9.4.3.2') then {
        id.extension as ext -> request.url = append('Practitioner?identifier=', ext) "UUID";
      } "2";
      participantRole.playingEntity as pe then {
        pe.name -> practitioner.name;
      } "pe";
    };
  };
}

group ObservationEsamiDuranteRicovero(source obs : Observation, target patient : Patient, target encounter : Encounter, target ob : Observation, target bundle : Bundle) {
  obs ->  ob.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
  obs ->  ob.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %encounter.id) "reference";
  obs.code -> ob.code;
  obs.statusCode as statusc where (code = 'completed') -> ob.status = 'final';
  obs.statusCode as statusc where (code = 'active') -> ob.status = 'registered';
  obs.statusCode as statusc where (code = 'aborted') -> ob.status = 'cancelled';
  obs.statusCode as statusc where (code = 'suspended') -> ob.status = 'partial';
  obs where obs.statusCode.exists().not() then {
    obs -> ob.status = 'final' "status";
  } "statuscode";
  obs.effectiveTime as effectiveTime -> ob.effective = create('dateTime') as value then TSDateTime(effectiveTime, value) "value2r";
  obs where effectiveTime.low.exists() or effectiveTime.high.exists() then {
    obs.effectiveTime as eff -> ob.effective = create('Period') as period then IVLTSPeriod(eff, period) "value3r";
  } "where";
  obs.value : INT as int -> ob.value = (int.value);
  obs.value : BL as boolean -> ob.value = (boolean.value) "boolean";
  obs.value : CE as val then {
    val -> ob.value = create('CodeableConcept') as ce then {
      val.originalText as originalText then {
        originalText.reference as reference -> ce.text = reference;
      } "originltext";
      val -> ce.coding as coding then {
        val.code as code -> coding.code = cast(code, 'string');
        val.codeSystem as system -> coding.system = translate(system, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri');
        val.displayName as display -> coding.display = cast(display, 'string');
        val.codeSystemVersion as version -> coding.version = cast(version, 'string');
      } "code";
      val.translation as translation -> ce.coding as coding then {
        translation.code as code -> coding.code = cast(code, 'string');
        translation.codeSystem as system -> coding.system = translate(system, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri');
        translation.displayName as display -> coding.display = cast(display, 'string');
        translation.codeSystemVersion as version -> coding.version = cast(version, 'string');
        translation.qualifier as qualifier then {
          qualifier.value as value -> ce.coding as coding then {
            value.code as code -> coding.code = cast(code, 'string');
            value.codeSystem as system -> coding.system = translate(system, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri');
            value.displayName as display -> coding.display = cast(display, 'string');
            value.codeSystemVersion as version -> coding.version = cast(version, 'string');
          };
        };
      };
    } "coding";
  } "val";
  obs.value : CD as val then {
    val -> ob.value = create('CodeableConcept') as ce then {
      val.originalText -> ce.text;
      val -> ce.coding as coding then {
        val.code as code -> coding.code = cast(code, 'string');
        val.codeSystem as system -> coding.system = translate(system, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri');
        val.displayName as display -> coding.display = cast(display, 'string');
      } "code";
      val.translation as translation -> ce.coding as coding then {
        translation.code as code -> coding.code = cast(code, 'string');
        translation.codeSystem as system -> coding.system = translate(system, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri');
        translation.displayName as display -> coding.display = cast(display, 'string');
        translation.qualifier as qualifier then {
          qualifier.value as value -> ce.coding as coding then {
            value.code as code -> coding.code = cast(code, 'string');
            value.codeSystem as system -> coding.system = translate(system, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri');
            value.displayName as display -> coding.display = cast(display, 'string');
          };
        };
      };
    } "coding";
  } "val";
  obs.value : PQ as val then {
    val -> ob.value = create('Quantity') as quantity then {
      val.value as value -> quantity.value = value;
      val.unit as unit -> quantity.unit = unit;
    } "quantity";
  } "valueQuantity";
  obs.value : ST as value ->  ob.value = create('string'),  ob.value = (value.dataString);
  obs ->  ob.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
  obs ->  ob.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %encounter.id) "reference";
  obs.interpretationCode -> ob.interpretation;
  obs.methodCode -> ob.method;
  obs.effectiveTime as eff -> ob.effective = create('Period') as per then IVLTSPeriod(eff, per);
  obs.referenceRange as refRange -> ob.referenceRange = create('BackboneElement') as ref then {
    refRange.observationRange as obsRange -> ref.low = create('SimpleQuantity') as Low then {
      obsRange.value : IVL_PQ as v then {
        v.low as l1 then {
          l1.value as decValue -> Low.value = decValue;
          l1.unit as Unit -> Low.unit = Unit;
        } "decValue";
      } "IVLPQ";
    } "obsRange";
  } "refRange";
  obs.performer as performer ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'PUT',  e1.resource = create('Practitioner') as practitioner,  practitioner.id = uuid() as uuid1 then {
    performer.assignedEntity as assEntity then {
      assEntity -> practitioner.meta as meta then {
        assEntity -> meta.tag = create('Coding') as coding then {
          assEntity -> coding.system = 'http://algoritmodiscoring' "system";
          assEntity -> coding.code = 'ClinicalDocument/body/EsamiDuranteRicovero/performer' "code";
        } "coding";
      } "meta";
      assEntity.id as id -> practitioner.identifier as identifier then {
        id.root as r -> identifier.system = translate(r, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri') "root1";
        id.extension as ext -> identifier.value = ext;
        id.assigningAuthorityName as s ->  identifier.assigner as a,  a.display = s;
        id.root as r then {
          id.extension as ext ->  practitioner.id = (r + '-' + ext) as uuid2,  e1.fullUrl = append('https://example/Practitioner/', uuid2),  ob.performer = create('Reference') as reference,  reference.reference = ('https://example/Practitioner/' + %practitioner.id) "aut";
        } "r";
      } "identifier";
      assEntity.id as id where (root = '2.16.840.1.113883.2.9.4.3.2') then {
        id.extension as ext -> request.url = append('Practitioner?identifier=', ext) "UUID";
      } "2";
      assEntity.assignedPerson as assi then {
        assi.name -> practitioner.name;
      } "assi";
    } "assEntity";
  } "perf";
  obs.participant as participant ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('ServiceRequest') as serviceRequest,  serviceRequest.id = uuid() as uuid1,  e1.fullUrl = append('https://example/ServiceRequest/', uuid1),  request.url = 'ServiceRequest',  ob.basedOn = create('Reference') as reference,  reference.reference = ('https://example/ServiceRequest/' + %serviceRequest.id) then {
    participant.time as t -> serviceRequest.authoredOn = (t.value);
    obs ->  serviceRequest.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
    obs ->  serviceRequest.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %encounter.id) "reference";
    obs -> serviceRequest.status = 'active' "status";
    obs -> serviceRequest.intent = 'order' "intent";
    participant.participantRole as participantRole ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'PUT',  e1.resource = create('Practitioner') as practitioner then {
      participantRole -> practitioner.meta as meta then {
        participantRole -> meta.tag = create('Coding') as coding then {
          participantRole -> coding.system = 'http://algoritmodiscoring' "system";
          participantRole -> coding.code = 'ClinicalDocument/body/EsamiDuranteRicovero/participant' "code";
        } "coding";
      } "meta";
      participantRole.id as id -> practitioner.identifier as identifier then {
        id.root as r -> identifier.system = translate(r, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri') "root1";
        id.extension as ext -> identifier.value = ext;
        id.assigningAuthorityName as s ->  identifier.assigner as a,  a.display = s;
        id.root as r then {
          id.extension as ext ->  practitioner.id = (r + '-' + ext) as uuid3,  e1.fullUrl = append('https://example/Practitioner/', uuid3),  serviceRequest.performer = create('Reference') as reference,  reference.reference = ('https://example/Practitioner/' + %practitioner.id) "aut";
        } "r";
      } "identifier";
      participantRole.id as id where (root = '2.16.840.1.113883.2.9.4.3.2') then {
        id.extension as ext -> request.url = append('Practitioner?identifier=', ext) "UUID";
      } "2";
      participantRole.playingEntity as pe then {
        pe.name -> practitioner.name;
      } "pe";
    };
  };
}

group periodTiming(source effectiveTime : PIVL_TS, target timing : Timing) {
  effectiveTime -> timing.repeat as r then {
    effectiveTime.period as p -> r.period = (p.value);
    effectiveTime.period as p -> r.periodUnit = (p.unit);
  } "repeat";
}

// ---------------------------------------------------------------------------------------
group Act(source cda : Act, target pat : Patient, target ac : DiagnosticReport, target enc : Encounter, target bundle : Bundle) {
  cda.code -> ac.code;
  cda.statusCode as statusc where (code = 'completed') -> ob.status = 'final';
  cda.statusCode as statusc where (code = 'active') -> ob.status = 'registered';
  cda.statusCode as statusc where (code = 'aborted') -> ob.status = 'cancelled';
  cda.statusCode as statusc where (code = 'suspended') -> ob.status = 'partial';
  cda.effectiveTime as effectiveTime -> ac.effective = create('dateTime') as value then TSDateTime(effectiveTime, value) "value2a";
  obs where effectiveTime.low.exists() or effectiveTime.high.exists() then {
    cda.effectiveTime as eff -> ac.effective = create('Period') as period then IVLTSPeriod(eff, period) "value3a";
  } "where";
  cda ->  ac.subject = create('Reference') as reference,  reference.reference = ('https://example/' + %pat.id) "reference";
  cda ->  ac.encounter = create('Reference') as reference,  reference.reference = ('https://example/' + %enc.id) "reference";
  cda.participant as part -> enc.participant as participant then {
    part -> participant.type as type then {
      part -> type.coding as coding then {
        part -> coding.code = (part.typeCode) "codice";
        part -> coding.system = 'http://terminology.hl7.org/CodeSystem/v3-ParticipationType' "system";
      } "codeType";
    } "type";
    part.participantRole as participantRole -> participant.individual = create('Reference') as reference then {
      participantRole ->  bundle.entry as e,  e.request = create('BackboneElement') as request,  request.method = 'PUT',  e.resource = create('Practitioner') as practitioner,  practitioner.id = uuid() as uuid1,  e.fullUrl = append('https://example/Practitioner/', uuid1),  reference.reference = ('https://example/Practitioner/' + %practitioner.id) then {
        participantRole -> practitioner.meta as meta then {
          participantRole -> meta.tag = create('Coding') as coding then {
            participantRole -> coding.system = 'http://algoritmodiscoring' "system";
            participantRole -> coding.code = 'ClinicalDocument/body/Act/participant' "code";
          } "coding";
        } "meta";
        participantRole.id as id -> practitioner.identifier as identifier then {
          id.root as r -> identifier.system = translate(r, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri') "root1";
          id.extension as ext -> identifier.value = ext then {
            participantRole -> request.url = append('Practitioner?identifier=', ext) "UUID";
          } "ext";
          id.assigningAuthorityName as s ->  identifier.assigner as a,  a.display = s;
        } "identifier";
        participantRole.playingEntity as playingEntity then {
          playingEntity.name -> practitioner.name;
        };
      } "participanRoleBund";
    };
  };
  cda.entryRelationship as entryRelationship then {
    entryRelationship.observation as observation ->  bundle.entry as e,  e.request = create('BackboneElement') as request,  request.method = 'POST',  e.resource = create('Observation') as obs,  obs.id = uuid() as uuid2,  e.fullUrl = append('https://example/Observation/', uuid2),  request.url = append('Observation/', uuid2),  ac.result = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %obs.id) then Observation(observation, pat, enc, obs, bundle) "OBS";
  };
}

group ClinicalDocumentSectionTerapiaDimissione(source cda : ClinicalDocument, source src : Section, target patient : Patient, target tgt, target bundle : Bundle, target enc : Encounter) {
  src.title as t -> tgt.title = (t.dataString);
  src.code -> tgt.code;
  src where src.entry.exists() then {
    src.text as cdaText -> tgt.text as fhirText then {
      cdaText -> fhirText.status = 'generated' "narrativeStatus";
      cdaText as t -> fhirText.div = t "narrativeText";
    } "cdaText";
  } "exist";
  src where src.entry.exists().not() then {
    src.text as cdaText ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('MedicationRequest') as medicationRq,  medicationRq.id = uuid() as uuid1,  e1.fullUrl = append('https://example/MedicationRequest/', uuid1),  request.url = 'MedicationRequest',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/MedicationRequest/' + %medicationRq.id) then {
      src ->  medicationRq.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
      src ->  medicationRq.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %enc.id) "reference";
      src -> medicationRq.status = 'active' "status";
      src -> medicationRq.intent = 'order' "intent";
      cdaText -> medicationRq.medication = create('CodeableConcept') as codecon then {
        cdaText -> codecon.text = 'string' "text";
      } "code";
      cdaText -> medicationRq.note as note then {
        cdaText as t -> note.text = t "reference";
      } "reference";
    } "cdaText";
  } "where";
  src.entry as entry1 ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('MedicationRequest') as medicationRq,  medicationRq.id = uuid() as uuid1,  e1.fullUrl = append('https://example/MedicationRequest/', uuid1),  request.url = 'MedicationRequest',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/MedicationRequest/' + %medicationRq.id) then {
    src ->  medicationRq.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
    src ->  medicationRq.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %enc.id) "reference";
    src -> medicationRq.status = 'active' "status";
    src -> medicationRq.intent = 'order' "intent";
    entry1.substanceAdministration as substract then {
      substract.consumable as cons then {
        cons.manufacturedProduct as man1 ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('Medication') as medication,  medication.id = uuid() as uuid1,  e1.fullUrl = append('https://example/Medication/', uuid1),  request.url = 'Medication',  medicationRq.medication = create('Reference') as medref,  medref.reference = ('https://example/Medication/' + %medication.id) then {
          man1.manufacturedMaterial as mm then {
            mm.code -> medication.code;
          } "mm";
          substract.administrationUnitCode -> medication.form;
          substract.entryRelationship as entryR then {
            entryR.observation as observation then {
              observation.code where displayName = 'Grammatura' -> medication.ingredient as ingredient then {
                substract.consumable as consumable then {
                  consumable.manufacturedProduct as manufacturedProduct then {
                    manufacturedProduct.manufacturedMaterial as manufacturedMaterial then {
                      manufacturedMaterial.code as code -> ingredient.item = create('CodeableConcept') as value then CECodeableConcept(code, value) "CE";
                    } "material";
                  } "product";
                };
                observation.value as value -> ingredient.strength as strength then {
                  value -> strength.numerator as numerator then {
                    value -> numerator.value = (value.value) "valueN";
                  } "numerator";
                  value -> strength.denominator as denominator then {
                    value -> denominator.value = 1 "valueD";
                  } "denominator";
                } "strenght";
              } "ingredient";
              observation.code where displayName = 'Quantità nella Confezione' then {
                observation.value as value -> medication.amount as amount then {
                  value -> amount.numerator as numerator then {
                    value -> numerator.value = (value.value) "valueN";
                  } "numerator";
                  value -> amount.denominator as denominator then {
                    value -> denominator.value = 1 "valueD";
                  } "denominator";
                } "amount";
              } "quantita";
            } "obs";
          } "entryR";
          substract.entryRelationship as entryRelationship then {
            entryRelationship.supply as sup -> medicationRq.dispenseRequest as dispreq then {
              sup -> dispreq.quantity = create('SimpleQuantity') as quantity then {
                sup.quantity as q -> quantity.value = (q.value);
              } "quantity";
            } "sub";
          } "entry";
        } "man1";
      } "cons";
      substract.text as tx -> medicationRq.note as note then {
        tx.reference as ref -> note.text = (ref.value);
      } "tx";
      substract.statusCode as st -> medicationRq.status = (st.code);
      substract.effectiveTime : IVL_TS as eff -> medicationRq.dosageInstruction = create('Dosage') as dosage then {
        eff -> dosage.timing = create('Timing') as timing then {
          eff -> timing.repeat as rep then {
            eff -> rep.bounds = create('Period') as period then IVLTSPeriod(eff, period) "period";
          } "rep";
        } "timing";
      } "period";
      substract.effectiveTime : EIVL_TS as eff -> medicationRq.dosageInstruction = create('Dosage') as dosage then {
        eff -> dosage.timing = create('Timing') as timing then {
          eff -> timing.repeat as rep then {
            eff.event as ev -> rep.when = (ev.code);
          } "rep";
        } "timing";
      } "period";
      substract.effectiveTime : IVL_TS as eff ->  medicationRq.dosageInstruction = create('Dosage') as dosage,  dosage.timing = create('Timing') as timing,  timing.event = (eff.value) "tim";
      substract.effectiveTime : PIVL_TS as eff -> medicationRq.dosageInstruction = create('Dosage') as dosage then {
        eff -> dosage.timing = create('Timing') as timing then periodTiming(eff, timing) "cod";
      } "eff";
      substract -> medicationRq.dosageInstruction = create('Dosage') as dosage then {
        substract.routeCode -> dosage.route;
      } "dosage";
      substract -> medicationRq.dosageInstruction = create('Dosage') as dosage then {
        substract.approachSiteCode -> dosage.site;
      } "dosage";
      substract.doseQuantity as doseQuant -> medicationRq.dosageInstruction = create('Dosage') as dosageInstruction then {
        doseQuant.originalText as ot then {
          ot.reference -> dosageInstruction.text;
        } "ot";
        doseQuant -> dosageInstruction.doseAndRate as dosageRate then {
          doseQuant -> dosageRate.dose = create('Range') as d then {
            doseQuant -> d.low = create('SimpleQuantity') as l then {
              doseQuant.low as lo -> l.value = (lo.value);
              doseQuant.low as lo -> l.unit = (lo.unit);
            } "low";
            doseQuant -> d.high = create('SimpleQuantity') as h then {
              doseQuant.high as hi -> h.value = (hi.value);
              doseQuant.high as hi -> h.unit = (hi.unit);
            } "low";
          } "d";
        } "dosageRate";
      } "Dosage";
      substract.rateQuantity as rateQuantity -> medicationRq.dosageInstruction = create('Dosage') as dosageInstruction1 then {
        rateQuantity.originalText as ot then {
          ot.reference -> dosageInstruction1.text;
        } "ot";
        rateQuantity -> dosageInstruction1.doseAndRate as dosageRate then {
          rateQuantity -> dosageRate.rate = create('Range') as d then {
            rateQuantity -> d.low = create('SimpleQuantity') as l then {
              rateQuantity.low as lo -> l.value = (lo.value);
              rateQuantity.low as lo -> l.unit = (lo.unit);
            } "low";
            rateQuantity -> d.high = create('SimpleQuantity') as h then {
              rateQuantity.high as hi -> h.value = (hi.value);
              rateQuantity.high as hi -> h.unit = (hi.unit);
            } "low";
          } "d";
        } "dosageRate";
      } "rateq";
      substract.participant as part ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'PUT',  e1.resource = create('Practitioner') as practitioner then {
        part.time as time -> medicationRq.authoredOn = (time.value);
        part.participantRole as partRole then {
          partRole -> practitioner.meta as meta then {
            partRole -> meta.tag = create('Coding') as coding then {
              partRole -> coding.system = 'http://algoritmodiscoring' "system";
              partRole -> coding.code = 'ClinicalDocument/body/TerapiaFarmacologicaRicovero/participant' "code";
            } "coding";
          } "meta";
          partRole.id as id -> practitioner.identifier as identifier then {
            id.root as r -> identifier.system = translate(r, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri') "root1";
            id.extension as ext -> identifier.value = ext;
            id.assigningAuthorityName as s ->  identifier.assigner as a,  a.display = s;
            id.root as r then {
              id.extension as ext ->  practitioner.id = (r + '-' + ext) as uuid2,  e1.fullUrl = append('https://example/Practitioner/', uuid2),  request.url = append('Practitioner/', uuid1),  medicationRq.performer = create('Reference') as reference,  reference.reference = ('https://example/Practitioner/' + %practitioner.id) "aut";
            } "r";
          } "identifier";
          partRole.id as id where (root = '2.16.840.1.113883.2.9.4.3.2') then {
            id.extension as ext -> request.url = append('Practitioner?identifier=', ext) "UUID";
          } "2";
          partRole.playingEntity as assi then {
            assi.name -> practitioner.name;
          } "assi";
        } "perf";
      } "partRole";
    } "participant";
  } "substract";
}