CDA to FHIR Maps
0.1.0 - ci-build IT

CDA to FHIR Maps - Local Development build (v0.1.0) built by the FHIR (HL7® FHIR® Standard) Build Tools. See the Directory of published versions

StructureMap: CDA to FHIR - PSS

Official URL: http://hl7.it/fhir/cda2fhir/StructureMap/cda2fhirPs Version: 0.1.0
Draft as of 2024-04-11 Computable Name: cda2fhirPs
map "http://hl7.it/fhir/cda2fhir/StructureMap/cda2fhirPs" = "cda2fhirPs"

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/List" alias List 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 e4,  e4.request = create('BackboneElement') as request,  request.method = 'POST',  e4.resource = create('DocumentReference') as DocumentReference,  DocumentReference.id = uuid() as uuid4,  e4.fullUrl = append('https://example/DocumentReference/', uuid4),  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 ext1 -> identifier.value = ext1 "value";
          id.assigningAuthorityName as s ->  identifier.assigner as a,  a.display = s;
        } "idfr";
        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 -> encounter.status = 'finished' "finished";
  cda -> encounter.class = create('Coding') as coding then {
    cda -> coding.code = 'summary' "code";
  } "coding";
  cda -> bundle.id = uuid() "id";
  cda.id -> bundle.identifier "identifier";
  cda -> bundle.type = 'transaction' "type";
  // cda.effectiveTime -> bundle.timestamp;
  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 {
        component.section as srcSection then {
          srcSection.code -> composition.section as tgtSection then ClinicalDocumentSection(cda, srcSection, patient, tgtSection, bundle, encounter, composition);
        };
      };
    } "body";
  } "diagnostic";
}

