def build_stage_1():
    """
    In stage 1 of generation we:
    1. Get the initial HEI Encounters
    2. Create a RegistryEntry for each one
    3. Calculate the age of the child at HEI presentation for each one
    4. Check if the mother is linked
    5. Add the obs for the HEI initial encounter

    Essentially, we do anything we can that's on the HEI form (except maybe
    format the actual defects in the event that there are some). Also, we see
    if we can link the mom.
    """
    # 1
    hei_enc = get_hei_encounters()
    # 2
    for enc in hei_enc:
        entry = RegistryEntry()
        entry.site = RegistryEntry.SITE_FACES
        entry.child_id = enc.patient_id
        entry.cohort_date = enc.encounter_datetime.date()
        # TODO May need to add a check to look at the section titled:
        # FINAL HEI OUTCOMES AT EXIT
        entry.outcome = RegistryEntry.OUTCOME_LIVE
        entry.date_of_outcome = enc.patient.patient.birthdate
        entry.gender = enc.patient.patient.gender
        entry.check_initial_paeds_lookup = True
        # 3
        entry.age_first_seen = (entry.cohort_date - entry.date_of_outcome).days
        # 4
        entry.save(using=APR_DB)
        mom = get_mom(entry.child_id)
        if mom != None:
            entry.mother_id = mom
            entry.check_mother_linked = True
            mom_patient = Patient.objects.using(FACES_OPENMRS_DB).get(pk=entry.mother_id)
            for mom_enc in mom_patient.encounter_set.all():
                encounter_to_encobs(entry, mom_enc, link_field='mother_entry')
            entry.check_added_moms_obs = True
        else:
            entry.voided = True
            entry.voided_reason = RegistryEntry.VOIDED_MOTHER_NOT_LINKED
        entry.save(using=APR_DB)
        set_mother_values(entry)
        # 5
        encounter_to_encobs(entry, enc)
        entry.check_added_child_obs = True
        set_child_values(entry)
        entry.save(using=APR_DB)
def set_non_livebirth_entry(outcome_type, enc):
    """
    Encounter is the blue card from when the mother had a marked
    stillborn/miscarriage etc.
    """
    entry = RegistryEntry()
    entry.site = RegistryEntry.SITE_FACES
    entry.cohort_date = enc.encounter_datetime.date()
    entry.outcome = outcome_type
    entry.date_of_outcome = enc.encounter_datetime.date()
    entry.save(using=APR_DB)
    for mom_enc in enc.patient.encounter_set.all():
        encounter_to_encobs(entry, mom_enc, link_field='mother_entry')
    entry.check_added_moms_obs = True
    try:
        set_mother_values(entry)
    except Patient.DoesNotExist:
        entry.voided = True
        entry.voided_reason = RegistryEntry.VOIDED_STILLBIRTH_MOTHER_MISSING
    entry.save(using=APR_DB)