eCQM QICore Content Implementation Guide
2024.0.0 - CI Build

eCQM QICore Content Implementation Guide, published by cqframework. This guide is not an authorized publication; it is the continuous build for version 2024.0.0 built by the FHIR (HL7® FHIR® Standard) CI Build. This version is based on the current content of https://github.com/cqframework/ecqm-content-qicore-2024/ and changes regularly. See the Directory of published versions

Measure: Cesarean BirthFHIR

Official URL: https://madie.cms.gov/Measure/CesareanBirthFHIR Version: 0.2.000
Draft as of 2024-07-09 Responsible: The Joint Commission Computable Name: CesareanBirthFHIR
Other Identifiers: Short Name (use: usual, ), UUID:e5be4439-ce75-43cc-aabc-856aec66e841 (use: official, ), UUID:b59bf22e-550d-4bb0-a530-4d5564dfa47a (use: official, ), Endorser (use: official, ), Publisher (use: official, )

Copyright/Legal: Measure specifications are in the Public Domain.

LOINC(R) copyright 2004-2023 Regenstrief Institute, Inc. This material contains SNOMED Clinical Terms(R) (SNOMED CT[R]) copyright 2004-2023 International Health Terminology Standards Development Organisation. ICD-10 copyright 2023 World Health Organization. All Rights Reserved.

Nulliparous women with a term, singleton baby in a vertex position delivered by cesarean birth

UNKNOWN

Title: Cesarean BirthFHIR
Id: CesareanBirthFHIR
Version: 0.2.000
Url: Cesarean BirthFHIR
short-name identifier:

CMS334FHIR

version-independent identifier:

urn:uuid:e5be4439-ce75-43cc-aabc-856aec66e841

version-specific identifier:

urn:uuid:b59bf22e-550d-4bb0-a530-4d5564dfa47a

endorser (CMS Consensus Based Entity) identifier:

0471e

publisher (CMS) identifier:

334FHIR

Effective Period: 2025-01-01..2025-12-31
Status: draft
Publisher: The Joint Commission
Author: The Joint Commission
Description:

Nulliparous women with a term, singleton baby in a vertex position delivered by cesarean birth

Purpose:

UNKNOWN

Copyright:

Measure specifications are in the Public Domain.

LOINC(R) copyright 2004-2023 Regenstrief Institute, Inc. This material contains SNOMED Clinical Terms(R) (SNOMED CT[R]) copyright 2004-2023 International Health Terminology Standards Development Organisation. ICD-10 copyright 2023 World Health Organization. All Rights Reserved.

Disclaimer:

These performance measures are not clinical guidelines and do not establish a standard of medical care and have not been tested for all potential applications. The measures and specifications are provided without warranty.

Scoring:

Proportion

Rationale:

The removal of any pressure to not perform a cesarean birth has led to a skyrocketing of hospital, state and national cesarean birth (CB) rates. Some hospitals’ CB rates were over 50%. Hospitals with CB rates at 15-20% have infant outcomes that are just as good and better maternal outcomes (Symum & Zayas-Castro, 2023). There is no data that higher rates improve any outcomes, yet the CB rates continue to rise (Bailit, Garrett, Miller, McMahon, & Cefalo, 2002; Main, Bloomfield, & Hunt, 2004). This measure seeks to focus attention on the most variable portion of the CB epidemic, the term labor CB in nulliparous women. This population segment accounts for the large majority of the variable portion of the CB rate and is the area most affected by subjectivity.

As compared to other CB measures, what is different about Nulliparous, Term, Singleton, Vertex (NTSV) CB rate is that there are clear cut quality improvement activities that can be done to address the differences. Main et al. (2012) found that over 60% of the variation among hospitals can be attributed to first birth labor induction rates and first birth early labor admission rates (Main et al., 2006). The results showed if labor was forced when the cervix was not ready the outcomes were poorer. Rosenstein et al. (2021) also showed that labor and delivery guidelines can make a difference in labor outcomes. Many authors have shown that physician factors, rather than patient characteristics or obstetric diagnoses are the major drivers for the difference in rates within a hospital (Berkowitz, Fiarman, Mojica, Bauman, & de Regt, 1989; Goyert, Bottoms, Treadwell, & Nehra, 1989; Luthy, Malmgren, Zingheim, & Leininger, 2003; Symum & Zayas-Castro, 2023; Main et al., 2006). The dramatic variation in cesarean rates seen in all populations studied is striking. Cesarean rates varied tenfold in US hospitals nationwide across hospitals (Agency for Healthcare Research and Quality [AHRQ], 2002), from 7.1% to 69.9%, and there was a 15-fold variation among low-risk women, from 2.4% to 36.5% (Kozhimannil, Law, & Virnig, 2013).