group ClinicalDocumentSection(source cda : ClinicalDocument, source src : Section, target patient : Patient, target tgt, target bundle : Bundle, target enc : Encounter, target composition : Composition) {
  src.title as t -> tgt.title = (t.dataString);
  src.code -> tgt.code;
  src.entry as entry then {
    src.text as cdaText -> tgt.text as fhirText then {
      cdaText -> fhirText.status = 'generated' "narrativeStatus";
      cdaText as t -> fhirText.div = t "narrativeText";
    } "cdaText";
    // sezioni che sono strutturate
    src.code where (code = '30954-2') then {
      entry.organizer as organizer ->  bundle.entry as e0,  e0.request = create('BackboneElement') as request,  request.method = 'POST',  e0.resource = create('DiagnosticReport') as dia,  dia.id = uuid() as uuid0,  e0.fullUrl = append('https://example/DiagnosticReport/', uuid0),  request.url = 'DiagnosticReport',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/DiagnosticReport/' + %dia.id) then DiagnosticReportFunction(organizer, patient, enc, dia, bundle) "diagnostic";
    } "entryObs";
    src.code where (code = '29762-2') or (code = '10162-6') then {
      entry.observation as observation ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('Observation') as obs1,  obs1.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/' + %obs1.id) then Observation(observation, patient, enc, obs1, bundle) "obs1";
    } "entryObs";
    src.code where (code = '8716-3') or (code = '47420-5') then {
      entry.organizer as organizer ->  bundle.entry as e2,  e2.request = create('BackboneElement') as request,  request.method = 'POST',  e2.resource = create('Observation') as obs2,  obs2.id = uuid() as uuid2,  e2.fullUrl = append('https://example/Observation/', uuid2),  request.url = 'Observation',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %obs2.id) then ObservationOrganizer(src, organizer, patient, enc, obs2, bundle) "obs2";
      entry.observation as organizer ->  bundle.entry as e2,  e2.request = create('BackboneElement') as request,  request.method = 'POST',  e2.resource = create('Observation') as obs2,  obs2.id = uuid() as uuid2,  e2.fullUrl = append('https://example/Observation/', uuid2),  request.url = 'Observation',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %obs2.id) then ObservationOrganizer(src, organizer, patient, enc, obs2, bundle) "obs2";
    } "organizer";
    src.code where code = '11450-4' then {
      entry.act as act ->  bundle.entry as e3,  e3.request = create('BackboneElement') as request,  request.method = 'POST',  e3.resource = create('Condition') as condition,  condition.id = uuid() as uuid3,  e3.fullUrl = append('https://example/Condition/', uuid3),  request.url = 'Condition',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Condition/' + %condition.id) then ConditionFunction(act, condition, patient, enc, bundle) "condition";
    } "listaDeiProblemi";
    src.code where (code = '48765-2') then {
      entry.act as act ->  bundle.entry as e5,  e5.request = create('BackboneElement') as request,  request.method = 'POST',  e5.resource = create('AllergyIntolerance') as allergy,  allergy.id = uuid() as uuid5,  e5.fullUrl = append('https://example/AllergyIntolerance/', uuid5),  request.url = 'AllergyIntolerance',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/AllergyIntolerance/' + %allergy.id) then allergyFunction(act, allergy, patient, enc) "allergy";
    } "entryAct";
    src.code where code = '10160-0' then {
      entry.substanceAdministration as subAdmin ->  bundle.entry as e6,  e6.request = create('BackboneElement') as request,  request.method = 'POST',  e6.resource = create('MedicationStatement') as medicationstatement,  medicationstatement.id = uuid() as uuid6,  e6.fullUrl = append('https://example/MedicationStatement/', uuid6),  request.url = 'MedicationStatement',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/MedicationStatement/' + %medicationstatement.id) then MedicationStatement(subAdmin, medicationstatement, patient, enc, bundle) "TerapiaFarmacologica";
    } "terapia";
    src.code where code = '11369-6' then {
      entry.substanceAdministration as subVACC ->  bundle.entry as e7,  e7.request = create('BackboneElement') as request,  request.method = 'POST',  e7.resource = create('Immunization') as immunization,  immunization.id = uuid() as uuid7,  e7.fullUrl = append('https://example/Immunization/', uuid7),  request.url = 'Immunization',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Immunization/' + %immunization.id) then Immunization(subVACC, patient, enc, immunization, bundle) "immunization";
    } "vacc";
    src.code where code = '10157-6' then {
      entry.organizer as organizer ->  bundle.entry as e12,  e12.request = create('BackboneElement') as request,  request.method = 'POST',  e12.resource = create('FamilyMemberHistory') as familyMember,  familyMember.id = uuid() as uuid12,  e12.fullUrl = append('https://example/FamilyMemberHistory/', uuid12),  request.url = 'FamilyMemberHistory',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/FamilyMemberHistory/' + %familyMember.id) then FamilyMemberFunction(organizer, familyMember, patient) "family";
    } "family";
    src.code where code = '46264-8' then {
      entry.supply as supply ->  bundle.entry as e8,  e8.request = create('BackboneElement') as request,  request.method = 'POST',  e8.resource = create('Procedure') as procedure,  procedure.id = uuid() as uuid8,  e8.fullUrl = append('https://example/Procedure/', uuid8),  request.url = 'Procedure',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Procedure/' + %procedure.id) then Procedure(supply, patient, enc, procedure, bundle) "protesi";
    } "impianti";
    src.code where code = '47519-4' then {
      entry.procedure as procedure ->  bundle.entry as e9,  e9.request = create('BackboneElement') as request,  request.method = 'POST',  e9.resource = create('Procedure') as procedure2,  procedure2.id = uuid() as uuid9,  e9.fullUrl = append('https://example/Procedure/', uuid9),  request.url = 'Procedure',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Procedure/' + %procedure2.id) then Procedure(procedure, patient, enc, procedure2, bundle) "tratt";
    } "trattamentiProcedure";
    src.code where code = '46240-8' then {
      // entry.encounter as encounter -> enc then{
      entry.encounter as encounter ->  bundle.entry as e9,  e9.request = create('BackboneElement') as request,  request.method = 'POST',  e9.resource = create('Encounter') as encounterF,  encounterF.id = uuid() as uuid9,  e9.fullUrl = append('https://example/Encounter/', uuid9),  request.url = 'Encounter',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %encounterF.id) then EncounterFunction(encounter, patient, enc, encounterF, bundle);
    } "visiteRicoveri";
    src.code where code = '57827-8' then {
      entry.act as act ->  bundle.entry as e13,  e13.request = create('BackboneElement') as request,  request.method = 'POST',  e13.resource = create('Coverage') as coverage,  coverage.id = uuid() as uuid13,  e13.fullUrl = append('https://example/Coverage/', uuid13),  request.url = 'Coverage',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Coverage/' + %coverage.id) then Coverage(act, patient, enc, coverage, bundle) "esen";
    } "esenzioni";
    src.code where code = 'PSSIT99' then {
      entry.act as act ->  bundle.entry as e14,  e14.request = create('BackboneElement') as request,  request.method = 'POST',  e14.resource = create('OrganizationAffiliation') as affiliation,  affiliation.id = uuid() as uuid14,  e14.fullUrl = append('https://example/OrganizationAffiliation/', uuid14),  request.url = 'OrganizationAffiliation',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/OrganizationAffiliation/' + %affiliation.id) then OrganizationAffiliation(act, patient, enc, affiliation, bundle) "OrgAffiliation";
    } "retiPatologia";
  };
  src where src.entry.exists() then {
    src.code where code = '18776-5' then {
      src ->  bundle.entry as e11,  e11.request = create('BackboneElement') as request,  request.method = 'POST',  e11.resource = create('CarePlan') as careplan,  careplan.id = uuid() as uuid11,  e11.fullUrl = append('https://example/CarePlan/', uuid11),  request.url = 'CarePlan',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/CarePlan/' + %careplan.id) then {
        src.entry as entry then CarePlanFunction(entry, careplan, patient, enc, bundle) "prestazioni";
      } "pianiCura";
    } "raccoglitore";
  } "esiste";
  src where src.entry.exists().not() then {
    // Anmanesi Familiare narrativa
    src.code where code = '10157-6' then {
      src.text as text ->  bundle.entry as e12,  e12.request = create('BackboneElement') as request,  request.method = 'POST',  e12.resource = create('FamilyMemberHistory') as familyMember,  familyMember.id = uuid() as uuid12,  e12.fullUrl = append('https://example/FamilyMemberHistory/', uuid12),  request.url = 'FamilyMemberHistory',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/FamilyMemberHistory/' + %familyMember.id) then {
        src ->  familyMember.patient = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
        src -> familyMember.status = 'health-unknown' "statusS";
        text -> familyMember.note as note then {
          text as t -> note.text = t "reference";
        } "reference";
        text -> familyMember.relationship = create('CodeableConcept') as relation then {
          text as txt -> relation.text = txt "text";
        } "medication";
      } "family";
    } "familyraccoglitore";
    // Piano di cura narrativa
    src.code where code = '18776-5' then {
      src.text as text ->  bundle.entry as e11,  e11.request = create('BackboneElement') as request,  request.method = 'POST',  e11.resource = create('CarePlan') as careplan,  careplan.id = uuid() as uuid11,  e11.fullUrl = append('https://example/CarePlan/', uuid11),  request.url = 'CarePlan',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/CarePlan/' + %careplan.id) then {
        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";
        text -> careplan.note as note then {
          text as t -> note.text = t "reference";
        } "reference";
      } "pianiCura";
    } "raccoglitore";
    // sezioni che sono narrative
    src.code where (code = '30954-2') or (code = '29762-2') or (code = '8716-3') or (code = '47420-5') or (code = '42348-3') then {
      src.text as text ->  bundle.entry as e13,  e13.request = create('BackboneElement') as request,  request.method = 'POST',  e13.resource = create('Observation') as obs1,  obs1.id = uuid() as uuid13,  e13.fullUrl = append('https://example/Observation/', uuid13),  request.url = 'Observation',  tgt.entry = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %obs1.id) then {
        src ->  obs1.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
        // src -> obs1.encounter=create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %enc.id) "reference";
        src -> obs1.status = 'preliminary' "obsst";
        src.code -> obs1.code "obscde";
        src -> obs1.status = 'final' "statusS";
        text -> obs1.note as note then {
          text as t -> note.text = create('string') as textNote then EDstring(t, textNote) "note";
        } "narrative";
      } "txtsec";
    } "narrative";
  } "code";
  src.component as component then {
    component.section as sec -> tgt.section as tgtSection then ClinicalDocumentSection(cda, sec, patient, tgtSection, bundle, enc, dReport);
  };
}

group Procedure(source src : cdaElement, target patient : Patient, target encounter : Encounter, target tgt : Procedure, target bundle : Bundle) {
  // toASK
  src.text as tx -> tgt.note as note then {
    tx.reference as reff -> note.text = (reff.value) "r";
  } "tx";
  src.templateId where root = '2.16.840.1.113883.2.9.10.1.4.3.10.3' then {
    src.effectiveTime as effectiveTime -> tgt.performed = (effectiveTime.value);
    src.code -> tgt.code;
  } "ref";
  src ->  tgt.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
  // src -> tgt.encounter=create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %encounter.id) "reference";
  src.statusCode as s then {
    s.code as cos -> tgt.status = translate(cos, '#EventStatus', 'code') "codeS";
  } "status";
  src where statusCode.exists().not() -> tgt.status = 'unknown' "status2";
  src.templateId where root = '2.16.840.1.113883.2.9.10.1.4.3.9.1' then {
    src ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('Device') as deviceRes,  deviceRes.id = uuid() as uuid1,  e1.fullUrl = append('https://example/Device/', uuid1),  request.url = 'Device',  tgt.usedReference = create('Reference') as reference,  reference.reference = ('https://example/Device/' + %deviceRes.id) then {
      src ->  deviceRes.patient = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
      src.code -> deviceRes.type;
    } "device";
    src.effectiveTime as effectiveTime where (value.exists()) -> tgt.performed = create('dateTime') as value then TSDateTime(effectiveTime, value) "value1";
    src.effectiveTime as effectiveTime where (low.exists()) -> tgt.performed = create('Period') as value then IVLTSPeriod(effectiveTime, value) "valuePeriod";
  } "presenzaProtesiImpianto";
  src.templateId where root = '2.16.840.1.113883.2.9.10.1.4.3.9.2' then {
    src.code as code -> tgt.note as note then {
      code.displayName as displayName -> note.text = (displayName) "text";
    } "note";
  } "assenza";
  src.templateId where root = '2.16.840.1.113883.2.9.10.1.4.3.11.1' then {
    src.id -> tgt.identifier;
    src.code -> tgt.code;
    src.effectiveTime as effectiveTime where (value.exists()) -> tgt.performed = create('dateTime') as value then TSDateTime(effectiveTime, value) "value1";
    src.effectiveTime as effectiveTime where (low.exists()) -> tgt.performed = create('Period') as value then IVLTSPeriod(effectiveTime, value) "valuePeriod";
    src.entryRelationship as entryR then {
      entryR.observation as observation ->  bundle.entry as e3,  e3.request = create('BackboneElement') as request,  request.method = 'POST',  e3.resource = create('Observation') as obs1,  obs1.id = uuid() as uuid3,  e3.fullUrl = append('https://example/Observation/', uuid3),  request.url = 'Observation',  tgt.reasonReference = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %obs1.id) then Observation(observation, patient, encounter, obs1, bundle);
    } "entryRelProcedure";
  } "procedureTrattamenti";
}

group Observation(source cda, target patient : Patient, target encounter : Encounter, target ob : Observation, target bundle : Bundle) {
  cda ->  ob.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
  // cda-> ob.encounter=create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %encounter.id) "reference";
  cda.id -> ob.identifier;
  cda.code -> ob.code;
  cda -> ob.status = 'final' "Stats";
  // value datatype
  cda.value : ST as st ->  ob.value = create('string'),  ob.value = (st.dataString);
  cda.value : BL as boolean -> ob.value = (boolean.value) "boolean";
  cda.value : INT as int -> ob.value = (int.value) "intval";
  cda.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.value);
      };
      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";
  cda.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.value);
      };
      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";
  cda.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";
  cda.effectiveTime as effectiveTime where (value.exists()) -> ob.effective = create('dateTime') as value then TSDateTime(effectiveTime, value) "value1";
  cda.effectiveTime as effectiveTime where (low.exists()) -> ob.effective = create('Period') as value then IVLTSPeriod(effectiveTime, value) "valuePeriod";
  cda.text as text -> ob.note as note then {
    text.reference as reference -> note.text = (reference.value) "text";
  } "note";
  cda.statusCode as s then {
    s.code as cos -> ob.status = translate(cos, '#OBSstatus', 'code') "codeS";
  } "status";
  // toASK è giusto siano invertiti?
  cda.methodCode -> ob.method;
  cda.interpretationCode -> ob.interpretation;
  cda.targetSiteCode -> ob.bodySite;
  // added
  cda.referenceRange as refrange then {
    refrange.observationRange as obsrange then {
      obsrange.value as val -> ob.referenceRange = create('BackboneElement') as refrangeFH then {
        val -> refrangeFH.low = create('SimpleQuantity') as lowfhir then {
          val.low as l -> lowfhir.value = (l.value) "val";
          val.low as l -> lowfhir.unit = (l.unit) "val";
        } "de";
        val -> refrangeFH.high = create('SimpleQuantity') as highfhir then {
          val.high as h -> highfhir.value = (h.value) "val";
          val.high as h -> highfhir.unit = (h.unit) "val";
        } "de";
      } "refFhir";
    } "obsrange";
  } "regrange";
}

group ObservationOrganizer(source section : section, source cda : organizer, target patient : Patient, target encounter : Encounter, target ob : Observation, target bundle : Bundle) {
  cda ->  ob.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
  // cda-> ob.encounter=create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %encounter.id) "reference";
  cda.id -> ob.identifier;
  section.code -> ob.code;
  cda -> ob.status = 'final' "Stats";
  cda.effectiveTime as effectiveTime where (value.exists()) -> ob.effective = create('dateTime') as value then TSDateTime(effectiveTime, value) "value1";
  cda.effectiveTime as effectiveTime where (low.exists()) -> ob.effective = create('Period') as value then IVLTSPeriod(effectiveTime, value) "valuePeriod";
  cda.text as text -> ob.note as note then {
    text.reference as reference -> note.text = (reference.value) "text";
  } "note";
  cda.statusCode as s then {
    s.code as cos -> ob.status = translate(cos, '#OBSstatus', 'code') "codeS";
  } "status";
  cda.component as component then {
    component.observation as observation ->  bundle.entry as ei,  ei.request = create('BackboneElement') as request,  request.method = 'POST',  ei.resource = create('Observation') as obsi,  obsi.id = uuid() as uuidi,  ei.fullUrl = append('https://example/Observation/', uuidi),  request.url = 'Observation',  ob.hasMember = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %obsi.id) then Observation(observation, patient, encounter, obsi, bundle) "hasMember";
  };
}

group Coverage(source src : act, target patient : Patient, target encounter : Encounter, target tgt : Coverage, target bundle : Bundle) {
  src ->  tgt.beneficiary = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
  src ->  tgt.payor = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
  src.id as id -> tgt.identifier as idf then {
    id -> idf.value = (id.root) "ID";
  };
  src.code -> tgt.type;
  src.statusCode as statusCode then {
    statusCode.code as s -> tgt.status = translate(s, '#FinancialStatus', 'code') "status";
  } "sc";
  src where statusCode.exists().not() -> tgt.status = 'active' "statusAbsent";
  // src.effectiveTime as effectiveTime -> tgt.period as period then{
  src.effectiveTime as effectiveTime where (value.exists()) -> tgt.period = create('dateTime') as value then TSDateTime(effectiveTime, value) "value1";
  src.effectiveTime as effectiveTime where (low.exists()) -> tgt.period = create('Period') as value then IVLTSPeriod(effectiveTime, value) "valuePeriod";
  src.entryRelationship as entryRelationship then {
    entryRelationship.act as ac -> tgt.class as class then {
      ac.text as text -> class.type as type then {
        text.reference as reference -> type.text = (reference.value) "value";
      } "ref";
      ac -> class.value = 'commenti' "note";
    } "QUI";
  } "entryr";
}