A reduction in the number of NTSV patients delivering by cesarean birth will result in increased patient safety, a substantial decrease in maternal and neonatal morbidity and substantial savings in health care costs (Main et al., 2019). Successful quality improvement efforts incorporate audit and feedback strategies combined with provider and nurse education, guidelines and peer review.

The measure will assist health care organizations to track NTSV patients delivering by cesarean birth to reduce the occurrence. Nulliparous women have 4-6 times the cesarean birth rate than multiparous women thus the NTSV population is the largest driver of primary cesarean birth rate (Sakala, Belanoff, Declercq, 2020). NTSV has a large variation among facilities, thus identifying an important population on which to focus quality improvement efforts.

In accordance with the American College of Obstetricians and Gynecologists (ACOG) recommendations (2020), cesarean delivery is indicated for patients with active genital lesions of genital herpes or prodromal symptoms (i.e., vulvar pain or burning at delivery) that may indicate viral shedding. Therefore, the measure will exclude encounters with a diagnosis of active genital herpes.

In addition, the accepted approach to treat placenta accreta spectrum, or the range of pathologic adherence of the placenta that includes placenta increta, placenta percreta, and placenta accreta, as well as placenta previa, is cesarean delivery (ACOG & Society for Maternal-Fetal Medicine (SMFM), 2018). Vasa previa is an indication for cesarean delivery (SMFM Publications Committee, Sinkey, Odibo, & Dashe, 2015). Accordingly, placenta previa, vasa previa, and placenta accreta spectrum are all qualifying conditions to also be excluded from the measure.

Ultimately, a reduction in primary cesarean births will reduce the number of women having repeat cesarean births (almost 90% of mothers who have a primary cesarean birth will have subsequent cesarean birth (CDC, 2020)). Thus, improvement in the rates of cesarean delivery for the first birth will reduce the morbidity of all future births and avoid all the controversies with trial of labor after cesarean/elective repeat cesarean deliveries.

Clinical recommendation statement:

The American College of Obstetrics and Gynecology (ACOG) report, Evaluation of Cesarean Delivery, recognizes the importance of the Nulliparous, Term Singleton Vertex (NTSV) population as the optimal focus for measurement and quality improvement action. A reduction in the number of nulliparous patients with live term singleton newborns in vertex position delivering by cesarean birth will result in increased patient safety, a substantial decrease in maternal and neonatal morbidity and substantial savings in health care costs.