group allergyFunction(source src : cdaElement, target tgt : AllergyIntolerance, target patient : Patient, target encounter : Encounter) {
  src ->  tgt.patient = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
  // src -> tgt.encounter=create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %encounter.id) "reference";
  src.effectiveTime as effTime then {
    effTime.low as l -> tgt.recordedDate as r then TSDateTime(l, r) "value";
  } "efftime";
  src.entryRelationship as entryRelationship1 then {
    entryRelationship1.observation as observation1 then {
      observation1.id -> tgt.identifier;
      observation1.templateId where root = '2.16.840.1.113883.2.9.10.1.4.3.1.4' -> tgt.code as code then {
        observation1 -> code.coding as coding then {
          observation1 -> coding.code = 'No known allergy' "code";
        } "code";
        src.effectiveTime as effectiveTime where (value.exists()) -> tgt.onset = create('dateTime') as value then TSDateTime(effectiveTime, value) "value1";
        src.effectiveTime as effectiveTime -> tgt.onset = create('Period') as value then IVLTSPeriod(effectiveTime, value) "valuePeriod";
      } "Noallergy";
      observation1.effectiveTime as effectiveTime where (value.exists()) -> tgt.onset = create('dateTime') as value then TSDateTime(effectiveTime, value) "value1";
      observation1.effectiveTime as effectiveTime -> tgt.onset = create('Period') as value then IVLTSPeriod(effectiveTime, value) "valuePeriod";
      observation1.value as code then {
        code.code as code1 -> tgt.type = translate(code1, '#AllergyTypeMap', 'code') "type";
        code.code as code1 -> tgt.category = translate(code1, '#AllergyCategoryMap', 'code') "category";
      } "code";
      // toASK qui dovrei fare un controllo sul code
      observation1.value -> tgt.code;
      observation1.participant as participant -> tgt.reaction as reaction then {
        observation1.entryRelationship as entryRelationship2 where (typeCode = 'MFST') then {
          entryRelationship2.observation as observation2 then {
            observation2.value -> reaction.manifestation "manifestation";
            observation2.code -> reaction.manifestation "manifestation";
            observation2.text as tx then {
              tx.reference as reff -> reaction.description = (reff.value) "tx";
            } "tx";
            observation2.effectiveTime as effectiveTime then {
              effectiveTime.low as low -> reaction.onset = create('dateTime') as value then TSDateTime(low, value) "valuePeriodLow";
              effectiveTime.high as high -> tgt.lastOccurrence = create('dateTime') as value then TSDateTime(high, value) "valuePeriodHigh";
            } "low";
          } "observ2";
        } "entryR2";
        participant.participantRole as participantRole then {
          participantRole.playingEntity as playingEntity then {
            playingEntity.code -> reaction.substance "reaction";
          };
        };
      };
      observation1.entryRelationship as entryRelationship2 where (typeCode = 'MFST') then {
        entryRelationship2.observation as observation2 where observation1.participant.exists().not() -> tgt.reaction as reaction then {
          observation2.value -> reaction.manifestation "manifestation";
          observation2.text as tx then {
            tx.reference as reff -> reaction.description = (reff.value) "tx";
          } "tx";
          observation2.effectiveTime as effectiveTime then {
            effectiveTime.low as low -> reaction.onset = create('dateTime') as value then TSDateTime(low, value) "valuePeriodLow";
          } "low";
        } "observ2";
      } "entryR2";
      observation1.entryRelationship as entryRelationship3 where (typeCode = 'SUBJ') then {
        entryRelationship3.observation as observation3 then {
          observation3.value as value then {
            value.code as c -> tgt.criticality = translate(c, '#CricalityMap', 'code') "value";
          } "criticality";
        } "observ3";
        entryRelationship3.act as act -> tgt.note as note then {
          act.text as text then {
            text.reference as reference -> note.text = (reference.value);
          } "note";
        };
      } "entryR3";
      observation1.entryRelationship as entryRelationship4 where (typeCode = 'REFR') then {
        entryRelationship4.observation as observation4 then {
          observation4 -> tgt.clinicalStatus as clinicalStatus then {
            observation4.value as value then {
              value as valu -> clinicalStatus.coding = create('Coding') as coding then {
                valu where (code = 'LA9041-0') -> coding.code = 'resolved' "code";
                valu where (code = 'LA18632-2') -> coding.code = 'inactive' "code";
                valu where (code = 'LA16666-2') -> coding.code = 'active' "code";
                valu -> coding.system = 'http://terminology.hl7.org/CodeSystem/allergyintolerance-clinical' "system";
                valu.displayName as display -> coding.display = cast(display, 'string') "display";
              } "coding";
            };
            observation4.text as tx then {
              tx.reference as ref -> clinicalStatus.text = (ref.value);
            } "tx";
          } "clinicalStatus";
        } "observ4";
      } "entryR4";
    };
  } "entryrelationship";
}