Guidance (Usage): Vertex position is modeled implicitly, as the measure excludes deliveries with abnormal presentations. Patients who do not receive prenatal care and have no documented gestational age or estimated due date are implicitly excluded from the measure, as gestational age is required to meet denominator criteria. This measure allows for 3 approaches to determine gestational age (GA) in the following order of precedence: 1. The GA is calculated using the American College of Obstetricians and Gynecologists ReVITALize guidelines.* 2. The GA is obtained from a discrete field in the electronic health record. This option is only used when the calculated GA is not available. 3. The GA is based on ICD10 or SNOMED codes indicative of weeks gestation. This option is only used when results from items #1 and #2 (see above) are not available. Wherever gestational age is mentioned, relative to the delivery, the intent is to capture the last estimated gestational age prior to or at the time of delivery. *ACOG ReVITALize Guidelines for Calculating Gestational Age: Gestational Age = (280-(EDD minus Reference Date))/7 --Estimated Due Date (EDD): The best obstetrical Estimated Due Date is determined by last menstrual period if confirmed by early ultrasound or no ultrasound performed, or early ultrasound if no known last menstrual period or the ultrasound is not consistent with last menstrual period, or known date of fertilization (e.g., assisted reproductive technology) --Reference Date is the date on which you are trying to determine gestational age. For purposes of this eCQM, Reference Date would be the Date of Delivery. Note however the calculation may yield a non-whole number and gestational age should be rounded off to the nearest completed week. For example, an infant born on the 5th day of the 36th week (35 weeks and 5/7 days) is at a gestational age of 35 weeks, not 36 weeks. The timing relationship of relevantDatetime 42 weeks or less before TimeOfDelivery is applied to the data elements of parity, gravida, preterm/term live births for which prenatal records may include relevant information. Note: The eCQM and chart-based measure slightly digress in the denominator and denominator exclusion logic. The chart-based measure excludes single stillbirth and patients with multiple gestations from the denominator. These concepts are mutually exclusive of the denominator requirement of live singleton newborn and therefore the logic does not address single stillbirth nor multiple gestation. Parity, preterm and term live births may be updated by the electronic health record software or by clinicians during a delivery encounter. To capture the pre-delivery value, organizations may need to create a rule or calculation to capture the number prior to the delivery start time. "Gravida", "PretermBirth", "TermBirth" and "Parity" results should be submitted via QRDA I as integer and not as number or quantity. This eCQM is an episode-based measure. An episode is defined as each inpatient hospitalization or encounter that ends during the measurement period. This FHIR-based measure has been derived from the QDM-based measure: CMS334v6.1. Please refer to the HL7 QI-Core Implementation Guide (https://hl7.org/fhir/us/qicore/STU4.1.1/) for more information on QI-Core and mapping recommendations from QDM to QI-Core 4.1.1 (https://hl7.org/fhir/us/qicore/STU4.1.1/qdm-to-qicore.html). Definitions: Parity: The number of pregnancies reaching 20 weeks gestation regardless of the number of fetuses or outcomes Gravidity: The number of pregnancies, current and past, regardless of the pregnancy outcome Preterm Birth: The number of births >= 20 weeks and < 37 weeks gestation, regardless of outcome Term Birth: The number of births >= 37 weeks gestation, regardless of outcome Nulliparous: Parity = 0 or Gravidity = 1 or Preterm & Term Births both = 0. Note regarding Improvement Notation: Within Optimal Range. The Joint Commission does not want to encourage inappropriately low Cesarean rates that may be unsafe to patients. Acceptable PC-02 rates are 30% or lower, however there is not an established threshold for what rate may be too low. PC-06 serves as a balancing measure for PC-02 to guard against any unanticipated or unintended consequences and to identify unforeseen complications that might arise as a result of quality improvement activities and efforts for this measure. In order to identify areas for improvement, hospitals may want to review results based on specific ICD-10 codes or patient populations. Data could then be analyzed further determine specific patterns or trends to help reduce cesarean births.
Population Criteria: Stratifier Criteria:
64fb5619da013638e7b3da14
Initial Population: Inpatient hospitalizations for patients age greater than or equal to 8 years and less than 65 admitted to the hospital for inpatient acute care who undergo a delivery procedure with a discharge date during the measurement period
Denominator: Inpatient hospitalizations for nulliparous patients who delivered a live term singleton newborn greater than or equal to 37 weeks' gestation See Guidance and Definition Sections for more details.
Denominator Exclusion: Inpatient hospitalizations for patients with any of the following conditions during the encounter: -abnormal presentation -genital herpes -placenta previa -vasa previa - placenta accreta -placenta increta -placenta percreta
Numerator: Inpatient hospitalizations for patients who deliver by cesarean section
Stratum: None
Supplemental Data Elements:

SDE Ethnicity

SDE Race

SDE Sex

SDE Payer

SDE Variable Calculated Gestational Age

Supplemental Data Guidance : For every patient evaluated by this measure also identify payer, race, ethnicity, sex and calculated gestational age.; SDE Ethnicity SDE Race SDE Sex SDE Payer SDE Variable Calculated Gestational Age
Libraries:
CesareanBirthFHIR
Terminology and Other Dependencies:
  • Library/SupplementalDataElements|3.5.000
  • Library/PCMaternal|5.19.000
  • Library/CQMCommon|2.2.000
  • Library/FHIRHelpers|4.4.000
  • Library/QICoreCommon|2.1.000
  • AdministrativeGender
  • Logical Observation Identifiers, Names and Codes (LOINC)
  • Encounter Inpatient
  • Delivery Procedures
  • Observation Services
  • http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1029.369
  • Estimated Gestational Age at Delivery
  • http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1110.68
  • Delivery of Singleton
  • Cesarean Birth
  • Payer
  • Abnormal Presentation
  • Placenta Previa
  • Genital Herpes
  • Parameters:
    name use min max type
    Measurement Period In 0 1 Period
    SDE Sex Out 0 1 Coding
    Numerator Out 0 * Resource
    Denominator Out 0 * Resource
    SDE Payer Out 0 * Resource
    Initial Population Out 0 * Resource
    SDE Ethnicity Out 0 1 Resource
    Denominator Exclusions Out 0 * Resource
    SDE Race Out 0 1 Resource
    SDE Variable Calculated Gestational Age Out 0 * Resource
    DataRequirements:
    Resource Type Resource Elements Valueset Name Valueset
    Patient(QICorePatient) ethnicity race
    Encounter(QICoreEncounter) type period status status.value condition condition.reference condition.reference.value id id.value Observation Services Observation Services
    Encounter(QICoreEncounter) type period status status.value condition condition.reference condition.reference.value id id.value ED Visit and OB Triage http://cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1029.369
    Encounter(QICoreEncounter) type status status.value period condition condition.reference condition.reference.value id id.value Encounter Inpatient Encounter Inpatient
    Procedure(QICoreProcedure) code status status.value performed Delivery Procedures Delivery Procedures
    Procedure(QICoreProcedure) code performed status status.value Cesarean Birth Cesarean Birth
    Observation(QICoreObservation) code value status status.value effective
    Observation(QICoreObservation) code value status status.value effective
    Observation(QICoreObservation) code effective value status status.value Estimated Gestational Age at Delivery Estimated Gestational Age at Delivery
    Observation(QICoreObservation) code value status status.value effective
    Observation(QICoreObservation) code effective status status.value value
    Observation(QICoreObservation) code effective status status.value value
    Observation(QICoreObservation) code effective status status.value value
    Observation(QICoreObservation) code effective status status.value Abnormal Presentation Abnormal Presentation
    Condition(QICoreCondition) id id.value code
    Coverage(QICoreCoverage) type period Payer Type Payer
    Direct Reference Codes:
    display code system
    Male M http://hl7.org/fhir/administrative-gender
    Female F http://hl7.org/fhir/administrative-gender
    Date and time of obstetric delivery 93857-1 http://loinc.org
    Delivery date Estimated 11778-8 http://loinc.org
    [#] Pregnancies 11996-6 http://loinc.org
    [#] Parity 11977-6 http://loinc.org
    [#] Births.preterm 11637-6 http://loinc.org
    [#] Births.term 11639-2 http://loinc.org
    Logic Definitions:
    Group Scoring Population Criteria Expression
    64fb5619da013638e7b3da14 Group scoring: proportion Measure scoring:

    Proportion

    Type:

    Outcome

    Rate Aggregation: None
    Initial Population
    define "Initial Population":
      PCMaternal."Delivery Encounter with Age Range"
    Denominator
    define "Denominator":
      "Singleton Delivery Encounters at 37 Plus Weeks Gravida 1 Parity 0, No Previous Births"
    Denominator Exclusion
    define "Denominator Exclusions":
      "Delivery Encounter with Abnormal Presentation, Genital Herpes, Placenta Previa, Vasa Previa or Placenta Accreta Spectrum"
    Numerator
    define "Numerator":
      "Delivery Encounter with Cesarean Birth"
    None
    Library Name Name
    SupplementalDataElements SDE Sex
    define "SDE Sex":
      case
        when Patient.gender = 'male' then "M"
        when Patient.gender = 'female' then "F"
        else null
      end
    Library Name Name
    CesareanBirthFHIR SDE Sex
    define "SDE Sex":
      SDE."SDE Sex"
    Library Name Name
    CQMCommon Inpatient Encounter
    define "Inpatient Encounter":
      [Encounter: "Encounter Inpatient"] EncounterInpatient
    		where EncounterInpatient.status = 'finished'
    		and EncounterInpatient.period ends during day of "Measurement Period"
    Library Name Name
    PCMaternal Encounter with Age Range
    define "Encounter with Age Range":
     CQMCommon."Inpatient Encounter" InpatientEncounter
                          where AgeInYearsAt(date from start of InpatientEncounter.period) in Interval[ 8, 65 )
    Library Name Name
    PCMaternal Delivery Encounter with Age Range
    define "Delivery Encounter with Age Range":
      "Encounter with Age Range" EncounterWithAge
                    with ["Procedure": "Delivery Procedures"] DeliveryProcedure
                    such that DeliveryProcedure.status = 'completed'
                    and DeliveryProcedure.performed.toInterval  ( ) starts during EncounterWithAge.hospitalizationWithEDOBTriageObservation ()
    Library Name Name
    CesareanBirthFHIR Delivery Encounter with Calculated Gestational Age Greater than or Equal to 37 Weeks
    define "Delivery Encounter with Calculated Gestational Age Greater than or Equal to 37 Weeks":
      PCMaternal."Delivery Encounter with Age Range" DeliveryEncounter
        where DeliveryEncounter.calculatedGestationalAge ( ) >= 37
    Library Name Name
    CesareanBirthFHIR Delivery Encounter with Estimated Gestational Age Greater than or Equal to 37 Weeks
    define "Delivery Encounter with Estimated Gestational Age Greater than or Equal to 37 Weeks":
      PCMaternal."Delivery Encounter with Age Range" DeliveryEncounter
        where DeliveryEncounter.calculatedGestationalAge ( ) is null
          and DeliveryEncounter.lastEstimatedGestationalAge ( ) >= 37 weeks
    Library Name Name
    CesareanBirthFHIR Delivery Encounter with Gestational Age Greater than or Equal to 37 Weeks Based on Coding
    define "Delivery Encounter with Gestational Age Greater than or Equal to 37 Weeks Based on Coding":
      PCMaternal."Delivery Encounter with Age Range" DeliveryEncounter
        let CGA: DeliveryEncounter.calculatedGestationalAge ( ),
        EGA: DeliveryEncounter.lastEstimatedGestationalAge ( )
        where CGA is null
          and EGA is null
          and exists ( ( DeliveryEncounter.encounterDiagnosis ( ) ) EncounterDiagnosis
              where EncounterDiagnosis.code in "37 to 42 Plus Weeks Gestation"
          )
    Library Name Name
    CesareanBirthFHIR Delivery Encounter with Gestational Age Greater than or Equal to 37 Weeks
    define "Delivery Encounter with Gestational Age Greater than or Equal to 37 Weeks":
      "Delivery Encounter with Calculated Gestational Age Greater than or Equal to 37 Weeks"
        union "Delivery Encounter with Estimated Gestational Age Greater than or Equal to 37 Weeks"
        union "Delivery Encounter with Gestational Age Greater than or Equal to 37 Weeks Based on Coding"
    Library Name Name
    CesareanBirthFHIR Encounter with Singleton Delivery
    define "Encounter with Singleton Delivery":
      PCMaternal."Delivery Encounter with Age Range" DeliveryEncounter
        where exists ( ( DeliveryEncounter.encounterDiagnosis ( ) ) EncounterDiagnosis
            where EncounterDiagnosis.code in "Delivery of Singleton"
        )
    Library Name Name
    CesareanBirthFHIR Singleton Delivery Encounters at 37 Plus Weeks Gravida 1 Parity 0, No Previous Births
    define "Singleton Delivery Encounters at 37 Plus Weeks Gravida 1 Parity 0, No Previous Births":
      ( "Delivery Encounter with Gestational Age Greater than or Equal to 37 Weeks"
        intersect "Encounter with Singleton Delivery" ) SingletonEncounterGE37Weeks
        where ( ( SingletonEncounterGE37Weeks.lastGravida ( ) = 1 )
            or ( SingletonEncounterGE37Weeks.lastParity ( ) = 0 )
            or ( ( SingletonEncounterGE37Weeks.lastHistoryPretermBirth ( ) = 0 )
                and ( SingletonEncounterGE37Weeks.lastHistoryTermBirth ( ) = 0 )
            )
        )
    Library Name Name
    CesareanBirthFHIR Delivery Encounter with Cesarean Birth
    define "Delivery Encounter with Cesarean Birth":
      "Singleton Delivery Encounters at 37 Plus Weeks Gravida 1 Parity 0, No Previous Births" ThirtysevenWeeksPlusEncounter
        with ["Procedure": "Cesarean Birth"] CSection
          such that CSection.performed.toInterval ( ) during ThirtysevenWeeksPlusEncounter.hospitalizationWithEDOBTriageObservation ( )
            and CSection.status = 'completed'
    Library Name Name
    CesareanBirthFHIR Numerator
    define "Numerator":
      "Delivery Encounter with Cesarean Birth"
    Library Name Name
    CesareanBirthFHIR Denominator
    define "Denominator":
      "Singleton Delivery Encounters at 37 Plus Weeks Gravida 1 Parity 0, No Previous Births"
    Library Name Name
    SupplementalDataElements SDE Payer
    define "SDE Payer":
      [Coverage: type in "Payer Type"] Payer
        return {
          code: Payer.type,
          period: Payer.period
        }
    Library Name Name
    CesareanBirthFHIR SDE Payer
    define "SDE Payer":
      SDE."SDE Payer"
    Library Name Name
    CesareanBirthFHIR Initial Population
    define "Initial Population":
      PCMaternal."Delivery Encounter with Age Range"
    Library Name Name
    SupplementalDataElements SDE Ethnicity
    define "SDE Ethnicity":
      Patient.ethnicity E
        return Tuple {
          codes: { E.ombCategory } union E.detailed,
          display: E.text
        }
    Library Name Name
    CesareanBirthFHIR SDE Ethnicity
    define "SDE Ethnicity":
      SDE."SDE Ethnicity"
    Library Name Name
    CesareanBirthFHIR Encounter with Abnormal Presentation
    define "Encounter with Abnormal Presentation":
      "Singleton Delivery Encounters at 37 Plus Weeks Gravida 1 Parity 0, No Previous Births" ThirtysevenWeeksPlusEncounter
        let LastAbnormalPresentation: Last(["Observation": "Abnormal Presentation"] AbnormalPresentation
            where AbnormalPresentation.effective.earliest() before or on ThirtysevenWeeksPlusEncounter.lastTimeOfDelivery()
              and AbnormalPresentation.status in { 'final', 'amended', 'corrected' }
            sort by effective.earliest()
        )
        where LastAbnormalPresentation.effective.earliest ( ) during ThirtysevenWeeksPlusEncounter.period
          or exists ( ( ThirtysevenWeeksPlusEncounter.encounterDiagnosis ( ) ) EncounterDiagnosis
              where EncounterDiagnosis.code in "Abnormal Presentation"
          )
    Library Name Name
    CesareanBirthFHIR Encounter with Genital Herpes, Placenta Previa, Vasa Previa or Placenta Accreta Spectrum
    define "Encounter with Genital Herpes, Placenta Previa, Vasa Previa or Placenta Accreta Spectrum":
      "Singleton Delivery Encounters at 37 Plus Weeks Gravida 1 Parity 0, No Previous Births" ThirtysevenWeeksPlusEncounter
        where exists ( ( ThirtysevenWeeksPlusEncounter.encounterDiagnosis ( ) ) EncounterDiagnosis
            where EncounterDiagnosis.code in "Placenta Accreta Spectrum Previa or Vasa Previa"
              or EncounterDiagnosis.code in "Genital Herpes"
        )
    Library Name Name
    CesareanBirthFHIR Delivery Encounter with Abnormal Presentation, Genital Herpes, Placenta Previa, Vasa Previa or Placenta Accreta Spectrum
    define "Delivery Encounter with Abnormal Presentation, Genital Herpes, Placenta Previa, Vasa Previa or Placenta Accreta Spectrum":
      "Encounter with Abnormal Presentation"
        union "Encounter with Genital Herpes, Placenta Previa, Vasa Previa or Placenta Accreta Spectrum"
    Library Name Name
    CesareanBirthFHIR Denominator Exclusions
    define "Denominator Exclusions":
      "Delivery Encounter with Abnormal Presentation, Genital Herpes, Placenta Previa, Vasa Previa or Placenta Accreta Spectrum"
    Library Name Name
    SupplementalDataElements SDE Race
    define "SDE Race":
      Patient.race R
        return Tuple {
          codes: R.ombCategory union R.detailed,
          display: R.text
        }
    Library Name Name
    CesareanBirthFHIR SDE Race
    define "SDE Race":
      SDE."SDE Race"
    Library Name Name
    PCMaternal Variable Calculated Gestational Age
    define "Variable Calculated Gestational Age":
     // This definition establishes a variable of CGA (Calculated Gestational Age).  CGA is a supplemental data element to store the calculated gestational age result from the "CalculatedGestationalAge" function.  The data element enables the capturing and saving of the CGA for data analysis post data receipt. Hospitals do not need to submit any additional data to comply with this definition
      "Delivery Encounter with Age Range" DeliveryEncounter
        let CGA: DeliveryEncounter.calculatedGestationalAge()
      //  return { QualifyingEncounter, CGA }
        return {
          EncounterID: DeliveryEncounter.id,
          CalculatedCGA: CGA
        }
    Library Name Name
    CesareanBirthFHIR SDE Variable Calculated Gestational Age
    define "SDE Variable Calculated Gestational Age":
      PCMaternal."Variable Calculated Gestational Age"
    Library Name Name
    PCMaternal hospitalizationWithEDOBTriageObservation
    /*define function "HospitalizationWithEDOBTriageObservation"(Encounter Encounter ):
      HospitalizationWithEDOBTriageObservation returns the total interval from the start of any immediately prior emergency department visit or OB Triage visit through the observation visit to the discharge of the given encounter
      Encounter Visit
        let ObsVisit: Last(["Encounter": "Observation Services"] LastObs
            where LastObs.period ends 1 hour or less on or before start of Visit.period
              and LastObs.status = 'finished'
            sort by 
            end of period
        ),
        VisitStart: Coalesce(start of ObsVisit.period, start of Visit.period),
        EDOBTriageVisit: Last(["Encounter": "ED Visit and OB Triage"] LastEDOBTriage
            where LastEDOBTriage.period ends 1 hour or less on or before VisitStart
              and LastEDOBTriage.status = 'finished'
            sort by 
            end of period
        )
        return Interval[Coalesce(start of EDOBTriageVisit.period, VisitStart), 
        end of Visit.period]*/
        
        
    define fluent function hospitalizationWithEDOBTriageObservation (TheEncounter Encounter ):
      /*hospitalizationWithEDOBTriageObservation returns the total interval from the start of any immediately prior emergency department visit or OB Triage visit through the observation visit to the discharge of the given encounter*/
      TheEncounter Visit
        let ObsVisit: Last(["Encounter": "Observation Services"] LastObs
            where LastObs.period ends 1 hour or less on or before start of Visit.period
              and LastObs.status = 'finished'
            sort by 
            end of period
        ),
        VisitStart: Coalesce(start of ObsVisit.period, start of Visit.period),
        EDOBTriageVisit: Last(["Encounter": "ED Visit and OB Triage"] LastEDOBTriage
            where LastEDOBTriage.period ends 1 hour or less on or before VisitStart
              and LastEDOBTriage.status = 'finished'
            sort by 
            end of period
        )
        return Interval[Coalesce(start of EDOBTriageVisit.period, VisitStart), 
        end of Visit.period]
    Library Name Name
    PCMaternal calculatedGestationalAge
    define fluent function calculatedGestationalAge (TheEncounter Encounter ):
      //Gestational Age = (280-(Estimated Delivery Date minus Reference Date/Delivery Date))/7
     ( 280 - ( difference in days between TheEncounter.lastTimeOfDelivery () and TheEncounter.lastEstimatedDeliveryDate( )) ) div 7
    Library Name Name
    PCMaternal lastTimeOfDelivery
    define fluent function lastTimeOfDelivery (TheEncounter Encounter ):
      Last(["Observation": "Date and time of obstetric delivery"] TimeOfDelivery
          where TimeOfDelivery.value as DateTime is not null
            and TimeOfDelivery.status in { 'final', 'amended', 'corrected' }
            and TimeOfDelivery.effective.earliest () during TheEncounter.hospitalizationWithEDOBTriageObservation ()
            and TimeOfDelivery.value as DateTime during TheEncounter.hospitalizationWithEDOBTriageObservation()
          sort by effective.earliest()
      ).value as DateTime
    Library Name Name
    QICoreCommon earliest
    /*
    @description: Given an interval, return the starting point if the interval has a starting boundary specified,
    otherwise, return the ending point
    */
    define fluent function earliest(choice Choice<DateTime, Quantity, Interval<DateTime>, Interval<Quantity>> ):
      (choice.toInterval()) period
        return
          if (period."hasStart"()) then start of period
          else end of period
    Library Name Name
    PCMaternal lastEstimatedDeliveryDate
    /*===============================================================*/
      /*  03/14/2022 from MATGlobalCommonFunctionsv7.000 - latest QDM  */
      /*     even though this PCMaternalFHIR was derived from          */
      /*     PCMaternal=2.1.000 cql, to make next update easier.       */
      /*     Will need to re-insert "Global". in front of these        */
      /*     function names later (whereever they are directly used.*/
    
    define fluent function lastEstimatedDeliveryDate (TheEncounter Encounter ):
      /*This function identifies the last time the EDD was assessed 42 weeks or less prior to or on delivery and stores the result of that assessment.*/
      Last(["Observation": "Delivery date Estimated"] EstimatedDateOfDelivery
          where EstimatedDateOfDelivery.value as DateTime is not null
            and EstimatedDateOfDelivery.status in { 'final', 'amended', 'corrected' }
            and EstimatedDateOfDelivery.effective.earliest ( ) 42 weeks or less before or on TheEncounter.lastTimeOfDelivery ()
          sort by effective.earliest ( )
      ).value as DateTime
    Library Name Name
    PCMaternal lastEstimatedGestationalAge
    /*define fluent function lastEstimatedGestationalAge (TheEncounter Encounter ):
      Last(["Observation": "Estimated Gestational Age at Delivery"] EstimatedGestationalAge
          where EstimatedGestationalAge.value is not null
            and EstimatedGestationalAge.status in { 'final', 'amended', 'corrected' }
            and EstimatedGestationalAge.effective.earliest() 24 hours or less before or on TheEncounter.lastTimeOfDelivery ()
          sort by effective.earliest ()
      ).value as Quantity*/
      
      define fluent function lastEstimatedGestationalAge (TheEncounter Encounter ):
      Last(["Observation": "Estimated Gestational Age at Delivery"] EstimatedGestationalAge
      let EGATiming:  EstimatedGestationalAge.effective.earliest() where 
      (EGATiming 24 hours or less before or on TheEncounter.lastTimeOfDelivery () 
      and EstimatedGestationalAge.value is not null 
      and EstimatedGestationalAge.status in { 'final', 'amended', 'corrected' }) or 
          (EGATiming same day as TheEncounter.lastTimeOfDelivery () 
          and EGATiming during TheEncounter.hospitalizationWithEDOBTriageObservation() 
          and EstimatedGestationalAge.value is not null)
     sort by effective.earliest ())
             .value as Quantity
    Library Name Name
    CQMCommon encounterDiagnosis
    /*
    @description: Returns the Condition resources referenced by the diagnosis element of the Encounter
    */
    define fluent function encounterDiagnosis(Encounter Encounter ):
      Encounter.diagnosis D
        return singleton from ([Condition] C where C.id = D.condition.reference.getId())
    Library Name Name
    QICoreCommon getId
    /*
    @description: Returns the tail of the given uri (i.e. everything after the last slash in the URI).
    @comment: This function can be used to determine the logical id of a given resource. It can be used in
    a single-server environment to trace references. However, this function does not attempt to resolve
    or distinguish the base of the given url, and so cannot be used safely in multi-server environments.
    */
    define fluent function getId(uri String):
      Last(Split(uri, '/'))
    Library Name Name
    CesareanBirthFHIR lastGravida
    //       and EncounterDiagnoses.verificationStatus  ~ FHIRCommon."confirmed"
    
    
    define fluent function lastGravida(TheEncounter Encounter):
      Last(["Observation": "[#] Pregnancies"] Gravida
          where Gravida.value is not null
            and Gravida.status in { 'final', 'amended', 'corrected' }
            and Gravida.effective.earliest() 42 weeks or less before TheEncounter.lastTimeOfDelivery()
          sort by effective.earliest()
      ).value as Integer
    Library Name Name
    CesareanBirthFHIR lastParity
    define fluent function lastParity(TheEncounter Encounter):
      Last(["Observation": "[#] Parity"] Parity
          where Parity.effective.earliest() 42 weeks or less before TheEncounter.lastTimeOfDelivery()
            and Parity.status in { 'final', 'amended', 'corrected' }
            and Parity.value is not null
          sort by effective.earliest()
      ).value as Integer
    Library Name Name
    CesareanBirthFHIR lastHistoryPretermBirth
    define fluent function lastHistoryPretermBirth(TheEncounter Encounter):
      Last(["Observation": "[#] Births.preterm"] PretermBirth
          where PretermBirth.effective.earliest() 42 weeks or less before TheEncounter.lastTimeOfDelivery()
            and PretermBirth.status in { 'final', 'amended', 'corrected' }
            and PretermBirth.value is not null
          sort by effective.earliest()
      ).value as Integer
    Library Name Name
    CesareanBirthFHIR lastHistoryTermBirth
    define fluent function lastHistoryTermBirth(TheEncounter Encounter):
      Last(["Observation": "[#] Births.term"] TermBirth
          where TermBirth.effective.earliest() 42 weeks or less before TheEncounter.lastTimeOfDelivery()
            and TermBirth.status in { 'final', 'amended', 'corrected' }
            and TermBirth.value is not null
          sort by effective.earliest()
      ).value as Integer
    Library Name Name
    FHIRHelpers ToString
    define function ToString(value uri): value.value
    Library Name Name
    FHIRHelpers ToCode
    /*
    @description: Converts the given FHIR [Coding](https://hl7.org/fhir/datatypes.html#Coding) value to a CQL Code.
    */
    define function ToCode(coding FHIR.Coding):
        if coding is null then
            null
        else
            System.Code {
              code: coding.code.value,
              system: coding.system.value,
              version: coding.version.value,
              display: coding.display.value
            }