group MedicationStatement(source src : substanceAdministration, target tgt : MedicationStatement, target patient : Patient, target encounter : Encounter, target bundle : Bundle) {
  src ->  tgt.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
  // src -> tgt.context = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %encounter.id) "reference";
  src.statusCode -> tgt.status "status";
  src.id -> tgt.identifier;
  src.text as text -> tgt.note as note then {
    text.reference as reference -> note.text = (reference.value) "text";
  } "note";
  src.effectiveTime as eff where (value.exists()) -> tgt.effective = create('dateTime') as value then TSDateTime(eff, value) "value1";
  src.effectiveTime : IVL_TS as eff -> tgt.effective = create('Period') as value then IVLTSPeriod(eff, value) "valuePeriod";
  src -> tgt.dosage = create('Dosage') as dosage then {
    src.effectiveTime : PIVL_TS as eff then {
      eff -> dosage.timing = create('Timing') as timing then periodTiming(eff, timing) "cod";
    } "eff";
    src where (src.doseQuantity.exists() or src.rateQuantity.exists() or src.routeCode.exists() or src.approachSiteCode.exists()) then {
      src.doseQuantity as doseQuant then {
        doseQuant.originalText as ot then {
          ot.reference -> dosage.text;
        } "ot";
        doseQuant -> dosage.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";
      };
      src.rateQuantity as rateQuantity then {
        rateQuantity.originalText as ot then {
          ot.reference -> dosage.text;
        } "ot";
        rateQuantity -> dosage.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);
            } "high";
          } "r";
        } "dosageRate";
      } "rate";
      src.routeCode -> dosage.route "route";
      src.approachSiteCode -> dosage.site "site";
      src.targetSiteCode -> dosage.site "site";
    } "route";
  } "dos";
  src.consumable as consumable then {
    consumable.manufacturedProduct as manufacturedProduct ->  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',  tgt.medication = create('Reference') as medref,  medref.reference = ('https://example/Medication/' + %medication.id) then Medication(src, medication, patient, bundle) "medication";
  };
}

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 Medication(source src : substanceAdministration, target tgt : Medication, target patient : Patient, target bundle : Bundle) {
  src.consumable as consumable then {
    consumable.manufacturedProduct as manufacturedProduct then {
      manufacturedProduct.manufacturedMaterial as manufacturedMaterial then {
        manufacturedMaterial.code -> tgt.code "CE";
        src.administrationUnitCode -> tgt.form "form";
      } "material";
    } "product";
  };
  src.entryRelationship as entryR then {
    entryR.observation as observation then {
      observation.code where displayName = 'Grammatura' -> tgt.ingredient as ingredient then {
        src.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 -> tgt.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";
}

group Immunization(source substance : substanceAdministration, target patient : Patient, target encounter : Encounter, target tgt : Immunization, target bundle : Bundle) {
  substance ->  tgt.patient = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "patientRef";
  // substance -> tgt.encounter  = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %encounter.id) "encounterRef";
  substance.id as id -> tgt.identifier as idf then {
    id.root as r -> idf.system = translate(r, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri') "root1";
  };
  substance.text as text -> tgt.note as note then {
    text.reference as reference -> note.text = (reference.value) "text";
  } "note";
  substance.statusCode as statusc where (code = 'completed') -> tgt.status = 'completed';
  substance.statusCode as statusc where (code = 'aborted') -> tgt.status = 'final';
  substance.statusCode as statusc where (code = 'suspended') -> tgt.status = 'enterer-in-error';
  substance.statusCode as statusc where (code = 'cancelled') -> tgt.status = 'not-done';
  substance.effectiveTime as time -> tgt.occurrence = create('dateTime') as value then TSDateTime(time, value) "efftime";
  substance.routeCode -> tgt.route;
  substance.approachSiteCode -> tgt.site;
  substance -> tgt.doseQuantity = create('SimpleQuantity') as quantity then {
    substance.doseQuantity as q then {
      q -> quantity.value = (q.value) "val";
      q -> quantity.unit = (q.unit) "uni";
    } "qua";
  } "q";
  substance.consumable as cons then {
    cons.manufacturedProduct as manufact then {
      manufact.manufacturedMaterial as manufactmat then {
        manufactmat.code -> tgt.vaccineCode;
        manufactmat.lotNumberText as t -> tgt.lotNumber = (t.dataString);
      } "manufactmat";
      manufact.manufacturerOrganization as manufactOrg ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'PUT',  e1.resource = create('Organization') as organization then {
        manufactOrg.id as id -> organization.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 {
            manufactOrg -> request.url = append('Organization?identifier=', ext) "UUID";
          } "ext";
          id.assigningAuthorityName as s ->  identifier.assigner as a,  a.display = s;
          id.root as r then {
            id.extension as ext ->  organization.id = (r + '-' + ext) as uuid,  e1.fullUrl = append('https://example/', uuid),  tgt.manufacturer = create('Reference') as reference,  reference.reference = ('https://example/' + %organization.id) "idasi";
          } "r";
        } "identifier";
        manufactOrg.name as n -> organization.name = (n.other);
        manufactOrg -> organization.meta as meta then {
          manufactOrg -> meta.tag = create('Coding') as coding then {
            manufactOrg -> coding.system = 'http://algoritmodiscoring' "system";
            manufactOrg -> coding.code = 'ClinicalDocument/body/Vaccinazioni/manufacturerOrganization' "code";
          } "coding";
        } "meta";
      } "manufactOrg";
    } "manufact";
  } "cons";
  substance.participant as part ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'PUT',  e1.resource = create('Location') as location,  location.id = uuid() as uuid1 then {
    part -> location.meta as meta then {
      part -> meta.tag = create('Coding') as coding then {
        part -> coding.system = 'http://algoritmodiscoring' "system";
        part -> coding.code = 'ClinicalDocument/body/Vaccinazione/participant' "code";
      } "coding";
    } "meta";
    part.participantRole as partRole then {
      partRole.id as id -> location.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 {
          partRole -> request.url = append('Location?identifier=', ext) "UUID";
        } "ext";
        id.assigningAuthorityName as s ->  identifier.assigner as a,  a.display = s;
        id.root as r then {
          id.extension as ext ->  location.id = (r + '-' + ext) as uuid,  e1.fullUrl = append('https://example/Location', uuid),  tgt.location = create('Reference') as reference,  reference.reference = ('https://example/' + %location.id) "idasi";
        } "r";
      } "identifier";
    } "role";
  } "part";
  substance.entryRelationship as entrirel1 then {
    entrirel1.observation as obs then {
      obs.code where (code = '30973-2') then {
        obs -> tgt.protocolApplied = create('BackboneElement') as prot then {
          obs.value as v then {
            v.value as int -> prot.doseNumber = (int.toString());
          };
        } "val";
      } "codecontrol";
    } "obs";
  } "entrirel1";
  substance.entryRelationship as entrirel2 then {
    entrirel2.observation as obs then {
      obs.code where (code = '59781-5') then {
        obs.value as value then {
          value.high as h then {
            h.value as value -> tgt.expirationDate = truncate(value, 10);
          } "val";
        };
      } "codecontrol";
    } "obs";
  } "entrirel2";
  substance.entryRelationship as entrirel4 then {
    entrirel4.observation as obs then {
      obs.code where (code = '59785-6') ->  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.reasonReference = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %observation.id) then {
        obs then Observation1(entrirel4, patient, tgt, bundle, enc, observation) "observation";
      } "codecontrol";
    } "obs";
  } "entrirel4";
  substance.entryRelationship as entrirel5 then {
    entrirel5.observation as obs then {
      obs.code where (code = '75321-0') or (code = '5321-0') -> tgt.reaction as reaction 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',  reaction.detail = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %observation.id) then Observation(obs, patient, encounter, observation, bundle) "observation";
      } "codecontrol";
    } "obs";
  } "entrirel5";
  substance.entryRelationship as entrirel5 then {
    entrirel5.act as act then {
      act.text as tx -> tgt.note as note then {
        tx.reference as reference -> note.text = (reference.value) "text";
      } "note";
    } "obs";
  } "entrirel5";
}

group ConditionFunction(source src : cdaElement, target tgt : Condition, target patient : patient, target encounter : encounter, target bundle : Bundle) {
  src.id -> tgt.identifier;
  src ->  tgt.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
  // src -> tgt.encounter=create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %encounter.id) "reference";
  src.statusCode as stscode -> tgt.verificationStatus as verifstatus then {
    stscode as codeS -> verifstatus.coding = create('Coding') as coding then {
      codeS.code -> coding.code = 'confirmed';
      codeS -> coding.system = 'http://terminology.hl7.org/CodeSystem/condition-ver-status' "system";
      codeS -> coding.display = cast('Confirmed', 'string') "display";
    } "coding";
  } "verifstatus";
  src where entryRelationship.exists().not() then {
    src.effectiveTime as effectiveTime where (value.exists()) -> tgt.onset = create('dateTime') as value then TSDateTime(effectiveTime, value) "value1";
    src.effectiveTime as effectiveTime -> tgt.onset = create('Period') as value then IVLTSPeriod(effectiveTime, value) "valuePeriod";
  } "onset";
  src.entryRelationship as entryRelationship then {
    entryRelationship.observation as obsentry then {
      // toASK
      obsentry.value -> tgt.code;
      obsentry.code -> tgt.category;
      obsentry.effectiveTime as effectiveTime where (value.exists()) -> tgt.onset = create('dateTime') as value then TSDateTime(effectiveTime, value) "value1";
      obsentry.effectiveTime as effectiveTime -> tgt.onset = create('Period') as value then IVLTSPeriod(effectiveTime, value) "valuePeriod";
      obsentry.text as text -> tgt.note as note then {
        text.reference as reference -> note.text = (reference.value) "text";
      } "note";
      obsentry.entryRelationship as entryR2 then {
        entryR2.observation as obsentry2 then {
          obsentry2.code where code = '89261-2' then {
            obsentry2 ->  tgt.evidence as evidence,  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('Observation') as obsy,  obsy.id = uuid() as uuid1,  e1.fullUrl = append('https://example/Observation/', uuid1),  request.url = 'Observation',  evidence.detail = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %obsy.id) then Observation(obsentry2, patient, encounter, obsy, bundle) "observation";
          } "observation";
          obsentry2.code where code = '33999-4' then {
            obsentry2.value as value -> tgt.clinicalStatus as clinicalstatus then {
              value as val -> clinicalstatus.coding = create('Coding') as coding then {
                val where (code = 'LA9041-0') -> coding.code = 'resolved' "code";
                val where (code = 'LA18632-2') -> coding.code = 'inactive' "code";
                val where (code = 'LA16666-2') -> coding.code = 'active' "code";
                val -> coding.system = 'http://terminology.hl7.org/CodeSystem/condition-clinical' "system";
                val.displayName as display -> coding.display = cast(display, 'string') "display";
              } "coding";
              obsentry2.text as text then {
                text.reference as reference -> clinicalstatus.text = (reference.value) "text";
              };
            } "clinicalstatus";
          } "clinicalStatus2";
          obsentry2.code where code = 'SEV' then {
            obsentry2.value -> tgt.severity;
          } "severity";
        };
        entryR2.act as act then {
          act.text as text -> tgt.note as note then {
            text.reference as reference -> note.text = (reference.value) "text";
          } "note";
        };
      } "entryR";
    } "EntryRelObsevation";
  } "entryR";
}

group FamilyMemberFunction(source src : organizer, target tgt : FamilyMemberHistory, target patient : patient) {
  src ->  tgt.patient = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "patReference";
  src.id -> tgt.identifier;
  src.statusCode -> tgt.status;
  src.effectiveTime as effectiveTime -> tgt.date = create('date') as value then TSDate(effectiveTime, value) "date";
  src.subject as subject then {
    subject.relatedSubject as relatedSubject then {
      relatedSubject.code -> tgt.relationship "relationshipCode";
      relatedSubject.subject as subject -> tgt.sex as sex then {
        subject.administrativeGenderCode as administrativeGenderCode -> sex.coding as coding then {
          administrativeGenderCode.code as sexCode -> coding.code = translate(sexCode, '#cm-v3-administrative-gender', 'code') "gender";
          administrativeGenderCode -> coding.system = 'http://hl7.org/fhir/administrative-gender' "system";
          administrativeGenderCode.displayName as dn -> coding.display = dn;
        } "coding";
      };
    } "relatedSub";
  } "relationship";
  src.component as component -> tgt.condition as condition then {
    component.observation as observation then {
      observation.code -> condition.code;
      observation.text as text -> tgt.note as note then {
        text.reference as reference -> note.text = (reference.value) "value";
      } "reference";
      observation.statusCode -> tgt.status;
      // observation.effectiveTime as effectiveTime -> condition.onset = create('Period') as value then IVLTSPeriod(effectiveTime, value) "valuePeriod";
      observation.value -> condition.outcome "codeable";
      observation.entryRelationship as entryR then {
        entryR.observation as obs then {
          obs where (code.code = '35267-4') then {
            obs.value as value -> condition.onset = create('Age') as Age then {
              value.value as valueAge -> Age.value = valueAge "age";
              value.unit as unit -> Age.code = unit;
              value.unit as unit -> Age.unit = unit;
              value -> Age.system = 'http://unitsofmeasure.org' "system";
            };
          } "insorgenza";
          obs where (code.code = '39016-1') then {
            obs.value as value -> tgt.deceased = create('Age') as Age then {
              value.value as valueAge -> Age.value = valueAge "age";
              value.unit as unit -> Age.code = unit;
              value.unit as unit -> Age.unit = unit;
              value -> Age.system = 'http://unitsofmeasure.org' "system";
            };
          } "death";
        } "obser";
      } "EntryRel";
    };
  };
}

group Practitioner(source src : performer, target tgt : Encounter, target bundle : Bundle) {
  src ->  bundle.entry as e22,  e22.request = create('BackboneElement') as request,  request.method = 'PUT',  e22.resource = create('Practitioner') as practitioner1 then {
    src.assignedEntity as assignedEntity -> tgt.participant as participant then {
      src.time as time where (value.exists()) -> participant.period = create('dateTime') as value then TSDateTime(time, value) "value1";
      src.time as time where (low.exists()) -> participant.period = create('Period') as value then IVLTSPeriod(time, value) "valuePeriod";
      // src.time as time -> participant.period as period then{
      assignedEntity.id as id -> practitioner1.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 "ext";
        id.assigningAuthorityName as s ->  identifier.assigner as a,  a.display = s;
        id.root as r then {
          id.extension as ext ->  practitioner1.id = (r + '-' + ext) as uuid22,  e22.fullUrl = append('https://example/Practitioner/', uuid22),  participant.individual = create('Reference') as reference,  reference.reference = ('https://example/Practitioner/' + %practitioner1.id) "id";
        } "r";
      } "identifier";
      assignedEntity.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";
      assignedEntity.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";
      assignedEntity -> practitioner1.meta as meta then {
        src -> meta.tag = create('Coding') as coding then {
          src -> coding.system = 'http://algoritmodiscoring' "system";
          src -> coding.code = 'ClinicalDocument/body/VisiteRicoveri/performer/' "code";
        } "coding";
      } "meta";
      assignedEntity.addr -> practitioner1.address;
      assignedEntity.telecom -> practitioner1.telecom;
      assignedEntity.assignedPerson as person then {
        person.name -> practitioner1.name;
        person.birthTime -> practitioner1.birthDate;
      } "partname";
    } "participant";
  } "resurceCreation";
}

group CarePlanFunction(source src : entry, target tgt : CarePlan, target patient : Patient, target encounter : Encounter, target bundle : Bundle) {
  src ->  tgt.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
  src -> tgt.status = 'unknown' "status";
  src -> tgt.intent = 'plan' "intent";
  src -> tgt.activity as activity then {
    src -> activity.detail as detail then {
      src.observation as observation then {
        observation then {
          observation -> detail.status = 'unknown' "status";
          observation ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('Observation') as obs1,  obs1.id = uuid() as uuid1,  e1.fullUrl = append('https://example/Observation/', uuid1),  request.url = 'Observation',  detail.reasonReference = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %obs1.id) then Observation(observation, patient, encounter, obs1, bundle) "obs1";
        } "activity";
      } "entryObs";
      src.substanceAdministration as substanceAdministration -> tgt.activity as activity then {
        substanceAdministration ->  bundle.entry as e2,  e2.request = create('BackboneElement') as request,  request.method = 'POST',  e2.resource = create('MedicationRequest') as medre1,  medre1.id = uuid() as uuid2,  e2.fullUrl = append('https://example/MedicationRequest/', uuid2),  request.url = 'MedicationRequest',  activity.reference = create('Reference') as reference,  reference.reference = ('https://example/MedicationRequest/' + %medre1.id) then MedicationRequest(substanceAdministration, patient, encounter, medre1, bundle) "Terapie";
      } "entrySub";
      src.procedure as procedureC ->  bundle.entry as e8,  e8.request = create('BackboneElement') as request,  request.method = 'POST',  e8.resource = create('Procedure') as procedure,  procedure.id = uuid() as uuid8,  e8.fullUrl = append('https://example/Procedure/', uuid8),  request.url = 'Procedure',  activity.outcomeReference = create('Reference') as reference,  reference.reference = ('https://example/Procedure/' + %procedure.id) then Procedure(procedureC, patient, encounter, procedure, bundle) "proc";
      src.encounter as encounterCDA ->  bundle.entry as e3,  e3.request = create('BackboneElement') as request,  request.method = 'POST',  e3.resource = create('Encounter') as encounterFHIR,  encounterFHIR.id = uuid() as uuid3,  e3.fullUrl = append('https://example/Encounter/', uuid3),  request.url = 'Encounter',  tgt.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %encounterFHIR.id) then {
        // encounterCDA -> encounterFHIR.partOf = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %encounter.id) "encounterHeader";
        encounterCDA ->  encounterFHIR.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "refPatient";
        encounterCDA.id -> encounterFHIR.identifier;
        encounterCDA.statusCode -> encounterFHIR.status;
        encounterCDA where statusCode.exists().not() -> encounterFHIR.status = 'unknown' "status";
        encounterCDA.code as code -> encounterFHIR.class as class then {
          code.code as code -> class.code = cast(code, 'string');
          code.codeSystem as system -> class.system = translate(system, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri');
          code.displayName as display -> class.display = cast(display, 'string');
        } "class";
        encounterCDA.text as text -> encounterFHIR.type as type then {
          text.reference as reference -> type.text = (reference.value) "value";
        };
        encounterCDA.effectiveTime as effectiveTime -> encounterFHIR.period = create('Period') as period then {
          effectiveTime -> period.start = create('dateTime') as start then TSDateTime(effectiveTime, start) "val";
        } "efft";
      } "viste";
      src.act as act then {
        act.id -> tgt.identifier;
        act.code -> activity.outcomeCodeableConcept;
        act.text as text -> activity.progress = create('Annotation') as progress then {
          text.reference as reference -> progress.text = (reference.value) "value";
        };
        act.effectiveTime as effectiveTime -> detail.scheduled = create('Period') as period then {
          effectiveTime -> period.start = create('dateTime') as start then TSDateTime(effectiveTime, start) "val";
        } "efft";
        act -> detail.status = 'completed' "status";
      };
    } "detail";
  } "activityIni";
}

group MedicationRequest(source src : substanceAdministration, target patient : Patient, target encounter : Encounter, target tgt : MedicationRequest, target bundle : Bundle) {
  // default  + mandatory
  src ->  tgt.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
  // src -> tgt.encounter = create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %encounter.id) "reference";
  src -> tgt.intent = 'order' "intent";
  src where statusCode.exists().not() -> tgt.status = 'unknown' "st";
  src.statusCode as sc then {
    sc.code as cos -> tgt.status = translate(cos, '#MedicationStatusMap', 'code') "codeS";
  } "status";
  src.id -> tgt.identifier;
  src.text as txt -> tgt.note as note then {
    txt.reference as reference -> note.text = (reference.value) "text";
  } "note";
  src.effectiveTime : IVL_TS as eff -> tgt.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 value then IVLTSPeriod(eff, value) "valuePeriod";
      } "rep";
    } "timing";
  } "period";
  src.effectiveTime : EIVL_TS as effe -> tgt.dosageInstruction = create('Dosage') as dosage then {
    effe -> dosage.timing = create('Timing') as timing then {
      effe -> timing.repeat as rep then {
        effe.eventCode as ev -> rep.when = (ev.code);
      } "rep";
    } "timing";
  } "period";
  src.effectiveTime : IVL_TS as eff ->  tgt.dosageInstruction = create('Dosage') as dosage,  dosage.timing = create('Timing') as timing,  timing.event = (eff.value) "tim";
  src.effectiveTime : PIVL_TS as eff -> tgt.dosageInstruction = create('Dosage') as dosage then {
    eff -> dosage.timing = create('Timing') as timing then periodTiming(eff, timing) "cod";
  } "eff";
  src where (src.doseQuantity.exists() or src.rateQuantity.exists()) then {
    src -> tgt.dosageInstruction = create('Dosage') as dosageInstruction then {
      src.doseQuantity as doseQuant 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";
      };
      src.rateQuantity as rateQuantity then {
        rateQuantity.originalText as ot then {
          ot.reference -> dosageInstruction.text;
        } "ot";
        rateQuantity -> dosageInstruction.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);
            } "high";
          } "r";
        } "dosageRate";
      } "rate";
      src.routeCode -> dosageInstruction.route "route";
      src.approachSiteCode -> dosageInstruction.site "site";
      src.targetSiteCode -> dosageInstruction.site "site";
    } "dosageIn";
  } "condition";
  src.consumable as consumable ->  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',  tgt.medication = create('Reference') as medref,  medref.reference = ('https://example/Medication/' + %medication.id) then Medication(src, medication, patient, bundle) "medication";
  src.entryRelationship as entryRelationship then {
    entryRelationship.supply as supply -> tgt.dispenseRequest as dispenseRequest then {
      supply.quantity as quantityCDA -> dispenseRequest.quantity as quantityFHIR then {
        quantityCDA -> quantityFHIR.value = (quantityCDA.value) "value";
      };
    };
  } "entryR";
  src.participant as participant then {
    participant then Practitioner(participant, tgt, bundle) "function";
    participant.effectiveTime -> tgt.authoredOn "autor";
  } "Partecipant";
}

group OrganizationAffiliation(source src : act, target patient : Patient, target enc : Encounter, target tgt : OrganizationAffiliation, target bundle : Bundle) {
  src.id -> tgt.identifier;
  // src.code -> tgt.specialty as specialty then{
  src.statusCode where code = 'active' -> tgt.active = true;
  src.statusCode where (code = 'active').not() -> tgt.active = false;
  src.effectiveTime as eff -> tgt.period;
  // src.code -> tgt.specialty;
  src -> tgt.specialty = create('CodeableConcept') as spec then {
    src.code as code then {
      code -> spec.coding = create('Coding') as cd then {
        code -> cd.code = (code.code) "code";
        code -> cd.display = (code.displayName) "code";
        code.codeSystem as r -> cd.system = translate(r, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri') "root1";
      } "cd";
    } "spec";
    src.entryRelationship as entry then {
      entry.act as a then {
        a.text as tx then {
          tx.reference as reff -> spec.text = (reff.value);
        } "ref";
      };
    } "entry";
  } "a";
}

group DiagnosticReportFunction(source src : organizer, target patient : Patient, target enc : Encounter, target tgt : DiagnosticReport, target bundle : Bundle) {
  src ->  tgt.subject = create('Reference') as reference,  reference.reference = ('https://example/Patient/' + %patient.id) "reference";
  // src -> tgt.encounter=create('Reference') as reference,  reference.reference = ('https://example/Encounter/' + %enc.id) "reference";
  src.code -> tgt.code;
  src.statusCode where code = 'completed' -> tgt.status = 'final';
  src.effectiveTime as eff where (value.exists()) -> tgt.effective = create('dateTime') as value then TSDateTime(eff, value) "value1";
  src.effectiveTime as eff where (low.exists()) -> tgt.effective = create('Period') as value then IVLTSPeriod(effectiveTime, value) "valuePeriod";
  src.component as component then {
    component.observation as observation ->  bundle.entry as ei,  ei.request = create('BackboneElement') as request,  request.method = 'POST',  ei.resource = create('Observation') as obsi,  obsi.id = uuid() as uuidi,  ei.fullUrl = append('https://example/Observation/', uuidi),  request.url = 'Observation',  tgt.result = create('Reference') as reference,  reference.reference = ('https://example/Observation/' + %obsi.id) then Observation(observation, patient, enc, obsi, bundle) "hasMember";
  };
}

group EncounterFunction(source src : cdaElement, target patient : Patient, target encounter : Encounter, target tgt : Encounter, target bundle : Bundle) {
  src.id -> tgt.identifier;
  src.statusCode -> tgt.status;
  src where statusCode.exists().not() -> tgt.status = 'unknown' "status";
  src.code as code -> tgt.class as class then {
    code -> class.code = (code.code) "code";
    code -> class.display = (code.displayName) "display";
    code.codeSystem as r -> class.system = translate(r, 'http://hl7.org/fhir/ConceptMap/special-oid2uri', 'uri') "root1";
  } "co";
  // src.effectiveTime as effective -> tgt.period as period then{
  src where effectiveTime.low.exists() or effectiveTime.high.exists() then {
    src.effectiveTime as eff -> tgt.period = create('Period') as period then IVLTSPeriod(eff, period);
  } "where";
  // effectiveTime = time-stamp
  src where effectiveTime.low.exists().not() or effectiveTime.high.exists().not() then {
    src.effectiveTime as effectivetime1 -> tgt.period = create('Period') as period then {
      effectivetime1 -> period.start = create('dateTime') as start then TSDateTime(effectivetime1, start) "val";
    } "efft";
  } "where";
  // src.effectiveTime as eff where (value.exists()) -> tgt.period = create('dateTime') as value then TSDateTime(eff, value) "value1";
  src.text as tx -> tgt.type as ty then {
    tx.reference as reff -> ty.text = (reff.value) "textType";
  };
  src.performer as performer -> tgt.participant as part then {
    performer -> part.period as period then {
      performer.time as time -> period.start as start then TSDateTime(time, start) "val";
    } "period";
    performer.assignedEntity as assentity ->  bundle.entry as e1,  e1.request = create('BackboneElement') as request,  request.method = 'POST',  e1.resource = create('PractitionerRole') as practitionerRole,  practitionerRole.id = uuid() as uuid1,  e1.fullUrl = append('https://example/PractitionerRole/', uuid1),  request.url = 'PractitionerRole',  tgt.participant = create('BackboneElement') as participant1,  participant1.individual = create('Reference') as referencepart,  referencepart.reference = ('https://example/PractitionerRole/' + %practitionerRole.id) then {
      assentity.code -> practitionerRole.code;
      assentity ->  bundle.entry as e2,  e2.request = create('BackboneElement') as request,  request.method = 'PUT',  e2.resource = create('Practitioner') as practitioner 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/encounter/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 then {
            assentity -> request.url = append('Practitioner?identifier=', ext) "UUID";
          } "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,  e2.fullUrl = append('https://example/Practitioner/', uuid2),  practitionerRole.practitioner = create('Reference') as reference,  reference.reference = ('https://example/Practitioner/' + %practitioner.id) "performer";
          } "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.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.addr -> practitioner.address;
        assentity.telecom -> practitioner.telecom;
        assentity.assignedPerson as person then {
          person.name -> practitioner.name;
          person.birthTime as birthTime then {
            birthTime.value as date -> practitioner.birthDate = truncate(date, 10);
          } "birth";
        } "name";
      } "assignedEntity";
    } "performer";
  } "01";
}