diff --git a/.github/workflows/openfn-a5573c8f-bfbd-447e-8e1d-5bab1d2901e7-deploy.yml b/.github/workflows/openfn-a5573c8f-bfbd-447e-8e1d-5bab1d2901e7-deploy.yml new file mode 100644 index 0000000..a8b868f --- /dev/null +++ b/.github/workflows/openfn-a5573c8f-bfbd-447e-8e1d-5bab1d2901e7-deploy.yml @@ -0,0 +1,21 @@ +on: + push: + branches: + - v2_staging + +concurrency: + group: openfn-deployment + cancel-in-progress: false + +jobs: + deploy-to-lightning: + runs-on: ubuntu-latest + name: A job to deploy to Lightning + permissions: + contents: write + steps: + - name: openfn deploy + uses: openfn/cli-deploy-action@v1.0.0 + with: + secret_input: ${{ secrets.OPENFN_a5573c8f_bfbd_447e_8e1d_5bab1d2901e7_API_KEY }} + config_path_input: 'openfn-a5573c8f-bfbd-447e-8e1d-5bab1d2901e7-config.json' diff --git a/README.md b/README.md index 79d6609..7e93566 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,9 @@ Lwala uses OpenFn to integrate its Salesforce database and CommCare CHW mobile application. The OpenFn jobs in this repository automate a bi-directional dataflow between the CommCare and Salesforce systems, ensuring regular data syncs and feedback loops for CHWs. -*N.B. Any commits to the `master` branch will be automatically deployed to -Lwala's OpenFn project* +## Notes on Version Control + +Lwala is running on OpenFn v2, and is being backed up on the `v2_staging` branch. What currently is on the `master` branch is a *snapshot* of the project/the `v2_staging` branch. Any live changes going forward will be synced to `v2_staging`. ## Worflows OpenFn jobs are used to automate the following workflows between CommCare and Salesforce. This integration is event-driven (triggered whenever a record is created/ updated). [This diagram](https://lucid.app/lucidchart/e3411bda-1f0e-492f-b35d-6baf2dd3972a/edit?view_items=laxJTiq3D_aN&invitationId=inv_269ce3a1-612b-49b8-ab06-4805e3e483de#) provides an overview of how data flows from CommCare forms to Salesforce objects through OpenFn jobs. diff --git a/openfn-a5573c8f-bfbd-447e-8e1d-5bab1d2901e7-config.json b/openfn-a5573c8f-bfbd-447e-8e1d-5bab1d2901e7-config.json new file mode 100644 index 0000000..3e15003 --- /dev/null +++ b/openfn-a5573c8f-bfbd-447e-8e1d-5bab1d2901e7-config.json @@ -0,0 +1,5 @@ +{ + "endpoint": "https://app.openfn.org", + "specPath": "openfn-a5573c8f-bfbd-447e-8e1d-5bab1d2901e7-spec.yaml", + "statePath": "openfn-a5573c8f-bfbd-447e-8e1d-5bab1d2901e7-state.json" +} \ No newline at end of file diff --git a/openfn-a5573c8f-bfbd-447e-8e1d-5bab1d2901e7-spec.yaml b/openfn-a5573c8f-bfbd-447e-8e1d-5bab1d2901e7-spec.yaml new file mode 100644 index 0000000..c04d187 --- /dev/null +++ b/openfn-a5573c8f-bfbd-447e-8e1d-5bab1d2901e7-spec.yaml @@ -0,0 +1,8238 @@ +name: lwala-chw-support +description: null +credentials: + "aleksa@openfn.org-Lwala-CommCare-HQ---openfn-user-": + name: 'Lwala CommCare HQ - openfn user ' + owner: aleksa@openfn.org + aleksa@openfn.org-Lwala-Salesforce-Prod---openfn-user: + name: Lwala Salesforce Prod - openfn user + owner: aleksa@openfn.org + rita@openfn.org-Lwala-Case-Endpoint-Test-User-HTTP: + name: Lwala Case Endpoint Test User HTTP + owner: rita@openfn.org + "rita@openfn.org-Lwala-Salesforce-Sandbox-(April-2024)": + name: 'Lwala Salesforce Sandbox (April 2024)' + owner: rita@openfn.org + rita@openfn.org-Lwala-case-endpoint-production-user: + name: Lwala case endpoint production user + owner: rita@openfn.org + rita@openfn.org-Lwala-cases-endpoint-test-user: + name: Lwala cases endpoint test user + owner: rita@openfn.org +workflows: + 1-Bulk-HH-cases: + name: 1-Bulk HH cases + jobs: + WF1-1-Bulk-get-HH-cases: + name: WF1-1 Bulk get HH cases + adaptor: '@openfn/language-http@6.5.1' + credential: rita@openfn.org-Lwala-case-endpoint-production-user + body: | + // comment + fn(state => { + const { baseUrl } = state.configuration; + + const caseTypes = ['Household']; + + //NOTE: You can use 'limit' to modify this batch size as desired + const limit = 1000; + + //NOTE: indexedOnStart is the default sync start data the FIRST time the job runs + const indexedOnStart = '2022-01-18T10:00:00'; + + //NOTE: After first job run, OpenFn will check the job sync data ("lastRunAt") to set as the indexedOnStart + const lastRunAt = + typeof state.lastRunAt !== 'undefined' ? state.lastRunAt : indexedOnStart; + console.log('Filtering cases with indexed_on_start > than ::', lastRunAt); + //May 31st, 2023 at 3:00:13 PM. + const queries = caseTypes.map( + t => `?type=${t}&indexed_on_start=${lastRunAt}&limit=${limit} + &owner_id=a3c31c9be392427a97f8704262065661` // User id of test user test.2021. Remove for production + + //NOTE: If for testing, you want to fetch data for a specific historical range (e.g., between April 23 and 24)... + //...then use the query string below instead of the one above on L16, and custom adjust the index_on start/end dates + //t => `?type=${t}&indexed_on_start=2023-03-03T00:00:00&limit=${limit}&indexed_on_end=2023-03-06T00:00:00` //returns 14 records + // t => `?type=${t}&indexed_on_start=2024-01-15T15:00:00&limit=${limit}&indexed_on_end=2024-01-16T23:59:59` + ); + + return { ...state, queries, baseUrl, payloads: [] }; + }); + + // create a "recursiveGet" which will call itself if CommCare tells us there's + // more data to fetch for the same form + fn(state => { + const recursiveGet = url => + get( + url, + { + headers: { 'content-type': 'application/json' }, + }, + nextState => { + const now = new Date(); + const { baseUrl, data, payloads } = nextState; + + const { meta, objects } = data; + console.log('Metadata in CommCare response:', meta); + + const finalState = { + ...nextState, + payloads: [...payloads, ...objects], + }; + + if (meta.next) { + console.log('Next query detected, recursing...'); + return recursiveGet(`${baseUrl}${meta.next}`)(finalState); + } + finalState.lastRunAt = now.toISOString().slice(0, 19); + return finalState; + } + ); + + return { ...state, recursiveGet }; + }); + + // for each initial query, fetch data recursively + each( + '$.queries[*]', + fn(state => { + return state.recursiveGet(`${state.baseUrl}${state.data}`)(state); + }) + ); + // log the total number of payloads returned + fn(state => { + console.log('Count of payloads', state.payloads.length); + console.log(state.data); + + return { ...state, references: [], data: {} }; + }); + + WF1-2-Bulk-upsert-HHs-and-HH-Visits: + name: WF1-2 Bulk upsert HHs and HH Visits + adaptor: '@openfn/language-salesforce@4.8.6' + credential: aleksa@openfn.org-Lwala-Salesforce-Prod---openfn-user + body: | + fn(state => { + if (state.payloads.length == 0) + return { ...state, housevisits: [], households: [] }; + + const owner_ids = state.payloads.map(data => data.properties.owner_id); + const uniq_owner_ids = [...new Set(owner_ids)]; + + return { ...state, uniq_owner_ids }; + }); + + + fn(state => { + if (state.payloads.length == 0) return state; + + return query( + `SELECT CommCare_User_ID__c, Id village, Parent_Geographic_Area__c area, Parent_Geographic_Area__r.Name name, Parent_Geographic_Area__r.Parent_Geographic_Area__c catchment FROM Location__c catchment WHERE CommCare_User_ID__c IN ('${state.uniq_owner_ids.join( + "','" + )}') GROUP BY Id, CommCare_User_ID__c, Parent_Geographic_Area__c, Parent_Geographic_Area__r.Name, Parent_Geographic_Area__r.Parent_Geographic_Area__c` + )(state); + }); + + fn(state => { + if (state.payloads.length == 0) return state; + + console.log('Done querying ✅'); + + return state; + }); + + fn(state => { + if (state.payloads.length == 0) return state; + + console.log( + 'Filtering out unwanted users and applying mapping for households and housevisits' + ); + + const [reference] = state.references; + + //HMN 06/11/2023 + // console.log(JSON.stringify(reference.records, null, 2)); + + const records = reference.records; + const fetchReference = (owner_id, arg) => { + const result = + records && records.length > 0 + ? records.filter(record => record.CommCare_User_ID__c === owner_id) + : 0; + + //TODO: Update default value for 'unknown location' before go-live + return result.length > 0 + ? result[0][arg] + : 'a000800001tMobaAAC' /*unknown location*/; + }; + + const supervisorMap = { + community_health_nurse: 'Community Health Nurse', + chw_supervisor: 'CHW Supervisor', + chewschas: 'CHEWs/CHAs', + other: 'Other', + none: 'None', + }; + + const insuranceMap = { + nhif: 'NHIF', + Linda_mama: 'Linda mama', + other_please_specify_if_active: 'Other', + none: 'None', + }; + + const households = state.payloads + /* HMN 050723 + .filter( + h => + h.properties.commcare_username !== 'openfn.test' && + h.properties.commcare_username !== 'test.2021' && + h.properties.test_user !== 'Yes' + ) + */ + .map(h => { + // Special calculations ================================================== + const insuranceStatus = h.properties.health_insurance; + const Health_insurance_type__c = + insuranceStatus && insuranceStatus === 'other_please_specify_if_active' + ? 'Other' + : insuranceStatus === 'nhif' + ? 'NHIF' + : insuranceStatus === 'Linda_mama' || 'linda_mama' + ? 'Linda mama' + : insuranceStatus; + + const hhStatus = h.properties.Household_Status; + const Active_Household__c = + hhStatus && hhStatus === 'No' + ? false + : hhStatus === 'Yes' + ? true + : hhStatus; + + const reason = h.properties.Reason_for_Inactive; + const Inactive_Reason__c = reason + ? reason.toString().replace(/_/g, ' ') + : null; + //HMN 06/11/2023 + // console.log(JSON.stringify(h.properties, null, 2)); + /*HMN remove this dependancy 07/07/2023 + const chw = h.properties.CHW_ID; + const Household_CHW__c = + chw === 'a030800001zQrk' ? 'a030800001zQrk5' : chw ? chw : undefined; + // ======================================================================= + */ + + return { + CommCare_Username__c: h.properties.commcare_username, + MOH_household_code__c: h.properties.moh_code, + CommCare_Code__c: h.case_id, + Source__c: true, + // TODO: Prod mapping to add back before go-live ======================= + Household_CHW__c: h.properties.CHW_ID, // Uncomment me to go live! + //Household_CHW__c: 'a032400000GHpdsAAD', // Comment me OUT to go live! + // Household_CHW__c: 'a03AW00000643nLYAQ', + // ===================================================================== + Catchment__c: fetchReference(h.properties.owner_id, 'catchment'), + Area__c: fetchReference(h.properties.owner_id, 'area'), + Village__c: fetchReference(h.properties.owner_id, 'village'), + Household_Village__c: h.properties.village, + Deaths_in_the_last_6_months__c: + h.properties.deaths_in_past_6_months > 0 ? 'Yes' : 'No', + Access_to_safe_water__c: h.properties.Safe_Water, + Treats_Drinking_Water__c: h.properties.Treats_Drinking_Water, + Tippy_Tap__c: h.properties.Active_Handwashing_Station, + Pit_Latrine__c: h.properties.Functional_Latrine, + Rubbish_Pit__c: h.properties.Rubbish_Pit, + Drying_Rack__c: h.properties.Drying_Rack, + Kitchen_Garden__c: h.properties.Kitchen_Garden, + Cookstove__c: h.properties.Improved_Cooking_Method, + Clothe__c: h.properties.Clothesline, + WASH_Trained__c: h.properties.WASH_Trained, + Uses_ITNs__c: h.properties.ITNs, + Has_muac_tape__c: h.properties.family_muac_tape_available, + Health_insurance__c: h.properties.health_insurace_cover, + Health_insurance_active_status__c: h.properties.healthinsurance_active, + Health_insurance_type__c, + Other_Health_Insurance__c: h.properties.if_other_please_specify, + Work_with_TBA__c: h.properties.tba, + TBA_name__c: h.properties.which_tba, + Last_Modified_Date_CommCare__c: h.server_date_modified, //Need a case property, + Active_Household__c, + Inactive_Reason__c, + Active_in_Nutrition_Program__c: + h.properties.enrolled_in_a_lwala_nutrition_program, + lwala_nutrition_program_enrollment_date__c: + h.properties.lwala_nutrition_program_enrollment_date, + Trained_in_gardening__c: h.properties.household_trained_on_gardening, + household_trained_on_gardening_date__c: + h.properties.when_was_the_household_trained_on_gardening, + Seed_Input_Support__c: + h.properties.household_provided_with_seed_input_support, + household_provided_with_seed_input_suppo__c: + h.properties.when_was_the_household_provided_with_seed_input_support, + MIYCN_Trained__c: h.properties.household_trained_on_MIYC, + // TODO: @Aleksa to find out if Case_Closed_Date__c still exist + Case_Closed_Date__c: h.date_closed //&& h.date_closed == true + ? h.date_closed + : undefined + }; + }); + + const housevisits = state.payloads + //HMN remove test user filters + /* + .filter( + h => + h.properties.commcare_username !== 'openfn.test' && + h.properties.commcare_username !== 'test.2021' && + h.properties.test_user !== 'Yes' + )*/ + .map(h => { + // Special calculations ================================================== + + + const visitIdC = + h.case_id + '_' + h.properties.last_form_opened_date_and_time; + + const hVstatus = h.properties.Household_Status; + const Active_Household__c = + hVstatus === 'No' ? false : hVstatus === 'Yes' ? true : hVstatus; + + const insuranceTypeC = () => { + let status = h.properties.health_insurance; + + let value = + status && status !== '' + ? status + .replace(/ /gi, ';') + .split(';') + .map(value => { + return insuranceMap[value] || value; + }) + : undefined; + return value ? value.join(';') : undefined; + }; + + const openedC = () => { + const form_opened = h.properties.last_form_opened_date_and_time; + + if (form_opened) { + const value1 = form_opened.split('-').slice(0, 2).join('-'); + const value2 = form_opened.split('-').slice(2).join('-'); + const formattedValue = [value1, value2].join(' '); + return new Date(formattedValue).toISOString(); + } + return undefined; + }; + + return { + CommCare_Username__c: h.properties.commcare_username, + CommCare_Visit_ID__c: visitIdC, + Catchment__c: fetchReference(h.properties.owner_id, 'catchment'), + 'Household__r.CommCare_Code__c': h.case_id, + Date__c: h.properties.Date, + Form_Submitted__c: h.properties.last_form_opened_name, + Active_Household__c: Active_Household__c, + Active_in_Nutrition_Program__c: + h.properties.enrolled_in_a_lwala_nutrition_program, + lwala_nutrition_program_enrollment_date__c: + h.properties.lwala_nutrition_program_enrollment_date, + Trained_in_gardening__c: h.properties.household_trained_on_gardening, + household_trained_on_gardening_date__c: + h.properties.when_was_the_household_trained_on_gardening, + Seed_Input_Support__c: + h.properties.household_provided_with_seed_input_support, + household_provided_with_seed_input_suppo__c: + h.properties.when_was_the_household_provided_with_seed_input_support, + MIYCN_Trained__c: h.properties.household_trained_on_MIYCN, + Kitchen_Garden__c: h.properties.Kitchen_Garden, + Access_to_safe_water__c: h.properties.Safe_Water, + Treats_Drinking_Water__c: h.properties.Treats_Drinking_Water, + Tippy_Tap__c: h.properties.Active_Handwashing_Station, + Pit_Latrine__c: h.properties.Functional_Latrine, + Rubbish_Pit__c: h.properties.Rubbish_Pit, + Drying_Rack__c: h.properties.Drying_Rack, + Cookstove__c: h.properties.Improved_Cooking_Method, + Clothe__c: h.properties.Clothesline, + WASH_Trained__c: h.properties.WASH_Trained, + Has_muac_tape__c: h.properties.family_muac_tape_available, + Uses_ITNs__c: h.properties.ITNs, + Supervisor_Visit__c: h.properties.supervisor_visit + ? supervisorMap[h.properties.supervisor_visit] + : null, + Health_insurance__c: h.properties.health_insurace_cover, + Health_insurance_active_status__c: h.properties.healthinsurance_active, + Health_insurance_type__c: insuranceTypeC(), + + Other_Health_Insurance__c: h.properties.if_other_please_specify, + CommCare_Form_Opened__c: openedC(), + + }; + }); + + return { ...state, households, housevisits, fetchReference }; + }); + + //JSON logging of records + //HMN 06/11/2023 + /*fn(state => { + console.log('HHs to upsert ::', JSON.stringify(state.households)); + return state; + });*/ + + + bulk( + 'Household__c', + 'upsert', + { + extIdField: 'CommCare_Code__c', + failOnError: true, + allowNoOp: true, + }, + state => { + console.log('Bulk upserting households...'); + return state.households; + } + ); + + fn(state => { + if (state.payloads.length == 0) return state; + + console.log('house holds bulk upsert done'); + return state; + }); + + // TODO clean up in QA used for troubleshooting + // Uncomment this block to add cooldown + // fn(state => { + // return new Promise((resolve, reject) => { + // setTimeout(() => { + // console.log('4 second cooldown finished.'); + // resolve(state); + // }, 4000); + // }); + // }); + + bulk( + 'Visit__c', + 'upsert', + { + extIdField: 'CommCare_Visit_ID__c', + failOnError: true, + allowNoOp: true, + }, + state => { + console.log('Bulk upserting housevisits...'); + return state.housevisits; + } + ); + + fn(state => { + if (state.payloads.length == 0) return state; + console.log('house visits bulk upsert done'); + return state; + }); + + // TODO clean up in QA for troubleshooting + // Uncomment this block to add cooldown + // fn(state => { + // return new Promise((resolve, reject) => { + // setTimeout(() => { + // console.log('Final 4 second cooldown finished.'); + // resolve(state); + // }, 4000); + // }); + // }); + + triggers: + cron: + type: cron + cron_expression: '0 * * * *' + enabled: true + edges: + cron->WF1-1-Bulk-get-HH-cases: + source_trigger: cron + target_job: WF1-1-Bulk-get-HH-cases + condition_type: always + enabled: true + WF1-1-Bulk-get-HH-cases->WF1-2-Bulk-upsert-HHs-and-HH-Visits: + source_job: WF1-1-Bulk-get-HH-cases + target_job: WF1-2-Bulk-upsert-HHs-and-HH-Visits + condition_type: on_job_success + enabled: true + 2-Bulk-Person-cases: + name: 2-Bulk Person cases + jobs: + WF2-1-Bulk-get-Person-cases: + name: WF2-1 Bulk get Person cases + adaptor: '@openfn/language-http@6.5.1' + credential: rita@openfn.org-Lwala-case-endpoint-production-user + body: | + fn(state => { + const { baseUrl } = state.configuration; + + const caseTypes = ['Person']; + + //NOTE: You can use 'limit' to modify this batch size as desired + const limit = 1000; //E.g., change to 10 to process records in smaller batch sizes + + //NOTE: indexedOnStart is the default sync start data the FIRST time the job runs + const indexedOnStart = '2021-01-17T00:00:00'; + + + //NOTE: After first job run, OpenFn will check the job sync data ("lastRunAt") to set as the indexedOnStart + const lastRunAt = + typeof state.lastRunAt !== 'undefined' ? state.lastRunAt : indexedOnStart; + console.log('Filtering cases with indexed_on_start > than ::', lastRunAt); + + const queries = caseTypes.map( + t => `?type=${t}&indexed_on_start=${lastRunAt}&limit=${limit} + &owner_id=a3c31c9be392427a97f8704262065661` // User id of test user test.2021. Remove for production + //NOTE: If for testing, you want to fetch data for a specific historical range (e.g., between April 23 and 24)... + //...then use the query string below instead of the one above on L16, and custom adjust the index_on start/end dates + // t => `?type=${t}&indexed_on_start=2024-01-16T00:00:00&limit=${limit}&indexed_on_end=2024-01-16T23:59:59` + ); + + return { ...state, queries, baseUrl, payloads: [] }; + }); + + // create a "recursiveGet" which will call itself if CommCare tells us there's + // more data to fetch for the same form + fn(state => { + const recursiveGet = url => + get( + url, + { + headers: { 'content-type': 'application/json' }, + }, + nextState => { + const now = new Date(); + const { baseUrl, data, payloads } = nextState; + + const { meta, objects } = data; + console.log('Metadata in CommCare response:', meta); + + const finalState = { + ...nextState, + payloads: [...payloads, ...objects], + }; + + if (meta.next) { + console.log('Next query detected, recursing...'); + return recursiveGet(`${baseUrl}${meta.next}`)(finalState); + } + finalState.lastRunAt = now.toISOString().slice(0, 19); + return finalState; + } + ); + + return { ...state, recursiveGet }; + }); + + // for each initial query, fetch data recursively + each( + '$.queries[*]', + fn(state => { + return state.recursiveGet(`${state.baseUrl}${state.data}`)(state); + }) + ); + // log the total number of payloads returned + fn(state => { + console.log('Count of payloads', state.payloads.length); + //HMN 11072023 + // console.log(JSON.stringify(state.payloads, null, 2)); + + return { ...state, references: [], data: {} }; + }); + + WF2-2-Bulk-upsert-Persons: + name: WF2-2 Bulk upsert Persons + adaptor: '@openfn/language-salesforce@4.8.6' + credential: aleksa@openfn.org-Lwala-Salesforce-Prod---openfn-user + body: | + fn(state => { + if (state.payloads.length == 0) + return { + ...state, + householdMapping: [], + headOfHouseholdMapping: [], + motherMapping: [], + caregiverMapping: [], + sfRecordMapping: [], + }; + // JSON logging of records + //HMN debug + //console.log('cases before query :: ', JSON.stringify(state.payloads, null, 2)); + const owner_ids = state.payloads.map(data => data.properties.owner_id); + const uniq_owner_ids = [...new Set(owner_ids)]; + + return { ...state, uniq_owner_ids }; + }); + + // get data from SF + fn(state => { + if (state.payloads.length == 0) return state; + + return query( + `SELECT CommCare_User_ID__c, Id village, Parent_Geographic_Area__c area, Parent_Geographic_Area__r.Name name, Parent_Geographic_Area__r.Parent_Geographic_Area__c catchment FROM Location__c WHERE CommCare_User_ID__c IN ('${state.uniq_owner_ids.join( + "','" + )}') GROUP BY Id, CommCare_User_ID__c, Parent_Geographic_Area__c, Parent_Geographic_Area__r.Name, Parent_Geographic_Area__r.Parent_Geographic_Area__c` + )(state); + }); + + fn(state => { + if (state.payloads.length == 0) return state; + + const [reference] = state.references; + + // console.log(JSON.stringify(reference.records, null, 2)); + + const records = reference.records; + const fetchReference = (owner_id, arg) => { + const result = + records && records.length > 0 + ? records.filter(record => record.CommCare_User_ID__c === owner_id) + : 0; + + //TODO: Update default value for 'unknown location' before go-live + return result.length > 0 ? result[0][arg] + : 'a000800001tMobaAAC' /*unknown location*/; + + }; + + const cleanChoice = choice => { + if (choice) { + return choice.charAt(0).toUpperCase() + choice.slice(1).replace('_', ' '); + } else { + return ''; + } + }; + + const handleMultiSelect = multiField => { + return multiField + ? multiField + .replace(/ /gi, ';') + .toLowerCase() + .split(';') + .map(value => { + return ( + value.charAt(0).toUpperCase() + value.slice(1).replace('_', ' ') + ); + }) + .join(';') + : ''; + }; + + const pregDangerMap = { + Vaginal_Bleeding: 'Vaginal Bleeding', + Water_Breaks: 'Water Breaks before Time of Delivery', + Prolonged_Labour: 'Prolonged Labour over 12 Hours', + Convulsions: 'Convulsions or Fits', + Abdominal_Pain: 'Severe Abdominal Pain before Delivery', + High_Fever: 'High Fever', + Low_Baby_Movement: 'Feeling the Baby move less or not at all', + Swelling: 'Swelling of Face and Hands', + Severe_Headache: 'Severe or Continuous Headache for more than 12 hours', + Severe_Vomiting: 'Severe or Continuous Vomiting', + none: 'None', + }; + + const counselMap = { + anc_visits: 'ANC Visits', + early_initiation_of_anc_less_than_3_months: + 'Early initiation of ANC (less than 3 months)', + completing_recomended_anc_visits: 'Completing recomended ANC visits', + danger_signs: 'Danger signs', + skilled_birth: 'Skilled birth', + immunization: 'Immunization', + individual_birth_plan: 'Individual Birth Plan', + emergency_preparedness: 'Emergency preparedness', + childcare_and_affection: 'Childcare and affection', + nutrition_counseling: 'Nutrition counseling', + growth_monitoring: 'Growth monitoring', + exclusive_breastfeeding: 'Exclusive breastfeeding', + complementary_feeding: 'Complementary feeding', + sleeping_under_llitn: 'Sleeping under LLITN', + knowing_hiv_status: 'Knowing HIV status', + indoor_pollution: 'Indoor pollution', + personal_hygiene: 'Personal Hygiene', + safe_drinking_water: 'Safe drinking water', + safe_disposal_of_human_waste: 'Safe disposal of human waste', + }; + + const serviceMap = { + Scheduled_PSC_Apt: 'Scheduled PSC Apt', + Adverse_Drug_Reaction_Side_Effect: 'Adverse Drug Reaction/Side Effect', + Malnutrition: 'Malnutrition', + Malaria: 'Malaria', + TB: 'TB', + Treatment_for_Other_OIs: 'Treatment for other Ols', + ARI: 'ARI', + Anemia: 'Anemia', + Diarrhea: 'Diarrhea', + Pregnancy_Care: 'Pregnancy Care (ANC)', + Family_Planning: 'Family Planning (FP)', + Preconception_Counseling: 'Preconception Counseling', + Injury: 'Injury', + Other: 'Other', + }; + + const reasonMapping = { + lack_of_access_to_fp_information: 'Lack of access to FP information', + no_access_to_fp_services_hospitals: + 'Lack of hospitals or places where FP services can be accessed', + not_willing_to_use_fp_due_to_negative_effects_myths_and_misconceptions: + 'Myths and misconceptions', + barriers_at_service_delivery_points: 'Barriers at service delivery points', + pregnant: 'The client is pregnant', + intentions_of_getting_pregnant: 'Intentions of getting pregnant', + not_sexually_active: 'The client is not sexually active', + other_barriers_culture_male_partners_parents_etc: + 'Other barriers (culture, male partners, parents, etc)', + }; + + const milestoneTypeMap = { + cognitive_delays_learning_difficulties: + 'Cognitive Delays Learning Difficulties', + motor_delays: 'Motor Delays', + speech_and_language_delay: 'Delay Speech and Language Delay', + social_and_emotional: 'Social and emotional', + }; + + const milestoneMap = { + movement: 'Movement', + hearing: 'Hearing', + communication: 'Communication', + seeing: 'Seeing', + cognitive_delays: 'Cognitive Delays', + play: 'Play', + }; + const nutritionMap = { + severe: 'Severely Malnourished', + moderate: 'Moderately Malnourished', + normal: 'Normal', + }; + + const fpMethodMap = { + male_condoms: 'Male condoms', + female_condoms: 'Female condoms', + pop: 'POP', + coc: 'COC', + emergency_pills: 'Emergency pills', + none: 'None', + }; + + return { + ...state, + counselMap, + serviceMap, + reasonMapping, + milestoneTypeMap, + milestoneMap, + nutritionMap, + pregDangerMap, + fpMethodMap, + cleanChoice, + handleMultiSelect, + fetchReference, + }; + }); + + // build sfRecord before upserting + fn(state => { + if (state.payloads.length == 0) return state; + + const { + counselMap, + reasonMapping, + milestoneTypeMap, + milestoneMap, + nutritionMap, + pregDangerMap, + fpMethodMap, + cleanChoice, + handleMultiSelect, + fetchReference, + } = state; + + const householdMapping = [ + ...new Map( + state.payloads + .filter( + p => + p.indices.parent.case_id !== undefined && + p.indices.parent.case_id !== '' + ) + .map(p => { + return { + CommCare_Code__c: + p.indices.parent.case_id || p.properties.parent_id, + }; + }) + .map(h => [h.CommCare_Code__c, h]) + ).values(), + ]; + + const headOfHouseholdMapping = state.payloads + .filter( + p => + p.properties.head_of_household_case_id !== undefined && + p.properties.head_of_household_case_id !== '' + ) + .map(p => { + return { + CommCare_Code__c: p.indices.parent.case_id || p.properties.parent_id, + 'Head_of_Household__r.CommCare_ID__c': + p.properties.head_of_household_case_id, + }; + }); + + const motherMapping = state.payloads + .filter( + p => + /*HMN 050723 p.properties.commcare_username !== 'test.2021' && + p.properties.test_user !== 'Yes' && + */ + p.properties.mother_case_id !== undefined && + p.properties.mother_case_id !== '' && + p.case_id!== undefined + ) + .map(p => { + return { + 'Mother__r.CommCare_ID__c': p.properties.mother_case_id, + CommCare_ID__c: p.case_id, + }; + }); + + const caregiverMapping = state.payloads + .filter( + p => + /*HMN 070523 p.properties.commcare_username !== 'test.2021' && + p.properties.test_user !== 'Yes' && + */ + p.properties.caretaker_case_id !== undefined && + p.properties.caretaker_case_id !== '' && + p.case_id!== undefined + ) + .map(p => { + return { + 'Primary_Caregiver_Lookup__r.CommCare_ID__c': + p.properties.caretaker_case_id, + CommCare_ID__c: p.case_id, + }; + }); + + const sfRecordMapping = state.payloads + .filter( + p => + /*HMN 050723 + p.properties.commcare_username !== 'test.2021' && + p.properties.test_user !== 'Yes' + */ + p.case_id !== undefined && + p.case_id !== '' + ) + .map(p => { + // For unbornOrName + const name1 = p.properties.Person_Name || p.properties.case_name; + const unborn = p.properties.name; + + const name2 = + name1 === undefined || name1 === '' || name1 === null + ? unborn + : name1.replace(/\w\S*/g, function (txt) { + return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); + }); + const unbornOrName = name1 !== null ? name2 : 'Unborn Child'; + // console.log('Person Name ::', unbornOrName); + + // For chronicIllness + const chronicChoice =p.properties.please_specify_which_chronic_illness_the_person_has; + const choice2 = handleMultiSelect(chronicChoice); + const chronicIllness = choice2 ? choice2.replace(/_/g, ' ') : ''; + + const disabilityC = + p.properties.disability !== undefined && p.properties.disability !=='---' && p.properties.disability !== null + ? p.properties.disability + .toLowerCase() + .split(' ') + .map(word => word.charAt(0).toUpperCase() + word.slice(1)) + .join(';') + : null; + //HMN remove + console.log(p.case_id) + //console.log(disabilityC) + // + const otherDisability = + p.properties.other_disability !== undefined && p.properties.other_disability !=='---' && p.properties.other_disability !== null + ? p.properties.other_disability + .toLowerCase() + .split(' ') + .map(word => word.charAt(0).toUpperCase() + word.slice(1)) + .join(';') + : null; + //HMN remove + //console.log(otherDisability) + //HMN + const hh_relation = p.properties.relation_to_hh; + + const relationToTheHead = hh_relation !== undefined && hh_relation !== null + ? hh_relation.toString().replace(/_/g, ' ').charAt(0).toUpperCase() + + hh_relation.toString().replace(/_/g, ' ').slice(1) + : null; + + const childStatus = + p.properties.Child_Status && p.properties.Record_Type === 'Unborn' + ? (p.properties.Child_Status = 'Unborn') + : p.properties.Child_Status && p.properties.Record_Type === 'Born' + ? (p.properties.Child_Status = 'Born') + : p.properties.Child_Status; + + const childDangerSigns = p.properties.Other_Danger_Signs !== undefined && p.properties.Other_Danger_Signs !== null + ? p.properties.Other_Danger_Signs.toLowerCase() + .split(' ') + .map(word => word.charAt(0).toUpperCase() + word.slice(1)) + .join(';') + .toString() + .replace(/_/g, ' ') + : p.properties.Other_Danger_Signs; + + //clientCounselled + const clientChoices = p.properties.counsel_topic; + const choiceGroups = clientChoices ? clientChoices.split(' ') : null; + const clientCounselled = choiceGroups + ? choiceGroups + .map(cg => { + return counselMap[cg]; + }) + .join(';') + : choiceGroups; + + // fpMethodDistributed + const fpStatus = p.properties.FP_commodity; + const fpValue = + fpStatus && fpStatus !== '' + ? fpStatus + .replace(/ /gi, ';') + .split(';') + .map(value => { + return fpMethodMap[value] || value; + }) + : undefined; + const fpMethodDistributed = fpValue ? fpValue.join(';') : undefined; + + // placeOfDelivery + const pFacility = p.properties.Delivery_Type; + const placeOfDelivery = + pFacility === 'Skilled' + ? 'Facility' + : pFacility === 'Unskilled' + ? 'Home' + : undefined; + + // reasonForNotTakingFP + const rStatus = p.properties.No_FPmethod_reason; + const rValue = + rStatus && rStatus !== '' + ? rStatus + .replace(/ /gi, ';') + .split(';') + .map(value => { + return reasonMapping[value] || value; + }) + : undefined; + const reasonForNotTakingFP = rValue ? rValue.join(';') : undefined; + + const recordType = p.properties.Record_Type; + + + return { + // TODO @aleksa, Source__c is causing an error + Source__c: true, + CommCare_ID__c: p.case_id, + + //HMN 05072023 'Primary_Caregiver_Lookup__r.CommCare_ID__c':p.properties.caretaker_case_id, + //HMN 05072023 'Mother__r.CommCare_ID__c': p.properties.mother_case_id, + 'Household__r.CommCare_Code__c': + p.properties.parent_id || p.indices.parent.case_id, + commcare_location_id__c: p.properties.commcare_location_id, + CommCare_Username__c: p.properties.commcare_username, + Telephone__c: p.properties.contact_phone_number, + + Consent_for_data_use__c: p.properties.data_sharing_consent, + CommCare_HH_Code__c: p.indices.parent.case_id, + Client_Status__c: p.properties.Client_Status, + Catchment__c: fetchReference(p.properties.owner_id, 'catchment'), + Area__c: fetchReference(p.properties.owner_id, 'area'), + Household_Village__c: fetchReference(p.properties.owner_id, 'village'), + Name: unbornOrName, + Chronic_illness__c: chronicIllness, + Currently_enrolled_in_school__c: p.properties.enrolled_in_school, + Education_Level__c: p.properties.Education_Level !== null && p.properties.Education_Level !== undefined + ? p.properties.Education_Level.toString().replace(/_/g, ' ') + : null, + Relation_to_the_head_of_the_household__c: relationToTheHead, + Gender__c: p.properties.Gender !== undefined ? p.properties.Gender : null, + Disability__c: disabilityC, + Other_disability__c: otherDisability, + Use_mosquito_net__c: p.properties.sleep_under_net, + Birth_Certificate__c: p.properties.birth_certificate, + Child_Status__c: childStatus, + 'RecordType.Name': recordType === 'Unborn' || recordType === '' + ? 'Child' + : recordType.toString().replace(/_/g, ' '), //convert Unborn children to Child RT + //TT5 Mother Information =====================// + MCH_booklet__c: p.properties.mch_booklet, + Reason_for_not_taking_a_pregnancy_test__c: p.properties.No_Preg_Test + ? p.properties.No_Preg_Test.toString().replace(/_/g, ' ') + : undefined, + Pregnancy_danger_signs__c: p.properties.pregnancy_danger_signs + ? pregDangerMap[p.properties.pregnancy_danger_signs] + : undefined, + Individual_birth_plan_counselling__c: + p.properties.individual_birth_plan, + Child_Danger_Signs__c: childDangerSigns, + //HAWI =====================// + + Unique_Patient_Code__c: p.properties.Unique_Patient_Code, + Active_in_Support_Group__c: p.properties.Active_in_Support_Group, + Preferred_Care_Facility__c: p.properties.Preferred_Care_Facility, + Currently_on_ART_s__c: p.properties.ART, + ART_Regimen__c: p.properties.ARVs, + HAWI_Defaulter__c: p.properties.default === 'Yes' ? true : false, + Date_of_Default__c: p.properties.date_of_default, + Know_HIV_status__c: p.properties.known_hiv_status, + HIV_Status__c: p.properties.hiv_status, + //Illness ========================// + Persons_temperature__c: p.properties.temperature, + Days_since_illness_start__c: p.properties.duration_of_sickness, + Current_Malaria_Status__c: p.properties.malaria_test_results, + Malaria_test__c: p.properties.malaria_test, + Last_Malaria_Home_Test__c: p.properties.malaria_test_date, + Last_Malaria_Home_Treatment__c: cleanChoice( + p.properties.malaria_test_date + ), + Cough_over_14days__c: p.properties.symptoms_check_cough, + TB_patients_therapy_observed__c: p.properties.observed_tb_therapy, + Injuries_or_wounds__c: p.properties.wounds_or_injuries, + Pulse_Oximeter__c: p.properties.pulse_oximeter_available, + Heart_Rate_Pulse_Oximeter__c: p.properties.heart_rate_pulse_oximeter, + Oxygen_Concentration_Pulse_Oximeter__c: + p.properties.oxygen_concentration, + Can_child_drink__c: p.properties.can_child_drink, + Antibiotic_provided_for_fast_breathing__c: cleanChoice( + p.properties.antibiotic_fast_breathing + ), + Antibiotic_provided_for_chest_indrawing__c: cleanChoice( + p.properties.antibiotic_chest_indrawing + ), + Default_on_TB_treatment__c: cleanChoice( + p.properties.default_tb_treatment + ), + Treatment_Distribution__c: cleanChoice( + p.properties.distributed_treatments + ), + //Delivery =====================// + Immediate_Breastfeeding__c: p.properties.Breastfeeding_Delivery, + Place_of_Delivery__c: placeOfDelivery, + Delivery_Facility__c: p.properties.Delivery_Facility + ? p.properties.Delivery_Facility.toString().replace(/_/g, ' ') + : null, + Delivery_Facility_Other__c: p.properties.Delivery_Facility_Other, + //Family Planning =====================// + LMP__c: p.properties.LMP, + Family_Planning__c: p.properties.family_planning, + Family_Planning_Method__c: p.properties.family_planning_method, + FP_Method_Distributed__c: fpMethodDistributed, + Reasons_for_not_taking_FP_method__c: reasonForNotTakingFP, + Pregnant__c: p.properties.Pregnant === 'Yes' ? true : false, + Date_of_Delivery__c: p.properties.delivery_date, + Counselled_on_FP_Methods__c: p.properties.CounselledFP_methods, + Client_counselled_on__c: clientCounselled, + Client_provided_with_FP__c: cleanChoice( + p.properties[ + 'was_the_woman_15-49yrs_provided_with_family_planning_commodities_by_chv' + ] + ), + Received_pregnancy_test__c: + p.properties.did_you_adminsiter_a_pregnancy_test, + Pregnancy_test_result__c: p.properties.pregnancy_test_result, + Gravida__c: p.properties.Gravida, + Parity__c: p.properties.Parity, + //TT5 Child Information =====================// + Exclusive_Breastfeeding__c: p.properties.Exclusive_Breastfeeding, + Counselled_on_Exclusive_Breastfeeding__c: p.properties.counseling, + Newborn_visited_48_hours_of_delivery__c: + p.properties.newborn_visited_48_hours_of_delivery, + Newborn_visit_counselling__c: cleanChoice( + p.properties.did_you_consel_the_mother_on1 + ), + mother_visited_48_hours_of_the_delivery__c: + p.properties.visit_mother_48, + Mother_visit_counselling__c: cleanChoice( + p.properties.did_you_consel_the_mother_on2 + ), + Newborn_visited_by_a_CHW_within_6_days__c: + p.properties.visit_6_days_from_delivery, + //Nutrition =====================// + Caretaker_action_after_muac_screening__c: + p.properties.mother_screened_muac_action, + Caretaker_muac_findings__c: + p.properties.mother_screened_child_muac_result, + Food_groups_3_times_a_day__c: p.properties.food_groups, + Caretaker_screened_for_muac_this__c: cleanChoice( + p.properties.mother_screened_child_muac + ), + Caretaker_trained_in_muac__c: cleanChoice( + p.properties.mother_trained_muac + ), + of_Caretaker_MUAC_screenings__c: p.properties.mother_nb_screening, + Current_Height__c: p.properties.current_height, + Current_MUAC__c: p.properties.MUAC, + Current_Nutrition_Status__c: p.properties.Nutrition_Status + ? nutritionMap[p.properties.Nutrition_Status] + : undefined, + //TT5 & HAWI =====================// + TT5_Mother_Registrant__c: p.properties.Pregnant == 'Yes' ? 'Yes' : null, + Enrollment_Date__c: + p.properties.age < 5 || p.properties.Pregnant == 'Yes' + ? p.server_date_modified + : null, + HAWI_Enrollment_Date__c: + p.properties.hiv_status == 'positive' ? p.server_date_modified : null, + Thrive_Thru_5_Registrant__c: + p.properties.age < 5 || p.properties.Pregnant == 'Yes' ? 'Yes' : 'No', + HAWI_Registrant__c: + p.properties.hiv_status == 'positive' ? 'Yes' : 'No', + //ANC =====================// + ANC_1__c: + p.properties.ANC_1 && p.properties.ANC_1 !== '' + ? p.properties.ANC_1 + : undefined, + ANC_2__c: + p.properties.ANC_2 && p.properties.ANC_2 !== '' + ? p.properties.ANC_2 + : undefined, + ANC_3__c: + p.properties.ANC_3 && p.properties.ANC_3 !== '' + ? p.properties.ANC_3 + : undefined, + ANC_4__c: + p.properties.ANC_4 && p.properties.ANC_4 !== '' + ? p.properties.ANC_4 + : undefined, + ANC_5__c: + p.properties.ANC_5 && p.properties.ANC_5 !== '' + ? p.properties.ANC_5 + : undefined, + Date_of_Birth__c: + p.properties.DOB && p.properties.DOB !== '' + ? p.properties.DOB.replace(/\\/g, '-') + : undefined, + //Immunization =====================// + // Child_missed_immunization_type__c: + // p.form.TT5.Child_Information.Immunizations.immunization_type, + BCG__c: p.properties.BCG, + OPV_0__c: p.properties.OPV_0, + Measles_6__c: p.properties.Measles_6, + Measles_9__c: p.properties.Measles_9, + Measles_18__c: p.properties.Measles_18, + OPV_1__c: p.properties.OPV_PCV_Penta_1, + OPV_2__c: p.properties.OPV_PCV_Penta_2, + OPV_3__c: p.properties.OPV_PCV_Penta_3, + Rotavirus_1__c: p.properties.rotavirus_1, + Rotavirus_2__c: p.properties.rotavirus_2, + IPV__c: p.properties.IPV, + Vitamin_A_12__c: p.properties.Vitamine_A, + Vitamin_A_18__c: p.properties.Vitamine_A_2, + Vitamin_A_24__c: p.properties.Vitamine_A_3, + Deworming_12__c: p.properties.Deworming_1, + Deworming_18__c: p.properties.Deworming_2, + Deworming_24__c: p.properties.Deworming_3, + //ECD =====================// + Did_you_counsel_caregiver_on__c: cleanChoice( + p.properties.did_you_counsel_the_caregiver_on_delayed_milestones + ), + Delayed_Milestone__c: cleanChoice( + p.properties.does_the_child_has_a_delayed_milestone + ), + Child_has_2_or_more_play_items__c: cleanChoice( + p.properties.does_the_child_has_2_or_more_play_items_at_home + ), + Child_has_3_or_more_picture_books__c: cleanChoice( + p.properties.does_the_child_has_3_or_more_picture_books + ), + Delayed_Milestones_Counselled_On__c: p.properties + .which_delayed_milestone_area_did_you_counsel_the_caregiver_on + ? milestoneMap[ + p.properties + .which_delayed_milestone_area_did_you_counsel_the_caregiver_on + ] + : undefined, + Delayed_Milestone_Type__c: p.properties.which_delayed_milestone + ? milestoneTypeMap[p.properties.which_delayed_milestone] + : undefined, + //Death =====================// + Date_of_Death__c: p.properties.Date_of_Death, + Cause_of_Death__c: p.properties.cause_of_death_dead + ? p.properties.cause_of_death_dead.toString().replace(/_/g, ' ') + : p.properties.cause_of_death_dead, + Verbal_autopsy__c: p.properties.verbal_autopsy, + //Closing =====================// + Last_Modified_Date_CommCare__c: p.date_modified, + Case_Closed_Date__c: p.date_closed, + }; + }); + + sfRecordMapping.forEach(rec => { + Object.entries(rec).forEach(([key, value]) => { + if (value === '' || value === null) rec[key] = undefined; + }); + }); + + // TODO clean up after QA + // console.log(JSON.stringify(caregiverMapping, null, 2), 'careGiver'); + // console.log(JSON.stringify(motherMapping, null, 2), 'Mother'); + //console.log(JSON.stringify(sfRecordMapping, null, 2), 'sfRecordMapping'); + // console.log(JSON.stringify(householdMapping, null, 2), 'householdMapping'); + // console.log( + // JSON.stringify(headOfHouseholdMapping, null, 2), + // 'headOfHouseholdMapping' + // ); + + return { + ...state, + motherMapping, + sfRecordMapping, + caregiverMapping, + householdMapping, + headOfHouseholdMapping, + }; + }); + + + // TODO, Clean up when pass QA + /*fn(state => { + state.sfRecordMapping.forEach(rec => { + Object.entries(rec).forEach(([key, value]) => { + if (typeof key !== 'string') throw `${key} is not a string`; + }); + }); + return state; + }); + */ + // bulk( + // 'Household__c', + // 'upsert', + // { + // extIdField: 'CommCare_Code__c', + // failOnError: true, + // allowNoOp: true, + // }, + // state => { + // console.log('Bulk upserting...'); + // return state.householdMapping; + // } + // ); + + // TODO, Clean up when pass QA + // upsert data to SF + // upsertIf( + // state.data.properties.commcare_username !== 'test.2021' && + // state.data.properties.test_user !== 'Yes', + // 'Person__c', + // 'CommCare_ID__c', + // state => state.sfRecord + // ); + + bulk( + 'Person__c', + 'upsert', + { + extIdField: 'CommCare_ID__c', + failOnError: true, + allowNoOp: true, + }, + state => { + console.log('Bulk upserting persons ::'); + //HMN commented this + //console.log(JSON.stringify(state.sfRecordMapping, null, 2)); + return state.sfRecordMapping; + } + ); + // TODO, Clean up when pass QA + // upsertIf( + // state.data.properties.commcare_username !== 'test.2021' && + // state.data.properties.test_user !== 'Yes' && + // state.data.properties.caretaker_case_id !== undefined && + // state.data.properties.caretaker_case_id !== '', + // 'Person__c', + // 'CommCare_ID__c', + // fields( + // relationship('Primary_Caregiver_Lookup__r', 'CommCare_ID__c', state => { + // return (caregiver = dataValue('properties.caretaker_case_id')(state)); + // }), + // field('CommCare_ID__c', dataValue('case_id')) + // ) + // ); + + bulk( + 'Person__c', + 'upsert', + { + extIdField: 'CommCare_ID__c', + failOnError: true, + allowNoOp: true, + }, + state => { + console.log('Bulk upserting primary caregiver Persons ::'); + //console.log(JSON.stringify(state.caregiverMapping, null, 2)); + return state.caregiverMapping; + } + ); + + // TODO, Clean up when pass QA + // upsertIf( + // state.data.properties.commcare_username !== 'test.2021' && + // state.data.properties.test_user !== 'Yes' && + // state.data.properties.mother_case_id !== undefined && + // state.data.properties.mother_case_id !== '', + // 'Person__c', + // 'CommCare_ID__c', + // fields( + // relationship('Mother__r', 'CommCare_ID__c', state => { + // return (caregiver = dataValue('properties.mother_case_id')(state)); + // }), + // field('CommCare_ID__c', dataValue('case_id')) + // ) + // ); + bulk( + 'Person__c', + 'upsert', + { + extIdField: 'CommCare_ID__c', + failOnError: true, + allowNoOp: true, + }, + state => { + console.log('Bulk upserting mother Person::'); + // console.log(JSON.stringify(state.motherMapping, null, 2)); + return state.motherMapping; + } + ); + + // TODO, Clean up when pass QA + // upsertIf( + // state.data.properties.commcare_username !== 'test.2021' && + // state.data.properties.test_user !== 'Yes' && + // state.data.properties.head_of_household_case_id !== undefined && + // state.data.properties.head_of_household_case_id !== '', + // 'Household__c', + // 'CommCare_Code__c', + // fields( + // field('CommCare_Code__c', dataValue('indices.parent.case_id')), + // relationship( + // 'Head_of_Household__r', + // 'CommCare_ID__c', + // dataValue('properties.head_of_household_case_id') + // ) + // ) + // ); + + bulk( + 'Household__c', + 'upsert', + { + extIdField: 'CommCare_Code__c', + failOnError: true, + allowNoOp: true, + }, + state => { + console.log('Bulk upserting head of household field on HH ::'); + // console.log(JSON.stringify(state.headOfHouseholdMapping, null, 2)); + return state.headOfHouseholdMapping; + } + ); + + triggers: + cron: + type: cron + cron_expression: '1 * * * *' + enabled: true + edges: + cron->WF2-1-Bulk-get-Person-cases: + source_trigger: cron + target_job: WF2-1-Bulk-get-Person-cases + condition_type: always + enabled: true + WF2-1-Bulk-get-Person-cases->WF2-2-Bulk-upsert-Persons: + source_job: WF2-1-Bulk-get-Person-cases + target_job: WF2-2-Bulk-upsert-Persons + condition_type: on_job_success + enabled: true + 3-Bulk-Person-Visit-cases: + name: 3-Bulk Person Visit cases + jobs: + WF3-1-Bulk-get-Person-Visit-cases: + name: WF3-1 Bulk get Person Visit cases + adaptor: '@openfn/language-http@6.5.1' + credential: rita@openfn.org-Lwala-case-endpoint-production-user + body: | + fn(state => { + const { baseUrl } = state.configuration; + + const caseTypes = ['visite']; + + //NOTE: You can use 'limit' to modify this batch size as desired + const limit = 1000; //E.g., change to 10 to process records in smaller batch sizes + + //NOTE: indexedOnStart is the default sync start data the FIRST time the job runs + const indexedOnStart = '2024-01-17T01:00:00'; + + //NOTE: After first job run, OpenFn will check the job sync data ("lastRunAt") to set as the indexedOnStart + const lastRunAt = + typeof state.lastRunAt !== 'undefined' ? state.lastRunAt : indexedOnStart; + console.log('Filtering cases with indexed_on_start > than ::', lastRunAt); + + const aMinuteAgo = new Date( Date.now() - 1000 * 60 ); + console.log(aMinuteAgo); + + const queries = caseTypes.map( + t => `?type=${t}&indexed_on_start=${lastRunAt}&limit=${limit} + &owner_id=a3c31c9be392427a97f8704262065661` // User id of test user test.2021. Remove for production + //NOTE: If for testing, you want to fetch data for a specific historical range (e.g., between April 23 and 24)... + //...then use the query string below instead of the one above on L16, and custom adjust the index_on start/end dates + //t => `?type=${t}&indexed_on_start=2024-01-15T00:00:00&limit=${limit}&indexed_on_end=2024-01-16T23:59:59` + ); + + return { ...state, queries, baseUrl, payloads: [] }; + }); + + // create a "recursiveGet" which will call itself if CommCare tells us there's + // more data to fetch for the same form + + fn(state => { + const recursiveGet = url => + get( + url, + { + headers: { 'content-type': 'application/json' }, + }, + nextState => { + const now = new Date(); + const { baseUrl, data, payloads } = nextState; + + const { meta, objects } = data; + console.log('Metadata in CommCare response:', meta); + + const finalState = { + ...nextState, + payloads: [...payloads, ...objects], + }; + + if (meta.next) { + console.log('Next query detected, recursing...'); + return recursiveGet(`${baseUrl}${meta.next}`)(finalState); + } + finalState.lastRunAt = now.toISOString().slice(0, 19); + return finalState; + } + ); + + return { ...state, recursiveGet }; + }); + + // for each initial query, fetch data recursively + each( + '$.queries[*]', + fn(state => { + return state.recursiveGet(`${state.baseUrl}${state.data}`)(state); + }) + ); + // log the total number of payloads returned + fn(state => { + console.log('Count of payloads', state.payloads.length); + + return { ...state, references: [], data: {} }; + }); + + WF3-2-Bulk-upsert-Person-Visits: + name: WF3-2 Bulk upsert Person Visits + adaptor: '@openfn/language-salesforce@4.8.6' + credential: aleksa@openfn.org-Lwala-Salesforce-Prod---openfn-user + body: | + fn(state => { + if (state.payloads.length == 0) return { ...state, personVisits: [] }; + + const owner_ids = state.payloads.map(data => data.properties.owner_id); + const uniq_owner_ids = [...new Set(owner_ids)]; + + return { ...state, uniq_owner_ids }; + }); + + fn(state => { + if (state.payloads.length == 0) return state; + return query( + `SELECT CommCare_User_ID__c, Id village, Parent_Geographic_Area__c area, Parent_Geographic_Area__r.Name name, Parent_Geographic_Area__r.Parent_Geographic_Area__c catchment FROM Location__c WHERE CommCare_User_ID__c IN ('${state.uniq_owner_ids.join( + "','" + )}') GROUP BY Id, CommCare_User_ID__c, Parent_Geographic_Area__c, Parent_Geographic_Area__r.Name, Parent_Geographic_Area__r.Parent_Geographic_Area__c` + )(state); + }); + + fn(state => { + if (state.payloads.length == 0) return state; + const [reference] = state.references; + + + // console.log(JSON.stringify(reference, null, 2)); + const records = reference.records; + const fetchReference = (owner_id, arg) => { + const result = + records && records.length > 0 + ? records.filter(record => record.CommCare_User_ID__c === owner_id) + : 0; + + return result.length > 0 ? result[0][arg] : undefined; + }; + const cleanChoice = choice => { + if (choice) { + return choice.charAt(0).toUpperCase() + choice.slice(1).replace('_', ' '); + } else { + return ''; + } + }; + + const handleMultiSelect = multiField => { + return multiField + ? multiField + .replace(/ /gi, ';') + .toLowerCase() + .split(';') + .map(value => { + return ( + value.charAt(0).toUpperCase() + value.slice(1).replace('_', ' ') + ); + }) + .join(';') + : ''; + }; + + const handleMultiSelectOriginal = multiField => { + return multiField + ? multiField + .replace(/ /gi, ';') + .toLowerCase() + .split(';') + .map(value => { + return value; + }) + .join(';') + : ''; + }; + + const pregDangerMap = { + Vaginal_Bleeding: 'Vaginal Bleeding', + Water_Breaks: 'Water Breaks before Time of Delivery', + Prolonged_Labour: 'Prolonged Labour over 12 Hours', + Convulsions: 'Convulsions or Fits', + Abdominal_Pain: 'Severe Abdominal Pain before Delivery', + High_Fever: 'High Fever', + Low_Baby_Movement: 'Feeling the Baby move less or not at all', + Swelling: 'Swelling of Face and Hands', + Severe_Headache: 'Severe or Continuous Headache for more than 12 hours', + Severe_Vomiting: 'Severe or Continuous Vomiting', + none: 'None', + }; + + const counselMap = { + anc_visits: 'ANC Visits', + early_initiation_of_anc_less_than_3_months: + 'Early initiation of ANC (less than 3 months)', + completing_recomended_anc_visits: 'Completing recomended ANC visits', + danger_signs: 'Danger signs', + skilled_birth: 'Skilled birth', + immunization: 'Immunization', + individual_birth_plan: 'Individual Birth Plan', + emergency_preparedness: 'Emergency preparedness', + childcare_and_affection: 'Childcare and affection', + nutrition_counseling: 'Nutrition counseling', + growth_monitoring: 'Growth monitoring', + exclusive_breastfeeding: 'Exclusive breastfeeding', + complementary_feeding: 'Complementary feeding', + sleeping_under_llitn: 'Sleeping under LLITN', + knowing_hiv_status: 'Knowing HIV status', + indoor_pollution: 'Indoor pollution', + personal_hygiene: 'Personal Hygiene', + safe_drinking_water: 'Safe drinking water', + safe_disposal_of_human_waste: 'Safe disposal of human waste', + }; + + const serviceMap = { + Scheduled_PSC_Apt: 'Scheduled PSC Apt', + Adverse_Drug_Reaction_Side_Effect: 'Adverse Drug Reaction/Side Effect', + Malnutrition: 'Malnutrition', + Malaria: 'Malaria', + TB: 'TB', + Treatment_for_Other_OIs: 'Treatment for other Ols', + ARI: 'ARI', + Anemia: 'Anemia', + Diarrhea: 'Diarrhea', + Pregnancy_Care: 'Pregnancy Care (ANC)', + Family_Planning: 'Family Planning (FP)', + Preconception_Counseling: 'Preconception Counseling', + Injury: 'Injury', + Other: 'Other', + }; + + const reasonMap = { + lack_of_access_to_fp_information: 'Lack of access to FP information', + no_access_to_fp_services_hospitals: + 'Lack of hospitals or places where FP services can be accessed', + not_willing_to_use_fp_due_to_negative_effects_myths_and_misconceptions: + 'Myths and misconceptions', + barriers_at_service_delivery_points: 'Barriers at service delivery points', + pregnant: 'The client is pregnant', + intentions_of_getting_pregnant: 'Intentions of getting pregnant', + not_sexually_active: 'The client is not sexually active', + other_barriers_culture_male_partners_parents_etc: + 'Other barriers (culture, male partners, parents, etc)', + }; + + const milestoneTypeMap = { + cognitive_delays_learning_difficulties: + 'Cognitive Delays Learning Difficulties', + motor_delays: 'Motor Delays', + speech_and_language_delay: 'Delay Speech and Language Delay', + social_and_emotional: 'Social and emotional', + }; + + const milestoneMap = { + movement: 'Movement', + hearing: 'Hearing', + communication: 'Communication', + seeing: 'Seeing', + cognitive_delays: 'Cognitive Delays', + play: 'Play', + }; + const nutritionMap = { + severe: 'Severely Malnourished', + moderate: 'Moderately Malnourished', + normal: 'Normal', + }; + + const fpMethodMap = { + male_condoms: 'Male condoms', + female_condoms: 'Female condoms', + pop: 'POP', + coc: 'COC', + emergency_pills: 'Emergency pills', + none: 'None', + //HMN -12/01/2023- + //adding normalization for the family_planning_method to Family_Planning_Method__c + iucd: 'IUCD', + condoms: 'Condoms', + depo: 'Depo', + implant: 'Implant', + injection: 'Injection', + pills: 'Pills', + traditional: 'Traditional', + }; + + const symptomsMap = { + convulsions: 'Convulsions', + not_able_to_eatdrink: 'Not able to drink or feed at all', + vomits_everything: 'Vomits everything', + 'chest_in-drawing': 'Chest in - drawing', + unusually_sleepyunconscious: 'Unusually sleepy or unconscious', + swelling_of_both_feet: 'Swelling of both feet', + none: 'None', + }; + + const supervisorMap = { + community_health_nurse: 'Community_health_nurse', + chw_supervisor: 'CHW_supervisor', + chewschas: 'Chewschas', + other: 'Other', + none: 'None', + }; + + const treatmentDistributionMap = { + ors_205gltr_sachets: 'ORS (20.5h/ltr): Sachets', + acts_6s: 'ACTs (6s)', + acts_12s: 'ACTs (12s)', + acts_18s: 'ACTs (18s)', + acts_24s: 'ACTs (24s)', + albendazole_abz_tabs: 'Albendazole (ABZ): Tabs', + paracetamol_tabs: 'Tetracycline Eye Ointment (TEO): 1%:tube', + tetracycline_eye_ointment_teo_1_tube: + 'Tetracycline Eye Ointment (TEO): 1%:tube', + amoxycillin: 'Amoxycillin (125mg/5mls: Bottle', + none: 'None', + }; + + const childDangerSignsMap = { + none: 'None', + Poor_Breastfeeding: 'Poor Breastfeeding', + not_able_to_feed_since_birth_or_stopped_feeding_well: + 'Not able to feed since birth, or stopped feeding well', + not_able_to_breastfeed: 'Not able to breastfeed', + Fever: 'Fever', + very_low_temperature: 'Very low temperature (35.4 C or less)', + shivering: 'Shivering', + Fast_Breathing: 'Fast Breathing', + Very_Sleepy: 'Very Sleepy', + Convulsions_and_Fits: 'Convulsions and Fits', + only_moves_when_stimulated_or_does_not_move_even_on_stimulation: + 'Only moves when stimulated, or does not move even on stimulation', + yellow_solebaby_body_turning_yellow_especially_eyes_palms_soles: + 'Yellow sole(Baby body turning yellow especially eyes, palms,soles)', + bleeding_from_the_umbilical_stump: 'Bleeding from the umbilical stump', + signs_of_local_infection_umbilicus_is_red_or_draining_pus_skin_boils_or_eye: + 'Signs of local infection: umbilicus is red or draining pus, skin boils, or eyes draining pus', + weight_chart_using_color_coded_scales_if_red_or_yellowweight_below_25kg_or_: + 'Weight chart using color coded scales if RED or YELLOW(Weight below 2.5kg or born less than 36 weeks of age)', + unable_to_cry: 'Unable to cry', + cyanosis: 'Cyanosis', + bulging_fontanelle: 'Bulging fontanelle', + }; + + return { + ...state, + counselMap, + serviceMap, + reasonMap, + milestoneTypeMap, + milestoneMap, + nutritionMap, + pregDangerMap, + fpMethodMap, + symptomsMap, + supervisorMap, + treatmentDistributionMap, + childDangerSignsMap, + fetchReference, + cleanChoice, + handleMultiSelect, + handleMultiSelectOriginal, + }; + }); + + fn(state => { + if (state.payloads.length == 0) return state; + const { + counselMap, + serviceMap, + reasonMap, + milestoneTypeMap, + milestoneMap, + nutritionMap, + pregDangerMap, + fpMethodMap, + symptomsMap, + supervisorMap, + treatmentDistributionMap, + childDangerSignsMap, + fetchReference, + cleanChoice, + handleMultiSelect, + handleMultiSelectOriginal, + } = state; + + const personVisits = state.payloads + //HMN 30/06/2023 Allow test user to post + /* + .filter( + p => + p.properties.username !== 'test.2021' && + p.properties.test_user !== 'Yes' + )*/ + .map(p => { + // commCareVisitID + const commCareCase_id = p.case_id; + const dateVisit = p.properties.date_opened; + const commCareVisitID = commCareCase_id + '_' + dateVisit; + + // personsSymptoms + const psCheck = p.properties.symptoms_check_other; + const psValue = + psCheck && psCheck !== '' + ? psCheck + .replace(/ /gi, ';') + .split(';') + .map(value => { + return symptomsMap[value] || value; + }) + : undefined; + const personsSymptoms = psValue ? psValue.join(';') : undefined; + + // familyPlanningMethod + const fpmStatus = p.properties.family_planning_method; + const fpmValue = + fpmStatus && fpmStatus !== '' + ? fpmStatus + .replace(/ /gi, ';') + .split(';') + .map(value => { + return fpMethodMap[value] || value; + }) + : undefined; + const familyPlanningMethod = fpmValue ? fpmValue.join(';') : undefined; + + // fpMethodDistributed + const fpmdStatus = p.properties.FP_commodity; + const fpmdValue = + fpmdStatus && fpmdStatus !== '' + ? fpmdStatus + .replace(/ /gi, ';') + .split(';') + .map(value => { + return fpMethodMap[value] || value; + }) + : undefined; + const fpMethodDistributed = fpmdValue ? fpmdValue.join(';') : undefined; + + // reasonForNotTakingFPMethod + const rfntStatus = p.properties.No_FPmethod_reason; + const rfntValue = + rfntStatus && rfntStatus !== '' + ? rfntStatus + .replace(/ /gi, ';') + .split(';') + .map(value => { + return reasonMap[value] || value; + }) + : undefined; + const reasonForNotTakingFPMethod = rfntValue + ? rfntValue.join(';') + : undefined; + + // clientCounselledOnC + const ccocChoices = + p.properties.counsel_topic || p.properties.counsel_topic; + const ccocVhoiceGroups = ccocChoices ? ccocChoices.split(' ') : null; + const clientCounselledOnC = ccocVhoiceGroups + ? ccocVhoiceGroups + .map(cg => { + return counselMap[cg]; + }) + .join(';') + : ccocVhoiceGroups; + + // treatmentDistributionC + //const tdcStatus = p.form.treatment_and_tracking.distribution.distributed_treatments; + const tdcStatus = p.properties.distributed_treatments; + const tdcValue = + tdcStatus && tdcStatus !== '' + ? tdcStatus + .replace(/ /gi, ';') + .split(';') + .map(value => { + return treatmentDistributionMap[value] || value; + }) + : undefined; + const treatmentDistributionC = tdcValue ? tdcValue.join(';') : undefined; + + // chronicIllnesC + const ciChoice = + p.properties.please_specify_which_chronic_illness_the_person_has; + const ciChoice2 = handleMultiSelect(ciChoice); + const chronicIllnesC = ciChoice2 ? ciChoice2.replace(/_/g, ' ') : ''; + + // supervisorVisit + const svCheck = p.properties.supervisor_visit; + const svValue = + svCheck && svCheck !== '' + ? svCheck + .replace(/ /gi, ';') + .split(';') + .map(value => { + return supervisorMap[value] || value; + }) + : undefined; + const supervisorVisit = svValue ? svValue.join(';') : undefined; + const recordType = p.properties.RecordType; + + return { + CommCare_ID__c: p.case_id, //'visit' case_id + 'Person__r.CommCare_ID__c': + p.indices.parent.case_id || p.properties.parent_id, + CommCare_Visit_ID__c: commCareVisitID, + Date__c: p.properties.Date, + Birth_Status__c: p.properties.child_status, + Catchment__c: fetchReference(p.properties.owner_id, 'catchment'), + //HMN Accommodating Record Type in Visit + 'RecordType.Name': recordType === 'Unborn' || recordType === 'Child' + ? 'Child Visit' + :recordType === 'Youth' + ? 'Youth Visit' + :recordType === 'Male Adult' + ? 'Adult Male Visit' + : recordType === 'Female Adult' + ? 'Adult Female Visit' + :undefined, + Use_mosquito_net__c: cleanChoice(p.properties.sleep_under_net), + Individual_birth_plan_counselling__c: + p.properties.individual_birth_plan, + Reason_for_not_taking_a_pregnancy_test__c: p.properties.No_Preg_Test + ? p.properties.No_Preg_Test.toString().replace(/_/g, ' ') + : undefined, + Pregnancy_danger_signs__c: p.properties.No_Preg_Test + ? pregDangerMap[p.properties.No_Preg_Test] + : undefined, + Child_Danger_Signs__c: p.properties.Other_Danger_Signs + ? childDangerSignsMap[p.properties.Other_Danger_Signs] + : undefined, + Current_Malaria_Status__c: cleanChoice( + p.properties.malaria_test_results + ), + Malaria_Home_Test__c: p.properties.malaria_test_date, + Malaria_Home_Treatment__c: p.properties.malaria_test_date, + Persons_symptoms__c: personsSymptoms, + Active_in_Support_Group__c: p.properties.Active_in_Support_Group, + HAWI_Defaulter__c: p.properties.default === 'Yes' ? true : false, + Date_of_Default__c: p.properties.date_of_default, + Persons_temperature__c: p.properties.temperature, + Days_since_illness_start__c: p.properties.duration_of_sickness, + Newborn_visited_48_hours_of_delivery__c: + p.properties.newborn_visited_48_hours_of_delivery, + Newborn_visited_by_a_CHW_within_6_days__c: + p.properties.visit_6_days_from_delivery, + Current_Malaria_Status__c: p.properties.malaria_test_results, + Malaria_test__c: cleanChoice(p.properties.malaria_test), + Fever__c: cleanChoice(p.properties.symptoms_check_fever), + Cough__c: cleanChoice(p.properties.symptoms_check_cough), + Diarrhoea__c: cleanChoice(p.properties.symptoms_check_diarrhea), + TB_patients_therapy_observed__c: p.properties.observed_tb_therapy, + Injuries_or_wounds__c: p.properties.wounds_or_injuries, + Currently_on_ART_s__c: p.properties.ART, + // ART_Regimen__c: () => { + // const choice = dataValue( + // 'properties.ARVs; + // return cleanChoice(choice); + // }, + Immediate_Breastfeeding__c: p.properties.Breastfeeding_Delivery, + Exclusive_Breastfeeding__c: p.properties.Exclusive_Breastfeeding, + Counselled_on_Exclusive_Breastfeeding__c: p.properties.counseling, + LMP__c: p.properties.when_was_your_lmp, + Family_Planning__c: cleanChoice(p.properties.family_planning), + Family_Planning_Method__c: p.properties.family_planning_method, + Family_Planning_Method__c: familyPlanningMethod, + FP_Method_Distributed__c: fpMethodDistributed, + Reasons_for_not_taking_FP_method__c: reasonForNotTakingFPMethod, + Pregnant__c: p.properties.Pregnant === 'Yes' ? true : false, + Counselled_on_FP_Methods__c: cleanChoice( + p.properties.CounselledFP_methods + ), + Client_counselled_on__c: clientCounselledOnC, + Client_provided_with_FP__c: cleanChoice( + p.properties[ + 'was_the_woman_15-49yrs_provided_with_family_planning_commodities_by_chv' + ] + ), + Newborn_visited_48_hours_of_delivery__c: + p.properties.newborn_visited_48_hours_of_delivery, + Mother_visit_counselling__c: cleanChoice( + p.properties.did_you_consel_the_mother_on1 + ), + mother_visited_48_hours_of_the_delivery__c: + p.properties.visit_mother_48, + Newborn_visit_counselling__c: cleanChoice( + p.properties.did_you_consel_the_mother_on2 + ), + Know_HIV_status__c: cleanChoice(p.properties.known_hiv_status), + HIV_Status__c: p.properties.hiv_status, + Treatment_Distribution__c: treatmentDistributionC, + // QUESTION: Field name not found : Current_Weight__c + // Current_Weight__c: p.properties.Current_Weight, + Current_Height__c: p.properties.current_height, + Current_MUAC__c: p.properties.MUAC, + Food_groups_3_times_a_day__c: p.properties.food_groups, + Nutrition_Case_Managed__c: p.properties.nutrition_case_managed, + Nutrition_Danger_Signs__c: handleMultiSelectOriginal( + p.properties.nutrition_danger_signs + ), + Why_was_nutrition_case_not_managed__c: + p.properties.nutrition_case_not_managed_why, + Community_Nutrition_Treatment__c: + p.properties.nutrition_treatment_severe, + Community_Nutrition_Treatment__c: + p.properties.nutrition_treatment_moderate, + Why_was_nutrition_treatment_not_given__c: + p.properties.nutrition_treatment_not_given, + Current_Nutrition_Status__c: p.properties.Nutrition_Status + ? nutritionMap[p.properties.Nutrition_Status] + : undefined, + Default_on_TB_treatment__c: cleanChoice( + p.properties.default_tb_treatment + ), + Received_pregnancy_test__c: cleanChoice( + p.properties.did_you_adminsiter_a_pregnancy_test + ), + Pregnancy_test_result__c: cleanChoice( + p.properties.pregnancy_test_result + ), + Chronic_illness__c: chronicIllnesC, + Childs_breath_per_minute__c: p.properties.breaths_per_minuite, + Child_chest_in_drawing__c: p.properties.Child_chest_in_drawing_c, + Caregiver_counseled_on_delayed_milestone__c: + p.properties.did_you_counsel_the_caregiver_on_delayed_milestones, + Delayed_Milestone__c: + p.properties.does_the_child_has_a_delayed_milestone, + Child_has_2_or_more_play_items__c: + p.properties.does_the_child_has_2_or_more_play_items_at_home, + Child_has_3_more_picture_books__c: + p.properties.does_the_child_has_3_or_more_picture_books, + Delayed_Milestones_Counselled_On__c: p.properties + .which_delayed_milestone_area_did_you_counsel_the_caregiver_on + ? milestoneMap[ + p.properties + .which_delayed_milestone_area_did_you_counsel_the_caregiver_on + ] + : undefined, + Delayed_Milestone_Type__c: p.properties.which_delayed_milestone + ? milestoneMap[p.properties.which_delayed_milestone] + : undefined, + Caretaker_trained_in_muac__c: p.properties.mother_trained_muac, + Caretaker_screened_for_muac_this__c: + p.properties.mother_screened_child_muac, + Caretaker_muac_findings__c: + p.properties.mother_screened_child_muac_result, + Caretaker_action_after_muac_screening__c: + p.properties.mother_screened_muac_action, + of_Caretaker_MUAC_screenings__c: p.properties.mother_nb_screening, + Pulse_Oximeter__c: p.properties.pulse_oximeter_available, + Heart_Rate_Pulse_Oximeter__c: p.properties.heart_rate_pulse_oximeter, + Oxygen_Concentration_Pulse_Oximeter__c: + p.properties.oxygen_concentration, + Can_child_drink__c: p.properties.can_child_drink, + Antibiotic_provided_for_fast_breathing__c: + p.properties.antibiotic_fast_breathing, + Antibiotic_provided_for_chest_indrawing__c: + p.properties.antibiotic_chest_indrawing, + Supervisor_Visit__c: supervisorVisit, + //HMN commented this one due to error "Error: InvalidBatch : Field name not found : Visit_Closed_Date__c" + //Visit_Closed_Date__c: p.properties.date_closed, + //29/06/2023 Added Malaria Vaccine mapping + malaria_vaccine_received__c: + p.properties.malaria_vaccine_received, + rts_s_1_date__c: + p.properties.rts_s_1_date, + rts_s_2_date__c: + p.properties.rts_s_2_date, + rts_s_3_date__c: + p.properties.rts_s_3_date, + rts_s_4_date__c: + p.properties.rts_s_4_date, + + //HMN 29/06/2023 + }; + }); + + personVisits.forEach(person => { + Object.entries(person).forEach(([key, value]) => { + if (value === '' || value === null) person[key] = undefined; + }); + }); + + // JSON logging of records + //HMN debugger 19/10/2023 + // console.log(JSON.stringify(personVisits, null, 2)); + + return { ...state, personVisits }; + }); + + bulk( + 'Person_visit__c', + 'upsert', + { + extIdField: 'CommCare_ID__c', + failOnError: true, + allowNoOp: true, + }, + state => { + console.log('Bulk upserting person visit...'); + return state.personVisits; + } + ); + + triggers: + cron: + type: cron + cron_expression: '2 * * * *' + enabled: true + edges: + cron->WF3-1-Bulk-get-Person-Visit-cases: + source_trigger: cron + target_job: WF3-1-Bulk-get-Person-Visit-cases + condition_type: always + enabled: true + WF3-1-Bulk-get-Person-Visit-cases->WF3-2-Bulk-upsert-Person-Visits: + source_job: WF3-1-Bulk-get-Person-Visit-cases + target_job: WF3-2-Bulk-upsert-Person-Visits + condition_type: on_job_success + enabled: true + 4-Bulk-Referral-cases: + name: 4-Bulk Referral cases + jobs: + WF4-1-Bulk-get-Referral-Cases: + name: WF4-1 Bulk get Referral Cases + adaptor: '@openfn/language-http@6.5.0' + credential: rita@openfn.org-Lwala-case-endpoint-production-user + body: | + fn(state => { + const { baseUrl } = state.configuration; + + const caseTypes = ['Case']; + + //NOTE: You can use 'limit' to modify this batch size as desired + const limit = 1000; //E.g., change to 10 to process records in smaller batch sizes + + //NOTE: indexedOnStart is the default sync start data the FIRST time the job runs + const indexedOnStart = '2024-01-17T00:00:00'; + + //NOTE: After first job run, OpenFn will check the job sync data ("lastRunAt") to set as the indexedOnStart + const lastRunAt = + typeof state.lastRunAt !== 'undefined' ? state.lastRunAt : indexedOnStart; + console.log('Filtering cases with indexed_on_start > than ::', lastRunAt); + + const queries = caseTypes.map( + t => `?type=${t}&indexed_on_start=${lastRunAt}&limit=${limit} + &owner_id=a3c31c9be392427a97f8704262065661` // User id of test user test.2021. Remove for production` + //NOTE: If for testing, you want to fetch data for a specific historical range (e.g., between April 23 and 24)... + //...then use the query string below instead of the one above on L16, and custom adjust the index_on start/end dates + //t => `?type=${t}&indexed_on_start=2024-01-14T00:00:00&limit=${limit}&indexed_on_end=2024-01-16T23:59:59` + ); + + return { ...state, queries, baseUrl, payloads: [] }; + }); + + // create a "recursiveGet" which will call itself if CommCare tells us there's + // more data to fetch for the same form + fn(state => { + const recursiveGet = url => + get( + url, + { + headers: { 'content-type': 'application/json' }, + }, + nextState => { + const now = new Date(); + const { baseUrl, data, payloads } = nextState; + + const { meta, objects } = data; + console.log('Metadata in CommCare response:', meta); + + const finalState = { + ...nextState, + payloads: [...payloads, ...objects], + }; + + if (meta.next) { + console.log('Next query detected, recursing...'); + return recursiveGet(`${baseUrl}${meta.next}`)(finalState); + } + finalState.lastRunAt = now.toISOString().slice(0, 19); + return finalState; + } + ); + + return { ...state, recursiveGet }; + }); + + // for each initial query, fetch data recursively + each( + '$.queries[*]', + fn(state => { + return state.recursiveGet(`${state.baseUrl}${state.data}`)(state); + }) + ); + // log the total number of payloads returned + fn(state => { + console.log('Count of payloads', state.payloads.length); + return { ...state, references: [], data: {} }; + }); + + WF4-2-Bulk-upsert-Services: + name: WF4-2 Bulk upsert Services + adaptor: '@openfn/language-salesforce@4.8.6' + credential: aleksa@openfn.org-Lwala-Salesforce-Prod---openfn-user + body: | + // NOTE: We perform a query before anything else if this is a 'Case' + fn(state => { + // state.type = state.data.indices.parent.case_type; + if (state.payloads.length == 0) return { ...state, services: [] }; + + const caseType = state.payloads + .filter(c => c.indices.parent.case_type === 'Case') + .map(c => c.indices.parent.case_id); + + console.log(JSON.stringify(caseType, null, 2)); + + if (caseType.length > 0) + return query( + `SELECT Person__r.CommCare_ID__c FROM Service__c WHERE Service_UID__c IN ('${caseType.join( + "','" + )}')` + )(state).then(state => { + const { records } = state.references[0]; + const ccId = + records.length == 1 ? records[0].Person__r.CommCare_ID__c : null; + return { ...state, ccId }; + }); + + return state; + }); + + // NOTE: We construct a facilityMap and populate some conditional relationships + fn(state => { + if (state.payloads.length == 0) return state; + const facilityMap = { + Lwala_Hospital: 'Lwala Hospital', + Minyenya_Dispensary: 'Minyenya Dispensary', + Ndege_Oriedo_Dispensary: 'Ndege Oriedo Dispensary', + 'Rongo_Sub-District_Hospital': 'Rongo Sub-District Hospital', + Kangeso_Dispensary: 'Kangeso Dispensary', + Ngodhe_Dispensary: 'Ngodhe Dispensary', + Ngere_Dispensary: 'Ngere Dispensary', + Verna_Health_Center: 'Verna Health Center', + Kochola_Dispensary: 'Kochola Dispensary', + Ongo_Health_Center: 'Ongo Health Center', + Royal_Medical_Center: 'Royal Medical Center', + Rosewood_Facility: 'Rosewood Facility', + Other: 'Other', + }; + + const pregDangerMap = { + Vaginal_Bleeding: 'Vaginal Bleeding', + Water_Breaks: 'Water Breaks before Time of Delivery', + Prolonged_Labour: 'Prolonged Labour over 12 Hours', + Convulsions: 'Convulsions or Fits', + Abdominal_Pain: 'Severe Abdominal Pain before Delivery', + High_Fever: 'High Fever', + Low_Baby_Movement: 'Feeling the Baby move less or not at all', + Swelling: 'Swelling of Face and Hands', + Severe_Headache: 'Severe or Continuous Headache for more than 12 hours', + Severe_Vomiting: 'Severe or Continuous Vomiting', + none: 'None', + }; + + const serviceMap = { + Scheduled_PSC_Apt: 'Scheduled PSC Apt', + Adverse_Drug_Reaction_Side_Effect: 'Adverse Drug Reaction/Side Effect', + Malnutrition: 'Malnutrition', + Malaria: 'Malaria', + TB: 'TB', + Treatment_for_Other_OIs: 'Treatment for Other OIs', + ARI: 'ARI', + Anemia: 'Anemia', + Diarrhea: 'Diarrhea', + Pregnancy_Care: 'Pregnancy Care (ANC)', + Family_Planning: 'Family Planning (FP)', + Preconception_Counseling: 'Preconception Counseling', + Injury: 'Injury', + Other: 'Other', + }; + + const milestoneTypeMap = { + cognitive_delays_learning_difficulties: + 'Cognitive Delays (Learning Difficulties)', + motor_delays: 'Motor Delays', + speech_and_language_delay: 'Speech and language Delay', + social_and_emotional: 'Social and emotional', + }; + + const symptomsMap = { + convulsions: 'Convulsions', + not_able_to_eatdrink: 'Not able to eat/drink', + vomits_everything: 'Vomits everything', + 'chest_in-drawing': 'Chest in-drawing', + unusually_sleepyunconscious: 'Unusually sleepy/unconscious', + swelling_of_both_feet: 'Swelling of both feet', + }; + + const childSignMap = { + Poor_Breastfeeding: 'Poor Breastfeeding (under 6 months old child)', + not_able_to_feed_since_birth_or_stopped_feeding_well: + 'Not able to feed since birth, or stopped feeding well', + not_able_to_breastfeed: 'Not able to breastfeed', + Fever: 'Fever (37.5 C or more)', + very_low_temperature: 'Very low temperature (35.4 C or less)', + shivering: 'Shivering', + Fast_Breathing: 'Fast Breathing', + Very_Sleepy: 'Very Sleepy', + Convulsions_and_Fits: 'Convulsions and Fits', + only_moves_when_stimulated_or_does_not_move_even_on_stimulation: + 'Only moves when stimulated, or does not move even on stimulation', + yellow_solebaby_body_turning_yellow_especially_eyes_palms_soles: + 'Yellow sole(Baby body turning yellow especially eyes, palms, soles)', + bleeding_from_the_umbilical_stump: 'Bleeding from the umbilical stump', + signs_of_local_infection_umbilicus_is_red_or_draining_pus_skin_boils_or_eye: + 'Signs of local infection: umbilicus is red or draining pus, skin boils, or eyes draining pus', + weight_chart_using_color_coded_scales_if_red_or_yellowweight_below_25kg_or_: + 'Weight chart using color coded scales if RED or YELLOW(Weight below 2.5kg or born less than 36 weeks of age)', + unable_to_cry: 'Unable to cry', + cyanosis: 'Cyanosis', + bulging_fontanelle: 'Bulging fontanelle', + }; + + const otherReferralMap = { + HIV_Testing_and_Counseling: 'HIV Testing and Counseling', + Visit_to_Clinician: 'Visit to Clinician', + Adverse_Drug_Reaction_Side_Effect: 'Adverse Drug Reaction Side Effect', + Malnutrition: 'Malnutrition', + Malaria: 'Malaria', + PMTCT: 'PMTCT', + TB: 'TB', + Treatment_for_other_OIs: 'Treatment for other OIs', + ARI: 'ARI', + Anemia: 'Anemia', + Diarrhea: 'Diarrhea', + Pregnancy_Care_ANCE: 'Pregnancy Care (ANC)', + Family_Planning_FP: 'Family Planning (FP)', + Preconception_Counseling: 'Preconception Counseling', + Injury: 'Injury', + blood_in_stool: 'Blood in Stool', + Blood_in_Stool: 'Blood in Stool', + Immunization: 'Immunization', + Routine_Health_Check_ups: 'Routine Health Check ups', + routine_health_check_ups: 'Routine Health Check ups', + Other: 'Other', + Poor_Breastfeeding: 'Poor Breastfeeding (under 6 months old child)', + not_able_to_feed_since_birth_or_stopped_feeding_well: + 'Not able to feed since birth, or stopped feeding well', + not_able_to_breastfeed: 'Not able to breastfeed', + Fever: 'Fever (37.5 C or more)', + very_low_temperature: 'Very low temperature (35.4 C or less)', + shivering: 'Shivering', + Fast_Breathing: 'Fast Breathing', + Very_Sleepy: 'Very Sleepy', + Convulsions_and_Fits: 'Convulsions and Fits', + only_moves_when_stimulated_or_does_not_move_even_on_stimulation: + 'Only moves when stimulated, or does not move even on stimulation', + yellow_solebaby_body_turning_yellow_especially_eyes_palms_soles: + 'Yellow sole(Baby body turning yellow especially eyes, palms, soles)', + bleeding_from_the_umbilical_stump: 'Bleeding from the umbilical stump', + signs_of_local_infection_umbilicus_is_red_or_draining_pus_skin_boils_or_eye: + 'Signs of local infection: umbilicus is red or draining pus, skin boils, or eyes draining pus', + weight_chart_using_color_coded_scales_if_red_or_yellowweight_below_25kg_or_: + 'Weight chart using color coded scales if RED or YELLOW(Weight below 2.5kg or born less than 36 weeks of age)', + unable_to_cry: 'Unable to cry', + cyanosis: 'Cyanosis', + bulging_fontanelle: 'Bulging fontanelle', + }; + + const homeCareMap = { + Adherence_Counseling: 'Adherence Counseling', + Pill_Count_Monitoring: 'Pill Count Monitoring', + Nutrition_Assessment_and_Counseling: 'Nutrition Assessment and Counseling', + WASH_Counseling: 'WASH Counseling', + Prevention_Counseling: 'Prevention Counseling', + Psychosocial_Support: 'Psychosocial Support', + Provision_of_Supplies: 'Provision of Supplies', + OI_Management_Support: 'OI Management Support', + }; + + const ecdMap = { + physiotherapy: 'Physiotherapy', + speech_therapy: 'Speech Therapy', + nutrition_education: 'Nutrition Education', + play_therapy: 'Play Therapy', + assessment: 'Assessment', + counselling: 'Counselling', + other: 'Other', + }; + + const clinicalMap = { + diarrhea: 'Diarrhea', + malnutrition: 'Malnutrition', + malaria: 'Malaria', + acute_respiratory_infection: 'Acute Respiratoy Infection (ARI)', + accident_injury: 'Accident/Injury', + other: 'Other', + }; + + const caseType = state.payloads + .filter(c => c.indices.parent.case_type === 'Case') + .map(c => c.indices.parent.case_id); + + const personType = state.payloads + .filter(c => c.indices.parent.case_type === 'Person') + .map(c => c.indices.parent.case_id); + + let relationships = []; + + // If it's a person, add the person relationship + if (personType.length > 0) { + personType.forEach(case_id => { + relationships.push({ 'Person__r.CommCare_ID__c': case_id }); + }); + } + + // If it's a service, add the service rship AND a different person rship + if (caseType.length > 0) { + caseType.forEach(case_id => { + relationships.push({ 'Parent_Service__r.Service_UID__c': case_id }); + }); + + relationships.push({ 'Person__r.CommCare_ID__c': state.ccId }); + } + + return { + ...state, + facilityMap, + relationships, + serviceMap, + pregDangerMap, + milestoneTypeMap, + symptomsMap, + childSignMap, + otherReferralMap, + homeCareMap, + clinicalMap, + ecdMap, + }; + }); + + // NOTE: We finally upsert to the Service__c object in Salesforce + fn(state => { + if (state.payloads.length == 0) return state; + const services = state.payloads + .filter(r => r.properties.owner_id !== '8e725928e3ce43d19b390dd604097069') + .map(r => { + // pregnancyDangerSigns + const pCheck = r.properties.pregnancy_danger_signs; + const pValue = + pCheck && pCheck !== '' + ? pCheck + .replace(/ /gi, ';') + .split(';') + .map(value => { + return state.pregDangerMap[value] || value; + }) + : undefined; + const pregnancyDangerSigns = pValue ? pValue.join(';') : undefined; + + // childDangerSigns + const cCheck = r.properties.Other_Danger_Signs; + const cValue = + cCheck && cCheck !== '' + ? cCheck + .replace(/ /gi, ';') + .split(';') + .map(value => { + return state.childSignMap[value] || value; + }) + : undefined; + const childDangerSigns = cValue ? cValue.join(';') : undefined; + + // delayedMilestone + const dCheck = r.properties.which_delayed_milestone; + const dValue = + dCheck && dCheck !== '' + ? dCheck + .replace(/ /gi, ';') + .split(';') + .map(value => { + return state.milestoneTypeMap[value] || value; + }) + : undefined; + const delayedMilestone = dValue ? dValue.join(';') : undefined; + + // seriousSymptoms + const sCheck = r.properties.symptoms_check_other; + const sValue = + sCheck && sCheck !== '' + ? sCheck + .replace(/ /gi, ';') + .split(';') + .map(value => { + return state.symptomsMap[value] || value; + }) + : undefined; + const seriousSymptoms = sValue ? sValue.join(';') : undefined; + + // otherReferralReason + const otCheck = r.properties.Other_Referral_Reasons; + const otValue = + otCheck && otCheck !== '' + ? otCheck + .replace(/ /gi, ';') + .split(';') + .map(value => { + return state.otherReferralMap[value] || value; + }) + : undefined; + const otherReferralReason = otValue ? otValue.join(';') : undefined; + + // homeBasedCareRendered + const homeCheck = r.properties.Home_Based_Care_Provided; + const homeValue = + homeCheck && homeCheck !== '' + ? homeCheck + .replace(/ /gi, ';') + .split(';') + .map(value => { + return state.homeCareMap[value] || value; + }) + : undefined; + const homeBasedCareRendered = homeValue ? homeValue.join(';') : undefined; + + // ecdClinicalService + const ecdCheck = r.properties.ECD_Clinical_Service; + const ecdValue = + ecdCheck && ecdCheck !== '' + ? ecdCheck + .replace(/ /gi, ';') + .split(';') + .map(value => { + return state.ecdMap[value] || value; + }) + : undefined; + const ecdClinicalService = ecdValue ? ecdValue.join(';') : undefined; + + return { + 'Person__r.CommCare_ID__c': + r.indices.parent.case_type === 'Person' + ? r.indices.parent.case_id + : r.indices.parent.case_type === 'Case' + ? state.ccId + : undefined, + Service_UID__c: r.case_id, + CommCare_Code__c: r.case_id, + RecordTypeID: '01224000000YAuK', + 'Household_CHW__r.CommCare_ID__c': r.properties.CHW_ID, + Open_Case__c: r.closed === false ? true : false, + Case_Closed_Date__c: r.properties.date_closed, + Age_Time_of_Service__c: r.properties.age, + Source__c: r.properties.Source === '1', + Clinical_facility__c: r.properties.Facility_Visited + ? state.facilityMap[r.properties.Facility_Visited] + : undefined, + Client_Received_Services_at_Facility2__c: r.properties.Facility_Visit, + Clinical_Visit_Date__c: + r.properties.Facility_Date === '' || + r.properties.Facility_Date === undefined + ? undefined + : r.properties.Facility_Date, + CHW_Followed_Up_with_the_Client__c: r['properties.Follow-Up']!== '' + ? r['properties.Follow-Up'] + : undefined, + Follow_Up_Date__c: r['properties.Follow-Up_Date'], + + Person_Complied_w_Referral_in_24_hrs__c:r.properties.referral_compliance, + Skillled_Delivery__c: r.properties.skilled_delivery, + Child_received_immunizations__c: r.properties.immunization, + Received_a_diagnosis_for_PSBI__c: r.properties.psbi_diagnosis !== '' + ? r.properties.psbi_diagnosis + : undefined, //Form: CHW.Follow-Up.PSBI.psbi_diagnosis + Received_antibiotics_per_protocol__c: r.properties.antibiotic_8days, //Form: CHW.Follow-Up.PSBI.antibiotic_8day + + Distributed_Treatment_on_Last_Visit__c: + r.properties.distribute_treatment, //Form: CHW.Follow-Up.distribute_treatment + Person_had_an_adverse_drug_reaction__c: + r.properties.adverse_drug_reaction, + Defaulted__c: + r.properties.date_of_default && r.properties.date_of_default !== '' + ? true + : false, + Date_of_Default__c: r.properties.date_of_default, + Client_s_Symptoms_Improved__c: r.properties.Client_Improved, + Case_Type__c: r.properties.Case_Type, + Follow_Up_By_Date__c: + r.properties['Follow-Up_By_Date'] && + r.properties['Follow-Up_By_Date'] !== '' + ? r.properties['Follow-Up_By_Date'] + : undefined, + Date__c: new Date(r.properties.date_opened).toISOString(), + Reason_for_Service__c: r.properties.Reason_for_Service, + Type_of_Service__c: r.properties.Type_of_Service, + Malaria_Status__c: r.properties.Malaria_Status, + Home_Treatment_Date__c: r.properties.home_treatment_date, + Malaria_Home_Test_Date__c: r.properties.malaria_test_date, + Home_ORS__c: r.properties.clinic_ors, + Home_Zinc__c: r.properties.clinic_zinc, + Height__c: r.properties.height, + Weight__c: r.properties.weight, + MUAC__c: r.properties.muac, + Nutrition_Status__c: r.properties.Nutrition_Status, + + //===== NEW MAPPINGS - JAN 14 ===========================// + Pregnancy_Danger_Signs__c: pregnancyDangerSigns, + Child_Danger_Signs__c: childDangerSigns, + Delayed_Milestone__c: delayedMilestone, + Serious_Symptoms__c: seriousSymptoms, + Other_Referral_Reasons__c: otherReferralReason, + Home_Based_Care_Rendered__c: homeBasedCareRendered, + PSBI_Visit__c: + r.properties.psbi_task && r.properties.psbi_task !== '' + ? `Day ${r.properties.psbi_task}` + : undefined, + Clinical_Services__c: r.properties.TT5_Clinical_Service + ? state.clinicalMap[r.properties.TT5_Clinical_Service] + : r.properties.TT5_Clinical_Service, + Referred_Facility__c: r.properties.referred_facility + ? state.facilityMap[r.properties.referred_facility] + : r.properties.referred_facility, + HAWI_Clinical_Services__c: r.properties.HAWI_Clinical_Service + ? state.serviceMap[r.properties.HAWI_Clinical_Service] + : r.properties.HAWI_Clinical_Service, + ECD_Clinical_Services__c: ecdClinicalService, + + }; + }); + + return { ...state, services }; + }); + /* JSON logging of records + fn(state => { + console.log('Services to upsert ::', JSON.stringify(state.services)); + return state; + }); + */ + + bulk( + 'Service__c', + 'upsert', + { + extIdField: 'Service_UID__c', + failOnError: true, + allowNoOp: true, + }, + state => { + console.log('Bulk upserting service...'); + return state.services; + } + ); + + triggers: + cron: + type: cron + cron_expression: '2 * * * *' + enabled: true + edges: + cron->WF4-1-Bulk-get-Referral-Cases: + source_trigger: cron + target_job: WF4-1-Bulk-get-Referral-Cases + condition_type: always + enabled: true + WF4-1-Bulk-get-Referral-Cases->WF4-2-Bulk-upsert-Services: + source_job: WF4-1-Bulk-get-Referral-Cases + target_job: WF4-2-Bulk-upsert-Services + condition_type: on_job_success + enabled: true + "Create-Distribution-and-Referral-in-SF-[Q3-2022]": + name: 'Create Distribution and Referral in SF [Q3 2022]' + jobs: + Q3-2022-Create-Distribution-and-Referral-in-SF: + name: Q3 2022 Create Distribution and Referral in SF + adaptor: '@openfn/language-salesforce@4.8.6' + credential: aleksa@openfn.org-Lwala-Salesforce-Prod---openfn-user + body: | + //Job to integrate CommCare 'Distribution & Referrals' form + upsert( + 'Family_Planning_community_Distribution__c', + 'Commcare_Case_ID__c', + fields( + field('Commcare_Case_ID__c', dataValue('id')), + relationship('RecordType', 'Name', 'FP Community Distribution & Referrals'), + field('Distribute_Date__c', dataValue('form.date')), + field('Client_Name__c', dataValue('form.name')), + field('Client_Gender__c', dataValue('form.gender')), + field('Client_Age__c', dataValue('form.age')), + field('Client_currently_on_FP__c', dataValue('form.current_use')), + field('Referral_Date__c', dataValue('form.Referral_Date')), + field('Referral_Method__c', state => { + var method = dataValue('form.referral_method')(state); + var newMethod = method + ? method + .split(/_/g) + .map( + word => + `${word.substring(0, 1).toUpperCase()}${word.substring(1)}` + ) + .join(' ') + : ''; + return newMethod; + }), + field('Implant_Type__c', state => { + var type = dataValue('form.implant_type')(state); + var newType = ''; + if (type) { + if (type === 'implanon') { + newType = '3-year Implanon'; + } else { + newType = type === 'jadelle' ? '5-year Jadelle' : null; + } + } + return newType; + }), + field('Male_Condoms__c', dataValue('form.male_condoms_count')), + field('Female_Condoms__c', dataValue('form.female_condoms_count')), + field('POP__c', dataValue('form.POP_count')), + field('COC__c', dataValue('form.COC_count')), + field('Emergency_Pills__c', dataValue('form.emergency_pills_count')), + field( + 'Pregnancy_test_positive__c', + dataValue('form.positive_pregnancy_tests') + ), + field('Pregnancy_referrals__c', dataValue('form.pregnancy_referrals')), + field( + 'Contraception_referrals__c', + dataValue('form.family_planning_referrals') + ) + ) + ); + + triggers: + webhook: + type: webhook + enabled: true + edges: + webhook->Q3-2022-Create-Distribution-and-Referral-in-SF: + source_trigger: webhook + target_job: Q3-2022-Create-Distribution-and-Referral-in-SF + condition_type: js_expression + condition_label: 'CommCare Distribution & Referral form submitted' + condition_expression: | + state.data.form["@name"] == "Distribution and Referrals" && state.data.form["test_user"] != "Yes" + enabled: true + "Referrals-Upsert-Service-in-SF-V2--[Q3-2022]-(private)": + name: 'Referrals Upsert Service in SF V2 [Q3 2022] (private)' + jobs: + Q3-2022-Referrals-Upsert-Service-in-SF-V2: + name: Q3 2022 Referrals Upsert Service in SF V2 + adaptor: '@openfn/language-salesforce@4.8.6' + credential: 'rita@openfn.org-Lwala-Salesforce-Sandbox-(April-2024)' + body: | + // NOTE: We perform a query before anything else if this is a 'Case' + fn(state => { + state.type = state.data.indices.parent.case_type; + + if (state.type === 'Case') + return query( + `SELECT Person__r.CommCare_ID__c FROM Service__c WHERE Service_UID__c = '${state.data.indices.parent.case_id}'` + )(state).then(state => { + const { records } = state.references[0]; + const ccId = + records.length == 1 ? records[0].Person__r.CommCare_ID__c : null; + return { ...state, ccId }; + }); + + return state; + }); + + // NOTE: We construct a facilityMap and populate some conditional relationships + fn(state => { + const facilityMap = { + Lwala_Hospital: 'Lwala Hospital', + Minyenya_Dispensary: 'Minyenya Dispensary', + Ndege_Oriedo_Dispensary: 'Ndege Oriedo Dispensary', + 'Rongo_Sub-District_Hospital': 'Rongo Sub-District Hospital', + Kangeso_Dispensary: 'Kangeso Dispensary', + Ngodhe_Dispensary: 'Ngodhe Dispensary', + Ngere_Dispensary: 'Ngere Dispensary', + Verna_Health_Center: 'Verna Health Center', + Kochola_Dispensary: 'Kochola Dispensary', + Ongo_Health_Center: 'Ongo Health Center', + Royal_Medical_Center: 'Royal Medical Center', + Rosewood_Facility: 'Rosewood Facility', + Other: 'Other', + }; + + const pregDangerMap = { + Vaginal_Bleeding: 'Vaginal Bleeding', + Water_Breaks: 'Water Breaks before Time of Delivery', + Prolonged_Labour: 'Prolonged Labour over 12 Hours', + Convulsions: 'Convulsions or Fits', + Abdominal_Pain: 'Severe Abdominal Pain before Delivery', + High_Fever: 'High Fever', + Low_Baby_Movement: 'Feeling the Baby move less or not at all', + Swelling: 'Swelling of Face and Hands', + Severe_Headache: 'Severe or Continuous Headache for more than 12 hours', + Severe_Vomiting: 'Severe or Continuous Vomiting', + none: 'None', + }; + + const serviceMap = { + Scheduled_PSC_Apt: 'Scheduled PSC Apt', + Adverse_Drug_Reaction_Side_Effect: 'Adverse Drug Reaction/Side Effect', + Malnutrition: 'Malnutrition', + Malaria: 'Malaria', + TB: 'TB', + Treatment_for_Other_OIs: 'Treatment for Other OIs', + ARI: 'ARI', + Anemia: 'Anemia', + Diarrhea: 'Diarrhea', + Pregnancy_Care: 'Pregnancy Care (ANC)', + Family_Planning: 'Family Planning (FP)', + Preconception_Counseling: 'Preconception Counseling', + Injury: 'Injury', + Other: 'Other', + }; + + const milestoneTypeMap = { + cognitive_delays_learning_difficulties: + 'Cognitive Delays (Learning Difficulties)', + motor_delays: 'Motor Delays', + speech_and_language_delay: 'Speech and language Delay', + social_and_emotional: 'Social and emotional', + }; + + const symptomsMap = { + convulsions: 'Convulsions', + not_able_to_eatdrink: 'Not able to eat/drink', + vomits_everything: 'Vomits everything', + 'chest_in-drawing': 'Chest in-drawing', + unusually_sleepyunconscious: 'Unusually sleepy/unconscious', + swelling_of_both_feet: 'Swelling of both feet', + }; + + const childSignMap = { + Poor_Breastfeeding: 'Poor Breastfeeding (under 6 months old child)', + not_able_to_feed_since_birth_or_stopped_feeding_well: + 'Not able to feed since birth, or stopped feeding well', + not_able_to_breastfeed: 'Not able to breastfeed', + Fever: 'Fever (37.5 C or more)', + very_low_temperature: 'Very low temperature (35.4 C or less)', + shivering: 'Shivering', + Fast_Breathing: 'Fast Breathing', + Very_Sleepy: 'Very Sleepy', + Convulsions_and_Fits: 'Convulsions and Fits', + only_moves_when_stimulated_or_does_not_move_even_on_stimulation: + 'Only moves when stimulated, or does not move even on stimulation', + yellow_solebaby_body_turning_yellow_especially_eyes_palms_soles: + 'Yellow sole(Baby body turning yellow especially eyes, palms, soles)', + bleeding_from_the_umbilical_stump: 'Bleeding from the umbilical stump', + signs_of_local_infection_umbilicus_is_red_or_draining_pus_skin_boils_or_eye: + 'Signs of local infection: umbilicus is red or draining pus, skin boils, or eyes draining pus', + weight_chart_using_color_coded_scales_if_red_or_yellowweight_below_25kg_or_: + 'Weight chart using color coded scales if RED or YELLOW(Weight below 2.5kg or born less than 36 weeks of age)', + unable_to_cry: 'Unable to cry', + cyanosis: 'Cyanosis', + bulging_fontanelle: 'Bulging fontanelle', + }; + + const otherReferralMap = { + HIV_Testing_and_Counseling: 'HIV Testing and Counseling', + Visit_to_Clinician: 'Visit to Clinician', + Adverse_Drug_Reaction_Side_Effect: 'Adverse Drug Reaction Side Effect', + Malnutrition: 'Malnutrition', + Malaria: 'Malaria', + PMTCT: 'PMTCT', + TB: 'TB', + Treatment_for_other_OIs: 'Treatment for other OIs', + ARI: 'ARI', + Anemia: 'Anemia', + Diarrhea: 'Diarrhea', + Pregnancy_Care_ANCE: 'Pregnancy Care (ANC)', + Family_Planning_FP: 'Family Planning (FP)', + Preconception_Counseling: 'Preconception Counseling', + Injury: 'Injury', + blood_in_stool: 'Blood in Stool', + Blood_in_Stool: 'Blood in Stool', + Immunization: 'Immunization', + Routine_Health_Check_ups: 'Routine Health Check ups', + routine_health_check_ups: 'Routine Health Check ups', + Other: 'Other', + Poor_Breastfeeding: 'Poor Breastfeeding (under 6 months old child)', + not_able_to_feed_since_birth_or_stopped_feeding_well: + 'Not able to feed since birth, or stopped feeding well', + not_able_to_breastfeed: 'Not able to breastfeed', + Fever: 'Fever (37.5 C or more)', + very_low_temperature: 'Very low temperature (35.4 C or less)', + shivering: 'Shivering', + Fast_Breathing: 'Fast Breathing', + Very_Sleepy: 'Very Sleepy', + Convulsions_and_Fits: 'Convulsions and Fits', + only_moves_when_stimulated_or_does_not_move_even_on_stimulation: + 'Only moves when stimulated, or does not move even on stimulation', + yellow_solebaby_body_turning_yellow_especially_eyes_palms_soles: + 'Yellow sole(Baby body turning yellow especially eyes, palms, soles)', + bleeding_from_the_umbilical_stump: 'Bleeding from the umbilical stump', + signs_of_local_infection_umbilicus_is_red_or_draining_pus_skin_boils_or_eye: + 'Signs of local infection: umbilicus is red or draining pus, skin boils, or eyes draining pus', + weight_chart_using_color_coded_scales_if_red_or_yellowweight_below_25kg_or_: + 'Weight chart using color coded scales if RED or YELLOW(Weight below 2.5kg or born less than 36 weeks of age)', + unable_to_cry: 'Unable to cry', + cyanosis: 'Cyanosis', + bulging_fontanelle: 'Bulging fontanelle', + }; + + const homeCareMap = { + Adherence_Counseling: 'Adherence Counseling', + Pill_Count_Monitoring: 'Pill Count Monitoring', + Nutrition_Assessment_and_Counseling: 'Nutrition Assessment and Counseling', + WASH_Counseling: 'WASH Counseling', + Prevention_Counseling: 'Prevention Counseling', + Psychosocial_Support: 'Psychosocial Support', + Provision_of_Supplies: 'Provision of Supplies', + OI_Management_Support: 'OI Management Support', + }; + + const ecdMap = { + physiotherapy: 'Physiotherapy', + speech_therapy: 'Speech Therapy', + nutrition_education: 'Nutrition Education', + play_therapy: 'Play Therapy', + assessment: 'Assessment', + counselling: 'Counselling', + other: 'Other' + }; + + const clinicalMap = { + diarrhea: 'Diarrhea', + malnutrition: 'Malnutrition', + malaria: 'Malaria', + acute_respiratory_infection: 'Acute Respiratoy Infection (ARI)', + accident_injury: 'Accident/Injury', + other: 'Other', + }; + + let relationships = []; + + // If it's a person, add the person relationship + if (state.type === 'Person') { + relationships.push( + relationship( + 'Person__r', + 'CommCare_ID__c', + state.data.indices.parent.case_id + ) + ); + } + + // If it's a service, add the service rship AND a different person rship + if (state.type === 'Case') { + relationships.push( + relationship( + 'Parent_Service__r', + 'Service_UID__c', + state.data.indices.parent.case_id + ) + ); + relationships.push(relationship('Person__r', 'CommCare_ID__c', state.ccId)); + } + + return { + ...state, + facilityMap, + relationships, + serviceMap, + pregDangerMap, + milestoneTypeMap, + symptomsMap, + childSignMap, + otherReferralMap, + homeCareMap, + clinicalMap, + ecdMap + }; + }); + + // NOTE: We finally upsert to the Service__c object in Salesforce + upsertIf( + state.data.properties.owner_id !== '8e725928e3ce43d19b390dd604097069', + 'Service__c', 'Service_UID__c', state => ({ + ...fields(...state.relationships), + ...fields( + field('Service_UID__c', dataValue('case_id')), + field('CommCare_Code__c', dataValue('case_id')), + field('RecordTypeID', '01224000000YAuK'), + //field('Household_CHW__c', 'a030Q000008XyXV'), //Sandbox MOTG test CHW + // relationship( //ADD BACK BEFORE PROD DEPLOYMENT; removed for sandbox testing + // 'Household_CHW__r', + // 'CommCare_ID__c', + // dataValue('properties.CHW_ID') + // ), + field('Open_Case__c', state => { + var status = dataValue('closed')(state); + return status === false ? true : false; + }), + field('Case_Closed_Date__c',dataValue('date_closed')), + field('Age_Time_of_Service__c', dataValue('properties.age')), + field('Source__c', dataValue('properties.Source') === '1'), + field('Clinical_facility__c', state => { + var facility = dataValue('properties.Facility_Visited')(state); + return facility ? state.facilityMap[facility] : undefined; + }), + field('Client_Received_Services_at_Facility2__c',dataValue('properties.Facility_Visit')), + field('Clinical_Visit_Date__c', state => { + var date = dataValue('properties.Facility_Date')(state); + return date === '' || date === undefined ? undefined : date; + }), + field( + 'CHW_Followed_Up_with_the_Client__c', + dataValue('properties.Follow-Up') + ), + field('Follow_Up_Date__c', dataValue('properties.Follow-Up_Date')), + field( + 'Person_Complied_w_Referral_in_24_hrs__c', + dataValue('properties.referral_compliance') + ), + field('Skillled_Delivery__c', dataValue('properties.skilled_delivery')), + field( + 'Child_received_immunizations__c', + dataValue('properties.immunization') + ), + field( + 'Received_a_diagnosis_for_PSBI__c', + dataValue('properties.psbi_diagnosis') //CHW.Follow-Up.PSBI.psbi_diagnosis + ), + field( + 'Received_antibiotics_per_protocol__c', + dataValue('properties.antibiotic_8days') //CHW.Follow-Up.PSBI.antibiotic_8day + ), + field( + 'Distributed_Treatment_on_Last_Visit__c', + dataValue('properties.distribute_treatment') //CHW.Follow-Up.distribute_treatment + ), + field( + 'Person_had_an_adverse_drug_reaction__c', + dataValue('properties.adverse_drug_reaction') + ), + field('Defaulted__c', state => { + var date = dataValue('properties.date_of_default')(state); + return date && date !== '' ? true : false; + }), + field('Date_of_Default__c', dataValue('properties.date_of_default')), + field( + 'Client_s_Symptoms_Improved__c', + dataValue('properties.Client_Improved') + ), + field('Case_Type__c', dataValue('properties.Case_Type')), + field('Follow_Up_By_Date__c', state => { + var date = dataValue('properties.Follow-Up_By_Date')(state); + return date && date !== '' ? date : undefined; + }), + field('Date__c', state => + new Date(state.data.properties.date_opened).toISOString() + ), + field('Reason_for_Service__c', dataValue('properties.Reason_for_Service')), + field('Type_of_Service__c', dataValue('properties.Type_of_Service')), + field('Malaria_Status__c', dataValue('properties.Malaria_Status')), + field( + 'Home_Treatment_Date__c', + dataValue('properties.home_treatment_date') + ), + field( + 'Malaria_Home_Test_Date__c', + dataValue('properties.malaria_test_date') + ), + field('Home_ORS__c', dataValue('properties.clinic_ors')), + field('Home_Zinc__c', dataValue('properties.clinic_zinc')), + field('Height__c', dataValue('properties.height')), + field('Weight__c', dataValue('properties.weight')), + field('MUAC__c', dataValue('properties.muac')), + field('Nutrition_Status__c', dataValue('properties.Nutrition_Status')), + //===== NEW MAPPINGS - JAN 14 ===========================// + field('Pregnancy_Danger_Signs__c', state => { + var check = dataValue('properties.pregnancy_danger_signs')(state); + var value = + check && check !== '' + ? check + .replace(/ /gi, ';') + .split(';') + .map(value => { + return state.pregDangerMap[value] || value; + }) + : undefined; + return value ? value.join(';') : undefined; + }), + field('Child_Danger_Signs__c', state => { + var check = dataValue('properties.Other_Danger_Signs')(state); + var value = + check && check !== '' + ? check + .replace(/ /gi, ';') + .split(';') + .map(value => { + return state.childSignMap[value] || value; + }) + : undefined; + return value ? value.join(';') : undefined; + }), + field('Delayed_Milestone__c', state => { + var check = dataValue('properties.which_delayed_milestone')(state); + var value = + check && check !== '' + ? check + .replace(/ /gi, ';') + .split(';') + .map(value => { + return state.milestoneTypeMap[value] || value; + }) + : undefined; + return value ? value.join(';') : undefined; + }), + field('Serious_Symptoms__c', state => { + var check = dataValue('properties.symptoms_check_other')(state); + var value = + check && check !== '' + ? check + .replace(/ /gi, ';') + .split(';') + .map(value => { + return state.symptomsMap[value] || value; + }) + : undefined; + return value ? value.join(';') : undefined; + }), + field('Other_Referral_Reasons__c', state => { + var check = dataValue('properties.Other_Referral_Reasons')(state); + var value = + check && check !== '' + ? check + .replace(/ /gi, ';') + .split(';') + .map(value => { + return state.otherReferralMap[value] || value; + }) + : undefined; + return value ? value.join(';') : undefined; + }), + field('Home_Based_Care_Rendered__c', state => { + var check = dataValue('properties.Home_Based_Care_Provided')(state); + var value = + check && check !== '' + ? check + .replace(/ /gi, ';') + .split(';') + .map(value => { + return state.homeCareMap[value] || value; + }) + : undefined; + return value ? value.join(';') : undefined; + }), + field('PSBI_Visit__c', state => { + var number = dataValue('properties.psbi_task')(state); + return number && number !== '' ? `Day ${number}` : undefined; //sample output: 'Day 3' + }), + field('Clinical_Services__c', state => { + var check = dataValue('properties.TT5_Clinical_Service')(state); + return check ? state.clinicalMap[check] : check; + }), + field('Referred_Facility__c', state => { + var check = dataValue('properties.referred_facility')(state); + return check ? state.facilityMap[check] : check; + }), + field('HAWI_Clinical_Services__c', state => { + var check = dataValue('properties.HAWI_Clinical_Service')(state); + return check ? state.serviceMap[check] : check; + }), + field('ECD_Clinical_Services__c', state => { + var check = dataValue('properties.ECD_Clinical_Service')(state); + var value = + check && check !== '' + ? check + .replace(/ /gi, ';') + .split(';') + .map(value => { + return state.ecdMap[value] || value; + }) + : undefined; + return value ? value.join(';') : undefined; + }), + //=====================================// + ), + })); + + triggers: + webhook: + type: webhook + enabled: true + edges: + webhook->Q3-2022-Referrals-Upsert-Service-in-SF-V2: + source_trigger: webhook + target_job: Q3-2022-Referrals-Upsert-Service-in-SF-V2 + condition_type: js_expression + condition_label: '"Case" task update ' + condition_expression: | + state.data.properties["case_type"] == "Case" && state.data.properties["test_user"] != "Yes" + enabled: true + "Update-HH-Name-in-CommCare-[Q3-2022]": + name: 'Update HH Name in CommCare [Q3 2022]' + jobs: + Q3-2022-Update-HH-Name-in-CommCare: + name: Q3 2022 Update HH Name in CommCare + adaptor: '@openfn/language-commcare@1.4.1' + credential: 'aleksa@openfn.org-Lwala-CommCare-HQ---openfn-user-' + body: | + // Update CommCare case + fn(state => { + const { Notification } = state.data.Envelope.Body.notifications; + + const Notifications = Array.isArray(Notification) + ? Notification + : [Notification]; + + const notifications = Notifications.map(notification => { + console.log( + `Mapping HH code to CommCare: `, + notification.sObject.Household_Code_Autonumber__c + ); + return { + case_id: notification.sObject.Commcare_Code__c, + name: notification.sObject.Household_Code_Autonumber__c, + }; + }); + + return { ...state, notifications }; + }); + + submitXls(state => state.notifications, { + case_type: 'Household', + search_field: 'case_id', + search_column: 'case_id', + name_column: 'name', + create_new_cases: 'off', + }); + + triggers: + webhook: + type: webhook + enabled: true + edges: + webhook->Q3-2022-Update-HH-Name-in-CommCare: + source_trigger: webhook + target_job: Q3-2022-Update-HH-Name-in-CommCare + condition_type: js_expression + condition_label: SF HH Code Updated + condition_expression: | + state.data.Envelope.Body.notifications.ActionId == "04k24000000GsEhAAK" + enabled: true + "Upsert-Supervision---Accompaniment-[Q4-2022]": + name: 'Upsert Supervision - Accompaniment [Q4 2022]' + jobs: + Q4-2022-Upsert-Supervision---Accompaniment: + name: Q4 2022 Upsert Supervision - Accompaniment + adaptor: '@openfn/language-salesforce@4.8.6' + credential: aleksa@openfn.org-Lwala-Salesforce-Prod---openfn-user + body: | + //Job to integrate CommCare 'Accompaniement' form from the Supervision App + fn(state => { + state.handleMultiSelect = function (state, multiField) { + return multiField + ? multiField + .replace(/ /g, ';') + : ''; + }; + + state.cleanChoice = function (state, choice) { + if (choice) { + return choice.charAt(0).toUpperCase() + choice.slice(1).replace('_', ' '); + } else { + return ''; + } + } + + return { + ...state + }; + + }); + + + upsert( + 'Supervision_Forms__c', + 'CommCare_Form_ID__c', + fields( + field('CommCare_Form_ID__c', dataValue('id')), + relationship('RecordType', 'Name', 'Accompanient Form'), + field('Supervisor_Name__c', dataValue('form.prologue.supervisor_sfid')), + field('CHW_Name__c', dataValue('form.prologue.chw_sfid')), + relationship( + 'Village__r', + 'CommCare_User_ID__c', + dataValue('form.prologue.chw_village') + ), + field('Form_Date__c',dataValue('form.Date')), + field('Fertile_Women_in_Household__c',dataValue('form.WRA_check')), + field('CHW_Asked_About_Family_Planning__c',dataValue('form.women_of_reproductive_age.fp_check')), + field('Contraception_Distributed__c', state => { + var choice = dataValue( + 'form.women_of_reproductive_age.fp_resources_check' + )(state); + return state.handleMultiSelect(state, choice); + }), + + + field('Household_members_aware_of_CHW_SRH__c',dataValue('form.women_of_reproductive_age.srh_awareness_check')), + field('Pregnant_Women_in_HH__c',dataValue('form.pregnancy_check')), + field('CHW_Asked_About_ANC_Visits__c',dataValue('form.pregnant_women.anc_check')), + field('CHW_Counseled_On_Value_of_ANC_Visits__c',dataValue('form.pregnant_women.anc_counsel_check')), + field('CHW_Read_Each_Pregnancy_Danger_Sign__c',dataValue('form.pregnant_women.danger_sign_check')), + field('Household_aware_of_CHW_MCH_Services__c',dataValue('form.pregnant_women.pregnancy_support_awareness_check')), + field('Pregnant_Woman_Delivered__c',dataValue('form.pregnant_women.delivery_check')), + field('Used_MCH_Booklet__c',dataValue('form.delivery.vaccination_check')), + field('Counsel_on_vaccination_schedule__c',dataValue('form.delivery.vaccination_counsel_check')), + field('Counselled_on_Exclusive_Breastfeeding__c',dataValue('form.delivery.ebf_check')), + field('Children_Under_5_in_Household__c',dataValue('form.cu5_check')), + field('All_children_under_5_registered__c',dataValue('form.children_under_5.cu5_enrollment_check')), + field('MUAC_taken_for_all_children__c',dataValue('form.children_under_5.muac_check')), + field('Measured_MUAC_circumference_properly__c',dataValue('form.children_under_5.muac_method_check')), + // field('Measured_MUAC_circumference_properly__c', state => { + // var choice = dataValue( + // 'form.children_under_5.muac_method_check' + // )(state); + // return state.cleanChoice(state, choice); + // }), + field('HIV_Members_in_the_Household__c',dataValue('form.hiv_check')), + field('Recorded_HIV_Status_Information__c',dataValue('form.hiv_clients.hiv_info_check')), + field('Counselled_on_ART_Adherence_HIV_Services__c',dataValue('form.hiv_clients.hiv_counsel_check')), + field('Sick_Household_Members_at_Visit__c',dataValue('form.illness_check')), + field('Household_member_reported_fever__c',dataValue('form.illness_referrals.fever_check')), + field('Conducted_malaria_home_test__c', dataValue('form.illness_referrals.malaria_test_check')), + field('Malaria_test_protocol_followed__c',dataValue('form.illness_referrals.malaria_test_method_check')), + field('Sick_person_referred__c',dataValue('form.illness_referrals.referral_accompaniment_check')), + field('Referral_discussed_with_family__c',dataValue('form.illness_referrals.referral_followup_check')), + field('Distributed_treatments_medications__c',dataValue('form.distribution_check')), + field('Stock_is_full__c',dataValue('form.stocks_check')), + field('Missing_Stock__c', state => { + var choice = dataValue( + 'form.missing_stocks_details' + )(state); + return state.handleMultiSelect(state, choice); + }), + field('Other_Missing_Stock__c',dataValue('form.missing_stocks_details_other')), + field('Demonstrated_active_listening__c',dataValue('form.chw_behavior.active_listening_check')), + field('Acted_with_respect_courtesy__c',dataValue('form.chw_behavior.respect_check')), + field('CHW_Rating__c',dataValue('form.chw_behavior.interview_technique_check')), + field('Tablet_used__c',dataValue('form.chw_behavior.tablet_use_check')), + field('Tablet_used_effectively__c',dataValue('form.chw_behavior.tablet_competency_check')), + field('Tablet_problem_observed__c', state => { + var choice = dataValue( + 'form.chw_behavior.tablet_issues' + )(state); + return state.handleMultiSelect(state, choice); + }), + field('Visit_Length_Mins__c',dataValue('form.visit_length')), + field('Accompanient_components_covered__c', state => { + var choice = dataValue( + 'form.feedback_type' + )(state); + return state.handleMultiSelect(state, choice); + }), + field('Other_comments__c',dataValue('form.supervisor_comments')), + field('Contraception_Distributed__c', state => { + var choice = dataValue( + 'form.women_of_reproductive_age.fp_resources_check' + )(state); + return state.handleMultiSelect(state, choice); + }), + ) + ); + + upsertIf( + state.data.form.prologue.hh_code !== '' && + state.data.form.prologue.hh_code !== null, + 'Supervision_Forms__c', + 'CommCare_Form_ID__c', + relationship('Household_Code__r', + 'Name', + dataValue('form.prologue.hh_code') + ) + ); + + triggers: + webhook: + type: webhook + enabled: true + edges: + webhook->Q4-2022-Upsert-Supervision---Accompaniment: + source_trigger: webhook + target_job: Q4-2022-Upsert-Supervision---Accompaniment + condition_type: js_expression + condition_label: Supervision - Accompaniment - Form + condition_expression: | + state.data.form["@name"] == "Accompaniment Form" && state.data.properties["test_user"] != "Yes" + enabled: true + "Upsert-Supervision---Feedback-[Q4-2022]": + name: 'Upsert Supervision - Feedback [Q4 2022]' + jobs: + Q4-2022-Upsert-Supervision---Feedback: + name: Q4 2022 Upsert Supervision - Feedback + adaptor: '@openfn/language-salesforce@4.8.6' + credential: aleksa@openfn.org-Lwala-Salesforce-Prod---openfn-user + body: | + //Job to integrate CommCare 'Feedback' form from the Supervision App + + upsert( + 'Supervision_Forms__c', + 'CommCare_Form_ID__c', + fields( + field('CommCare_Form_ID__c', dataValue('id')), + relationship('RecordType', 'Name', 'Feedback Form'), + field('Supervisor_Name__c', dataValue('form.prologue.supervisor_sfid')), + field('CHW_Name__c', dataValue('form.prologue.chw_sfid')), + relationship( + 'Village__r', + 'CommCare_User_ID__c', + dataValue('form.prologue.chw_village') + ), + relationship('Catchment__r', + 'Name', + dataValue('form.prologue.catchment') + ), + field('Form_Date__c',dataValue('form.Date')), + field('Strengths__c', dataValue('form.chw_perspectives_and_reflections.chw_strengths')), + field('Weaknesses__c', dataValue('form.chw_perspectives_and_reflections.chw_improvement_areas')), + field('Challenges__c', dataValue('form.chw_perspectives_and_reflections.chw_challenges')), + field('Solutions__c', dataValue('form.chw_perspectives_and_reflections.chw_improvement_areas')), + field('of_Household_Visit_As_Expected__c', dataValue('form.supervision_dashboard_feedback.hh_visits_check')), + field('of_Household_Visit_Explanation__c',dataValue('form.supervision_dashboard_feedback.hh_visits_explanation')), + field('of_Priority_Clients_as_Expected__c', dataValue('form.supervision_dashboard_feedback.priority_hh_visits_check')), + field('of_Priority_Clients_Explanation__c',dataValue('form.supervision_dashboard_feedback.priority_hh_visits_explanation')), + field('Feedback_on_Indicators__c',dataValue('form.supervision_dashboard_feedback.chw_sd_feedback')), + field('CHW_Strengths__c',dataValue('form.supervisor_perspectives_and_reflections.chw_strengths_supervisor')), + field('CHW_Areas_for_Improvement__c',dataValue('form.supervisor_perspectives_and_reflections.chw_improvement_areas_supervisor')), + field('CHW_Immediate_Solutions__c',dataValue('form.supervisor_perspectives_and_reflections.chw_solutions_supervisor')), + field('Other_Recommendations__c',dataValue('form.supervisor_perspectives_and_reflections.chw_recommendation_other_supervisor')), + ) + ); + + triggers: + webhook: + type: webhook + enabled: true + edges: + webhook->Q4-2022-Upsert-Supervision---Feedback: + source_trigger: webhook + target_job: Q4-2022-Upsert-Supervision---Feedback + condition_type: js_expression + condition_label: Supervision - Feedback - Form + condition_expression: | + state.data.form["@name"] == "Feedback Form" && state.data.properties["test_user"] != "Yes" + enabled: true + "Upsert-Supervision---Household-Spot-Check-[Q4-2022]": + name: 'Upsert Supervision - Household Spot Check [Q4 2022]' + jobs: + Q4-2022-Upsert-Supervision---Household-Spot-Check: + name: Q4 2022 Upsert Supervision - Household Spot Check + adaptor: '@openfn/language-salesforce@4.8.6' + credential: aleksa@openfn.org-Lwala-Salesforce-Prod---openfn-user + body: | + //Job to integrate CommCare 'Household Spotcheck' form from the Supervision App + fn(state => { + state.handleMultiSelect = function (state, multiField) { + return multiField + ? multiField + .replace(/ /g, ';') + : ''; + }; + return { + ...state + }; + }); + + + upsert( + 'Supervision_Forms__c', + 'CommCare_Form_ID__c', + fields( + field('CommCare_Form_ID__c', dataValue('id')), + relationship('RecordType', 'Name', 'Household Spotcheck Form'), + // relationship('Household_Code__r', + //'Name', + //dataValue('form.prologue.hh_code') + // ), + field('Supervisor_Name__c', dataValue('form.prologue.spot_checker_sfid')), + field('CHW_Name__c', dataValue('form.prologue.chw_sfid')), + relationship( + 'Village__r', + 'CommCare_User_ID__c', + dataValue('form.prologue.village') + ), + relationship('Catchment__r', + 'Name', + dataValue('form.prologue.catchment') + ), + field('Form_Date__c',dataValue('form.Date')), + field('CHW_Name_Identified__c',dataValue('form.chw_awareness.chw_name_reported')), + field('Knows_where_CHW_lives__c',dataValue('form.chw_awareness.chw_location_confirmation')), + field('Knows_CHW_contact_number__c',dataValue('form.chw_awareness.chw_contact_number')), + field('CHW_paid_for_services__c',dataValue('form.chw_awareness.service_fee')), + field('CHW_Visit_Frequency__c',dataValue('form.chw_awareness.chw_visit_frequency')), + field('Household_member_reported_fever__c',dataValue('form.iccm.fever_management')), + field('details_on_chw_conduct__c',dataValue('form.chw_behavior.chw_conduct_detail')), + field('Tablet_used__c',dataValue('form.chw_behavior.tablet_use_check')), + field('Other_Recommendations__c',dataValue('form.community_comments.community_recommendations_detail')), + field('Other_comments__c',dataValue('form.community_comments.do_you_have_any_other_comments_at_this_time')), + field('CHW_tested_treated_child_for_malaria__c',dataValue('form.iccm.malaria_management')), + field('If_so_when_Within_the__c',dataValue('form.iccm.malaria_management_timeline')), + field('CHW_ever_managed_your_child_for_diarrhea__c',dataValue('form.iccm.diarrhea_management')), + field('CHW_measured_child_s_arm_past_90_days__c',dataValue('form.iccm.muac_check')), + field('CHW_ever_managed_child_for__c',dataValue('form.iccm.pneumonia_management')), + field('rate_the_quality_of_services__c',dataValue('form.iccm.chw_service_quality')), + field('CHW_revisit__c',dataValue('form.referrals_and_follow-up_visits.follow_up_check_1')), + field('follow_up_within_3_days_of_initial_visit__c',dataValue('form.referrals_and_follow-up_visits.follow_up_check_2')), + field('does_CHW_revisit_child_for_follow_up__c',dataValue('form.referrals_and_follow-up_visits.follow_up_check_3')), + field('when_child_is_sick__c',dataValue('form.referrals_and_follow-up_visits.follow_up_check_4')), + field('CHW_conduct__c',dataValue('form.chw_behavior.chw_conduct_check')), + field('comfortable_sharing_sensitive_info__c',dataValue('form.chw_behavior.sensitive_info_check')), + field('Please_explain__c',dataValue('form.chw_behavior.sensitive_info_detail')), + field('Does_your_CHW_listen_to_your_perspective__c',dataValue('form.chw_behavior.listening_check')), + field('ever_experienced_a_problem_with_CHW__c', dataValue('form.chw_behavior.problem_check')), + field('describe_problem_experienced_with_CHW__c',dataValue('form.chw_behavior.problem_detail')), + field('any_recommendations_for_impr__c',dataValue('form.community_comments.community_recommendations')), + field('How_was_the_fever_managed__c', state => { + var choice = dataValue( + 'form.iccm.fever_management_detail' + )(state); + return state.handleMultiSelect(state, choice); + }), + field('How_was_the_malaria_managed__c', state => { + var choice = dataValue( + 'form.iccm.malaria_management_detail' + )(state); + return state.handleMultiSelect(state, choice); + }), + field('How_did_she_he_manage_the_diarrhea__c', state => { + var choice = dataValue( + 'form.iccm.malaria_management_detail' + )(state); + return state.handleMultiSelect(state, choice); + }), + field('How_did_she_he_manage_the_pneumonia__c', state => { + var choice = dataValue( + 'form.iccm.pneumonia_managemnt_detail' + )(state); + return state.handleMultiSelect(state, choice); + }), + field('COHORT_ONE_Maternal_and_Child_Health__c', state => { + var choice = dataValue( + 'form.chw_service_provision.cohort_one' + )(state); + return state.handleMultiSelect(state, choice); + }), + field('COHORT_TWO_Childcare__c', state => { + var choice = dataValue( + 'form.chw_service_provision.cohort_two' + )(state); + return state.handleMultiSelect(state, choice); + }), + field('COHORT_THREE_WASH_and_Nutrition__c', state => { + var choice = dataValue( + 'form.chw_service_provision.cohort_three' + )(state); + return state.handleMultiSelect(state, choice); + }), + field('COHORT_FOUR_FIVE_Sexual_Reproductive__c', state => { + var choice = dataValue( + 'form.chw_service_provision.cohort_four_-_five' + )(state); + return state.handleMultiSelect(state, choice); + }), + ) + ); + + upsertIf( + state.data.form.prologue.hh_code !== '' && + state.data.form.prologue.hh_code !== null, + 'Supervision_Forms__c', + 'CommCare_Form_ID__c', + relationship('Household_Code__r', + 'Name', + dataValue('form.prologue.hh_code') + ) + ); + + triggers: + webhook: + type: webhook + enabled: true + edges: + webhook->Q4-2022-Upsert-Supervision---Household-Spot-Check: + source_trigger: webhook + target_job: Q4-2022-Upsert-Supervision---Household-Spot-Check + condition_type: js_expression + condition_label: Supervision - Household Spotcheck - Form + condition_expression: | + state.data.form["@name"] == "Household Spotcheck Form " && state.data.properties["test_user"] != "Yes" + enabled: true + "x-[archive-]Workflow-Q3-2022-Upsert-Person": + name: 'x [archive ]Workflow Q3 2022 Upsert Person' + jobs: + Q3-2022-Upsert-Person: + name: Q3 2022 Upsert Person + adaptor: '@openfn/language-salesforce@latest' + credential: 'rita@openfn.org-Lwala-Salesforce-Sandbox-(April-2024)' + body: | + // create constants and functions + fn(state => { + state.cleanChoice = function (state, choice) { + if (choice) { + return choice.charAt(0).toUpperCase() + choice.slice(1).replace('_', ' '); + } else { + return ''; + } + }; + + state.handleMultiSelect = function (state, multiField) { + return multiField + ? multiField + .replace(/ /gi, ';') + .toLowerCase() + .split(';') + .map(value => { + return ( + value.charAt(0).toUpperCase() + value.slice(1).replace('_', ' ') + ); + }) + .join(';') + : ''; + }; + + const pregDangerMap = { + Vaginal_Bleeding: 'Vaginal Bleeding', + Water_Breaks: 'Water Breaks before Time of Delivery', + Prolonged_Labour: 'Prolonged Labour over 12 Hours', + Convulsions: 'Convulsions or Fits', + Abdominal_Pain: 'Severe Abdominal Pain before Delivery', + High_Fever: 'High Fever', + Low_Baby_Movement: 'Feeling the Baby move less or not at all', + Swelling: 'Swelling of Face and Hands', + Severe_Headache: 'Severe or Continuous Headache for more than 12 hours', + Severe_Vomiting: 'Severe or Continuous Vomiting', + none: 'None', + }; + + const counselMap = { + anc_visits: 'ANC Visits', + early_initiation_of_anc_less_than_3_months: + 'Early initiation of ANC (less than 3 months)', + completing_recomended_anc_visits: 'Completing recomended ANC visits', + danger_signs: 'Danger signs', + skilled_birth: 'Skilled birth', + immunization: 'Immunization', + individual_birth_plan: 'Individual Birth Plan', + emergency_preparedness: 'Emergency preparedness', + childcare_and_affection: 'Childcare and affection', + nutrition_counseling: 'Nutrition counseling', + growth_monitoring: 'Growth monitoring', + exclusive_breastfeeding: 'Exclusive breastfeeding', + complementary_feeding: 'Complementary feeding', + sleeping_under_llitn: 'Sleeping under LLITN', + knowing_hiv_status: 'Knowing HIV status', + indoor_pollution: 'Indoor pollution', + personal_hygiene: 'Personal Hygiene', + safe_drinking_water: 'Safe drinking water', + safe_disposal_of_human_waste: 'Safe disposal of human waste', + }; + + const serviceMap = { + Scheduled_PSC_Apt: 'Scheduled PSC Apt', + Adverse_Drug_Reaction_Side_Effect: 'Adverse Drug Reaction/Side Effect', + Malnutrition: 'Malnutrition', + Malaria: 'Malaria', + TB: 'TB', + Treatment_for_Other_OIs: 'Treatment for other Ols', + ARI: 'ARI', + Anemia: 'Anemia', + Diarrhea: 'Diarrhea', + Pregnancy_Care: 'Pregnancy Care (ANC)', + Family_Planning: 'Family Planning (FP)', + Preconception_Counseling: 'Preconception Counseling', + Injury: 'Injury', + Other: 'Other', + }; + + const reasonMapping = { + lack_of_access_to_fp_information: 'Lack of access to FP information', + no_access_to_fp_services_hospitals: + 'Lack of hospitals or places where FP services can be accessed', + not_willing_to_use_fp_due_to_negative_effects_myths_and_misconceptions: + 'Myths and misconceptions', + barriers_at_service_delivery_points: 'Barriers at service delivery points', + pregnant: 'The client is pregnant', + intentions_of_getting_pregnant: 'Intentions of getting pregnant', + not_sexually_active: 'The client is not sexually active', + other_barriers_culture_male_partners_parents_etc: + 'Other barriers (culture, male partners, parents, etc)', + }; + + const milestoneTypeMap = { + cognitive_delays_learning_difficulties: + 'Cognitive Delays Learning Difficulties', + motor_delays: 'Motor Delays', + speech_and_language_delay: 'Delay Speech and Language Delay', + social_and_emotional: 'Social and emotional', + }; + + const milestoneMap = { + movement: 'Movement', + hearing: 'Hearing', + communication: 'Communication', + seeing: 'Seeing', + cognitive_delays: 'Cognitive Delays', + play: 'Play', + }; + const nutritionMap = { + severe: 'Severely Malnourished', + moderate: 'Moderately Malnourished', + normal: 'Normal', + }; + + const fpMethodMap = { + male_condoms: 'Male condoms', + female_condoms: 'Female condoms', + pop: 'POP', + coc: 'COC', + emergency_pills: 'Emergency pills', + none: 'None', + }; + + return { + ...state, + counselMap, + serviceMap, + reasonMapping, + milestoneTypeMap, + milestoneMap, + nutritionMap, + pregDangerMap, + fpMethodMap, + }; + }); + + // get data from SF + query( + `SELECT Id, Parent_Geographic_Area__c, Parent_Geographic_Area__r.Name, Parent_Geographic_Area__r.Parent_Geographic_Area__c FROM Location__c WHERE CommCare_User_ID__c = '${dataValue( + 'properties.owner_id' + )(state)}'` + ); + + // build IDs from queried SF data + fn(state => ({ + ...state, + data: { + ...state.data, + villageNewId: + state.references[0].records && state.references[0].records.length !== 0 + ? state.references[0].records[0].Id + : undefined, + areaNewId: + state.references[0].records && state.references[0].records.length !== 0 + ? state.references[0].records[0].Parent_Geographic_Area__c + : undefined, + catchmentNewId: + state.references[0].records && state.references[0].records.length !== 0 + ? state.references[0].records[0].Parent_Geographic_Area__r + ? state.references[0].records[0].Parent_Geographic_Area__r + .Parent_Geographic_Area__c + : undefined + : undefined, + }, + })); + + upsertIf( + state.data.properties.commcare_username !== 'test.2021' && + state.data.properties.test_user !== 'Yes', + 'Household__c', + 'CommCare_Code__c', + fields( + field('CommCare_Code__c', state => { + return ( + dataValue('indices.parent.case_id')(state) || + dataValue('properties.parent_id')(state) + ); + }) + ) + ), + + // build sfRecord before upserting + fn(state => { + // This mapping was initially constructed with fields(field(), ...) syntax. We + // preserve it here and use "expandReferences" but could also refactor this to + // use standard object syntax, as Salesforce looks for { k: v, ... }. + const originalMapping = fields( + /* field( + 'deworming_medication__c', + dataValue('form.TT5.Child_Information.Deworming') + ),depracated field*/ + field('Source__c', 1), + field('CommCare_ID__c', dataValue('case_id')), + relationship( + 'Household__r', + 'CommCare_Code__c', state => { + // (dataValue('properties.parent_id') || dataValue('indices.parent.case_id')) + return ( + dataValue('properties.parent_id')(state) || + dataValue('indices.parent.case_id')(state) + ); + }), + field('commcare_location_id__c',dataValue('properties.commcare_location_id')), + field('CommCare_Username__c',dataValue('properties.commcare_username')), + field('Telephone__c', dataValue('properties.contact_phone_number')), + field( + 'Consent_for_data_use__c', + dataValue('properties.data_sharing_consent') + ), + field('CommCare_HH_Code__c', dataValue('indices.parent.case_id')), + field('Client_Status__c', dataValue('properties.Client_Status')), + field('Catchment__c', dataValue('catchmentNewId')), + field('Area__c', dataValue('areaNewId')), + field('Household_Village__c', dataValue('villageNewId')), + field('Name', state => { + var name1 = dataValue('properties.Person_Name')(state); //check + var unborn = dataValue('properties.name')(state); //check + var name2 = + name1 === undefined || name1 === '' || name1 === null + ? unborn + : name1.replace(/\w\S*/g, function (txt) { + return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); + }); + return name1 !== null ? name2 : 'Unborn Child'; + }), + field('Chronic_illness__c', state => { + var choice = dataValue( + 'properties.please_specify_which_chronic_illness_the_person_has' + )(state); + var choice2 = state.handleMultiSelect(state, choice); + return choice2 ? choice2.replace(/_/g, ' ') : ''; + }), + field( + 'Currently_enrolled_in_school__c', + dataValue('properties.enrolled_in_school') + ), + field('Education_Level__c', state => { + var level = dataValue('properties.Education_Level')(state); + return level ? level.toString().replace(/_/g, ' ') : null; + }), + field('Relation_to_the_head_of_the_household__c', state => { + var relation = dataValue('properties.relation_to_hh')(state); + if (relation) { + relation = relation.toString().replace(/_/g, ' '); + var toTitleCase = relation.charAt(0).toUpperCase() + relation.slice(1); + return toTitleCase; + } + + return null; + }), + field('Gender__c',dataValue('properties.Gender')), + field('Disability__c', state => { + var disability = dataValue('properties.disability')(state); + var toTitleCase = + disability !== undefined + ? disability + .toLowerCase() + .split(' ') + .map(word => word.charAt(0).toUpperCase() + word.slice(1)) + .join(';') + : null; + return toTitleCase; + }), //need case property + field('Other_disability__c', state => { + var disability = dataValue('properties.other_disability')(state); + var toTitleCase = + disability !== undefined + ? disability + .toLowerCase() + .split(' ') + .map(word => word.charAt(0).toUpperCase() + word.slice(1)) + .join(';') + : null; + return toTitleCase; + }), //need case property + + field('Use_mosquito_net__c', dataValue('properties.sleep_under_net')), //need case property + // field('Birth_Certificate__c',dataValue('properties.birth_certificate')), + field('Birth_Certificate__c', dataValue('properties.birth_certificate')), + field('Child_Status__c', state => { + var status = dataValue('properties.Child_Status')(state); + var rt = dataValue('properties.Record_Type')(state); //check that this is the right one + if (status && rt === 'Unborn') { + status = 'Unborn'; + } else if (status && rt === 'Born') { + status = 'Born'; + } + return status; + }), + //===================================================// + relationship('RecordType', 'Name', state => { + var rt = dataValue('properties.Record_Type')(state); + return rt === 'Unborn' || rt === '' + ? 'Child' + : rt.toString().replace(/_/g, ' '); //convert Unborn children to Child RT + }), + + //TT5 Mother Information + + field('MCH_booklet__c', dataValue('properties.mch_booklet')), //need to create a case property + field('Reason_for_not_taking_a_pregnancy_test__c', state => { + var reason = dataValue('properties.No_Preg_Test')(state); + return reason ? reason.toString().replace(/_/g, ' ') : undefined; + }), + field('Pregnancy_danger_signs__c', state => { + var signs = dataValue('properties.pregnancy_danger_signs')(state); + return signs ? state.pregDangerMap[signs] : undefined; + }), + field( + 'Individual_birth_plan_counselling__c', + dataValue('properties.individual_birth_plan') + ), + field('Child_Danger_Signs__c', state => { + var signs = dataValue('properties.Other_Danger_Signs')(state); + return signs + ? signs + .toLowerCase() + .split(' ') + .map(word => word.charAt(0).toUpperCase() + word.slice(1)) + .join(';') + .toString() + .replace(/_/g, ' ') + : signs; + }), + + //HAWI + field( + 'Unique_Patient_Code__c', + dataValue('properties.Unique_Patient_Code') + ), + field( + 'Active_in_Support_Group__c', + dataValue('properties.Active_in_Support_Group') + ), + field( + 'Preferred_Care_Facility__c', + dataValue('properties.Preferred_Care_Facility') + ), + field('Currently_on_ART_s__c', dataValue('properties.ART')), + field('ART_Regimen__c', dataValue('properties.ARVs')), + field('HAWI_Defaulter__c', state => { + var hawi = dataValue('properties.default')(state); + return hawi === 'Yes' ? true : false; + }), + field('Date_of_Default__c', dataValue('properties.date_of_default')), + field('Know_HIV_status__c', dataValue('properties.known_hiv_status')), + field('HIV_Status__c', dataValue('properties.hiv_status')), + /*field('HIV_Status__c', state => { + var status = dataValue('properties.hiv_status')(state); + return status === 'yes' + ? 'Known' + : status === 'no' + ? 'Unknown' + : undefined; + }),//CHECK MAPPING ON THIS ONE*/ + + //Illness + field('Persons_temperature__c', dataValue('properties.temperature')), + field( + 'Days_since_illness_start__c', + dataValue('properties.duration_of_sickness') + ), + field( + 'Current_Malaria_Status__c', + dataValue('properties.malaria_test_results') + ), + field('Malaria_test__c', dataValue('properties.malaria_test')), + field( + 'Last_Malaria_Home_Test__c', + dataValue('properties.malaria_test_date') + ), + field('Last_Malaria_Home_Treatment__c', state => { + var choice = dataValue( + 'properties.malaria_test_date' + )(state); + return state.cleanChoice(state, choice); + }), + /*field('Current_Malaria_Status__c', dataValue('form.Malaria_Status')),//check + field('Malaria_Facility__c',dataValue('form.treatment_and_tracking.malaria_referral_facility')), + field('Fever_over_7days__c',dataValue('form.treatment_and_tracking.symptoms_check_fever')),//check*/ + field('Cough_over_14days__c', dataValue('properties.symptoms_check_cough')), + /*field('Diarrhoea_over_14days__c',dataValue('form.treatment_and_tracking.symptoms_check_diarrhea')),//check + field('Diarrhoea_less_than_14_days__c',dataValue('form.treatment_and_tracking.mild_symptoms_check_diarrhea')),//check*/ + field( + 'TB_patients_therapy_observed__c', + dataValue('properties.observed_tb_therapy') + ), + field('Injuries_or_wounds__c', dataValue('properties.wounds_or_injuries')), + field( + 'Pulse_Oximeter__c', + dataValue('properties.pulse_oximeter_available') + ), + field( + 'Heart_Rate_Pulse_Oximeter__c', + dataValue('properties.heart_rate_pulse_oximeter') + ), + field( + 'Oxygen_Concentration_Pulse_Oximeter__c', + dataValue('properties.oxygen_concentration') + ), + field('Can_child_drink__c', dataValue('properties.can_child_drink')), + // field('Antibiotic_provided_for_fast_breathing__c',dataValue('properties.antibiotic_fast_breathing')), + field('Antibiotic_provided_for_fast_breathing__c', state => { + var choice = dataValue('properties.antibiotic_fast_breathing')(state); + return state.cleanChoice(state, choice); + }), + // field('Antibiotic_provided_for_chest_indrawing__c',dataValue('properties.antibiotic_chest_indrawing')), + field('Antibiotic_provided_for_chest_indrawing__c', state => { + var choice = dataValue('properties.antibiotic_chest_indrawing')(state); + return state.cleanChoice(state, choice); + }), + /*field('Child_zinc__c',dataValue('form.TT5.Child_Information.Clinical_Services.diarrhea_clinic_treatment_zinc')),//check + field('Child_ORS__c',dataValue('form.TT5.Child_Information.Clinical_Services.diarrhea_clinic_treatment_ORS')),//check + field('Childs_breath_per_minute__c',dataValue('form.psbi.breaths_per_minuite')),//check + field('Child_chest_in_drawing__c',dataValue('form.psbi.Child_chest_in_drawing_c')),//check*/ + field('Default_on_TB_treatment__c', state => { + var choice = dataValue('properties.default_tb_treatment')(state); //check + return state.cleanChoice(state, choice); + }), + field('Treatment_Distribution__c', state => { + var choice = dataValue('properties.distributed_treatments')(state); + return state.cleanChoice(state, choice); + }), //check + + //Delivery + field( + 'Immediate_Breastfeeding__c', + dataValue('properties.Breastfeeding_Delivery') + ), + field('Place_of_Delivery__c', state => { + var facility = dataValue('properties.Delivery_Type')(state); + return facility === 'Skilled' + ? 'Facility' + : facility === 'Unskilled' + ? 'Home' + : undefined; + }), + field('Delivery_Facility__c', state => { + var facility = dataValue('properties.Delivery_Facility')(state); + return facility ? facility.toString().replace(/_/g, ' ') : null; + }), + /* field('Delivery_Facility__c', state => { + //HMN 21//11/2022 + var birthFacility =dataValue('properties.Birth_Facility')(state); + var deliveryFacility = dataValue('properties.Delivery_Facility')(state); + var facilityOfBirth = dataValue ('properties.Facility_of_Birth')(state); + var faciliy_val = + facilityOfBirth //!== undefined || facilityOfBirth !== '' || facilityOfBirth !== null + ? facilityOfBirth + :birthFacility //!== undefined || birthFacility !== '' || birthFacility !== null + ? birthFacility + :deliveryFacility //!== undefined || deliveryFacility !== '' || deliveryFacility !== null + ? deliveryFacility + :""; + return faciliy_val.toString().replace(/_/g, ' '); + //HMN + }), */ + //field('Delivery_Facility__c', state => { + // var facility = dataValue('properties.Birth_Facility')(state); + // return facility ? facility.toString().replace(/_/g, ' ') : null; + //}), + field( + 'Delivery_Facility_Other__c', + dataValue('properties.Delivery_Facility_Other') + ), + + //Family Planning + + field('LMP__c', dataValue('properties.LMP')), + field('Family_Planning__c', dataValue('properties.family_planning')), + field( + 'Family_Planning_Method__c', + dataValue('properties.family_planning_method') + ), + field('FP_Method_Distributed__c', state => { + var status = dataValue('properties.FP_commodity')(state); + var value = + status && status !== '' + ? status + .replace(/ /gi, ';') + .split(';') + .map(value => { + return state.fpMethodMap[value] || value; + }) + : undefined; + return value ? value.join(';') : undefined; + }), + field('Reasons_for_not_taking_FP_method__c', state => { + var status = dataValue('properties.No_FPmethod_reason')(state); + var value = + status && status !== '' + ? status + .replace(/ /gi, ';') + .split(';') + .map(value => { + return state.reasonMapping[value] || value; + }) + : undefined; + return value ? value.join(';') : undefined; + }), + field('Pregnant__c', state => { + var preg = dataValue('properties.Pregnant')(state); + return preg === 'Yes' ? true : false; + }), + field('Date_of_Delivery__c', dataValue('properties.delivery_date')), + field( + 'Counselled_on_FP_Methods__c', + dataValue('properties.CounselledFP_methods') + ), + field('Client_counselled_on__c', state => { + var choices = + dataValue('properties.counsel_topic')(state) || + dataValue('properties.counsel_topic')(state); //need to create a case property + var choiceGroups = choices ? choices.split(' ') : null; + var choicesMulti = choiceGroups + ? choiceGroups + .map(cg => { + return state.counselMap[cg]; + }) + .join(';') + : choiceGroups; + return choicesMulti; + }), //OpenFn Question - can this be simplified now that this is a case property + field('Client_provided_with_FP__c', state => { + var choice = dataValue( + 'properties.was_the_woman_15-49yrs_provided_with_family_planning_commodities_by_chv' + )(state); + return state.cleanChoice(state, choice); + }), + field( + 'Received_pregnancy_test__c', + dataValue('properties.did_you_adminsiter_a_pregnancy_test') + ), + field( + 'Pregnancy_test_result__c', + dataValue('properties.pregnancy_test_result') + ), + field('Gravida__c', dataValue('properties.Gravida')), + field('Parity__c', dataValue('properties.Parity')), + + //TT5 Child Information + + field( + 'Exclusive_Breastfeeding__c', + dataValue('properties.Exclusive_Breastfeeding') + ), + field( + 'Counselled_on_Exclusive_Breastfeeding__c', + dataValue('properties.counseling') + ), + field( + 'Newborn_visited_48_hours_of_delivery__c', + dataValue('properties.newborn_visited_48_hours_of_delivery') + ), + field('Newborn_visit_counselling__c', state => { + var choice = dataValue('properties.did_you_consel_the_mother_on1')(state); + return state.cleanChoice(state, choice); + }), + field( + 'mother_visited_48_hours_of_the_delivery__c', + dataValue('properties.visit_mother_48') + ), + /* + //HMN -06012023- The object Visit_after_unskilled__c seems to be missing in sfRecord + //Investigation issue https://lwala.atlassian.net/browse/LWAL-716 raised + //Meanwhile this is being removed to allow re-processing + field( + 'Visit_after_unskilled__c', + dataValue('properties.visit_24hours_after_unskilled_delivery') + ), + */ + field('Mother_visit_counselling__c', state => { + var choice = dataValue('properties.did_you_consel_the_mother_on2')(state); + return state.cleanChoice(state, choice); + }), + /*field('Newborn_visited_48_hours_of_delivery__c',dataValue('properties.newborn_visited_48_hours_of_delivery')), Duplicate Mapping*/ + field( + 'Newborn_visited_by_a_CHW_within_6_days__c', + dataValue('properties.visit_6_days_from_delivery') + ), + + //Nutrition + + field( + 'Caretaker_action_after_muac_screening__c', + dataValue('properties.mother_screened_muac_action') + ), + field( + 'Caretaker_muac_findings__c', + dataValue('properties.mother_screened_child_muac_result') + ), + field('Food_groups_3_times_a_day__c',dataValue('properties.food_groups')), + // field('Caretaker_screened_for_muac_this__c', dataValue('properties.mother_screened_child_muac')), + field('Caretaker_screened_for_muac_this__c', state => { + var choice = dataValue('properties.mother_screened_child_muac')(state); //check + return state.cleanChoice(state, choice); + }), + // field('Caretaker_trained_in_muac__c', dataValue('properties.mother_trained_muac')), + field('Caretaker_trained_in_muac__c', state => { + var choice = dataValue('properties.mother_trained_muac')(state); //check + return state.cleanChoice(state, choice); + }), + field( + 'of_Caretaker_MUAC_screenings__c', + dataValue('properties.mother_nb_screening') + ), + field('Current_Weight__c', dataValue('properties.Current_Weight')), //Only on task update + field('Current_Height__c', dataValue('properties.current_height')), + field('Current_MUAC__c', dataValue('properties.MUAC')), + field('Current_Nutrition_Status__c', state => { + var status = dataValue('properties.Nutrition_Status')(state); + return status ? state.nutritionMap[status] : undefined; + }), + + //TT5 & HAWI + field('TT5_Mother_Registrant__c', state => { + var preg = dataValue('properties.Pregnant')(state); + return preg == 'Yes' ? 'Yes' : null; + }), + field('Enrollment_Date__c', state => { + var age = dataValue('properties.age')(state); + var date = dataValue('server_date_modified')(state); + var preg = dataValue('properties.Pregnant')(state); + return age < 5 || preg == 'Yes' ? date : null; + }), + field('HAWI_Enrollment_Date__c', state => { + var date = dataValue('server_date_modified')(state); + var status = dataValue('properties.hiv_status')(state); + return status == 'positive' ? date : null; + }), + field('Thrive_Thru_5_Registrant__c', state => { + var age = dataValue('properties.age')(state); + var preg = dataValue('properties.Pregnant')(state); + return age < 5 || preg == 'Yes' ? 'Yes' : 'No'; + }), //check mapping + field('HAWI_Registrant__c', state => { + var status = dataValue('properties.hiv_status')(state); + return status == 'positive' ? 'Yes' : 'No'; + }), + + //ANC + field('ANC_1__c', state => { + var date = dataValue('properties.ANC_1')(state); + return date && date !== '' ? date : undefined; + }), + field('ANC_2__c', state => { + var date = dataValue('properties.ANC_2')(state); + return date && date !== '' ? date : undefined; + }), + field('ANC_3__c', state => { + var date = dataValue('properties.ANC_3')(state); + return date && date !== '' ? date : undefined; + }), + field('ANC_4__c', state => { + var date = dataValue('properties.ANC_4')(state); + return date && date !== '' ? date : undefined; + }), + field('ANC_5__c', state => { + var date = dataValue('properties.ANC_5')(state); + return date && date !== '' ? date : undefined; + }), + field('Date_of_Birth__c', state => { + var date = dataValue('properties.DOB')(state); + return date && date !== '' ? date : undefined; + }), + + //Immunization + + field( + 'Child_missed_immunization_type__c', + dataValue('form.TT5.Child_Information.Immunizations.immunization_type') + ), //check + field('BCG__c', dataValue('properties.BCG')), + field('OPV_0__c', dataValue('properties.OPV_0')), + field('Measles_6__c', dataValue('properties.Measles_6')), + field('Measles_9__c', dataValue('properties.Measles_9')), + field('Measles_18__c', dataValue('properties.Measles_18')), + field('OPV_1__c', dataValue('properties.OPV_PCV_Penta_1')), + field('OPV_2__c', dataValue('properties.OPV_PCV_Penta_2')), + field('OPV_3__c', dataValue('properties.OPV_PCV_Penta_3')), + field('Rotavirus_1__c', dataValue('properties.rotavirus_1')), + field('Rotavirus_2__c', dataValue('properties.rotavirus_2')), + field('IPV__c', dataValue('properties.IPV')), + field('Vitamin_A_12__c', dataValue('properties.Vitamine_A')), + field('Vitamin_A_18__c', dataValue('properties.Vitamine_A_2')), + field('Vitamin_A_24__c', dataValue('properties.Vitamine_A_3')), + field('Deworming_12__c', dataValue('properties.Deworming_1')), + field('Deworming_18__c', dataValue('properties.Deworming_2')), + field('Deworming_24__c', dataValue('properties.Deworming_3')), + + //ECD + // field('Did_you_counsel_caregiver_on__c',dataValue('properties.did_you_counsel_the_caregiver_on_delayed_milestones')), + field('Did_you_counsel_caregiver_on__c', state => { + var choice = dataValue( + 'properties.did_you_counsel_the_caregiver_on_delayed_milestones' + )(state); + return state.cleanChoice(state, choice); + }), + // field('Delayed_Milestone__c',dataValue('properties.does_the_child_has_a_delayed_milestone')), + field('Delayed_Milestone__c', state => { + var choice = dataValue( + 'properties.does_the_child_has_a_delayed_milestone' + )(state); + return state.cleanChoice(state, choice); + }), + // field('Child_has_2_or_more_play_items__c',dataValue('properties.does_the_child_has_2_or_more_play_items_at_home')), + field('Child_has_2_or_more_play_items__c', state => { + var choice = dataValue( + 'properties.does_the_child_has_2_or_more_play_items_at_home' + )(state); + return state.cleanChoice(state, choice); + }), + // field('Child_has_3_or_more_picture_books__c',dataValue('properties.does_the_child_has_3_or_more_picture_books')), + field('Child_has_3_or_more_picture_books__c', state => { + var choice = dataValue( + 'properties.does_the_child_has_3_or_more_picture_books' + )(state); + return state.cleanChoice(state, choice); + }), + field('Delayed_Milestones_Counselled_On__c', state => { + var ms = dataValue( + 'properties.which_delayed_milestone_area_did_you_counsel_the_caregiver_on' + )(state); + return ms ? state.milestoneMap[ms] : undefined; + }), + field('Delayed_Milestone_Type__c', state => { + var ms = dataValue('properties.which_delayed_milestone')(state); + return ms ? state.milestoneTypeMap[ms] : undefined; + }), + + //Death + field('Date_of_Death__c', dataValue('properties.Date_of_Death')), + field('Cause_of_Death__c', state => { + var death = dataValue('properties.cause_of_death_dead')(state); + return death ? death.toString().replace(/_/g, ' ') : death; + }), //check which case property to use - there are 2 + field('Verbal_autopsy__c', dataValue('properties.verbal_autopsy')), + + //Closing + field('Last_Modified_Date_CommCare__c', dataValue('date_modified')), + field('Case_Closed_Date__c',dataValue('date_closed')), + //field('Case_Closed_Date__c', state => { + // var closed = dataValue('date_closed')(state); + // var date = dataValue('date_modified')(state); + // return closed && closed == true ? date : undefined; + //}) //need case property + ); + + let sfRecord = expandReferences(originalMapping)(state); + + Object.entries(sfRecord).forEach(([key, value]) => { + if (value === '') sfRecord[key] = undefined; + }); + + return { ...state, sfRecord }; + }); + + // upsert data to SF + upsertIf( + state.data.properties.commcare_username !== 'test.2021' && + state.data.properties.test_user !== 'Yes' , + 'Person__c', 'CommCare_ID__c', state => state.sfRecord); + + upsertIf( + state.data.properties.commcare_username !== 'test.2021' && + state.data.properties.test_user !== 'Yes' && + state.data.properties.caretaker_case_id !== undefined && state.data.properties.caretaker_case_id !== '', + 'Person__c', 'CommCare_ID__c', + fields( + relationship('Primary_Caregiver_Lookup__r', 'CommCare_ID__c', state => { + return caregiver = dataValue('properties.caretaker_case_id')(state); + }), + field('CommCare_ID__c', dataValue('case_id')), + ) + ); + + upsertIf( + state.data.properties.commcare_username !== 'test.2021' && + state.data.properties.test_user !== 'Yes' && + state.data.properties.mother_case_id !== undefined && state.data.properties.mother_case_id !== '', + 'Person__c', 'CommCare_ID__c', + fields( + relationship('Mother__r', 'CommCare_ID__c', state => { + return caregiver = dataValue('properties.mother_case_id')(state); + }), + field('CommCare_ID__c', dataValue('case_id')), + ) + ); + + upsertIf( + state.data.properties.commcare_username !== 'test.2021' && + state.data.properties.test_user !== 'Yes' && + state.data.properties.head_of_household_case_id !== undefined && state.data.properties.head_of_household_case_id !== '', + 'Household__c', 'CommCare_Code__c', + fields( + field('CommCare_Code__c', state => { + return ( + dataValue('indices.parent.case_id')(state) || + dataValue('properties.parent_id')(state) + ) + }), + relationship('Head_of_Household__r', 'CommCare_ID__c', dataValue('properties.head_of_household_case_id')), + ) + ) + + triggers: + webhook: + type: webhook + enabled: false + edges: + webhook->Q3-2022-Upsert-Person: + source_trigger: webhook + target_job: Q3-2022-Upsert-Person + condition_type: js_expression + condition_label: Person + condition_expression: | + state.data.properties["case_type"] == "Person" && state.data.properties["test_user"] != "Yes" + enabled: false + "x-[archive-]Workflow-WF3-2a-Repeat-Failed-Person-Visits": + name: 'x [archive ]Workflow WF3-2a Repeat Failed Person Visits' + jobs: + WF3-2a-Repeat-Failed-Person-Visits: + name: WF3-2a Repeat Failed Person Visits + adaptor: '@openfn/language-salesforce@latest' + credential: null + body: | + fn(state => { + const { baseUrl } = state.configuration; + + const caseTypes = ['visite']; + + //NOTE: You can use 'limit' to modify this batch size as desired + const limit = 1000; //E.g., change to 10 to process records in smaller batch sizes + + //NOTE: indexedOnStart is the default sync start data the FIRST time the job runs + const indexedOnStart = '2024-01-17T01:00:00'; + + //NOTE: After first job run, OpenFn will check the job sync data ("lastRunAt") to set as the indexedOnStart + const lastRunAt = + typeof state.lastRunAt !== 'undefined' ? state.lastRunAt : indexedOnStart; + console.log('Filtering cases with indexed_on_start > than ::', lastRunAt); + + const aMinuteAgo = new Date( Date.now() - 1000 * 60 ); + console.log(aMinuteAgo); + + const queries = caseTypes.map( + t => `?type=${t}&indexed_on_start=${lastRunAt}&limit=${limit}` + //NOTE: If for testing, you want to fetch data for a specific historical range (e.g., between April 23 and 24)... + //...then use the query string below instead of the one above on L16, and custom adjust the index_on start/end dates + //t => `?type=${t}&indexed_on_start=2024-01-15T00:00:00&limit=${limit}&indexed_on_end=2024-01-16T23:59:59` + ); + + return { ...state, queries, baseUrl, payloads: [] }; + }); + + // create a "recursiveGet" which will call itself if CommCare tells us there's + // more data to fetch for the same form + + fn(state => { + const recursiveGet = url => + get( + url, + { + headers: { 'content-type': 'application/json' }, + }, + nextState => { + const now = new Date(); + const { baseUrl, data, payloads } = nextState; + + const { meta, objects } = data; + console.log('Metadata in CommCare response:', meta); + + const finalState = { + ...nextState, + payloads: [...payloads, ...objects], + }; + + if (meta.next) { + console.log('Next query detected, recursing...'); + return recursiveGet(`${baseUrl}${meta.next}`)(finalState); + } + finalState.lastRunAt = now.toISOString().slice(0, 19); + return finalState; + } + ); + + return { ...state, recursiveGet }; + }); + + // for each initial query, fetch data recursively + each( + '$.queries[*]', + fn(state => { + return state.recursiveGet(`${state.baseUrl}${state.data}`)(state); + }) + ); + // log the total number of payloads returned + fn(state => { + console.log('Count of payloads', state.payloads.length); + + return { ...state, references: [], data: {} }; + }); + + triggers: + cron: + type: cron + cron_expression: '0 * * * *' + enabled: false + edges: + cron->WF3-2a-Repeat-Failed-Person-Visits: + source_trigger: cron + target_job: WF3-2a-Repeat-Failed-Person-Visits + condition_type: always + enabled: false + "x-[archive]-Input-Seed-Support-and-Kitchen-Garden-Adoption": + name: 'x [archive] Input Seed Support and Kitchen Garden Adoption' + jobs: + Input-Seed-Support-and-Kitchen-Garden-Adoption: + name: Input Seed Support and Kitchen Garden Adoption + adaptor: '@openfn/language-salesforce@v1.3.2' + credential: null + body: | + alterState(state => { + var input_seed_support = dataValue('form.input_seed_support')(state).split( + ' ' + ); + for (i = 0; i < input_seed_support.length; i++) { + upsert( + 'Household__c', + 'CommCare_Code__c', + fields( + field('CommCare_Code__c', input_seed_support[i]), + field('Seed_Input_Support__c', 'Yes') + ) + )(state); + } + return state; + }); + + alterState(state => { + var kitchen_garden = dataValue('form.kitchen_garden')(state).split(' '); + for (i = 0; i < kitchen_garden.length; i++) { + upsert( + 'Household__c', + 'CommCare_Code__c', + fields( + field('CommCare_Code__c', kitchen_garden[i]), + field('Kitchen_Garden__c', 'Yes') + ) + )(state); + } + return state; + }); + // Your job goes here. + + triggers: + webhook: + type: webhook + enabled: false + edges: + webhook->Input-Seed-Support-and-Kitchen-Garden-Adoption: + source_trigger: webhook + target_job: Input-Seed-Support-and-Kitchen-Garden-Adoption + condition_type: js_expression + condition_label: Input Seed Support and Kitchen Garden Adoption + condition_expression: | + state.data.form["@name"] == "Copy of Register Training" + enabled: false + "x-[archive]-Update-Household-in-CommCare": + name: 'x [archive] Update Household in CommCare' + jobs: + Update-Household-in-CommCare: + name: Update Household in CommCare + adaptor: '@openfn/language-commcare@latest' + credential: null + body: | + submit( + fields( + field('@', state => { + return { + 'xmlns:jrm': 'http://dev.commcarehq.org/jr/xforms', + xmlns: + 'http://openrosa.org/formdesigner/980c10cdb3b140101225e25c6e8aff48f471b3d', + uiVersion: '1', + version: '46', + name: 'Update Household', + }; + }), + field('Source', false), + field('Household_Status', state => { + var str = ''; + if (dataValue('new[0].Active_Household__c')(state) === false) { + str = 'No'; + } else { + str = 'Yes'; + } + return str; + }), + field('Run_Code', 'Household_Lwala'), + field('name', dataValue('new[0].Name')), + field('area', dataValue('new[0].Area__c')), + + field('Household_Information', state => { + return { + Active_Handwashing_Station: dataValue('new[0].Tippy_Tap__c')(state), + Drying_Rack: dataValue('new[0].Drying_Rack__c')(state), + + WASH_Compliant: () => { + var ans = ''; + if (dataValue('new[0].WASH_Compliant__c')(state) === true) { + ans = 'Yes'; + } else { + ans = 'No'; + } + return ans; + }, + Functional_Latrine: dataValue('new[0].Pit_Latrine__c')(state), + Clothesline: dataValue('new[0].Clothe__c')(state), + ITNs: dataValue('new[0].Uses_ITNs__c')(state), + Improved_Cooking_Method: dataValue('new[0].Cookstove__c')(state), + Kitchen_Garden: dataValue('new[0].Kitchen_Garden__c')(state), + Number_of_Over_5_Males: dataValue('new[0].Number_of_Over_5_Males__c')( + state + ), + Number_of_Over_5_Females: dataValue( + 'new[0].Number_of_Over_5_Females__c' + )(state), + Number_of_Under_5_Males: dataValue('new[0].Number_of_Under_5_Males__c')( + state + ), + Number_of_Under_5_Females: dataValue( + 'new[0].Number_of_Under_5_Females__c' + )(state), + Rubbish_Pit: dataValue('new[0].Rubbish_Pit__c')(state), + Treats_Drinking_Water: dataValue('new[0].Treats_Drinking_Water__c')( + state + ), + WASH_Trained: dataValue('new[0].WASH_Trained__c')(state), + Total_Under_5: dataValue('new[0].Total_Number_of_Under_5s__c')(state), + Total_Males: dataValue('new[0].Total_Number_of_Males__c')(state), + Total_Females: dataValue('new[0].Total_Number_of_Females__c')(state), + Total_Household_Members: dataValue('new[0].Total_Number_of_Members__c')( + state + ), + Total_Over_5: () => { + var num = 0; + num = + dataValue('new[0].Total_Number_of_Members__c')(state) - + dataValue('new[0].Total_Number_of_Under_5s__c')(state); + return num; + }, + }; + }), + field('n0:case', state => { + return { + '@': { + case_id: dataValue('new[0].Commcare_Code__c')(state), + date_modified: new Date().toISOString(), + user_id: 'e298884bfb6ee2d2b38591a6e8ae0228', + 'xmlns:n0': 'http://commcarehq.org/case/transaction/v2', + }, + 'n0:update': { + 'n0:case_name': dataValue('new[0].Name')(state), + 'n0:owner_id': () => { + var id = ''; + if (dataValue('new[0].chw_owner_id__c')(state) === undefined) { + id = 'acf8595692c76095eb5afd809c628091'; + } else { + id = dataValue('new[0].chw_owner_id__c')(state); + } + return id; + }, + 'n0:case_type': 'Household', + 'n0:WASH_Compliant': () => { + var ans = ''; + if (dataValue('new[0].WASH_Compliant__c')(state) === true) { + ans = 'Yes'; + } else { + ans = 'No'; + } + return ans; + }, + 'n0:Active_Handwashing_Station': dataValue('new[0].Tippy_Tap__c')( + state + ), + 'n0:Drying_Rack': dataValue('new[0].Drying_Rack__c')(state), + 'n0:Functional_Latrine': dataValue('new[0].Pit_Latrine__c')(state), + 'n0:Clothesline': dataValue('new[0].Clothe__c')(state), + 'n0:ITNs': dataValue('new[0].Uses_ITNs__c')(state), + 'n0:Active_in_Nutrition_Program': dataValue( + 'new[0].Active_in_Nutrition_Program__c' + )(state), + 'n0:Nutrition_Group': dataValue('new[0].Nutrition_Group__c')(state), + 'n0:seed_input_support': dataValue('new[0].Seed_Input_Support__c')( + state + ), + 'n0:name_concat': dataValue('new[0].Name_Concatenation__c')(state), + 'n0:CHW_ID': dataValue('new[0].Household_CHW__c')(state), + 'n0:Improved_Cooking_Method': dataValue('new[0].Cookstove__c')(state), + 'n0:Kitchen_Garden': dataValue('new[0].Kitchen_Garden__c')(state), + 'n0:Number_of_Over_5_Males': dataValue( + 'new[0].Number_of_Over_5_Males__c' + )(state), + 'n0:Number_of_Over_5_Females': dataValue( + 'new[0].Number_of_Over_5_Females__c' + )(state), + 'n0:Number_of_Under_5_Males': dataValue( + 'new[0].Number_of_Under_5_Males__c' + )(state), + 'n0:Number_of_Under_5_Females': dataValue( + 'new[0].Number_of_Under_5_Females__c' + )(state), + 'n0:Rubbish_Pit': dataValue('new[0].Rubbish_Pit__c')(state), + 'n0:Treats_Drinking_Water': dataValue( + 'new[0].Treats_Drinking_Water__c' + )(state), + 'n0:WASH_Trained': dataValue('new[0].WASH_Trained__c')(state), + 'n0:Total_Under_5': dataValue('new[0].Total_Number_of_Under_5s__c')( + state + ), + 'n0:Total_Males': dataValue('new[0].Total_Number_of_Males__c')(state), + 'n0:Total_Females': dataValue('new[0].Total_Number_of_Females__c')( + state + ), + 'n0:area': dataValue('new[0].Area__c')(state), + 'n0:Area_Name': dataValue('new[0].Area_Name__c')(state), + 'n0:Total_Household_Members': dataValue( + 'new[0].Total_Number_of_Members__c' + )(state), + 'n0:Household_Status': () => { + var str = ''; + if (dataValue('new[0].Active_Household__c')(state) === false) { + str = 'No'; + } else { + str = 'Yes'; + } + return str; + }, + 'n0:Total_Over_5': () => { + var num = 0; + num = + dataValue('new[0].Total_Number_of_Members__c')(state) - + dataValue('new[0].Total_Number_of_Under_5s__c')(state); + return num; + }, + }, + 'n0:index': { + 'n0:parent': { + '@': { + case_type: 'Area', + }, + '#': dataValue('new[0].Area_Case_ID__c')(state), + }, + }, + }; + }), + field('n1:meta', state => { + return { + '@': { 'xmlns:n1': 'http://openrosa.org/jr/xforms' }, + 'n1:deviceID': 'Formplayer', + 'n1:timeStart': new Date().toISOString(), + 'n1:timeEnd': new Date().toISOString(), + 'n1:userID': 'e298884bfb6ee2d2b38591a6e8ae0228', + }; + }) + ) + ); + + triggers: + webhook: + type: webhook + enabled: false + edges: + webhook->Update-Household-in-CommCare: + source_trigger: webhook + target_job: Update-Household-in-CommCare + condition_type: js_expression + condition_label: SF Update HH + condition_expression: | + state.data.label == "Update Household" + enabled: false + "x-[archive]-Update-Person-in-CommCare-V2": + name: 'x [archive] Update Person in CommCare V2' + jobs: + Update-Person-in-CommCare-V2: + name: Update Person in CommCare V2 + adaptor: '@openfn/language-commcare@latest' + credential: null + body: | + submit( + fields( + field('@', state => { + return { + 'xmlns:jrm': 'http://dev.commcarehq.org/jr/xforms', + xmlns: () => { + return dataValue('new[0].Catchment__c')(state) == 'a001p000017gpfZAAQ' + ? 'http://openrosa.org/formdesigner/457C806C-B47D-44F0-BE4B-7E88F7162D1D' + : 'http://openrosa.org/formdesigner/a34af027a7fa943998c39f64bc84a337a668114a'; + }, + uiVersion: '1', + version: '81', + name: () => { + return dataValue('new[0].Catchment__c')(state) == 'a001p000017gpfZAAQ' + ? 'Update Person MOH' + : 'Update Person'; + }, + }; + }), + field('Source', 0), + field('Status', state => { + return { + Client_Status: dataValue('new[0].Client_Status__c')(state), + Date_of_Transfer_Out: dataValue('new[0].Date_of_Transfer_Out__c')( + state + ), + Date_Last_Seen: dataValue('new[0].Date_Last_Seen__c')(state), + Date_of_Death: dataValue('new[0].Date_of_Death__c')(state), + Cause_of_Death: dataValue('new[0].Cause_of_Death__c')(state), + }; + }), + field('Basic_Information', state => { + return { + Basic_Information: { + Phone_Number: dataValue('new[0].Telephone__c')(state), + Final_Program: () => { + var program = ''; + if ( + dataValue('new[0].Active_In_Thrive_Thru_5__c')(state) == 'Yes' || + dataValue('new[0].Active_TT5_Mother__c')(state) == 'Yes' + ) { + if (dataValue('new[0].Active_In_HAWI__c')(state) == 'Yes') { + program = 'Both'; + } else { + program = 'Thrive_Through_5'; + } + } else { + if (dataValue('new[0].Active_In_HAWI__c')(state) == 'Yes') { + program = 'HAWI'; + } + } + return program; + }, + }, + }; + }), + field('TT5', state => { + return { + Child_Information: { + ANCs: { + ANC_1: dataValue('new[0].ANC_1__c')(state), + ANC_2: dataValue('new[0].ANC_2__c')(state), + ANC_3: dataValue('new[0].ANC_3__c')(state), + ANC_4: dataValue('new[0].ANC_4__c')(state), + ANC_5: dataValue('new[0].ANC_5__c')(state), + }, + Delivery_Information: { + Person_Name: dataValue('new[0].Name')(state), + DOB: dataValue('new[0].Date_of_Birth__c')(state), + Delivery_Type: () => { + var val = ''; + if (dataValue('new[0].Place_of_Delivery__c')(state) == 'Home') { + val = 'Unskilled'; + } else if ( + dataValue('new[0].Place_of_Delivery__c')(state) == 'Facility' + ) { + val = 'Skilled'; + } + return val; + }, + Delivery_Facility: dataValue('new[0].Delivery_Facility__c')(state), + }, + Immunizations: { + BCG: dataValue('new[0].BCG__c')(state), + OPV_0: dataValue('new[0].OPV_0__c')(state), + OPV_PCV_Penta_1: dataValue('new[0].OPV_1__c')(state), + OPV_PCV_Penta_2: dataValue('new[0].OPV_2__c')(state), + OPV_PCV_Penta_3: dataValue('new[0].OPV_3__c')(state), + Measles_6: dataValue('new[0].Measles_6__c')(state), + Measles_9: dataValue('new[0].Measles_9__c')(state), + Measles_18: dataValue('new[0].Measles_18__c')(state), + Fully_Immunized: dataValue( + 'new[0].Fully_Immunized_at_12_Months__c' + )(state), + }, + /*"CCMM":{ + "Home_Test_Date":dataValue("new[0].Measles_18__c")(state), + "Home_Test_Date":dataValue("new[0].Measles_18__c")(state), + "Home_Test_Date":dataValue("new[0].Measles_18__c")(state), + "Home_Test_Date":dataValue("new[0].Measles_18__c")(state), + "Home_Test_Date":dataValue("new[0].Measles_18__c")(state), + }*/ + }, + Mother_Information: { + Pregnant: () => { + if (dataValue('new[0].Pregnant__c')(state) === true) { + return 'Yes'; + } + }, + }, + }; + }), + field('HAWI', state => { + return { + Unique_Patient_Code: dataValue('new[0].Unique_Patient_Code__c')(state), + Support_Group: dataValue('new[0].Active_in_Support_Group__c')(state), + Preferred_Care_F: { + Preferred_Care_Facility: dataValue( + 'new[0].Preferred_Care_Facility__c' + )(state), + }, + }; + }), + + field('n0:case', state => { + return { + '@': { + case_id: dataValue('new[0].CommCare_ID__c')(state), + date_modified: new Date().toISOString(), + user_id: 'e298884bfb6ee2d2b38591a6e8ae0228', + 'xmlns:n0': 'http://commcarehq.org/case/transaction/v2', + }, + 'n0:create': { + 'n0:case_name': () => { + var name1 = dataValue('new[0].Name')(state); + var name2 = name1.replace(/\w\S*/g, function (txt) { + return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); + }); + return name2; + }, + 'n0:case_type': 'Person', + 'n0:parent_id': dataValue('new[0].CommCare_HH_Code__c')(state), + }, + 'n0:update': { + 'n0:ANC_1': dataValue('new[0].ANC_1__c')(state), + + 'n0:ANC_2': dataValue('new[0].ANC_2__c')(state), + 'n0:ANC_3': dataValue('new[0].ANC_3__c')(state), + 'n0:ANC_4': dataValue('new[0].ANC_4__c')(state), + 'n0:ANC_5': dataValue('new[0].ANC_5__c')(state), + 'n0:BCG': dataValue('new[0].BCG__c')(state), + 'n0:Fully_Immunized': dataValue( + 'new[0].Fully_Immunized_at_12_Months__c' + )(state), + 'n0:Delivery_Type': () => { + var val = ''; + if (dataValue('new[0].Place_of_Delivery__c')(state) == 'Home') { + val = 'Unskilled'; + } else if ( + dataValue('new[0].Place_of_Delivery__c')(state) == 'Facility' + ) { + val = 'Skilled'; + } + return val; + }, + 'n0:Delivery_Facility': dataValue('new[0].Delivery_Facility__c')( + state + ), + 'n0:Family_Planning_Method': dataValue( + 'new[0].Family_Planning_Method__c' + )(state), + 'n0:Child_Status': dataValue('new[0].Child_Status__c')(state), + 'n0:Active_in_OSG_Mentoring': dataValue('new[0].Active_in_OSG__c')( + state + ), + 'n0:OSG_Mentoring_Group': dataValue('new[0].OSG_Group__c')(state), + 'n0:OPV_0': dataValue('new[0].OPV_0__c')(state), + 'n0:OPV_PCV_Penta_1': dataValue('new[0].OPV_1__c')(state), + 'n0:OPV_PCV_Penta_2': dataValue('new[0].OPV_2__c')(state), + 'n0:OPV_PCV_Penta_3': dataValue('new[0].OPV_3__c')(state), + 'n0:Current_Height': dataValue('new[0].Current_Height__c')(state), + 'n0:Current_Weight': dataValue('new[0].Current_Weight__c')(state), + 'n0:Current_MUAC': dataValue('new[0].Current_MUAC__c')(state), + 'n0:Measles_6': dataValue('new[0].Measles_6__c')(state), + 'n0:Measles_9': dataValue('new[0].Measles_9__c')(state), + 'n0:LMP': dataValue('new[0].LMP__c')(state), + 'n0:EDD': dataValue('new[0].EDD__c')(state), + 'n0:Measles_18': dataValue('new[0].Measles_18__c')(state), + 'n0:Pregnant': () => { + if (dataValue('new[0].Pregnant__c')(state) === true) { + return 'Yes'; + } + }, + 'n0:ART': dataValue('new[0].Currently_on_ART_s__c')(state), + 'n0:ARVs': dataValue('new[0].ART_Regimen__c')(state), + 'n0:Active_in_Support_Group': dataValue( + 'new[0].Active_in_Support_Group__c' + )(state), + 'n0:Client_Program': () => { + var program = ''; + if ( + dataValue('new[0].Active_in_Thrive_Thru_5__c')(state) == 'Yes' || + dataValue('new[0].Active_TT5_Mother__c')(state) == 'Yes' + ) { + if (dataValue('new[0].Active_in_HAWI__c')(state) == 'Yes') { + program = 'Both'; + } else { + program = 'Thrive_Through_5'; + } + } else { + if (dataValue('new[0].Active_in_HAWI__c')(state) == 'Yes') { + program = 'HAWI'; + } + } + return program; + }, + 'n0:Currently_on_family_planning': dataValue( + 'new[0].Family_Planning__c' + )(state), + 'n0:DOB': dataValue('new[0].Date_of_Birth__c')(state), + 'n0:Education_Level': () => { + if (dataValue('new[0].Education_Level__c')(state) !== undefined) { + return dataValue('new[0].Education_Level__c')(state) + .toString() + .replace(/ /g, '_'); + } + }, + 'n0:Ever_on_Family_Planning': dataValue( + 'new[0].Ever_on_Family_Planning__c' + )(state), + 'n0:Gender': dataValue('new[0].Gender__c')(state), + 'n0:Gravida': dataValue('new[0].Gravida__c')(state), + 'n0:Active_in_TT5': dataValue('new[0].Active_in_Thrive_Thru_5__c')( + state + ), + 'n0:Active_in_HAWI': dataValue('new[0].Active_in_HAWI__c')(state), + 'n0:Marital_Status': dataValue('new[0].Marital_Status__c')(state), + 'n0:Exclusive_Breastfeeding': dataValue( + 'new[0].Exclusive_Breastfeeding__c' + )(state), + 'n0:Next_of_Kin': dataValue('new[0].Next_of_Kin__c')(state), + 'n0:Next_of_Kin_Phone': dataValue('new[0].Next_of_Kin_Phone__c')( + state + ), + 'n0:Parity': dataValue('new[0].Parity__c')(state), + + 'n0:Phone_Number': dataValue('new[0].Telephone__c')(state), + 'n0:Preferred_Care_Facility': dataValue( + 'new[0].Preferred_Care_Facility__c' + )(state), + 'n0:Record_Type': () => { + return dataValue('new[0].Record_Type_Name__c')(state) + .toString() + .replace(/ /g, '_'); + }, + 'n0:Unique_Patient_Code': dataValue('new[0].Unique_Patient_Code__c')( + state + ), + }, + 'n0:index': { + 'n0:parent': { + '@': { + case_type: 'Household', + }, + '#': dataValue('new[0].CommCare_HH_Code__c')(state), + }, + }, + }; + }), + + field('n2:meta', state => { + return { + '@': { 'xmlns:n2': 'http://openrosa.org/jr/xforms' }, + 'n2:deviceID': 'Formplayer', + 'n2:timeStart': new Date().toISOString(), + 'n2:timeEnd': new Date().toISOString(), + 'n2:userID': 'e298884bfb6ee2d2b38591a6e8ae0228', + }; + }) + ) + ); + + triggers: + webhook: + type: webhook + enabled: false + edges: + webhook->Update-Person-in-CommCare-V2: + source_trigger: webhook + target_job: Update-Person-in-CommCare-V2 + condition_type: js_expression + condition_label: SF Update Person + condition_expression: | + state.data.label == "Update Person" + enabled: false + "x-[archive]-Upsert-Person-Visit-[Q3-2022]": + name: 'x [archive] Upsert Person Visit [Q3 2022]' + jobs: + Q3-2022-Upsert-Person-Visit: + name: Q3 2022 Upsert Person Visit + adaptor: '@openfn/language-salesforce@4.8.6' + credential: aleksa@openfn.org-Lwala-Salesforce-Prod---openfn-user + body: | + //UPSERT PERSON VISIT + query( + `SELECT Id, Parent_Geographic_Area__c, Parent_Geographic_Area__r.Name, Parent_Geographic_Area__r.Parent_Geographic_Area__c FROM Location__c WHERE CommCare_User_ID__c = '${dataValue( + 'properties.owner_id' + )(state)}'` + ); + + fn(state => { + state.cleanChoice = function (state, choice) { + if (choice) { + return choice.charAt(0).toUpperCase() + choice.slice(1).replace('_', ' '); + } else { + return ''; + } + }; + + fn(state => ({ + ...state, + data: { + ...state.data, + catchmentNewId: + state.references[0].records && state.references[0].records.length !== 0 + ? (state.references[0].records[0].Parent_Geographic_Area__r + ? state.references[0].records[0].Parent_Geographic_Area__r.Parent_Geographic_Area__c + : undefined) + : undefined, + }, + })); + + state.handleMultiSelect = function (state, multiField) { + return multiField + ? multiField + .replace(/ /gi, ';') + .toLowerCase() + .split(';') + .map(value => { + return ( + value.charAt(0).toUpperCase() + value.slice(1).replace('_', ' ') + ); + }) + .join(';') + : ''; + }; + + state.handleMultiSelectOriginal = function (state, multiField) { + return multiField + ? multiField + .replace(/ /gi, ';') + .toLowerCase() + .split(';') + .map(value => { + return ( + value + ); + }) + .join(';') + : ''; + }; + + const pregDangerMap = { + Vaginal_Bleeding: 'Vaginal Bleeding', + Water_Breaks: 'Water Breaks before Time of Delivery', + Prolonged_Labour: 'Prolonged Labour over 12 Hours', + Convulsions: 'Convulsions or Fits', + Abdominal_Pain: 'Severe Abdominal Pain before Delivery', + High_Fever: 'High Fever', + Low_Baby_Movement: 'Feeling the Baby move less or not at all', + Swelling: 'Swelling of Face and Hands', + Severe_Headache: 'Severe or Continuous Headache for more than 12 hours', + Severe_Vomiting: 'Severe or Continuous Vomiting', + none: 'None', + }; + + const counselMap = { + anc_visits: 'ANC Visits', + early_initiation_of_anc_less_than_3_months: + 'Early initiation of ANC (less than 3 months)', + completing_recomended_anc_visits: 'Completing recomended ANC visits', + danger_signs: 'Danger signs', + skilled_birth: 'Skilled birth', + immunization: 'Immunization', + individual_birth_plan: 'Individual Birth Plan', + emergency_preparedness: 'Emergency preparedness', + childcare_and_affection: 'Childcare and affection', + nutrition_counseling: 'Nutrition counseling', + growth_monitoring: 'Growth monitoring', + exclusive_breastfeeding: 'Exclusive breastfeeding', + complementary_feeding: 'Complementary feeding', + sleeping_under_llitn: 'Sleeping under LLITN', + knowing_hiv_status: 'Knowing HIV status', + indoor_pollution: 'Indoor pollution', + personal_hygiene: 'Personal Hygiene', + safe_drinking_water: 'Safe drinking water', + safe_disposal_of_human_waste: 'Safe disposal of human waste', + }; + + const serviceMap = { + Scheduled_PSC_Apt: 'Scheduled PSC Apt', + Adverse_Drug_Reaction_Side_Effect: 'Adverse Drug Reaction/Side Effect', + Malnutrition: 'Malnutrition', + Malaria: 'Malaria', + TB: 'TB', + Treatment_for_Other_OIs: 'Treatment for other Ols', + ARI: 'ARI', + Anemia: 'Anemia', + Diarrhea: 'Diarrhea', + Pregnancy_Care: 'Pregnancy Care (ANC)', + Family_Planning: 'Family Planning (FP)', + Preconception_Counseling: 'Preconception Counseling', + Injury: 'Injury', + Other: 'Other', + }; + + const reasonMap = { + lack_of_access_to_fp_information: 'Lack of access to FP information', + no_access_to_fp_services_hospitals: + 'Lack of hospitals or places where FP services can be accessed', + not_willing_to_use_fp_due_to_negative_effects_myths_and_misconceptions: + 'Myths and misconceptions', + barriers_at_service_delivery_points: 'Barriers at service delivery points', + pregnant: 'The client is pregnant', + intentions_of_getting_pregnant: 'Intentions of getting pregnant', + not_sexually_active: 'The client is not sexually active', + other_barriers_culture_male_partners_parents_etc: + 'Other barriers (culture, male partners, parents, etc)', + }; + + const milestoneTypeMap = { + cognitive_delays_learning_difficulties: + 'Cognitive Delays Learning Difficulties', + motor_delays: 'Motor Delays', + speech_and_language_delay: 'Delay Speech and Language Delay', + social_and_emotional: 'Social and emotional', + }; + + const milestoneMap = { + movement: 'Movement', + hearing: 'Hearing', + communication: 'Communication', + seeing: 'Seeing', + cognitive_delays: 'Cognitive Delays', + play: 'Play', + }; + const nutritionMap = { + severe: 'Severely Malnourished', + moderate: 'Moderately Malnourished', + normal: 'Normal', + }; + + const fpMethodMap = { + male_condoms: "Male condoms", + female_condoms: "Female condoms", + pop: "POP", + coc: "COC", + emergency_pills: "Emergency pills", + none: "None", + //HMN -12/01/2023- + //adding normalization for the family_planning_method to Family_Planning_Method__c + iucd: "IUCD", + condoms: "Condoms", + depo:"Depo", + implant: "Implant", + injection: "Injection", + pills: "Pills", + traditional: "Traditional" + }; + + const symptomsMap = { + convulsions: 'Convulsions', + not_able_to_eatdrink: 'Not able to drink or feed at all', + vomits_everything: 'Vomits everything', + 'chest_in-drawing': 'Chest in - drawing', + unusually_sleepyunconscious: 'Unusually sleepy or unconscious', + swelling_of_both_feet: 'Swelling of both feet', + none: "None", + }; + + const supervisorMap ={ + community_health_nurse: "Community_health_nurse", + chw_supervisor: "CHW_supervisor", + chewschas: "Chewschas", + other: "Other", + none: "None" + }; + + const treatmentDistributionMap = { + ors_205gltr_sachets: 'ORS (20.5h/ltr): Sachets', + acts_6s: 'ACTs (6s)', + acts_12s: 'ACTs (12s)', + acts_18s: 'ACTs (18s)', + acts_24s: 'ACTs (24s)', + albendazole_abz_tabs: 'Albendazole (ABZ): Tabs', + paracetamol_tabs: 'Tetracycline Eye Ointment (TEO): 1%:tube', + tetracycline_eye_ointment_teo_1_tube: 'Tetracycline Eye Ointment (TEO): 1%:tube', + amoxycillin: 'Amoxycillin (125mg/5mls: Bottle', + none: 'None' + }; + + const childDangerSignsMap = { + none: 'None', + Poor_Breastfeeding: 'Poor Breastfeeding', + not_able_to_feed_since_birth_or_stopped_feeding_well: 'Not able to feed since birth, or stopped feeding well', + not_able_to_breastfeed: 'Not able to breastfeed', + Fever: 'Fever', + very_low_temperature: 'Very low temperature (35.4 C or less)', + shivering: 'Shivering', + Fast_Breathing: 'Fast Breathing', + Very_Sleepy: 'Very Sleepy', + Convulsions_and_Fits: 'Convulsions and Fits', + only_moves_when_stimulated_or_does_not_move_even_on_stimulation: 'Only moves when stimulated, or does not move even on stimulation', + yellow_solebaby_body_turning_yellow_especially_eyes_palms_soles: 'Yellow sole(Baby body turning yellow especially eyes, palms,soles)', + bleeding_from_the_umbilical_stump: 'Bleeding from the umbilical stump', + signs_of_local_infection_umbilicus_is_red_or_draining_pus_skin_boils_or_eye: 'Signs of local infection: umbilicus is red or draining pus, skin boils, or eyes draining pus', + weight_chart_using_color_coded_scales_if_red_or_yellowweight_below_25kg_or_: 'Weight chart using color coded scales if RED or YELLOW(Weight below 2.5kg or born less than 36 weeks of age)', + unable_to_cry: 'Unable to cry', + cyanosis: 'Cyanosis', + bulging_fontanelle: 'Bulging fontanelle' + } + + return { + ...state, + counselMap, + serviceMap, + reasonMap, + milestoneTypeMap, + milestoneMap, + nutritionMap, + pregDangerMap, + fpMethodMap, + symptomsMap, + supervisorMap, + treatmentDistributionMap, + childDangerSignsMap + }; + }); + + upsertIf( + // state.data.properties.username !== 'openfn.test' && + state.data.properties.username !== 'test.2021' && + state.data.properties.test_user !== 'Yes' , + 'Person_visit__c', + 'CommCare_ID__c', + fields( + //field('CommCare_ID__c', dataValue('form.case.@case_id')), + // field('CommCare_ID__c', dataValue('id')), + //field('CommCare_ID__c', state => { + // var case_id = dataValue('case_id')(state); + // var submitted = dataValue('properties.last_form_opened_date_and_time')(state); + // return case_id + '_' + submitted; + //}), + field('CommCare_ID__c',dataValue('case_id')), + + relationship( + 'Person__r', + 'CommCare_ID__c', + dataValue('indices.parent.case_id') + ), + /*relationship( + 'Household_CHW__r', + 'CommCare_ID__c', + dataValue('properties.sfid')),*/ + // field('CommCare_Visit_ID__c',dataValue('metadata.instanceID')), + field('CommCare_Visit_ID__c', state => { + var case_id = dataValue('case_id')(state); + var submitted = dataValue('properties.last_form_opened_date_and_time')(state); + return case_id + '_' + submitted; + }), + field('Date__c',dataValue('properties.Date')), + field('Form_Submitted__c', dataValue('properties.last_form_opened_name')), + field('Birth_Status__c',dataValue('properties.child_status')), + field('Catchment__c', dataValue('catchmentNewId')), + /* + //HMN 05/01/2022 Caused alot of failures, removed this RecordType Field + relationship('RecordType', 'Name', state => { + var rt = dataValue('properties.RecordType')(state); + if (rt === 'Unborn' || rt === 'Child') { + return 'Child Visit'; + }; + if (rt === 'Youth') { + return 'Youth Visit'; + }; + if (rt === 'Male Adult') { + return 'Adult Male Visit'; + }; + if (rt === 'Female Adult') { + return 'Adult Female Visit'; + }; + }),*/ + field('Use_mosquito_net__c', state => { + var choice = dataValue( + 'properties.sleep_under_net' + )(state); + return state.cleanChoice(state, choice); + }), + field( + 'Individual_birth_plan_counselling__c', + dataValue('properties.individual_birth_plan') + ), + field('Reason_for_not_taking_a_pregnancy_test__c', state => { + var reason = dataValue('properties.No_Preg_Test')(state); + return reason ? reason.toString().replace(/_/g, ' ') : undefined; + }), + field('Pregnancy_danger_signs__c', state => { + var signs = dataValue( + 'properties.No_Preg_Test' + )(state); + return signs ? state.pregDangerMap[signs] : undefined; + }), + field('Child_Danger_Signs__c', state => { + var signs = dataValue( + 'properties.Other_Danger_Signs' + )(state); + return signs ? state.childDangerSignsMap[signs] : undefined + }), + field('Current_Malaria_Status__c', state => { + var choice = dataValue( + 'properties.malaria_test_results' + )(state); + return state.cleanChoice(state, choice); + }), + field('Malaria_Home_Test__c', dataValue('properties.malaria_test_date')), + /*field('Current_Malaria_Status__c', state => { + var choice = dataValue( + 'properties.Malaria_Status' + )(state); + return state.cleanChoice(state, choice); + }),*/ + // field('Malaria_Home_Treatment__c',dataValue('form.treatment_and_tracking.home_treatment')), + field('Malaria_Home_Treatment__c', dataValue('properties.malaria_test_date')), + field('Persons_symptoms__c', state => { + var check = dataValue('properties.symptoms_check_other')(state); + var value = + check && check !== '' + ? check + .replace(/ /gi, ';') + .split(';') + .map(value => { + return state.symptomsMap[value] || value; + }) + : undefined; + return value ? value.join(';') : undefined; + }), + field('Active_in_Support_Group__c', dataValue('properties.Active_in_Support_Group')), + field('HAWI_Defaulter__c', state => { + var hawi = dataValue('properties.default')(state); + return hawi === 'Yes' ? true : false; + }), + field( + 'Date_of_Default__c', + dataValue('properties.date_of_default') + ), + field( + 'Persons_temperature__c', + dataValue('properties.temperature') + ), + field( + 'Days_since_illness_start__c', + dataValue('properties.duration_of_sickness') + ), + field( + 'Newborn_visited_48_hours_of_delivery__c', + dataValue( + 'properties.newborn_visited_48_hours_of_delivery' + ) + ), + field( + 'Newborn_visited_by_a_CHW_within_6_days__c', + dataValue('properties.visit_6_days_from_delivery') + ), + field( + 'Current_Malaria_Status__c', + dataValue('properties.malaria_test_results') + ), + field('Malaria_test__c', state => { + var choice = dataValue( + 'properties.malaria_test' + )(state); + return state.cleanChoice(state, choice); + }), + field('Fever__c', state => { + var choice = dataValue( + 'properties.symptoms_check_fever' + )(state); + return state.cleanChoice(state, choice); + }), + field('Cough__c', state => { + var choice = dataValue( + 'properties.symptoms_check_cough' + )(state); + return state.cleanChoice(state, choice); + }), + field('Diarrhoea__c', state => { + var choice = dataValue( + 'properties.symptoms_check_diarrhea' + )(state); + return state.cleanChoice(state, choice); + }), + field( + 'TB_patients_therapy_observed__c', + dataValue('properties.observed_tb_therapy') + ), + field( + 'Injuries_or_wounds__c', + dataValue('properties.wounds_or_injuries') + ), + field('Currently_on_ART_s__c', dataValue('properties.ART')), + /*field('ART_Regimen__c', state => { + var choice = dataValue( + 'properties.ARVs' + )(state); + return state.cleanChoice(state, choice); + }),*/ + field( + 'Immediate_Breastfeeding__c', + dataValue( + 'properties.Breastfeeding_Delivery' + ) + ), + field( + 'Exclusive_Breastfeeding__c', + dataValue( + 'properties.Exclusive_Breastfeeding' + ) + ), + field( + 'Counselled_on_Exclusive_Breastfeeding__c', + dataValue('properties.counseling') + ), + field('LMP__c',dataValue('properties.when_was_your_lmp')), + field('Family_Planning__c', state => { + var choice = dataValue( + 'properties.family_planning' + )(state); + return state.cleanChoice(state, choice); + }), + //HMN 12/01/2023 Failures on picklist within Salesforce + /* + field( + 'Family_Planning_Method__c', + dataValue('properties.family_planning_method') + ),*/ + field('Family_Planning_Method__c', state => { + //var status = dataValue('form.treatment_and_tracking.distribution.distributed_treatments')(state); + var status = dataValue('properties.family_planning_method')(state); + var value = + status && status !== '' + ? status + .replace(/ /gi, ';') + .split(';') + .map(value => { + return state.fpMethodMap[value] || value; + }) + : undefined; + return value ? value.join(';') : undefined; + }), + field('FP_Method_Distributed__c', state => { + //var status = dataValue('form.treatment_and_tracking.distribution.distributed_treatments')(state); + var status = dataValue('properties.FP_commodity')(state); + var value = + status && status !== '' + ? status + .replace(/ /gi, ';') + .split(';') + .map(value => { + return state.fpMethodMap[value] || value; + }) + : undefined; + return value ? value.join(';') : undefined; + }), + field('Reasons_for_not_taking_FP_method__c', state => { + // var reason = dataValue('form.TT5.Mother_Information.No_FPmethod_reason')(state); + // return reason ? state.reasonMap[reason] : undefined; + var status = dataValue('properties.No_FPmethod_reason')(state); + var value = + status && status !== '' + ? status + .replace(/ /gi, ';') + .split(';') + .map(value => { + return state.reasonMap[value] || value; + }) + : undefined; + return value ? value.join(';') : undefined; + }), + field('Pregnant__c', state => { + var preg = dataValue('properties.Pregnant')(state); + return preg === 'Yes' ? true : false; + }), + field('Counselled_on_FP_Methods__c', state => { + var choice = dataValue( + 'properties.CounselledFP_methods' + )(state); + return state.cleanChoice(state, choice); + }), + field('Client_counselled_on__c', state => { + var choices = + dataValue('properties.counsel_topic')( + state + ) || dataValue('properties.counsel_topic')(state); + var choiceGroups = choices ? choices.split(' ') : null; + var choicesMulti = choiceGroups + ? choiceGroups + .map(cg => { + return state.counselMap[cg]; + }) + .join(';') + : choiceGroups; + return choicesMulti; + }), + field('Client_provided_with_FP__c', state => { + var choice = dataValue( + 'properties.was_the_woman_15-49yrs_provided_with_family_planning_commodities_by_chv' + )(state); + return state.cleanChoice(state, choice); + }), + field( + 'Newborn_visited_48_hours_of_delivery__c', + dataValue( + 'properties.newborn_visited_48_hours_of_delivery' + ) + ), + field('Mother_visit_counselling__c', state => { + var choice = dataValue( + 'properties.did_you_consel_the_mother_on1' + )(state); + return state.handleMultiSelectOriginal(state, choice); + }), + field( + 'mother_visited_48_hours_of_the_delivery__c', + dataValue('properties.visit_mother_48') + ), + field('Newborn_visit_counselling__c', state => { + var choice = dataValue( + 'properties.did_you_consel_the_mother_on2' + )(state); + return state.handleMultiSelectOriginal(state, choice); + }), + field('Know_HIV_status__c', state => { + var choice = dataValue( + 'properties.known_hiv_status' + )(state); + return state.cleanChoice(state, choice); + }), + field('HIV_Status__c', dataValue('properties.hiv_status')), + field('Treatment_Distribution__c', state => { + //var status = dataValue('form.treatment_and_tracking.distribution.distributed_treatments')(state); + var status = dataValue('properties.distributed_treatments')(state); + var value = + status && status !== '' + ? status + .replace(/ /gi, ';') + .split(';') + .map(value => { + return state.treatmentDistributionMap[value] || value; + }) + : undefined; + return value ? value.join(';') : undefined; + }), + field( + 'Current_Weight__c', + dataValue('properties.Current_Weight') + ), + field( + 'Current_Height__c', + dataValue('properties.current_height') + ), + field( + 'Current_MUAC__c', + dataValue('properties.MUAC') + ), + field('Food_groups_3_times_a_day__c',dataValue('properties.food_groups')), + field('Nutrition_Case_Managed__c',dataValue('properties.nutrition_case_managed')), + field('Nutrition_Danger_Signs__c',state => { + var choice = dataValue( + 'properties.nutrition_danger_signs' + )(state); + return state.handleMultiSelectOriginal(state, choice); + + }), + field('Why_was_nutrition_case_not_managed__c',dataValue('properties.nutrition_case_not_managed_why')), + field('Community_Nutrition_Treatment__c',dataValue('properties.nutrition_treatment_severe')), + field('Community_Nutrition_Treatment__c',dataValue('properties.nutrition_treatment_moderate')), + field('Why_was_nutrition_treatment_not_given__c',dataValue('properties.nutrition_treatment_not_given')), + field('Current_Nutrition_Status__c', state => { + var status = dataValue( + 'properties.Nutrition_Status' + )(state); + return status ? state.nutritionMap[status] : undefined; + }), + field('Default_on_TB_treatment__c', state => { + var choice = dataValue( + 'properties.default_tb_treatment' + )(state); + return state.cleanChoice(state, choice); + }), + field('Received_pregnancy_test__c', state => { + var choice = dataValue( + 'properties.did_you_adminsiter_a_pregnancy_test' + )(state); + return state.cleanChoice(state, choice); + }), + field('Pregnancy_test_result__c', state => { + var choice = dataValue( + 'properties.pregnancy_test_result' + )(state); + return state.cleanChoice(state, choice); + }), + field('Chronic_illness__c', state => { + var choice = dataValue( + 'properties.please_specify_which_chronic_illness_the_person_has' + )(state); + var choice2 = state.handleMultiSelect(state, choice); + return choice2 ? choice2.replace(/_/g, ' ') : ''; + }), + /*field( + 'Birth_Certificate__c', + dataValue('form.Status.birth_certificate') + ), + field( + 'Child_zinc__c', + dataValue( + 'form.TT5.Child_Information.Clinical_Services.diarrhea_clinic_treatment_zinc' + ) + ), + field( + 'Child_ORS__c', + dataValue( + 'form.TT5.Child_Information.Clinical_Services.diarrhea_clinic_treatment_ORS' + ) + ),*/ + field( + 'Childs_breath_per_minute__c', + dataValue('properties.breaths_per_minuite') + ), + field( + 'Child_chest_in_drawing__c', + dataValue('properties.Child_chest_in_drawing_c') + ), + field( + 'Caregiver_counseled_on_delayed_milestone__c', + dataValue( + 'properties.did_you_counsel_the_caregiver_on_delayed_milestones' + ) + ), + field( + 'Delayed_Milestone__c', + dataValue( + 'properties.does_the_child_has_a_delayed_milestone' + ) + ), + field( + 'Child_has_2_or_more_play_items__c', + dataValue( + 'properties.does_the_child_has_2_or_more_play_items_at_home' + ) + ), + field( + 'Child_has_3_more_picture_books__c', + dataValue( + 'properties.does_the_child_has_3_or_more_picture_books' + ) + ), + field('Delayed_Milestones_Counselled_On__c', state => { + var ms = dataValue( + 'properties.which_delayed_milestone_area_did_you_counsel_the_caregiver_on' + )(state); + return ms ? state.milestoneMap[ms] : undefined; + }), + field('Delayed_Milestone_Type__c', state => { + var ms = dataValue('properties.which_delayed_milestone')( + state + ); + return ms ? state.milestoneTypeMap[ms] : undefined; + }), + field( + 'Caretaker_trained_in_muac__c', + dataValue('properties.mother_trained_muac') + ), + field( + 'Caretaker_screened_for_muac_this__c', + dataValue( + 'properties.mother_screened_child_muac' + ) + ), + field( + 'Caretaker_muac_findings__c', + dataValue( + 'properties.mother_screened_child_muac_result' + ) + ), + field( + 'Caretaker_action_after_muac_screening__c', + dataValue( + 'properties.mother_screened_muac_action' + ) + ), + field( + 'of_Caretaker_MUAC_screenings__c', + dataValue('properties.mother_nb_screening') + ), + field('Pulse_Oximeter__c', dataValue('properties.pulse_oximeter_available')), + field( + 'Heart_Rate_Pulse_Oximeter__c', + dataValue('properties.heart_rate_pulse_oximeter') + ), + field( + 'Oxygen_Concentration_Pulse_Oximeter__c', + dataValue('properties.oxygen_concentration') + ), + field('Can_child_drink__c', dataValue('properties.can_child_drink')), + field( + 'Antibiotic_provided_for_fast_breathing__c', + dataValue('properties.antibiotic_fast_breathing') + ), + field( + 'Antibiotic_provided_for_chest_indrawing__c', + dataValue('properties.antibiotic_chest_indrawing') + ), + field('Supervisor_Visit__c', state => { + var check = dataValue('properties.supervisor_visit')(state); + var value = + check && check !== '' + ? check + .replace(/ /gi, ';') + .split(';') + .map(value => { + return state.supervisorMap[value] || value; + }) + : undefined; + return value ? value.join(';') : undefined; + }), + /* + //HMN- 05012023 - Removed field('Visit_Closed_Date__c', dataValue('date_closed')), + //Because I could not find it in Salesforce. It was causing errors on staging + field('Visit_Closed_Date__c', dataValue('date_closed')), + */ + //field('Case_Closed_Date__c', state => { + // var closed = dataValue('date_closed')(state); + // var date = dataValue('date_modified')(state); + // return closed && closed == true ? date : undefined; + // }) + ) + ); + + triggers: + webhook: + type: webhook + enabled: false + edges: + webhook->Q3-2022-Upsert-Person-Visit: + source_trigger: webhook + target_job: Q3-2022-Upsert-Person-Visit + condition_type: js_expression + condition_label: Person Visit + condition_expression: | + state.data.properties["app_release"] == "Q2-2022" && state.data.properties["case_type"] == "visite" && state.data.properties["test_user"] != "Yes" + enabled: true + "x-[archive]-Workflow-Nutrition-Survey-Submissions": + name: 'x [archive] Workflow Nutrition Survey Submissions' + jobs: + Nutrition-Survey-Submissions: + name: Nutrition Survey Submissions + adaptor: '@openfn/language-salesforce@v1.3.2' + credential: null + body: | + upsert( + 'Service__c', + 'Service_UID__c', + fields( + field('Service_UID__c', state => { + const id = dataValue('form.subcase_0.case.@case_id')(state); + const date = dataValue('$.form.Date')(state); + return id + date + 'Nutrition-Screening'; + }), + field('Source__c', 1), + field('Catchment__c', 'a002400000pAcOe'), + field('Date__c', dataValue('$.form.Date')), + field('Type_of_Service__c', 'CHW Mobile Survey'), + field('Household_CHW__c', dataValue('$.form.Household_CHW')), + field('RecordTypeID', '01224000000YAuK'), + field('Reason_for_Service__c', 'Nutrition Screening'), + relationship( + 'Person__r', + 'CommCare_ID__c', + dataValue('$.form.case.@case_id') + ), + field( + 'Primary_Caregiver__c', + dataValue('$.form.Child_Information.Primary_Caregiver') + ), + field('Height__c', dataValue('$.form.Child_Information.body_specs.Height')), + field('Weight__c', dataValue('$.form.Child_Information.body_specs.Weight')), + field('MUAC__c', dataValue('$.form.Child_Information.body_specs.MUAC')), + field('Nutrition_Status__c', state => { + var status = ''; + if ( + dataValue('$.form.Child_Information.malnourished.Nutrition_Status')( + state + ) == 'normal' + ) { + status = 'Normal'; + } else if ( + dataValue('$.form.Child_Information.malnourished.Nutrition_Status')( + state + ) == 'moderate' + ) { + status = 'Moderately Malnourished'; + } else if ( + dataValue('$.form.Child_Information.malnourished.Nutrition_Status')( + state + ) == 'severe' + ) { + status = 'Severely Malnourished'; + } + return status; + }), + field( + 'Ever_been_breastfed__c', + dataValue('$.form.Child_Information.infant_diet.ever_been_breastfed') + ), + field( + 'Age_at_which_breastfed__c', + dataValue('$.form.Child_Information.infant_diet.age_at_which_breastfed') + ), + field( + 'X24_Hours_Breastfed__c', + dataValue('$.form.Child_Information.infant_diet.how_many_times_24_hours') + ), + field( + 'Formula_Milk__c', + dataValue('$.form.Child_Information.infant_diet.has_had_formula') + ), + field( + 'Water__c', + dataValue('$.form.Child_Information.infant_diet.has_had_water') + ), + field( + 'Glucose__c', + dataValue('$.form.Child_Information.infant_diet.has_had_glucose') + ), + field( + 'Animal_Milk__c', + dataValue('$.form.Child_Information.infant_diet.has_had_animal_milk') + ), + field( + 'Juice__c', + dataValue('$.form.Child_Information.infant_diet.has_had_juice') + ), + field( + 'Sweetened_Drinks__c', + dataValue('$.form.Child_Information.infant_diet.has_had_sweetened_drinks') + ), + field( + 'Honey__c', + dataValue('$.form.Child_Information.infant_diet.has_had_honey') + ), + field( + 'Sugar__c', + dataValue('$.form.Child_Information.infant_diet.has_had_sugar') + ), + field( + 'Clear_Soup__c', + dataValue('$.form.Child_Information.infant_diet.has_had_clear_soup') + ), + field( + 'Grains__c', + dataValue('$.form.Child_Information.infant_diet.has_had_grains') + ), + field( + 'Yellow_Flesh__c', + dataValue('$.form.Child_Information.infant_diet.has_had_yellow_flesh') + ), + field( + 'Roots__c', + dataValue('$.form.Child_Information.infant_diet.has_had_roots') + ), + field( + 'Leafy_Vegetables__c', + dataValue('$.form.Child_Information.infant_diet.has_had_leafy_veg') + ), + field( + 'Fruits_or_Vegetables__c', + dataValue('$.form.Child_Information.infant_diet.has_had_other_fruit_veg') + ), + field( + 'Meat__c', + dataValue('$.form.Child_Information.infant_diet.has_had_meat') + ), + field( + 'Organ_Meat__c', + dataValue('$.form.Child_Information.infant_diet.has_had_organ_meat') + ), + field( + 'Eggs__c', + dataValue('$.form.Child_Information.infant_diet.has_had_eggs') + ), + field( + 'Dried_Silver_Fish__c', + dataValue('$.form.Child_Information.infant_diet.has_had_silver_fish') + ), + field( + 'Seafood__c', + dataValue('$.form.Child_Information.infant_diet.has_had_other_seafood') + ), + field( + 'Dairy__c', + dataValue('$.form.Child_Information.infant_diet.has_had_milk_products') + ), + field( + 'Fats__c', + dataValue('$.form.Child_Information.infant_diet.has_had_fats') + ), + field( + 'Sugary_Foods__c', + dataValue('$.form.Child_Information.infant_diet.has_had_sugary_foods') + ), + field( + 'Insects__c', + dataValue('$.form.Child_Information.infant_diet.has_had_insects') + ) + ) + ); + + alterState(state => { + if ( + dataValue('$.form.Child_Information.malnourished.Follow-Up_Required')( + state + ) === 'Yes' + ) { + return upsert( + 'Service__c', + 'Service_UID__c', + fields( + field('Service_UID__c', state => { + const id = dataValue('form.subcase_0.case.@case_id')(state); + const date = dataValue('$.form.Date')(state); + return id + date + 'Nutrition-Referral'; + }), + field('Source__c', 1), + field('Catchment__c', 'a002400000pAcOe'), + field('Date__c', dataValue('$.form.Date')), + field('Type_of_Service__c', 'CHW Mobile Survey'), + field('Household_CHW__c', dataValue('$.form.Household_CHW')), + field('RecordTypeID', '01224000000kOto'), + field('Referred__c', 1), + field( + 'Follow_Up_By_Date__c', + dataValue('$.form.Child_Information.malnourished.Follow-Up_By_Date') + ), + field('Reason_for_Service__c', 'Referral'), + field('Open_Case__c', 1), + field('CommCare_Code__c', dataValue('form.subcase_0.case.@case_id')), + field( + 'Purpose_of_Referral__c', + dataValue('form.Child_Information.malnourished.Purpose_of_Referral') + ), + relationship( + 'Person__r', + 'CommCare_ID__c', + dataValue('$.form.case.@case_id') + ) + ) + )(state); + } + + return state; + }); + + triggers: + webhook: + type: webhook + enabled: false + edges: + webhook->Nutrition-Survey-Submissions: + source_trigger: webhook + target_job: Nutrition-Survey-Submissions + condition_type: js_expression + condition_label: CommCare Nutrition Survey Update Person + condition_expression: | + state.data.form["@name"] == "Nutrition Survey" && state.data.metadata.username != "test.2021" + enabled: false + "x-[archive]-Workflow-Q3-2022-Upsert-Household-&-Household-Visit-in-SF": + name: 'x [archive] Workflow Q3 2022 Upsert Household & Household Visit in SF' + jobs: + Q3-2022-Upsert-Household-and-Household-Visit-in-SF: + name: Q3 2022 Upsert Household and Household Visit in SF + adaptor: '@openfn/language-salesforce@latest' + credential: null + body: | + query( + `SELECT Id, Parent_Geographic_Area__c, Parent_Geographic_Area__r.Name, Parent_Geographic_Area__r.Parent_Geographic_Area__c FROM Location__c WHERE CommCare_User_ID__c = '${dataValue( + 'properties.owner_id' + )(state)}'` + ); + + fn(state => { console.log("query1 done"); return state; }); + fn(state => { + return new Promise((resolve, reject) => { + setTimeout(() => { + console.log('4 second cooldown finished.'); + resolve(state); + }, 4000); + }); + }); + + fn(state => ({ + ...state, + data: { + ...state.data, + villageNewId: + state.references[0].records && state.references[0].records.length !== 0 + ? state.references[0].records[0].Id + : undefined, + areaNewId: + state.references[0].records && state.references[0].records.length !== 0 + ? state.references[0].records[0].Parent_Geographic_Area__c + : undefined, + catchmentNewId: + state.references[0].records && state.references[0].records.length !== 0 + ? (state.references[0].records[0].Parent_Geographic_Area__r + ? state.references[0].records[0].Parent_Geographic_Area__r.Parent_Geographic_Area__c + : undefined) + : undefined, + }, + })); + + upsertIf( + state.data.properties.commcare_username !== 'openfn.test' && + state.data.properties.commcare_username !== 'test.2021' && + state.data.properties.test_user !== 'Yes' , + 'Household__c', + 'CommCare_Code__c', + fields( + field('CommCare_Username__c', dataValue('properties.commcare_username')), + field('MOH_household_code__c', dataValue('properties.moh_code')), + field('CommCare_Code__c', dataValue('case_id')), + field('Source__c', true), + //field('Household_CHW__c', 'a030Q00000A0jeYQAR'), //sandbox hardcoded mapping + field('Household_CHW__c', state => { + var chw = dataValue('properties.CHW_ID')(state); + return chw === 'a030800001zQrk' + ? 'a030800001zQrk5' + : chw + ? chw + : undefined; + }), + //TODO: Prod mapping to add back before go-live + field('Catchment__c', dataValue('catchmentNewId')), + field('Area__c', dataValue('areaNewId')), + field('Village__c', dataValue('villageNewId')), + field('Household_Village__c', dataValue('properties.village')), + // relationship('Catchment__r', 'Name', state => { + // var catchment = + // state.data.properties.catchement || + // state.data.properties.catchment_name; + // return catchment === '' || catchment === undefined + // ? 'Unknown Location' + // : catchment; + // }), // check + // field('Area__c', state => { + // // var area = dataValue('properties.Area_Name')(state); + // return area === '' || area === undefined ? 'a000Q00000Egmu4' : area; + // }), // Commented out because it was causing a job error + // field('Household_village__c', dataValue('properties.village')),//case property, but not in message + + // field('Village__c',dataValue('properties.village_name')), //lookup + field('Deaths_in_the_last_6_months__c', state => { + var death = dataValue( + 'properties.deaths_in_past_6_months' + )(state); + return death > 0 ? 'Yes' : 'No'; + }), + field('Access_to_safe_water__c',dataValue('properties.Safe_Water')),//not coming through + field('Treats_Drinking_Water__c',dataValue('properties.Treats_Drinking_Water')),//not coming through + field('Tippy_Tap__c',dataValue('properties.Active_Handwashing_Station')),//not coming through + field('Pit_Latrine__c',dataValue('properties.Functional_Latrine')),//not coming through + field('Rubbish_Pit__c',dataValue('properties.Rubbish_Pit')),//not coming through + field('Drying_Rack__c',dataValue('properties.Drying_Rack')),//not coming through + field('Kitchen_Garden__c',dataValue('properties.Kitchen_Garden')),//not coming through + field('Cookstove__c',dataValue('properties.Improved_Cooking_Method')),//not coming through + field('Clothe__c',dataValue('properties.Clothesline')),//not coming through + field('WASH_Trained__c',dataValue('properties.WASH_Trained')),//not coming through + field('Uses_ITNs__c',dataValue('properties.ITNs')), + field( + 'Has_muac_tape__c', + dataValue('properties.family_muac_tape_available') + ), + //field('Total_household_people__c',dataValue('properties.Total_Number_of_Members')), //not coming through + field('Health_insurance__c', dataValue('properties.health_insurace_cover')), + field('Health_insurance_active_status__c',dataValue('properties.healthinsurance_active')), + field('Health_insurance_type__c', state => { + var status = dataValue('properties.health_insurance')(state); + return status && status === 'other_please_specify_if_active' + ? 'Other' + : status === 'nhif' + ? 'NHIF' + : status === 'Linda_mama' || 'linda_mama' + ? 'Linda mama' + : status; + }), + field('Other_Health_Insurance__c',dataValue('properties.if_other_please_specify')), + field('Work_with_TBA__c', dataValue('properties.tba')), + field('TBA_name__c', dataValue('properties.which_tba')), + field('Last_Modified_Date_CommCare__c', dataValue('server_date_modified')),//Need a case property), + field('Active_Household__c', state => { + var status = dataValue('properties.Household_Status')(state); + return status && status === 'No' + ? false + : status === 'Yes' + ? true + : status; + }), + // relationship('Head_of_Household__r', 'CommCare_ID__c', dataValue('properties.head_of_household_case_id')), + field('Inactive_Reason__c', state => { + var reason = dataValue('properties.Reason_for_Inactive')(state); + return reason ? reason.toString().replace(/_/g, ' ') : null; + }), + field( + 'Active_in_Nutrition_Program__c', + dataValue( + 'properties.enrolled_in_a_lwala_nutrition_program' + ) + ), + field( + 'lwala_nutrition_program_enrollment_date__c', + dataValue( + 'properties.lwala_nutrition_program_enrollment_date' + ) + ), + field( + 'Trained_in_gardening__c', + dataValue('properties.household_trained_on_gardening') + ), + field( + 'household_trained_on_gardening_date__c', + dataValue( + 'properties.when_was_the_household_trained_on_gardening' + ) + ), + field( + 'Seed_Input_Support__c', + dataValue('properties.household_provided_with_seed_input_support' + ) + ), + field( + 'household_provided_with_seed_input_suppo__c', + dataValue( + 'properties.when_was_the_household_provided_with_seed_input_support' + ) + ), + field( + 'MIYCN_Trained__c', + dataValue('properties.household_trained_on_MIYCN') + ), + // not in message: + // field( + // 'Kitchen_Garden__c', + // dataValue('properties.nutrition_enrollment.household_has_kitchen_garden') + // ), + + //field('Case_Closed_Date__c', state => { + // var closed = dataValue('date_closed')(state); + // var date = dataValue('server_date_modified')(state); + // return closed && closed == true ? date : undefined; + // }) + ) + ); + + fn(state => { console.log("upsertIf1 done"); return state; }); + fn(state => { + return new Promise((resolve, reject) => { + setTimeout(() => { + console.log('4 second cooldown finished.'); + resolve(state); + }, 4000); + }); + }); + + //Household Visit + query( + `SELECT Id, Parent_Geographic_Area__c, Parent_Geographic_Area__r.Name, Parent_Geographic_Area__r.Parent_Geographic_Area__c FROM Location__c WHERE CommCare_User_ID__c = '${dataValue( + 'properties.owner_id' + )(state)}'` + ); + + fn(state => { console.log("query2 done"); return state; }); + fn(state => { + return new Promise((resolve, reject) => { + setTimeout(() => { + console.log('4 second cooldown finished.'); + resolve(state); + }, 4000); + }); + }); + + fn(state => ({ + ...state, + data: { + ...state.data, + catchmentNewId: + state.references[0].records && state.references[0].records.length !== 0 + ? (state.references[0].records[0].Parent_Geographic_Area__r + ? state.references[0].records[0].Parent_Geographic_Area__r.Parent_Geographic_Area__c + : undefined) + : undefined, + }, + })); + + fn(state => { + /* const deaths = state.data.form.household_deaths + ? state.data.form.household_deaths.deaths + : ''; + if (deaths !== '' && !Array.isArray(deaths)) { + state.data.form.household_deaths.deaths = [deaths]; + }*/ + + const supervisorMap = { + community_health_nurse: 'Community Health Nurse', + chw_supervisor: 'CHW Supervisor', + chewschas: 'CHEWs/CHAs', + other: 'Other', + none: 'None', + }; + + const insuranceMap = { + nhif: 'NHIF', + Linda_mama: 'Linda mama', + other_please_specify_if_active: 'Other', + none: 'None', + }; + + return { ...state, supervisorMap, insuranceMap }; + }); + + upsertIf( + // state.data.properties.username !== 'openfn.test' && + state.data.properties.username !== 'test.2021' && + state.data.properties.test_user !== 'Yes' , + 'Visit__c', + 'CommCare_Visit_ID__c', + fields( + field('CommCare_Username__c', dataValue('properties.commcare_username')),// + // field('CommCare_Visit_ID__c', dataValue('id')), + field('CommCare_Visit_ID__c', state => { + var case_id = dataValue('case_id')(state); + var submitted = dataValue('properties.last_form_opened_date_and_time')(state); + return case_id + '_' + submitted; + }), + // field('Household_CHW__c', 'a030Q00000A0jeY'), + // field('Catchment__c', dataValue('a000Q00000Egmtk')), + field('Catchment__c', dataValue('catchmentNewId')), + // field('Household__c','a010Q00000BL6lT'), + // field('Household__c', dataValue('form.case.@case_id')), + relationship( + 'Household__r', + 'CommCare_Code__c', + dataValue('case_id')), + field('Date__c',dataValue('properties.Date')), + field('Form_Submitted__c', dataValue('properties.last_form_opened_name')), + + //field('MOH_household_code__c', state => { + // var moh = dataValue('form.Household_Information.moh_code')(state); + // var mohLinked = dataValue('form.MOH_household_code_linked')(state); + // return moh ? moh : mohLinked && mohLinked !== '' ? mohLinked : undefined; + // }), + field('Active_Household__c', state => { + var status = dataValue('properties.Household_Status')(state); + return status && status === 'No' + ? false + : status === 'Yes' + ? true + : status; + }), + //field('Inactive_Reason__c', state => { + // var reason = dataValue('form.Reason_for_Inactive')(state); + // return reason ? reason.toString().replace(/_/g, ' ') : null; + //}), + //field('Source__c', 1),// + //relationship( + // 'Household_CHW__r', + // 'CommCare_ID__c', + // dataValue('form.sfid')),TO UPDATE IN PRODUCTION + // field('Household_village__c', dataValue('form.village')),// + //New Nutrition Field (MOTG) + field( + 'Active_in_Nutrition_Program__c', + dataValue( + 'properties.enrolled_in_a_lwala_nutrition_program' + ) + ), + field( + 'lwala_nutrition_program_enrollment_date__c', + dataValue( + 'properties.lwala_nutrition_program_enrollment_date' + ) + ), + field( + 'Trained_in_gardening__c', + dataValue('properties.household_trained_on_gardening') + ), + field( + 'household_trained_on_gardening_date__c', + dataValue( + 'properties.when_was_the_household_trained_on_gardening' + ) + ), + field( + 'Seed_Input_Support__c', + dataValue( + 'properties.household_provided_with_seed_input_support' + ) + ), + field( + 'household_provided_with_seed_input_suppo__c', + dataValue( + 'properties.when_was_the_household_provided_with_seed_input_support' + ) + ), + field( + 'MIYCN_Trained__c', + dataValue('properties.household_trained_on_MIYCN') + ), + field( + 'Kitchen_Garden__c', + dataValue('properties.Kitchen_Garden') + ), + + field( + 'Access_to_safe_water__c', + dataValue('properties.Safe_Water') + ), + field( + 'Treats_Drinking_Water__c', + dataValue('properties.Treats_Drinking_Water') + ), + field( + 'Tippy_Tap__c', + dataValue('properties.Active_Handwashing_Station') + ), + field( + 'Pit_Latrine__c', + dataValue('properties.Functional_Latrine') + ), + field( + 'Rubbish_Pit__c', + dataValue('properties.Rubbish_Pit') + ), + field( + 'Drying_Rack__c', + dataValue('properties.Drying_Rack') + ), + field( + 'Kitchen_Garden__c', + dataValue('properties.Kitchen_Garden') + ), + field( + 'Cookstove__c', + dataValue('properties.Improved_Cooking_Method') + ), + field('Clothe__c', dataValue('properties.Clothesline')), + field( + 'WASH_Trained__c', + dataValue('properties.WASH_Trained') + ), + field( + 'Has_muac_tape__c', + dataValue('properties.family_muac_tape_available') + ), + field('Uses_ITNs__c', dataValue('properties.ITNs')), + field('Supervisor_Visit__c', state => + state.data.properties.supervisor_visit + ? state.supervisorMap[state.data.properties.supervisor_visit] + : null + ), + field('Health_insurance__c', dataValue('properties.health_insurace_cover')), + field( + 'Health_insurance_active_status__c', + dataValue('properties.healthinsurance_active') + ), + field('Health_insurance_type__c', state => { + var status = dataValue('properties.health_insurance')(state); + var value = + status && status !== '' + ? status + .replace(/ /gi, ';') + .split(';') + .map(value => { + return state.insuranceMap[value] || value; + }) + : undefined; + return value ? value.join(';') : undefined; + }), + field( + 'Other_Health_Insurance__c', + dataValue('properties.if_other_please_specify') + ), + //field('Last_Modified_Date_CommCare__c', dataValue('server_modified_on')), + field('CommCare_Form_Opened__c', state=> { + var form_opened = dataValue('properties.last_form_opened_date_and_time')(state); + var value1 = form_opened.split('-').slice(0, 2).join('-'); + var value2 = form_opened.split('-').slice(2).join('-'); + var formattedValue = [value1, value2].join(' '); + return new Date(formattedValue).toISOString(); + }), + field('Case_Closed_Date__c', state => { + var closed = dataValue('date_closed')(state); + var date = dataValue('server_modified_on')(state); + return closed && closed == true ? date : undefined; + }) + ) + ); + + fn(state => { console.log("upsertIf2 done"); return state; }); + fn(state => { + return new Promise((resolve, reject) => { + setTimeout(() => { + console.log('Final 4 second cooldown finished.'); + resolve(state); + }, 4000); + }); + }); + + triggers: + webhook: + type: webhook + enabled: false + edges: + webhook->Q3-2022-Upsert-Household-and-Household-Visit-in-SF: + source_trigger: webhook + target_job: Q3-2022-Upsert-Household-and-Household-Visit-in-SF + condition_type: js_expression + condition_label: Household + condition_expression: | + state.data.properties["app_release"] == "Q2-2022" && state.data.properties["case_type"] == "Household" && state.data.properties["test_user"] != "Yes" + enabled: false + "x-[archive]-Workflow-Register-OSG-Mentoring-Attendance": + name: 'x [archive] Workflow Register OSG Mentoring Attendance' + jobs: + Register-OSG-Mentoring-Attendance: + name: Register OSG Mentoring Attendance + adaptor: '@openfn/language-salesforce@v1.3.2' + credential: null + body: | + create( + 'Activity__c', + fields( + field('Date__c', dataValue('form.info.date')), + field('Catchment__c', 'a002400000pAcOe'), + field('Module_Type__c', state => { + var str1 = dataValue('form.module_number')(state) + .toString() + .replace(/_/g, ' '); + return str1; + }), + field('Facilitator__c', dataValue('form.info.Facilitator')), + field('Name', state => { + var str1 = dataValue('form.module_name')(state) + .toString() + .replace(/_/g, ' '); + return str1; + }), + field('Group__c', dataValue('form.sfid')), + field('Program__c', dataValue('form.program')), + field('CommCare_ID__c', dataValue('metadata.instanceID')) + ) + ); + + alterState(state => { + var attendees = dataValue('form.attendees')(state).split(' '); + for (i = 0; i < attendees.length; i++) { + create( + 'Attendance__c', + fields( + field('Activity__c', lastReferenceValue('id')), + field('Date__c', dataValue('form.info.date')), + relationship('Person__r', 'CommCare_ID__c', attendees[i]) + ) + )(state); + } + return state; + }); + /*create("Household_Attendance__c",fields( + field("Activity__c",lastReferenceValue("id")), + field("Date__c",dataValue("form.info.date")), + relationship("Household__c","Name","01465") + ))*/ + + triggers: + webhook: + type: webhook + enabled: false + edges: + webhook->Register-OSG-Mentoring-Attendance: + source_trigger: webhook + target_job: Register-OSG-Mentoring-Attendance + condition_type: js_expression + condition_label: Register OSG Mentoring Attendance + condition_expression: | + state.data.form["@name"] == "Register OSG Mentoring Session" + enabled: false + "x-[archive]-Workflow-Register-Training": + name: 'x [archive] Workflow Register Training' + jobs: + Register-Training: + name: Register Training + adaptor: '@openfn/language-salesforce@v1.3.2' + credential: null + body: | + create( + 'Activity__c', + fields( + field('Date__c', dataValue('form.info.date')), + field('Catchment__c', 'a002400000pAcOe'), + field('Module_Type__c', state => { + var str1 = dataValue('form.info.module_number')(state) + .toString() + .replace(/_/g, ' '); + return str1; + }), + field('Facilitator__c', dataValue('form.info.Facilitator')), + field('Name', state => { + var str1 = dataValue('form.info.name')(state) + .toString() + .replace(/_/g, ' '); + return str1; + }), + field('Group__c', dataValue('form.sfid')), + field('Program__c', dataValue('form.program')), + field('CommCare_ID__c', dataValue('metadata.instanceID')) + ) + ); + + alterState(state => { + var attendees = dataValue('form.attendees')(state).split(' '); + for (i = 0; i < attendees.length; i++) { + create( + 'Household_Attendance__c', + fields( + field('Activity__c', lastReferenceValue('id')), + field('Date__c', dataValue('form.info.date')), + relationship('Household__r', 'CommCare_Code__c', attendees[i]) + ) + )(state); + } + return state; + }); + /*create("Household_Attendance__c",fields( + field("Activity__c",lastReferenceValue("id")), + field("Date__c",dataValue("form.info.date")), + relationship("Household__c","Name","01465") + ))*/ + + triggers: + webhook: + type: webhook + enabled: false + edges: + webhook->Register-Training: + source_trigger: webhook + target_job: Register-Training + condition_type: js_expression + condition_label: Register Training + condition_expression: | + state.data.form["@name"] == "Register Training" + enabled: false + "x-[archive]-Workflow-TEST-Create-HH-in-Sandbox": + name: 'x [archive] Workflow TEST Create HH in Sandbox' + jobs: + TEST-Create-HH-in-Sandbox: + name: TEST Create HH in Sandbox + adaptor: '@openfn/language-salesforce@v1.3.2' + credential: null + body: | + //Alters CommCare arrays so that they are formatted as arrays instead of just single values. + alterState(state => { + const person = state.data.form.Person; + if (!Array.isArray(person)) { + state.data.form.Person = [person]; + } + return state; + }); + + upsert( + 'Household__c', + 'CommCare_Code__c', + fields( + field('Name', '00000'), + //state =>{ + // return dataValue('$.form.case.@case_id')(state).substring(0,5); //<- Will, this change we made was causing errors? what does the '0000' do? + // }), + field('Catchment__c', state => { + if (dataValue('form.catchment')(state) == 'East Kamagambo') { + return 'a002400000pAcQt'; + } else { + return 'a002400000pAcOe'; + } + }), + field('CommCare_Code__c', dataValue('$.form.case.@case_id')), + field('Household_CHW__c', dataValue('$.form.CHW_ID')), + field('Area__c', dataValue('$.form.area')), + field('Household_Head_No_Program__c', dataValue('form.No_Program_Head')), + field( + 'Treats_Drinking_Water__c', + dataValue('$.form.Household_Information.Treats_Drinking_Water') + ), + field( + 'WASH_Trained__c', + dataValue('$.form.Household_Information.WASH_Trained') + ), + field( + 'Rubbish_Pit__c', + dataValue('$.form.Household_Information.Rubbish_Pit') + ), + field( + 'Kitchen_Garden__c', + dataValue('$.form.Household_Information.Kitchen_Garden') + ), + field( + 'Cookstove__c', + dataValue('$.form.Household_Information.Improved_Cooking_Method') + ), + field('Uses_ITNs__c', dataValue('$.form.Household_Information.ITNs')), + field( + 'Pit_Latrine__c', + dataValue('$.form.Household_Information.Functional_Latrine') + ), + field('Clothe__c', dataValue('$.form.Household_Information.Clothesline')), + field( + 'Drying_Rack__c', + dataValue('$.form.Household_Information.Drying_Rack') + ), + field( + 'Tippy_Tap__c', + dataValue('$.form.Household_Information.Active_Handwashing_Station') + ), + field( + 'Number_of_Over_5_Females__c', + dataValue('$.form.Household_Information.Number_of_over_5_Females') + ), + field( + 'Number_of_Under_5_Males__c', + dataValue('$.form.Household_Information.Number_of_Under_5_Males') + ), + field( + 'Number_of_Under_5_Females__c', + dataValue('$.form.Household_Information.Number_of_Under_5_Females') + ), + field( + 'Number_of_Over_5_Males__c', + dataValue('$.form.Household_Information.Number_of_Over_5_Males') + ), + field('Source__c', true) + ) + ); + + alterState(state => { + if (dataValue('$.form.Person[0].Source')(state) == 1) { + return beta.each( + dataPath('$.form.Person[*]'), + upsert( + 'Person__c', + 'CommCare_ID__c', + fields( + field('Name', state => { + var name1 = dataValue('Basic_Information.Person_Name')(state); + var name2 = name1.replace(/\w\S*/g, function (txt) { + return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); + }); + return name2; + }), + relationship('RecordType', 'Name', state => { + return dataValue('Basic_Information.Record_Type')(state) + .toString() + .replace(/_/g, ' '); + }), + field('Catchment__c', state => { + if (dataValue('catchment')(state) == 'East Kamagambo') { + return 'a002400000pAcQt'; + } else { + return 'a002400000pAcOe'; + } + }), + field('HAWI_Registrant__c', state => { + if (dataValue('Basic_Information.HAWI_Status')(state) == 'Yes') { + return 'Yes'; + } + }), + field('Active_in_HAWI__c', state => { + if (dataValue('Basic_Information.HAWI_Status')(state) == 'Yes') { + return 'Yes'; + } + }), + field('Active_in_Thrive_Thru_5__c', state => { + if ( + dataValue('Basic_Information.Record_Type')(state) + .toString() + .replace(/_/g, ' ') == 'Child' && + dataValue('Basic_Information.TT5_Status')(state) == 'Yes' + ) { + return 'Yes'; + } + }), + field('Thrive_Thru_5_Registrant__c', state => { + if ( + dataValue('Basic_Information.Record_Type')(state) + .toString() + .replace(/_/g, ' ') == 'Child' && + dataValue('Basic_Information.TT5_Status')(state) == 'Yes' + ) { + return 'Yes'; + } + }), + field('Active_TT5_Mother__c', state => { + if ( + dataValue('Basic_Information.Record_Type')(state) + .toString() + .replace(/_/g, ' ') == 'Female Adult' && + dataValue('Basic_Information.TT5_Status')(state) == 'Yes' + ) { + return 'Yes'; + } + }), + field('TT5_Mother_Registrant__c', state => { + if ( + dataValue('Basic_Information.Record_Type')(state) + .toString() + .replace(/_/g, ' ') == 'Female Adult' && + dataValue('Basic_Information.TT5_Status')(state) == 'Yes' + ) { + return 'Yes'; + } + }), + field('Enrollment_Date__c', state => { + if (dataValue('Basic_Information.TT5_Status')(state) == 'Yes') { + return dataValue('case.@date_modified')(state); + } + }), + field('HAWI_Enrollment_Date__c', state => { + if (dataValue('Basic_Information.HAWI_Status')(state) == 'Yes') { + return dataValue('case.@date_modified')(state); + } + }), + field('LMP__c', dataValue('TT5.Child_Information.ANCs.LMP')), + field('Source__c', true), + field('CommCare_ID__c', dataValue('case.@case_id')), + field('Date_of_Birth__c', dataValue('Basic_Information.DOB')), + field( + 'Exclusive_Breastfeeding__c', + dataValue( + 'TT5.Child_Information.Exclusive_Breastfeeding.Exclusive_Breastfeeding' + ) + ), + field('Gender__c', dataValue('Basic_Information.Final_Gender')), + field( + 'Marital_Status__c', + dataValue('Basic_Information.Marital_Status') + ), + field( + 'Telephone__c', + dataValue('Basic_Information.Contact_Info.contact_phone_number') + ), + field( + 'Next_of_Kin__c', + dataValue('Basic_Information.Contact_Info.Next_of_Kin') + ), + field( + 'Next_of_Kin_Phone__c', + dataValue('Basic_Information.Contact_Info.next_of_kin_phone') + ), + field('Client_Status__c', 'Active'), + field( + 'Ever_on_Family_Planning__c', + dataValue('Basic_Information.Ever_on_Family_Planning') + ), + field( + 'Family_Planning__c', + dataValue('Basic_Information.Currently_on_family_planning') + ), + field( + 'Family_Planning_Method__c', + dataValue('Basic_Information.Family_Planning_Method') + ), + field('ANC_1__c', dataValue('TT5.Child_Information.ANCs.ANC_1')), + field('ANC_2__c', dataValue('TT5.Child_Information.ANCs.ANC_2')), + field('ANC_3__c', dataValue('TT5.Child_Information.ANCs.ANC_3')), + field('ANC_4__c', dataValue('TT5.Child_Information.ANCs.ANC_4')), + field('ANC_5__c', dataValue('TT5.Child_Information.ANCs.ANC_5')), + field('BCG__c', dataValue('TT5.Child_Information.Immunizations.BCG')), + field( + 'OPV_0__c', + dataValue('TT5.Child_Information.Immunizations.OPV_0') + ), + field( + 'OPV_1__c', + dataValue('TT5.Child_Information.Immunizations.OPV_PCV_Penta_1') + ), + field( + 'OPV_2__c', + dataValue('TT5.Child_Information.Immunizations.OPV_PCV_Penta_2') + ), + field( + 'OPV_3__c', + dataValue('TT5.Child_Information.Immunizations.OPV_PCV_Penta_3') + ), + field( + 'Measles_6__c', + dataValue('TT5.Child_Information.Immunizations.Measles_6') + ), + field( + 'Measles_9__c', + dataValue('TT5.Child_Information.Immunizations.Measles_9') + ), + field( + 'Measles_18__c', + dataValue('TT5.Child_Information.Immunizations.Measles_18') + ), + field('Pregnant__c', state => { + if (dataValue('TT5.Mother_Information.Pregnant')(state) == 'Yes') + return 1; + }), + field('Education_Level__c', state => { + if ( + dataValue('Basic_Information.Record_Type')(state) !== 'Child' && + dataValue('Basic_Information.Record_Type')(state) !== 'Youth' + ) { + return dataValue('Basic_Information.Education_Level')(state) + .toString() + .replace(/_/g, ' '); + } + }), + field( + 'Gravida__c', + dataValue('TT5.Mother_Information.Pregnancy_Information.Gravida') + ), + field( + 'Parity__c', + dataValue('TT5.Mother_Information.Pregnancy_Information.Parity') + ), + field( + 'Unique_Patient_Code__c', + dataValue('HAWI.Unique_Patient_Code') + ), + field( + 'Active_in_Support_Group__c', + dataValue('HAWI.Active_in_Support_Group') + ), + + field('Currently_on_ART_s__c', dataValue('HAWI.ART')), + field('ART_Regimen__c', state => { + var art = ''; + var str = dataValue('HAWI.ARVs')(state); + if (str !== undefined) { + art = str.replace(/ /g, '; '); + } + return art; + }), + field('Preferred_Care_Facility__c', state => { + var val = ''; + if ( + dataValue('HAWI.Preferred_Care_Facility')(state) !== undefined + ) { + val = dataValue('HAWI.Preferred_Care_Facility')(state) + .toString() + .replace(/_/g, ' '); + } + return val; + }), + field('CommCare_HH_Code__c', dataValue('case.index.parent.#text')), + field('Child_Status__c', dataValue('Basic_Information.Child_Status')), + field('Place_of_Delivery__c', state => { + var val = ''; + var placeholder = ''; + if ( + dataValue( + 'TT5.Child_Information.Delivery_Information.Skilled_Unskilled' + )(state) !== undefined + ) { + placeholder = dataValue( + 'TT5.Child_Information.Delivery_Information.Skilled_Unskilled' + )(state); + if (placeholder == 'Skilled') { + val = 'Facility'; + } else if (placeholder == 'Unskilled') { + val = 'Home'; + } + } + return val; + }), + field('Delivery_Facility__c', state => { + var val = ''; + var placeholder = ''; + if ( + dataValue( + 'TT5.Child_Information.Delivery_Information.Birth_Facility' + )(state) !== undefined + ) { + placeholder = dataValue( + 'TT5.Child_Information.Delivery_Information.Birth_Facility' + )(state); + val = placeholder.toString().replace(/_/g, ' '); + } + return val; + }) + ) + ) + )(state); + } + + return state; + }); + + triggers: + webhook: + type: webhook + enabled: false + edges: + webhook->TEST-Create-HH-in-Sandbox: + source_trigger: webhook + target_job: TEST-Create-HH-in-Sandbox + condition_type: js_expression + condition_label: Commcare Create HH + condition_expression: | + state.data.form.Source == "1" && state.data.form["@name"] == "Enroll New Household" + enabled: false + "x-[archive]-Workflow-Test-Job": + name: 'x [archive] Workflow Test Job' + jobs: + Test-Job: + name: Test Job + adaptor: '@openfn/language-salesforce@v1.3.2' + credential: null + body: | + // Your job goes here. + + triggers: + webhook: + type: webhook + enabled: false + edges: + webhook->Test-Job: + source_trigger: webhook + target_job: Test-Job + condition_type: js_expression + condition_label: SF Update HH + condition_expression: | + state.data.label == "Update Household" + enabled: false + "x-[archive]-Workflow-Test-Service-Upsert": + name: 'x [archive] Workflow Test Service Upsert' + jobs: + Test-Service-Upsert: + name: Test Service Upsert + adaptor: '@openfn/language-salesforce@v2.7.4' + credential: null + body: | + upsert('Service__c', 'Service_UID__c', + fields( + relationship('Parent_Service__r', + 'Service_UID__c', + dataValue('indices.parent.case_id')), + field('Service_UID__c', dataValue('case_id')) + )); + + triggers: + webhook: + type: webhook + enabled: false + edges: + webhook->Test-Service-Upsert: + source_trigger: webhook + target_job: Test-Service-Upsert + condition_type: js_expression + condition_label: Case + condition_expression: | + state.data.properties["case_type"] == "Case" && state.data.properties["test_user"] != "Yes" + enabled: false + "x-[archive]-Workflow-Update-Household-in-CommCare-V2": + name: 'x [archive] Workflow Update Household in CommCare V2' + jobs: + Update-Household-in-CommCare-V2: + name: Update Household in CommCare V2 + adaptor: '@openfn/language-commcare@latest' + credential: null + body: | + submit( + fields( + field('@', state => { + return { + 'xmlns:jrm': 'http://dev.commcarehq.org/jr/xforms', + xmlns: () => { + return dataValue('new[0].Catchment__c')(state) == 'a001p000017gpfZAAQ' + ? 'http://openrosa.org/formdesigner/7bdbfcc02fd44260837d799d24051449' + : 'http://openrosa.org/formdesigner/980c10cdb3b140101225e25c6e8aff48f471b3d'; + }, + uiVersion: '1', + version: '46', + name: 'Update Household', + }; + }), + field('Source', 0), + field('Household_Status', state => { + var str = ''; + if (dataValue('new[0].Active_Household__c')(state) === false) { + str = 'No'; + } else { + str = 'Yes'; + } + return str; + }), + field('Run_Code', 'Household_Lwala'), + field('name', state => { + var name = dataValue('new[0].Name')(state); + var code = dataValue('new[0].Household_Code_Autonumber__c')(state); + return name.length > 6 ? code : name; + //return hh autonumber if name = sf id + }), + field('area', dataValue('new[0].Area__c')), + + field('Household_Information', state => { + return { + moh_code: dataValue('new[0].MOH_household_code__c')(state), //NEW + Active_Handwashing_Station: dataValue('new[0].Tippy_Tap__c')(state), + Drying_Rack: dataValue('new[0].Drying_Rack__c')(state), + + WASH_Compliant: () => { + var ans = ''; + if (dataValue('new[0].WASH_Compliant__c')(state) === true) { + ans = 'Yes'; + } else { + ans = 'No'; + } + return ans; + }, + Functional_Latrine: dataValue('new[0].Pit_Latrine__c')(state), + Clothesline: dataValue('new[0].Clothe__c')(state), + ITNs: dataValue('new[0].Uses_ITNs__c')(state), + Improved_Cooking_Method: dataValue('new[0].Cookstove__c')(state), + Kitchen_Garden: dataValue('new[0].Kitchen_Garden__c')(state), + Number_of_Over_5_Males: dataValue('new[0].Number_of_Over_5_Males__c')( + state + ), + Number_of_Over_5_Females: dataValue( + 'new[0].Number_of_Over_5_Females__c' + )(state), + Number_of_Under_5_Males: dataValue('new[0].Number_of_Under_5_Males__c')( + state + ), + Number_of_Under_5_Females: dataValue( + 'new[0].Number_of_Under_5_Females__c' + )(state), + Rubbish_Pit: dataValue('new[0].Rubbish_Pit__c')(state), + Treats_Drinking_Water: dataValue('new[0].Treats_Drinking_Water__c')( + state + ), + WASH_Trained: dataValue('new[0].WASH_Trained__c')(state), + Total_Under_5: dataValue('new[0].Total_Number_of_Under_5s__c')(state), + Total_Males: dataValue('new[0].Total_Number_of_Males__c')(state), + Total_Females: dataValue('new[0].Total_Number_of_Females__c')(state), + Total_Household_Members: dataValue('new[0].Total_Number_of_Members__c')( + state + ), + Total_Number_of_Members: dataValue('Total_household_people__c')(state), //NEW + Total_Over_5: () => { + var num = 0; + num = + dataValue('new[0].Total_Number_of_Members__c')(state) - + dataValue('new[0].Total_Number_of_Under_5s__c')(state); + return num; + }, + }; + }), + field('n0:case', state => { + return { + '@': { + case_id: dataValue('new[0].Commcare_Code__c')(state), + date_modified: new Date().toISOString(), + user_id: 'e298884bfb6ee2d2b38591a6e8ae0228', + 'xmlns:n0': 'http://commcarehq.org/case/transaction/v2', + }, + 'n0:update': { + 'n0:case_name': () => { + var name = dataValue('new[0].Name')(state); + var code = dataValue('new[0].Household_Code_Autonumber__c')(state); + return name.length > 6 ? code : name; + //return hh autonumber if name = sf id + }, + 'n0:owner_id': () => { + var id = ''; + if (dataValue('new[0].chw_owner_id__c')(state) === undefined) { + id = 'acf8595692c76095eb5afd809c628091'; + } else { + id = dataValue('new[0].chw_owner_id__c')(state); + } + return id; + }, + 'n0:case_type': 'Household', + 'n0:WASH_Compliant': () => { + var ans = ''; + if (dataValue('new[0].WASH_Compliant__c')(state) === true) { + ans = 'Yes'; + } else { + ans = 'No'; + } + return ans; + }, + 'n0:Active_Handwashing_Station': dataValue('new[0].Tippy_Tap__c')( + state + ), + 'n0:Drying_Rack': dataValue('new[0].Drying_Rack__c')(state), + 'n0:Functional_Latrine': dataValue('new[0].Pit_Latrine__c')(state), + 'n0:Clothesline': dataValue('new[0].Clothe__c')(state), + 'n0:ITNs': dataValue('new[0].Uses_ITNs__c')(state), + 'n0:Active_in_Nutrition_Program': dataValue( + 'new[0].Active_in_Nutrition_Program__c' + )(state), + 'n0:Nutrition_Group': dataValue('new[0].Nutrition_Group__c')(state), + 'n0:seed_input_support': dataValue('new[0].Seed_Input_Support__c')( + state + ), + 'n0:name_concat': dataValue('new[0].Household_Code_Autonumber__c')(state), + 'n0:CHW_ID': dataValue('new[0].Household_CHW__c')(state), + 'n0:Improved_Cooking_Method': dataValue('new[0].Cookstove__c')(state), + 'n0:Kitchen_Garden': dataValue('new[0].Kitchen_Garden__c')(state), + 'n0:Number_of_Over_5_Males': dataValue( + 'new[0].Number_of_Over_5_Males__c' + )(state), + 'n0:Number_of_Over_5_Females': dataValue( + 'new[0].Number_of_Over_5_Females__c' + )(state), + 'n0:Number_of_Under_5_Males': dataValue( + 'new[0].Number_of_Under_5_Males__c' + )(state), + 'n0:Number_of_Under_5_Females': dataValue( + 'new[0].Number_of_Under_5_Females__c' + )(state), + 'n0:Rubbish_Pit': dataValue('new[0].Rubbish_Pit__c')(state), + 'n0:Treats_Drinking_Water': dataValue( + 'new[0].Treats_Drinking_Water__c' + )(state), + 'n0:WASH_Trained': dataValue('new[0].WASH_Trained__c')(state), + 'n0:Total_Under_5': dataValue('new[0].Total_Number_of_Under_5s__c')( + state + ), + 'n0:Total_Males': dataValue('new[0].Total_Number_of_Males__c')(state), + 'n0:Total_Females': dataValue('new[0].Total_Number_of_Females__c')( + state + ), + 'n0:area': dataValue('new[0].Area__c')(state), + 'n0:Area_Name': dataValue('new[0].Area_Name__c')(state), + 'n0:Total_Household_Members': dataValue( + 'new[0].Total_Number_of_Members__c' + )(state), + Total_Number_of_Members: dataValue('new[0].Total_household_people__c')( + state + ), //NEW + 'n0:Household_Status': () => { + var str = ''; + if (dataValue('new[0].Active_Household__c')(state) === false) { + str = 'No'; + } else { + str = 'Yes'; + } + return str; + }, + 'n0:Total_Over_5': () => { + var num = 0; + num = + dataValue('new[0].Total_Number_of_Members__c')(state) - + dataValue('new[0].Total_Number_of_Under_5s__c')(state); + return num; + }, + }, + 'n0:index': { + 'n0:parent': { + '@': { + case_type: 'Area', + }, + '#': dataValue('new[0].Area_Case_ID__c')(state), + }, + }, + }; + }), + field('n1:meta', state => { + return { + '@': { 'xmlns:n1': 'http://openrosa.org/jr/xforms' }, + 'n1:deviceID': 'Formplayer', + 'n1:timeStart': new Date().toISOString(), + 'n1:timeEnd': new Date().toISOString(), + 'n1:userID': 'e298884bfb6ee2d2b38591a6e8ae0228', + }; + }) + ) + ); + + triggers: + webhook: + type: webhook + enabled: false + edges: + webhook->Update-Household-in-CommCare-V2: + source_trigger: webhook + target_job: Update-Household-in-CommCare-V2 + condition_type: js_expression + condition_label: SF Update HH + condition_expression: | + state.data.label == "Update Household" + enabled: false + "x-[archive]-Workflow-Update-Person-in-CommCare": + name: 'x [archive] Workflow Update Person in CommCare' + jobs: + Update-Person-in-CommCare: + name: Update Person in CommCare + adaptor: '@openfn/language-commcare@latest' + credential: null + body: | + submit( + fields( + field('@', state => { + return { + 'xmlns:jrm': 'http://dev.commcarehq.org/jr/xforms', + xmlns: + 'http://openrosa.org/formdesigner/a34af027a7fa943998c39f64bc84a337a668114a', + uiVersion: '1', + version: '81', + name: 'Update Person', + }; + }), + field('Source', 0), + field('Status', state => { + return { + Client_Status: dataValue('new[0].Client_Status__c')(state), + Date_of_Transfer_Out: dataValue('new[0].Date_of_Transfer_Out__c')( + state + ), + Date_Last_Seen: dataValue('new[0].Date_Last_Seen__c')(state), + Date_of_Death: dataValue('new[0].Date_of_Death__c')(state), + Cause_of_Death: dataValue('new[0].Cause_of_Death__c')(state), + }; + }), + field('Basic_Information', state => { + return { + Basic_Information: { + Phone_Number: dataValue('new[0].Telephone__c')(state), + Final_Program: () => { + var program = ''; + if ( + dataValue('new[0].Active_In_Thrive_Thru_5__c')(state) == 'Yes' || + dataValue('new[0].Active_TT5_Mother__c')(state) == 'Yes' + ) { + if (dataValue('new[0].Active_In_HAWI__c')(state) == 'Yes') { + program = 'Both'; + } else { + program = 'Thrive_Through_5'; + } + } else { + if (dataValue('new[0].Active_In_HAWI__c')(state) == 'Yes') { + program = 'HAWI'; + } + } + return program; + }, + }, + }; + }), + field('TT5', state => { + return { + Child_Information: { + ANCs: { + ANC_1: dataValue('new[0].ANC_1__c')(state), + ANC_2: dataValue('new[0].ANC_2__c')(state), + ANC_3: dataValue('new[0].ANC_3__c')(state), + ANC_4: dataValue('new[0].ANC_4__c')(state), + ANC_5: dataValue('new[0].ANC_5__c')(state), + }, + Delivery_Information: { + Person_Name: dataValue('new[0].Name')(state), + DOB: dataValue('new[0].Date_of_Birth__c')(state), + Delivery_Type: () => { + var val = ''; + if (dataValue('new[0].Place_of_Delivery__c')(state) == 'Home') { + val = 'Unskilled'; + } else if ( + dataValue('new[0].Place_of_Delivery__c')(state) == 'Facility' + ) { + val = 'Skilled'; + } + return val; + }, + Delivery_Facility: dataValue('new[0].Delivery_Facility__c')(state), + }, + Immunizations: { + BCG: dataValue('new[0].BCG__c')(state), + OPV_0: dataValue('new[0].OPV_0__c')(state), + OPV_PCV_Penta_1: dataValue('new[0].OPV_1__c')(state), + OPV_PCV_Penta_2: dataValue('new[0].OPV_2__c')(state), + OPV_PCV_Penta_3: dataValue('new[0].OPV_3__c')(state), + Measles_6: dataValue('new[0].Measles_6__c')(state), + Measles_9: dataValue('new[0].Measles_9__c')(state), + Measles_18: dataValue('new[0].Measles_18__c')(state), + Fully_Immunized: dataValue( + 'new[0].Fully_Immunized_at_12_Months__c' + )(state), + }, + /*"CCMM":{ + "Home_Test_Date":dataValue("new[0].Measles_18__c")(state), + "Home_Test_Date":dataValue("new[0].Measles_18__c")(state), + "Home_Test_Date":dataValue("new[0].Measles_18__c")(state), + "Home_Test_Date":dataValue("new[0].Measles_18__c")(state), + "Home_Test_Date":dataValue("new[0].Measles_18__c")(state), + }*/ + }, + Mother_Information: { + Pregnant: () => { + if (dataValue('new[0].Pregnant__c')(state) === true) { + return 'Yes'; + } + }, + }, + }; + }), + field('HAWI', state => { + return { + Unique_Patient_Code: dataValue('new[0].Unique_Patient_Code__c')(state), + Support_Group: dataValue('new[0].Active_in_Support_Group__c')(state), + Preferred_Care_F: { + Preferred_Care_Facility: dataValue( + 'new[0].Preferred_Care_Facility__c' + )(state), + }, + }; + }), + + field('n0:case', state => { + return { + '@': { + case_id: dataValue('new[0].CommCare_ID__c')(state), + date_modified: new Date().toISOString(), + user_id: 'e298884bfb6ee2d2b38591a6e8ae0228', + 'xmlns:n0': 'http://commcarehq.org/case/transaction/v2', + }, + 'n0:create': { + 'n0:case_name': () => { + var name1 = dataValue('new[0].Name')(state); + var name2 = name1.replace(/\w\S*/g, function (txt) { + return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); + }); + return name2; + }, + 'n0:case_type': 'Person', + 'n0:parent_id': dataValue('new[0].CommCare_HH_Code__c')(state), + }, + 'n0:update': { + 'n0:ANC_1': dataValue('new[0].ANC_1__c')(state), + + 'n0:ANC_2': dataValue('new[0].ANC_2__c')(state), + 'n0:ANC_3': dataValue('new[0].ANC_3__c')(state), + 'n0:ANC_4': dataValue('new[0].ANC_4__c')(state), + 'n0:ANC_5': dataValue('new[0].ANC_5__c')(state), + 'n0:BCG': dataValue('new[0].BCG__c')(state), + 'n0:Fully_Immunized': dataValue( + 'new[0].Fully_Immunized_at_12_Months__c' + )(state), + 'n0:Delivery_Type': () => { + var val = ''; + if (dataValue('new[0].Place_of_Delivery__c')(state) == 'Home') { + val = 'Unskilled'; + } else if ( + dataValue('new[0].Place_of_Delivery__c')(state) == 'Facility' + ) { + val = 'Skilled'; + } + return val; + }, + 'n0:Delivery_Facility': dataValue('new[0].Delivery_Facility__c')( + state + ), + 'n0:Family_Planning_Method': dataValue( + 'new[0].Family_Planning_Method__c' + )(state), + 'n0:Child_Status': dataValue('new[0].Child_Status__c')(state), + 'n0:Active_in_OSG_Mentoring': dataValue('new[0].Active_in_OSG__c')( + state + ), + 'n0:OSG_Mentoring_Group': dataValue('new[0].OSG_Group__c')(state), + 'n0:OPV_0': dataValue('new[0].OPV_0__c')(state), + 'n0:OPV_PCV_Penta_1': dataValue('new[0].OPV_1__c')(state), + 'n0:OPV_PCV_Penta_2': dataValue('new[0].OPV_2__c')(state), + 'n0:OPV_PCV_Penta_3': dataValue('new[0].OPV_3__c')(state), + 'n0:Current_Height': dataValue('new[0].Current_Height__c')(state), + 'n0:Current_Weight': dataValue('new[0].Current_Weight__c')(state), + 'n0:Current_MUAC': dataValue('new[0].Current_MUAC__c')(state), + 'n0:Measles_6': dataValue('new[0].Measles_6__c')(state), + 'n0:Measles_9': dataValue('new[0].Measles_9__c')(state), + 'n0:LMP': dataValue('new[0].LMP__c')(state), + 'n0:EDD': dataValue('new[0].EDD__c')(state), + 'n0:Measles_18': dataValue('new[0].Measles_18__c')(state), + 'n0:Pregnant': () => { + if (dataValue('new[0].Pregnant__c')(state) === true) { + return 'Yes'; + } + }, + 'n0:ART': dataValue('new[0].Currently_on_ART_s__c')(state), + 'n0:ARVs': dataValue('new[0].ART_Regimen__c')(state), + 'n0:Active_in_Support_Group': dataValue( + 'new[0].Active_in_Support_Group__c' + )(state), + 'n0:Client_Program': () => { + var program = ''; + if ( + dataValue('new[0].Active_in_Thrive_Thru_5__c')(state) == 'Yes' || + dataValue('new[0].Active_TT5_Mother__c')(state) == 'Yes' + ) { + if (dataValue('new[0].Active_in_HAWI__c')(state) == 'Yes') { + program = 'Both'; + } else { + program = 'Thrive_Through_5'; + } + } else { + if (dataValue('new[0].Active_in_HAWI__c')(state) == 'Yes') { + program = 'HAWI'; + } + } + return program; + }, + 'n0:Currently_on_family_planning': dataValue( + 'new[0].Family_Planning__c' + )(state), + 'n0:DOB': dataValue('new[0].Date_of_Birth__c')(state), + 'n0:Education_Level': () => { + if (dataValue('new[0].Education_Level__c')(state) !== undefined) { + return dataValue('new[0].Education_Level__c')(state) + .toString() + .replace(/ /g, '_'); + } + }, + 'n0:Ever_on_Family_Planning': dataValue( + 'new[0].Ever_on_Family_Planning__c' + )(state), + 'n0:Gender': dataValue('new[0].Gender__c')(state), + 'n0:Gravida': dataValue('new[0].Gravida__c')(state), + 'n0:Active_in_TT5': dataValue('new[0].Active_in_Thrive_Thru_5__c')( + state + ), + 'n0:Active_in_HAWI': dataValue('new[0].Active_in_HAWI__c')(state), + 'n0:Marital_Status': dataValue('new[0].Marital_Status__c')(state), + 'n0:Exclusive_Breastfeeding': dataValue( + 'new[0].Exclusive_Breastfeeding__c' + )(state), + 'n0:Next_of_Kin': dataValue('new[0].Next_of_Kin__c')(state), + 'n0:Next_of_Kin_Phone': dataValue('new[0].Next_of_Kin_Phone__c')( + state + ), + 'n0:Parity': dataValue('new[0].Parity__c')(state), + + 'n0:Phone_Number': dataValue('new[0].Telephone__c')(state), + 'n0:Preferred_Care_Facility': dataValue( + 'new[0].Preferred_Care_Facility__c' + )(state), + 'n0:Record_Type': () => { + return dataValue('new[0].Record_Type_Name__c')(state) + .toString() + .replace(/ /g, '_'); + }, + 'n0:Unique_Patient_Code': dataValue('new[0].Unique_Patient_Code__c')( + state + ), + }, + 'n0:index': { + 'n0:parent': { + '@': { + case_type: 'Household', + }, + '#': dataValue('new[0].CommCare_HH_Code__c')(state), + }, + }, + }; + }), + + field('n2:meta', state => { + return { + '@': { 'xmlns:n2': 'http://openrosa.org/jr/xforms' }, + 'n2:deviceID': 'Formplayer', + 'n2:timeStart': new Date().toISOString(), + 'n2:timeEnd': new Date().toISOString(), + 'n2:userID': 'e298884bfb6ee2d2b38591a6e8ae0228', + }; + }) + ) + ); + + triggers: + webhook: + type: webhook + enabled: false + edges: + webhook->Update-Person-in-CommCare: + source_trigger: webhook + target_job: Update-Person-in-CommCare + condition_type: js_expression + condition_label: SF Update Person + condition_expression: | + state.data.label == "Update Person" + enabled: false + "x-[archive]-Workflow-Upsert-Household-Visit": + name: 'x [archive] Workflow Upsert Household Visit' + jobs: + Upsert-Household-Visit: + name: Upsert Household Visit + adaptor: '@openfn/language-salesforce@latest' + credential: null + body: | + query( + `SELECT Id, Parent_Geographic_Area__c, Parent_Geographic_Area__r.Name, Parent_Geographic_Area__r.Parent_Geographic_Area__c FROM Location__c WHERE CommCare_User_ID__c = '${dataValue( + 'form.owner_id' + )(state)}'` + ); + + fn(state => ({ + ...state, + data: { + ...state.data, + catchmentNewId: + state.references[0].records && state.references[0].records.length !== 0 + ? (state.references[0].records[0].Parent_Geographic_Area__r + ? state.references[0].records[0].Parent_Geographic_Area__r.Parent_Geographic_Area__c + : undefined) + : undefined, + }, + })); + + fn(state => { + const deaths = state.data.form.household_deaths + ? state.data.form.household_deaths.deaths + : ''; + if (deaths !== '' && !Array.isArray(deaths)) { + state.data.form.household_deaths.deaths = [deaths]; + } + + const supervisorMap = { + community_health_nurse: 'Community Health Nurse', + chw_supervisor: 'CHW Supervisor', + chewschas: 'CHEWs/CHAs', + other: 'Other', + none: 'None', + }; + + const insuranceMap = { + nhif: 'NHIF', + Linda_mama: 'Linda mama', + other_please_specify_if_active: 'Other', + none: 'None', + }; + + return { ...state, supervisorMap, insuranceMap }; + }); + + upsertIf( + state.data.metadata.username !== 'test.2021' && + state.data.form.test_user !== 'Yes' , + 'Visit__c', + 'CommCare_Visit_ID__c', + fields( + field('CommCare_Username__c', dataValue('form.meta.username')),// + field('CommCare_Visit_ID__c', dataValue('id')), + // field('Household_CHW__c', 'a030Q00000A0jeY'), + // field('Catchment__c', dataValue('a000Q00000Egmtk')), + field('Catchment__c', dataValue('catchmentNewId')), + // field('Household__c','a010Q00000BL6lT'), + // field('Household__c', dataValue('form.case.@case_id')), + relationship( + 'Household__r', + 'CommCare_Code__c', + dataValue('form.case.@case_id')), + field('Date__c',dataValue('form.Date')), + //field('MOH_household_code__c', state => { + // var moh = dataValue('form.Household_Information.moh_code')(state); + // var mohLinked = dataValue('form.MOH_household_code_linked')(state); + // return moh ? moh : mohLinked && mohLinked !== '' ? mohLinked : undefined; + // }), + field('Active_Household__c', state => { + var status = dataValue('form.Household_Status')(state); + return status && status === 'No' + ? false + : status === 'Yes' + ? true + : status; + }), + //field('Inactive_Reason__c', state => { + // var reason = dataValue('form.Reason_for_Inactive')(state); + // return reason ? reason.toString().replace(/_/g, ' ') : null; + //}), + //field('Source__c', 1),// + field('Household_CHW__c', state => { + var chw = dataValue('properties.CHW_ID')(state); + return chw === 'a030800001zQrk' + ? 'a030800001zQrk5' + : chw + ? chw + : undefined; + }), //TO UPDATE IN PRODUCTION + field( + 'Completed_COVID_19_Phone_Screening__c', + dataValue( + 'form.did_you_complete_the_covid-19_phone_screening_for_this_household' + ) + ), + field('Household_Visit_Type__c', state => { + var visit = dataValue( + 'form.is_this_a_physical_home_visit_or_a_phone_call_visit' + )(state); + return visit ? visit.toString().replace(/_/g, ' ') : null; + }), + // field('Household_village__c', dataValue('form.village')),// + //New Nutrition Field (MOTG) + field( + 'Active_in_Nutrition_Program__c', + dataValue( + 'form.nutrition_enrollment.enrolled_in_a_lwala_nutrition_program' + ) + ), + field( + 'lwala_nutrition_program_enrollment_date__c', + dataValue( + 'form.nutrition_enrollment.lwala_nutrition_program_enrollment_date' + ) + ), + field( + 'Trained_in_gardening__c', + dataValue('form.nutrition_enrollment.household_trained_on_gardening') + ), + field( + 'household_trained_on_gardening_date__c', + dataValue( + 'form.nutrition_enrollment.when_was_the_household_trained_on_gardening' + ) + ), + field( + 'Seed_Input_Support__c', + dataValue( + 'form.nutrition_enrollment.household_provided_with_seed_input_support' + ) + ), + field( + 'household_provided_with_seed_input_suppo__c', + dataValue( + 'form.nutrition_enrollment.when_was_the_household_provided_with_seed_input_support' + ) + ), + field( + 'MIYCN_Trained__c', + dataValue('form.nutrition_enrollment.household_trained_on_MIYCN') + ), + field( + 'Kitchen_Garden__c', + dataValue('form.nutrition_enrollment.household_has_kitchen_garden') + ), + + field( + 'Access_to_safe_water__c', + dataValue('form.Household_Information.Safe_Water') + ), + field( + 'Treats_Drinking_Water__c', + dataValue('form.Household_Information.Treats_Drinking_Water') + ), + field( + 'Tippy_Tap__c', + dataValue('form.Household_Information.Active_Handwashing_Station') + ), + field( + 'Pit_Latrine__c', + dataValue('form.Household_Information.Functional_Latrine') + ), + field( + 'Rubbish_Pit__c', + dataValue('form.Household_Information.Rubbish_Pit') + ), + field( + 'Drying_Rack__c', + dataValue('form.Household_Information.Drying_Rack') + ), + field( + 'Kitchen_Garden__c', + dataValue('form.Household_Information.Kitchen_Garden') + ), + field( + 'Cookstove__c', + dataValue('form.Household_Information.Improved_Cooking_Method') + ), + field('Clothe__c', dataValue('form.Household_Information.Clothesline')), + field( + 'WASH_Trained__c', + dataValue('form.Household_Information.WASH_Trained') + ), + field( + 'Has_muac_tape__c', + dataValue('form.Household_Information.family_muac_tape_available') + ), + field('Uses_ITNs__c', dataValue('form.Household_Information.ITNs')), + field('Deaths_in_the_last_6_months__c', state => { + var deaths = dataValue('form.household_deaths.deaths_in_past_6_months')( + state + ); + return deaths && deaths > 0 ? 'Yes' : 'No'; + }), + //field( + // 'Total_household_people__c', + // dataValue('form.Total_Number_of_Members') + // ), + field('Supervisor_Visit__c', state => + state.data.form.supervisor_visit + ? state.supervisorMap[state.data.form.supervisor_visit] + : null + ), + field('Health_insurance__c', dataValue('form.health_insurace_cover')), + field( + 'Health_insurance_active_status__c', + dataValue('form.healthinsurance_active') + ), + field('Health_insurance_type__c', state => { + var status = dataValue('form.health_insurance')(state); + var value = + status && status !== '' + ? status + .replace(/ /gi, ';') + .split(';') + .map(value => { + return state.insuranceMap[value] || value; + }) + : undefined; + return value ? value.join(';') : undefined; + }), + field( + 'Other_Health_Insurance__c', + dataValue('form.if_other_please_specify') + ), + //field('Last_Modified_Date_CommCare__c', dataValue('server_modified_on')), + field('Case_Closed_Date__c', state => { + var closed = dataValue('form.case.update.closed')(state); + var date = dataValue('server_modified_on')(state); + return closed && closed == true ? date : undefined; + }) + ) + ); + + triggers: + webhook: + type: webhook + enabled: false + edges: + webhook->Upsert-Household-Visit: + source_trigger: webhook + target_job: Upsert-Household-Visit + condition_type: js_expression + condition_label: Upsert Household Visit App Release Q2-2022 + condition_expression: | + state.data.form["@name"] == "Update Household Revised" && state.data.form["app_release"] == "Q2-2022" && state.data.properties["test_user"] != "Yes" + enabled: false + "x-[archive]-Workflow-test-get-forms": + name: 'x [archive] Workflow test get forms' + jobs: + test-get-forms: + name: test get forms + adaptor: '@openfn/language-http@v2.4.15' + credential: null + body: | + get("https://www.commcarehq.org/a/lwala-community-alliance/api/v0.5/form/", { + headers: {"content-type": "application/json"}, + authentication: {username: "aleksa@verasolutions.org", password: "chw$@kamo20"}, + query: {"limit": "1"} + }, + function(state) { + return state; + } + ); + console.log(state); + each(dataPath('objects[*]'), state => { + return post("https://www.openfn.org/inbox/e77693cc-71d5-49a9-8192-5b15679450df", { body: state => state.data })(state); + }); + + triggers: + cron: + type: cron + cron_expression: '1 * * * *' + enabled: false + edges: + cron->test-get-forms: + source_trigger: cron + target_job: test-get-forms + condition_type: always + enabled: false + "x-[archive]-Workflow-test-revised": + name: 'x [archive] Workflow test revised' + jobs: + test-revised: + name: test revised + adaptor: '@openfn/language-salesforce@v1.3.2' + credential: null + body: | + // REVISED Form - To replace old Update HH + alterState(state => { + const data = state.data.data; + + const deaths = state.data.data.form.household_deaths ? state.data.data.form.household_deaths.deaths : ''; + if (deaths !== '' &&!Array.isArray(deaths)) { + state.data.data.form.household_deaths.deaths = [deaths]; + } + + const supervisorMap = { + community_health_nurse: 'Community Health Nurse', + chw_supervisor: 'CHW Supervisor', + chewschas: 'CHEWs/CHAs', + other: 'Other', + none: 'None', + }; + + return { ...state, supervisorMap }; + }); + upsert( + 'Household__c', + 'CommCare_Code__c', + fields( + field('CommCare_Code__c', dataValue('form.case.@case_id')), + field('MOH_household_code__c', state => { + var moh = dataValue('form.Household_Information.moh_code')(state); + var mohLinked = dataValue('form.MOH_household_code_linked')(state); + return moh ? moh : mohLinked; + }), + field('Active_Household__c', state => { + var status = dataValue('form.Household_Status')(state); + if(status==='No'){ + status = false; + } else if(status==='Yes'){ + status = true; + } + return status; + //return status=='No'? false : true; + }), + /*field('Reactivated__c', state => { + var status = dataValue('form.Household_Status')(state); + return status=='No'? false : true; + }),*/ + field('Inactive_Reason__c', state => { + var reason = dataValue('form.Reason_for_Inactive')(state); + return reason !== undefined ? reason : null; + }), + field('Source__c', 1), + field('Household_village__c', dataValue('form.village')), + field( + 'Access_to_safe_water__c', + dataValue('form.Household_Information.Safe_Water') + ), + field( + 'Treats_Drinking_Water__c', + dataValue('form.Household_Information.Treats_Drinking_Water') + ), + field( + 'Tippy_Tap__c', + dataValue('form.Household_Information.Active_Handwashing_Station') + ), + field( + 'Pit_Latrine__c', + dataValue('form.Household_Information.Functional_Latrine') + ), + field( + 'Rubbish_Pit__c', + dataValue('form.Household_Information.Rubbish_Pit') + ), + field( + 'Drying_Rack__c', + dataValue('form.Household_Information.Drying_Rack') + ), + field( + 'Kitchen_Garden__c', + dataValue('form.Household_Information.Kitchen_Garden') + ), + field( + 'Cookstove__c', + dataValue('form.Household_Information.Improved_Cooking_Method') + ), + field('Clothe__c', dataValue('form.Household_Information.Clothesline')), + field( + 'WASH_Trained__c', + dataValue('form.Household_Information.WASH_Trained') + ), + field('Uses_ITNs__c', dataValue('form.Household_Information.ITNs')), + //field("Family_planning__c", dataValue("form.Household_Information.family_planning")), // new mapping + //field("Family_planning_method__c", dataValue("form.Household_Information.Family_planning_method")), // new mapping + field('Deaths_in_the_last_6_months__c', state => { + var deaths = dataValue('form.household_deaths.deaths_in_past_6_months')( + state + ); + return deaths && deaths > 0 ? 'Yes' : 'No'; + }), + field( + 'Total_household_people__c', + dataValue('form.Total_Number_of_Members') + ), + field('Supervisor_Visit__c', state => + state.data.form.supervisor_visit + ? state.supervisorMap[state.data.form.supervisor_visit] + : null + ) + ) + ), + upsert( + 'Visit__c', + 'CommCare_Visit_ID__c', + fields( + field('CommCare_Visit_ID__c', dataValue('id')), + relationship( + 'Household__r', + 'CommCare_Code__c', + dataValue('form.case.@case_id') + ), + field('Date__c', dataValue('form.metadata.timeEnd')), + //field("Household_CHW__c", "a031x000002S9lm"), //Hardcoded for sandbox testing + field('Household_CHW__c', dataValue('form.chw')), + field('Name', 'CHW Visit'), + field('Supervisor_Visit__c', state => + state.data.form.supervisor_visit + ? state.supervisorMap[state.data.form.supervisor_visit] + : null + ) + ) + ), + //New logic to insert child Person records if person is marked as deceased in HH form + each( + merge( + dataPath('$.form.household_deaths.deaths[*]'), + fields( + field('caseId', dataValue('form.case.@case_id')), + field('catchment', dataValue('form.catchment')), + field('Date', dataValue('form.Date')) + ) + ), + upsertIf( + state.data.form.household_deaths && state.data.form.household_deaths.deaths_in_past_6_months > 0, //only insert deceased Person if deaths + 'Person__c', + 'CommCare_ID__c', + fields( + field('CommCare_ID__c', state => { + var age = dataValue('age_dead')(state); + return `${state.data.caseId}${age}`; + }), + field('CommCare_HH_Code__c', dataValue('caseId')), + relationship('RecordType', 'Name', state => { + var age = dataValue('age_dead')(state); + var gender = dataValue('gender_dead')(state); + var rt = ''; + if (age < 5) { + rt = 'Child'; + } else if (age < 18) { + rt = 'Youth'; + } else if (gender === 'female') { + rt = 'Female Adult'; + } else { + rt = 'Male Adult'; + } + return rt; + }), + field('Name', 'Deceased Person'), + field('Source__c', true), + relationship('Catchment__r', 'Name', dataValue('catchment')), + field('Client_Status__c', 'Deceased'), + field('Dead_age__c', dataValue('age_dead')), + field('Cause_of_Death__c', state => { + var cause = dataValue('cause_of_death_dead')(state); + return cause !== undefined + ? cause.toString().replace(/_/g, ' ') + : null; + }), + field('Verbal_autopsy__c', dataValue('verbal_autopsy')), + field('Client_Status__c', 'Deceased'), + field('Active_in_Thrive_Thru_5__c', 'No'), + field('Active_in_HAWI__c', 'No'), + field('Active_TT5_Mother__c', 'No'), + field('TT5_Mother_Registrant__c', 'No'), + field('Date_of_Death__c', dataValue('Date')), + field('Inactive_Date__c', dataValue('Date')) + ) + ) + ); + + triggers: + webhook: + type: webhook + enabled: false + edges: + webhook->test-revised: + source_trigger: webhook + target_job: test-revised + condition_type: js_expression + condition_label: test form csv + condition_expression: | + state.data["form.@name"] == "Update Household Revised" + enabled: false + "z-[archive]-Upsert-Household": + name: 'z [archive] Upsert Household' + jobs: + Upsert-Household: + name: Upsert Household + adaptor: '@openfn/language-salesforce@latest' + credential: null + body: | + query( + `SELECT Id, Parent_Geographic_Area__c, Parent_Geographic_Area__r.Name, Parent_Geographic_Area__r.Parent_Geographic_Area__c FROM Location__c WHERE CommCare_User_ID__c = '${dataValue( + 'properties.owner_id' + )(state)}'` + ); + + fn(state => ({ + ...state, + data: { + ...state.data, + villageNewId: + state.references[0].records && state.references[0].records.length !== 0 + ? state.references[0].records[0].Id + : undefined, + areaNewId: + state.references[0].records && state.references[0].records.length !== 0 + ? state.references[0].records[0].Parent_Geographic_Area__c + : undefined, + catchmentNewId: + state.references[0].records && state.references[0].records.length !== 0 + ? (state.references[0].records[0].Parent_Geographic_Area__r + ? state.references[0].records[0].Parent_Geographic_Area__r.Parent_Geographic_Area__c + : undefined) + : undefined, + }, + })); + + upsertIf( + state.data.properties.commcare_username !== 'test.2021' && + state.data.properties.test_user !== 'Yes' , + 'Household__c', + 'CommCare_Code__c', + fields( + field('CommCare_Username__c', dataValue('properties.commcare_username')), + field('MOH_household_code__c', dataValue('properties.moh_code')), + field('CommCare_Code__c', dataValue('case_id')), + field('Source__c', true), + //field('Household_CHW__c', 'a030Q00000A0jeYQAR'), //sandbox hardcoded mapping + field('Household_CHW__c', state => { + var chw = dataValue('properties.CHW_ID')(state); + return chw === 'a030800001zQrk' + ? 'a030800001zQrk5' + : chw + ? chw + : undefined; + }), + //TODO: Prod mapping to add back before go-live + field('Catchment__c', dataValue('catchmentNewId')), + field('Area__c', dataValue('areaNewId')), + field('Village__c', dataValue('villageNewId')), + field('Household_Village__c', dataValue('properties.village')), + // relationship('Catchment__r', 'Name', state => { + // var catchment = + // state.data.properties.catchement || + // state.data.properties.catchment_name; + // return catchment === '' || catchment === undefined + // ? 'Unknown Location' + // : catchment; + // }), // check + // field('Area__c', state => { + // // var area = dataValue('properties.Area_Name')(state); + // return area === '' || area === undefined ? 'a000Q00000Egmu4' : area; + // }), // Commented out because it was causing a job error + // field('Household_village__c', dataValue('properties.village')),//case property, but not in message + + // field('Village__c',dataValue('properties.village_name')), //lookup + field('Deaths_in_the_last_6_months__c', state => { + var death = dataValue( + 'properties.deaths_in_past_6_months' + )(state); + return death > 0 ? 'Yes' : 'No'; + }), + field('Access_to_safe_water__c',dataValue('properties.Safe_Water')),//not coming through + field('Treats_Drinking_Water__c',dataValue('properties.Treats_Drinking_Water')),//not coming through + field('Tippy_Tap__c',dataValue('properties.Active_Handwashing_Station')),//not coming through + field('Pit_Latrine__c',dataValue('properties.Functional_Latrine')),//not coming through + field('Rubbish_Pit__c',dataValue('properties.Rubbish_Pit')),//not coming through + field('Drying_Rack__c',dataValue('properties.Drying_Rack')),//not coming through + field('Kitchen_Garden__c',dataValue('properties.Kitchen_Garden')),//not coming through + field('Cookstove__c',dataValue('properties.Improved_Cooking_Method')),//not coming through + field('Clothe__c',dataValue('properties.Clothesline')),//not coming through + field('WASH_Trained__c',dataValue('properties.WASH_Trained')),//not coming through + field('Uses_ITNs__c',dataValue('properties.ITNs')), + field( + 'Has_muac_tape__c', + dataValue('properties.family_muac_tape_available') + ), + //field('Total_household_people__c',dataValue('properties.Total_Number_of_Members')), //not coming through + field('Health_insurance__c', dataValue('properties.health_insurace_cover')), + field('Health_insurance_active_status__c',dataValue('properties.healthinsurance_active')), + field('Health_insurance_type__c', state => { + var status = dataValue('properties.health_insurance')(state); + return status && status === 'other_please_specify_if_active' + ? 'Other' + : status === 'nhif' + ? 'NHIF' + : status === 'Linda_mama' || 'linda_mama' + ? 'Linda mama' + : status; + }), + field('Other_Health_Insurance__c',dataValue('properties.if_other_please_specify')), + field('Work_with_TBA__c', dataValue('properties.tba')), + field('TBA_name__c', dataValue('properties.which_tba')), + field('Last_Modified_Date_CommCare__c', dataValue('server_date_modified')),//Need a case property), + field('Active_Household__c', state => { + var status = dataValue('properties.Household_Status')(state); + return status && status === 'No' + ? false + : status === 'Yes' + ? true + : status; + }), + // relationship('Head_of_Household__r', 'CommCare_ID__c', dataValue('properties.head_of_household_case_id')), + field('Inactive_Reason__c', state => { + var reason = dataValue('properties.Reason_for_Inactive')(state); + return reason ? reason.toString().replace(/_/g, ' ') : null; + }), + field( + 'Active_in_Nutrition_Program__c', + dataValue( + 'properties.enrolled_in_a_lwala_nutrition_program' + ) + ), + field( + 'lwala_nutrition_program_enrollment_date__c', + dataValue( + 'properties.lwala_nutrition_program_enrollment_date' + ) + ), + field( + 'Trained_in_gardening__c', + dataValue('properties.household_trained_on_gardening') + ), + field( + 'household_trained_on_gardening_date__c', + dataValue( + 'properties.when_was_the_household_trained_on_gardening' + ) + ), + field( + 'Seed_Input_Support__c', + dataValue('properties.household_provided_with_seed_input_support' + ) + ), + field( + 'household_provided_with_seed_input_suppo__c', + dataValue( + 'properties.when_was_the_household_provided_with_seed_input_support' + ) + ), + field( + 'MIYCN_Trained__c', + dataValue('properties.household_trained_on_MIYCN') + ), + // not in message: + // field( + // 'Kitchen_Garden__c', + // dataValue('properties.nutrition_enrollment.household_has_kitchen_garden') + // ), + + //field('Case_Closed_Date__c', state => { + // var closed = dataValue('date_closed')(state); + // var date = dataValue('server_date_modified')(state); + // return closed && closed == true ? date : undefined; + // }) + ) + ); + + triggers: + webhook: + type: webhook + enabled: false + edges: + webhook->Upsert-Household: + source_trigger: webhook + target_job: Upsert-Household + condition_type: js_expression + condition_label: Household + condition_expression: | + state.data.properties["app_release"] == "Q2-2022" && state.data.properties["case_type"] == "Household" && state.data.properties["test_user"] != "Yes" + enabled: false diff --git a/openfn-a5573c8f-bfbd-447e-8e1d-5bab1d2901e7-state.json b/openfn-a5573c8f-bfbd-447e-8e1d-5bab1d2901e7-state.json new file mode 100644 index 0000000..cef00f9 --- /dev/null +++ b/openfn-a5573c8f-bfbd-447e-8e1d-5bab1d2901e7-state.json @@ -0,0 +1,1054 @@ +{ + "id": "a5573c8f-bfbd-447e-8e1d-5bab1d2901e7", + "name": "lwala-chw-support", + "description": null, + "inserted_at": "2024-03-22T14:37:07Z", + "updated_at": "2024-11-18T12:16:49Z", + "project_credentials": { + "rita@openfn.org-Lwala-Salesforce-Sandbox-(April-2024)": { + "id": "96a3843d-5d9c-4f03-8289-508b87901c9b", + "name": "Lwala Salesforce Sandbox (April 2024)", + "owner": "rita@openfn.org" + }, + "rita@openfn.org-Lwala-cases-endpoint-test-user": { + "id": "f12cfa8a-2863-487c-8243-5684bc13936d", + "name": "Lwala cases endpoint test user", + "owner": "rita@openfn.org" + }, + "rita@openfn.org-Lwala-Case-Endpoint-Test-User-HTTP": { + "id": "bce72a90-c711-441c-9000-31098cb33167", + "name": "Lwala Case Endpoint Test User HTTP", + "owner": "rita@openfn.org" + }, + "rita@openfn.org-Lwala-case-endpoint-production-user": { + "id": "8d4d9b2d-e41a-40ab-92dc-e2280bb5ee2b", + "name": "Lwala case endpoint production user", + "owner": "rita@openfn.org" + }, + "aleksa@openfn.org-Lwala-Salesforce-Prod---openfn-user": { + "id": "25ba06d8-5559-4d1c-a8b8-828cc3021465", + "name": "Lwala Salesforce Prod - openfn user", + "owner": "aleksa@openfn.org" + }, + "aleksa@openfn.org-Lwala-CommCare-HQ---openfn-user-": { + "id": "fee3669f-c133-4bb5-86ca-c090eec4bc99", + "name": "Lwala CommCare HQ - openfn user ", + "owner": "aleksa@openfn.org" + } + }, + "scheduled_deletion": null, + "history_retention_period": 365, + "dataclip_retention_period": null, + "retention_policy": "retain_all", + "workflows": { + "x-[archive]-Workflow-Register-Training": { + "id": "07e2a931-d8ec-437b-b563-fbe934640707", + "name": "x [archive] Workflow Register Training", + "inserted_at": "2024-09-10T15:45:41.545642Z", + "lock_version": 3, + "triggers": { + "webhook": { + "enabled": false, + "id": "25151889-2559-48c4-b2c7-06632a42a30c", + "type": "webhook" + } + }, + "jobs": { + "Register-Training": { + "id": "8e86ab00-c6b0-4a00-a996-9fba290db5e0", + "name": "Register Training", + "body": "create(\n 'Activity__c',\n fields(\n field('Date__c', dataValue('form.info.date')),\n field('Catchment__c', 'a002400000pAcOe'),\n field('Module_Type__c', state => {\n var str1 = dataValue('form.info.module_number')(state)\n .toString()\n .replace(/_/g, ' ');\n return str1;\n }),\n field('Facilitator__c', dataValue('form.info.Facilitator')),\n field('Name', state => {\n var str1 = dataValue('form.info.name')(state)\n .toString()\n .replace(/_/g, ' ');\n return str1;\n }),\n field('Group__c', dataValue('form.sfid')),\n field('Program__c', dataValue('form.program')),\n field('CommCare_ID__c', dataValue('metadata.instanceID'))\n )\n);\n\nalterState(state => {\n var attendees = dataValue('form.attendees')(state).split(' ');\n for (i = 0; i < attendees.length; i++) {\n create(\n 'Household_Attendance__c',\n fields(\n field('Activity__c', lastReferenceValue('id')),\n field('Date__c', dataValue('form.info.date')),\n relationship('Household__r', 'CommCare_Code__c', attendees[i])\n )\n )(state);\n }\n return state;\n});\n/*create(\"Household_Attendance__c\",fields(\n field(\"Activity__c\",lastReferenceValue(\"id\")),\n field(\"Date__c\",dataValue(\"form.info.date\")),\n relationship(\"Household__c\",\"Name\",\"01465\")\n))*/\n", + "adaptor": "@openfn/language-salesforce@v1.3.2", + "project_credential_id": null + } + }, + "edges": { + "webhook->Register-Training": { + "enabled": false, + "id": "b86e05d0-236d-4b82-bc7b-e60083c10b87", + "target_job_id": "8e86ab00-c6b0-4a00-a996-9fba290db5e0", + "source_trigger_id": "25151889-2559-48c4-b2c7-06632a42a30c", + "condition_type": "js_expression", + "condition_label": "Register Training", + "condition_expression": "state.data.form[\"@name\"] == \"Register Training\"" + } + } + }, + "x-[archive]-Workflow-Register-OSG-Mentoring-Attendance": { + "id": "9285a0e0-3289-4d7a-a310-59f5758c076a", + "name": "x [archive] Workflow Register OSG Mentoring Attendance", + "inserted_at": "2024-09-10T15:45:41.549556Z", + "lock_version": 3, + "triggers": { + "webhook": { + "enabled": false, + "id": "2be52c24-173f-46e6-a598-8773d66cb018", + "type": "webhook" + } + }, + "jobs": { + "Register-OSG-Mentoring-Attendance": { + "id": "dd99c03b-3a5d-4012-8734-7fb5b20e90f4", + "name": "Register OSG Mentoring Attendance", + "body": "create(\n 'Activity__c',\n fields(\n field('Date__c', dataValue('form.info.date')),\n field('Catchment__c', 'a002400000pAcOe'),\n field('Module_Type__c', state => {\n var str1 = dataValue('form.module_number')(state)\n .toString()\n .replace(/_/g, ' ');\n return str1;\n }),\n field('Facilitator__c', dataValue('form.info.Facilitator')),\n field('Name', state => {\n var str1 = dataValue('form.module_name')(state)\n .toString()\n .replace(/_/g, ' ');\n return str1;\n }),\n field('Group__c', dataValue('form.sfid')),\n field('Program__c', dataValue('form.program')),\n field('CommCare_ID__c', dataValue('metadata.instanceID'))\n )\n);\n\nalterState(state => {\n var attendees = dataValue('form.attendees')(state).split(' ');\n for (i = 0; i < attendees.length; i++) {\n create(\n 'Attendance__c',\n fields(\n field('Activity__c', lastReferenceValue('id')),\n field('Date__c', dataValue('form.info.date')),\n relationship('Person__r', 'CommCare_ID__c', attendees[i])\n )\n )(state);\n }\n return state;\n});\n/*create(\"Household_Attendance__c\",fields(\n field(\"Activity__c\",lastReferenceValue(\"id\")),\n field(\"Date__c\",dataValue(\"form.info.date\")),\n relationship(\"Household__c\",\"Name\",\"01465\")\n))*/\n", + "adaptor": "@openfn/language-salesforce@v1.3.2", + "project_credential_id": null + } + }, + "edges": { + "webhook->Register-OSG-Mentoring-Attendance": { + "enabled": false, + "id": "4f813c96-5a6d-4538-b04b-73c92532b211", + "target_job_id": "dd99c03b-3a5d-4012-8734-7fb5b20e90f4", + "source_trigger_id": "2be52c24-173f-46e6-a598-8773d66cb018", + "condition_type": "js_expression", + "condition_label": "Register OSG Mentoring Attendance", + "condition_expression": "state.data.form[\"@name\"] == \"Register OSG Mentoring Session\"" + } + } + }, + "x-[archive]-Workflow-Nutrition-Survey-Submissions": { + "id": "3f7e72f7-b51d-45a6-be16-be871a4c2db9", + "name": "x [archive] Workflow Nutrition Survey Submissions", + "inserted_at": "2024-09-10T15:45:41.559082Z", + "lock_version": 3, + "triggers": { + "webhook": { + "enabled": false, + "id": "5d20e502-4c14-44e3-83a8-2bfdea17fb1e", + "type": "webhook" + } + }, + "jobs": { + "Nutrition-Survey-Submissions": { + "id": "08dba782-6da4-4cbf-83e0-46b0eeca4957", + "name": "Nutrition Survey Submissions", + "body": "upsert(\n 'Service__c',\n 'Service_UID__c',\n fields(\n field('Service_UID__c', state => {\n const id = dataValue('form.subcase_0.case.@case_id')(state);\n const date = dataValue('$.form.Date')(state);\n return id + date + 'Nutrition-Screening';\n }),\n field('Source__c', 1),\n field('Catchment__c', 'a002400000pAcOe'),\n field('Date__c', dataValue('$.form.Date')),\n field('Type_of_Service__c', 'CHW Mobile Survey'),\n field('Household_CHW__c', dataValue('$.form.Household_CHW')),\n field('RecordTypeID', '01224000000YAuK'),\n field('Reason_for_Service__c', 'Nutrition Screening'),\n relationship(\n 'Person__r',\n 'CommCare_ID__c',\n dataValue('$.form.case.@case_id')\n ),\n field(\n 'Primary_Caregiver__c',\n dataValue('$.form.Child_Information.Primary_Caregiver')\n ),\n field('Height__c', dataValue('$.form.Child_Information.body_specs.Height')),\n field('Weight__c', dataValue('$.form.Child_Information.body_specs.Weight')),\n field('MUAC__c', dataValue('$.form.Child_Information.body_specs.MUAC')),\n field('Nutrition_Status__c', state => {\n var status = '';\n if (\n dataValue('$.form.Child_Information.malnourished.Nutrition_Status')(\n state\n ) == 'normal'\n ) {\n status = 'Normal';\n } else if (\n dataValue('$.form.Child_Information.malnourished.Nutrition_Status')(\n state\n ) == 'moderate'\n ) {\n status = 'Moderately Malnourished';\n } else if (\n dataValue('$.form.Child_Information.malnourished.Nutrition_Status')(\n state\n ) == 'severe'\n ) {\n status = 'Severely Malnourished';\n }\n return status;\n }),\n field(\n 'Ever_been_breastfed__c',\n dataValue('$.form.Child_Information.infant_diet.ever_been_breastfed')\n ),\n field(\n 'Age_at_which_breastfed__c',\n dataValue('$.form.Child_Information.infant_diet.age_at_which_breastfed')\n ),\n field(\n 'X24_Hours_Breastfed__c',\n dataValue('$.form.Child_Information.infant_diet.how_many_times_24_hours')\n ),\n field(\n 'Formula_Milk__c',\n dataValue('$.form.Child_Information.infant_diet.has_had_formula')\n ),\n field(\n 'Water__c',\n dataValue('$.form.Child_Information.infant_diet.has_had_water')\n ),\n field(\n 'Glucose__c',\n dataValue('$.form.Child_Information.infant_diet.has_had_glucose')\n ),\n field(\n 'Animal_Milk__c',\n dataValue('$.form.Child_Information.infant_diet.has_had_animal_milk')\n ),\n field(\n 'Juice__c',\n dataValue('$.form.Child_Information.infant_diet.has_had_juice')\n ),\n field(\n 'Sweetened_Drinks__c',\n dataValue('$.form.Child_Information.infant_diet.has_had_sweetened_drinks')\n ),\n field(\n 'Honey__c',\n dataValue('$.form.Child_Information.infant_diet.has_had_honey')\n ),\n field(\n 'Sugar__c',\n dataValue('$.form.Child_Information.infant_diet.has_had_sugar')\n ),\n field(\n 'Clear_Soup__c',\n dataValue('$.form.Child_Information.infant_diet.has_had_clear_soup')\n ),\n field(\n 'Grains__c',\n dataValue('$.form.Child_Information.infant_diet.has_had_grains')\n ),\n field(\n 'Yellow_Flesh__c',\n dataValue('$.form.Child_Information.infant_diet.has_had_yellow_flesh')\n ),\n field(\n 'Roots__c',\n dataValue('$.form.Child_Information.infant_diet.has_had_roots')\n ),\n field(\n 'Leafy_Vegetables__c',\n dataValue('$.form.Child_Information.infant_diet.has_had_leafy_veg')\n ),\n field(\n 'Fruits_or_Vegetables__c',\n dataValue('$.form.Child_Information.infant_diet.has_had_other_fruit_veg')\n ),\n field(\n 'Meat__c',\n dataValue('$.form.Child_Information.infant_diet.has_had_meat')\n ),\n field(\n 'Organ_Meat__c',\n dataValue('$.form.Child_Information.infant_diet.has_had_organ_meat')\n ),\n field(\n 'Eggs__c',\n dataValue('$.form.Child_Information.infant_diet.has_had_eggs')\n ),\n field(\n 'Dried_Silver_Fish__c',\n dataValue('$.form.Child_Information.infant_diet.has_had_silver_fish')\n ),\n field(\n 'Seafood__c',\n dataValue('$.form.Child_Information.infant_diet.has_had_other_seafood')\n ),\n field(\n 'Dairy__c',\n dataValue('$.form.Child_Information.infant_diet.has_had_milk_products')\n ),\n field(\n 'Fats__c',\n dataValue('$.form.Child_Information.infant_diet.has_had_fats')\n ),\n field(\n 'Sugary_Foods__c',\n dataValue('$.form.Child_Information.infant_diet.has_had_sugary_foods')\n ),\n field(\n 'Insects__c',\n dataValue('$.form.Child_Information.infant_diet.has_had_insects')\n )\n )\n);\n\nalterState(state => {\n if (\n dataValue('$.form.Child_Information.malnourished.Follow-Up_Required')(\n state\n ) === 'Yes'\n ) {\n return upsert(\n 'Service__c',\n 'Service_UID__c',\n fields(\n field('Service_UID__c', state => {\n const id = dataValue('form.subcase_0.case.@case_id')(state);\n const date = dataValue('$.form.Date')(state);\n return id + date + 'Nutrition-Referral';\n }),\n field('Source__c', 1),\n field('Catchment__c', 'a002400000pAcOe'),\n field('Date__c', dataValue('$.form.Date')),\n field('Type_of_Service__c', 'CHW Mobile Survey'),\n field('Household_CHW__c', dataValue('$.form.Household_CHW')),\n field('RecordTypeID', '01224000000kOto'),\n field('Referred__c', 1),\n field(\n 'Follow_Up_By_Date__c',\n dataValue('$.form.Child_Information.malnourished.Follow-Up_By_Date')\n ),\n field('Reason_for_Service__c', 'Referral'),\n field('Open_Case__c', 1),\n field('CommCare_Code__c', dataValue('form.subcase_0.case.@case_id')),\n field(\n 'Purpose_of_Referral__c',\n dataValue('form.Child_Information.malnourished.Purpose_of_Referral')\n ),\n relationship(\n 'Person__r',\n 'CommCare_ID__c',\n dataValue('$.form.case.@case_id')\n )\n )\n )(state);\n }\n\n return state;\n});\n", + "adaptor": "@openfn/language-salesforce@v1.3.2", + "project_credential_id": null + } + }, + "edges": { + "webhook->Nutrition-Survey-Submissions": { + "enabled": false, + "id": "4f7fc3e0-9797-43f5-a89a-c0a022dff2e9", + "target_job_id": "08dba782-6da4-4cbf-83e0-46b0eeca4957", + "source_trigger_id": "5d20e502-4c14-44e3-83a8-2bfdea17fb1e", + "condition_type": "js_expression", + "condition_label": "CommCare Nutrition Survey Update Person", + "condition_expression": "state.data.form[\"@name\"] == \"Nutrition Survey\" && state.data.metadata.username != \"test.2021\"" + } + } + }, + "x-[archive]-Update-Household-in-CommCare": { + "id": "b8a898eb-0d97-471c-a856-6556fc1d6407", + "name": "x [archive] Update Household in CommCare", + "inserted_at": "2024-09-10T15:45:41.563276Z", + "lock_version": 4, + "triggers": { + "webhook": { + "enabled": false, + "id": "0a479779-2542-446a-82a3-2c2abaa8d5e6", + "type": "webhook" + } + }, + "jobs": { + "Update-Household-in-CommCare": { + "id": "bfaf158c-c125-4a1b-aed4-ae57688aac05", + "name": "Update Household in CommCare", + "body": "submit(\n fields(\n field('@', state => {\n return {\n 'xmlns:jrm': 'http://dev.commcarehq.org/jr/xforms',\n xmlns:\n 'http://openrosa.org/formdesigner/980c10cdb3b140101225e25c6e8aff48f471b3d',\n uiVersion: '1',\n version: '46',\n name: 'Update Household',\n };\n }),\n field('Source', false),\n field('Household_Status', state => {\n var str = '';\n if (dataValue('new[0].Active_Household__c')(state) === false) {\n str = 'No';\n } else {\n str = 'Yes';\n }\n return str;\n }),\n field('Run_Code', 'Household_Lwala'),\n field('name', dataValue('new[0].Name')),\n field('area', dataValue('new[0].Area__c')),\n\n field('Household_Information', state => {\n return {\n Active_Handwashing_Station: dataValue('new[0].Tippy_Tap__c')(state),\n Drying_Rack: dataValue('new[0].Drying_Rack__c')(state),\n\n WASH_Compliant: () => {\n var ans = '';\n if (dataValue('new[0].WASH_Compliant__c')(state) === true) {\n ans = 'Yes';\n } else {\n ans = 'No';\n }\n return ans;\n },\n Functional_Latrine: dataValue('new[0].Pit_Latrine__c')(state),\n Clothesline: dataValue('new[0].Clothe__c')(state),\n ITNs: dataValue('new[0].Uses_ITNs__c')(state),\n Improved_Cooking_Method: dataValue('new[0].Cookstove__c')(state),\n Kitchen_Garden: dataValue('new[0].Kitchen_Garden__c')(state),\n Number_of_Over_5_Males: dataValue('new[0].Number_of_Over_5_Males__c')(\n state\n ),\n Number_of_Over_5_Females: dataValue(\n 'new[0].Number_of_Over_5_Females__c'\n )(state),\n Number_of_Under_5_Males: dataValue('new[0].Number_of_Under_5_Males__c')(\n state\n ),\n Number_of_Under_5_Females: dataValue(\n 'new[0].Number_of_Under_5_Females__c'\n )(state),\n Rubbish_Pit: dataValue('new[0].Rubbish_Pit__c')(state),\n Treats_Drinking_Water: dataValue('new[0].Treats_Drinking_Water__c')(\n state\n ),\n WASH_Trained: dataValue('new[0].WASH_Trained__c')(state),\n Total_Under_5: dataValue('new[0].Total_Number_of_Under_5s__c')(state),\n Total_Males: dataValue('new[0].Total_Number_of_Males__c')(state),\n Total_Females: dataValue('new[0].Total_Number_of_Females__c')(state),\n Total_Household_Members: dataValue('new[0].Total_Number_of_Members__c')(\n state\n ),\n Total_Over_5: () => {\n var num = 0;\n num =\n dataValue('new[0].Total_Number_of_Members__c')(state) -\n dataValue('new[0].Total_Number_of_Under_5s__c')(state);\n return num;\n },\n };\n }),\n field('n0:case', state => {\n return {\n '@': {\n case_id: dataValue('new[0].Commcare_Code__c')(state),\n date_modified: new Date().toISOString(),\n user_id: 'e298884bfb6ee2d2b38591a6e8ae0228',\n 'xmlns:n0': 'http://commcarehq.org/case/transaction/v2',\n },\n 'n0:update': {\n 'n0:case_name': dataValue('new[0].Name')(state),\n 'n0:owner_id': () => {\n var id = '';\n if (dataValue('new[0].chw_owner_id__c')(state) === undefined) {\n id = 'acf8595692c76095eb5afd809c628091';\n } else {\n id = dataValue('new[0].chw_owner_id__c')(state);\n }\n return id;\n },\n 'n0:case_type': 'Household',\n 'n0:WASH_Compliant': () => {\n var ans = '';\n if (dataValue('new[0].WASH_Compliant__c')(state) === true) {\n ans = 'Yes';\n } else {\n ans = 'No';\n }\n return ans;\n },\n 'n0:Active_Handwashing_Station': dataValue('new[0].Tippy_Tap__c')(\n state\n ),\n 'n0:Drying_Rack': dataValue('new[0].Drying_Rack__c')(state),\n 'n0:Functional_Latrine': dataValue('new[0].Pit_Latrine__c')(state),\n 'n0:Clothesline': dataValue('new[0].Clothe__c')(state),\n 'n0:ITNs': dataValue('new[0].Uses_ITNs__c')(state),\n 'n0:Active_in_Nutrition_Program': dataValue(\n 'new[0].Active_in_Nutrition_Program__c'\n )(state),\n 'n0:Nutrition_Group': dataValue('new[0].Nutrition_Group__c')(state),\n 'n0:seed_input_support': dataValue('new[0].Seed_Input_Support__c')(\n state\n ),\n 'n0:name_concat': dataValue('new[0].Name_Concatenation__c')(state),\n 'n0:CHW_ID': dataValue('new[0].Household_CHW__c')(state),\n 'n0:Improved_Cooking_Method': dataValue('new[0].Cookstove__c')(state),\n 'n0:Kitchen_Garden': dataValue('new[0].Kitchen_Garden__c')(state),\n 'n0:Number_of_Over_5_Males': dataValue(\n 'new[0].Number_of_Over_5_Males__c'\n )(state),\n 'n0:Number_of_Over_5_Females': dataValue(\n 'new[0].Number_of_Over_5_Females__c'\n )(state),\n 'n0:Number_of_Under_5_Males': dataValue(\n 'new[0].Number_of_Under_5_Males__c'\n )(state),\n 'n0:Number_of_Under_5_Females': dataValue(\n 'new[0].Number_of_Under_5_Females__c'\n )(state),\n 'n0:Rubbish_Pit': dataValue('new[0].Rubbish_Pit__c')(state),\n 'n0:Treats_Drinking_Water': dataValue(\n 'new[0].Treats_Drinking_Water__c'\n )(state),\n 'n0:WASH_Trained': dataValue('new[0].WASH_Trained__c')(state),\n 'n0:Total_Under_5': dataValue('new[0].Total_Number_of_Under_5s__c')(\n state\n ),\n 'n0:Total_Males': dataValue('new[0].Total_Number_of_Males__c')(state),\n 'n0:Total_Females': dataValue('new[0].Total_Number_of_Females__c')(\n state\n ),\n 'n0:area': dataValue('new[0].Area__c')(state),\n 'n0:Area_Name': dataValue('new[0].Area_Name__c')(state),\n 'n0:Total_Household_Members': dataValue(\n 'new[0].Total_Number_of_Members__c'\n )(state),\n 'n0:Household_Status': () => {\n var str = '';\n if (dataValue('new[0].Active_Household__c')(state) === false) {\n str = 'No';\n } else {\n str = 'Yes';\n }\n return str;\n },\n 'n0:Total_Over_5': () => {\n var num = 0;\n num =\n dataValue('new[0].Total_Number_of_Members__c')(state) -\n dataValue('new[0].Total_Number_of_Under_5s__c')(state);\n return num;\n },\n },\n 'n0:index': {\n 'n0:parent': {\n '@': {\n case_type: 'Area',\n },\n '#': dataValue('new[0].Area_Case_ID__c')(state),\n },\n },\n };\n }),\n field('n1:meta', state => {\n return {\n '@': { 'xmlns:n1': 'http://openrosa.org/jr/xforms' },\n 'n1:deviceID': 'Formplayer',\n 'n1:timeStart': new Date().toISOString(),\n 'n1:timeEnd': new Date().toISOString(),\n 'n1:userID': 'e298884bfb6ee2d2b38591a6e8ae0228',\n };\n })\n )\n);\n", + "adaptor": "@openfn/language-commcare@latest", + "project_credential_id": null + } + }, + "edges": { + "webhook->Update-Household-in-CommCare": { + "enabled": false, + "id": "47ccfdfb-b8a7-4b15-8184-d3d0f9ffbb9d", + "target_job_id": "bfaf158c-c125-4a1b-aed4-ae57688aac05", + "source_trigger_id": "0a479779-2542-446a-82a3-2c2abaa8d5e6", + "condition_type": "js_expression", + "condition_label": "SF Update HH", + "condition_expression": "state.data.label == \"Update Household\"" + } + } + }, + "x-[archive-]Workflow-WF3-2a-Repeat-Failed-Person-Visits": { + "id": "0f92c3e3-9ac7-4adc-b6f6-c58c031db241", + "name": "x [archive ]Workflow WF3-2a Repeat Failed Person Visits", + "inserted_at": "2024-09-10T15:45:41.895684Z", + "lock_version": 2, + "triggers": { + "cron": { + "enabled": false, + "id": "68aee10a-9835-420f-b95d-96fb303147c7", + "type": "cron", + "cron_expression": "0 * * * *" + } + }, + "jobs": { + "WF3-2a-Repeat-Failed-Person-Visits": { + "id": "10ea6db1-99fe-445e-bace-ec1554898247", + "name": "WF3-2a Repeat Failed Person Visits", + "body": "fn(state => {\n const { baseUrl } = state.configuration;\n\n const caseTypes = ['visite'];\n\n //NOTE: You can use 'limit' to modify this batch size as desired\n const limit = 1000; //E.g., change to 10 to process records in smaller batch sizes\n\n //NOTE: indexedOnStart is the default sync start data the FIRST time the job runs\n const indexedOnStart = '2024-01-17T01:00:00';\n\n //NOTE: After first job run, OpenFn will check the job sync data (\"lastRunAt\") to set as the indexedOnStart\n const lastRunAt =\n typeof state.lastRunAt !== 'undefined' ? state.lastRunAt : indexedOnStart;\n console.log('Filtering cases with indexed_on_start > than ::', lastRunAt);\n \n const aMinuteAgo = new Date( Date.now() - 1000 * 60 );\n console.log(aMinuteAgo);\n\n const queries = caseTypes.map(\n t => `?type=${t}&indexed_on_start=${lastRunAt}&limit=${limit}`\n //NOTE: If for testing, you want to fetch data for a specific historical range (e.g., between April 23 and 24)...\n //...then use the query string below instead of the one above on L16, and custom adjust the index_on start/end dates\n //t => `?type=${t}&indexed_on_start=2024-01-15T00:00:00&limit=${limit}&indexed_on_end=2024-01-16T23:59:59`\n );\n\n return { ...state, queries, baseUrl, payloads: [] };\n});\n\n// create a \"recursiveGet\" which will call itself if CommCare tells us there's\n// more data to fetch for the same form\n\nfn(state => {\n const recursiveGet = url =>\n get(\n url,\n {\n headers: { 'content-type': 'application/json' },\n },\n nextState => {\n const now = new Date();\n const { baseUrl, data, payloads } = nextState;\n\n const { meta, objects } = data;\n console.log('Metadata in CommCare response:', meta);\n\n const finalState = {\n ...nextState,\n payloads: [...payloads, ...objects],\n };\n\n if (meta.next) {\n console.log('Next query detected, recursing...');\n return recursiveGet(`${baseUrl}${meta.next}`)(finalState);\n }\n finalState.lastRunAt = now.toISOString().slice(0, 19);\n return finalState;\n }\n );\n\n return { ...state, recursiveGet };\n});\n\n// for each initial query, fetch data recursively\neach(\n '$.queries[*]',\n fn(state => {\n return state.recursiveGet(`${state.baseUrl}${state.data}`)(state);\n })\n);\n// log the total number of payloads returned\nfn(state => {\n console.log('Count of payloads', state.payloads.length);\n\n return { ...state, references: [], data: {} };\n});\n", + "adaptor": "@openfn/language-salesforce@latest", + "project_credential_id": null + } + }, + "edges": { + "cron->WF3-2a-Repeat-Failed-Person-Visits": { + "enabled": false, + "id": "79ed047d-0d9a-429f-ac54-2e1a70127d50", + "target_job_id": "10ea6db1-99fe-445e-bace-ec1554898247", + "source_trigger_id": "68aee10a-9835-420f-b95d-96fb303147c7", + "condition_type": "always" + } + } + }, + "x-[archive]-Workflow-Upsert-Household-Visit": { + "id": "32adf090-f088-4a0e-be7a-7e7d837221b9", + "name": "x [archive] Workflow Upsert Household Visit", + "inserted_at": "2024-09-10T15:45:41.986159Z", + "lock_version": 3, + "triggers": { + "webhook": { + "enabled": false, + "id": "6817ef95-7bc4-4665-8c40-5c90d0b3a6f2", + "type": "webhook" + } + }, + "jobs": { + "Upsert-Household-Visit": { + "id": "eaca8d7a-febb-4ac4-8590-47a02b104d60", + "name": "Upsert Household Visit", + "body": "query(\n `SELECT Id, Parent_Geographic_Area__c, Parent_Geographic_Area__r.Name, Parent_Geographic_Area__r.Parent_Geographic_Area__c FROM Location__c WHERE CommCare_User_ID__c = '${dataValue(\n 'form.owner_id'\n )(state)}'`\n);\n\nfn(state => ({\n ...state,\n data: {\n ...state.data,\n catchmentNewId:\n state.references[0].records && state.references[0].records.length !== 0\n ? (state.references[0].records[0].Parent_Geographic_Area__r \n ? state.references[0].records[0].Parent_Geographic_Area__r.Parent_Geographic_Area__c\n : undefined)\n : undefined,\n },\n}));\n\nfn(state => {\n const deaths = state.data.form.household_deaths\n ? state.data.form.household_deaths.deaths\n : '';\n if (deaths !== '' && !Array.isArray(deaths)) {\n state.data.form.household_deaths.deaths = [deaths];\n }\n\n const supervisorMap = {\n community_health_nurse: 'Community Health Nurse',\n chw_supervisor: 'CHW Supervisor',\n chewschas: 'CHEWs/CHAs',\n other: 'Other',\n none: 'None',\n };\n\n const insuranceMap = {\n nhif: 'NHIF',\n Linda_mama: 'Linda mama',\n other_please_specify_if_active: 'Other',\n none: 'None',\n };\n\n return { ...state, supervisorMap, insuranceMap };\n});\n\nupsertIf(\n state.data.metadata.username !== 'test.2021' &&\n state.data.form.test_user !== 'Yes' ,\n 'Visit__c',\n 'CommCare_Visit_ID__c',\n fields(\n field('CommCare_Username__c', dataValue('form.meta.username')),//\n field('CommCare_Visit_ID__c', dataValue('id')),\n // field('Household_CHW__c', 'a030Q00000A0jeY'),\n // field('Catchment__c', dataValue('a000Q00000Egmtk')),\n field('Catchment__c', dataValue('catchmentNewId')),\n // field('Household__c','a010Q00000BL6lT'),\n // field('Household__c', dataValue('form.case.@case_id')),\n relationship(\n 'Household__r',\n 'CommCare_Code__c',\n dataValue('form.case.@case_id')),\n field('Date__c',dataValue('form.Date')),\n //field('MOH_household_code__c', state => {\n // var moh = dataValue('form.Household_Information.moh_code')(state);\n // var mohLinked = dataValue('form.MOH_household_code_linked')(state);\n // return moh ? moh : mohLinked && mohLinked !== '' ? mohLinked : undefined;\n // }),\n field('Active_Household__c', state => {\n var status = dataValue('form.Household_Status')(state);\n return status && status === 'No'\n ? false\n : status === 'Yes'\n ? true\n : status;\n }),\n //field('Inactive_Reason__c', state => {\n // var reason = dataValue('form.Reason_for_Inactive')(state);\n // return reason ? reason.toString().replace(/_/g, ' ') : null;\n //}),\n //field('Source__c', 1),//\n field('Household_CHW__c', state => {\n var chw = dataValue('properties.CHW_ID')(state);\n return chw === 'a030800001zQrk'\n ? 'a030800001zQrk5'\n : chw\n ? chw\n : undefined;\n }), //TO UPDATE IN PRODUCTION\n field(\n 'Completed_COVID_19_Phone_Screening__c',\n dataValue(\n 'form.did_you_complete_the_covid-19_phone_screening_for_this_household'\n )\n ),\n field('Household_Visit_Type__c', state => {\n var visit = dataValue(\n 'form.is_this_a_physical_home_visit_or_a_phone_call_visit'\n )(state);\n return visit ? visit.toString().replace(/_/g, ' ') : null;\n }),\n // field('Household_village__c', dataValue('form.village')),//\n //New Nutrition Field (MOTG)\n field(\n 'Active_in_Nutrition_Program__c',\n dataValue(\n 'form.nutrition_enrollment.enrolled_in_a_lwala_nutrition_program'\n )\n ),\n field(\n 'lwala_nutrition_program_enrollment_date__c',\n dataValue(\n 'form.nutrition_enrollment.lwala_nutrition_program_enrollment_date'\n )\n ),\n field(\n 'Trained_in_gardening__c',\n dataValue('form.nutrition_enrollment.household_trained_on_gardening')\n ),\n field(\n 'household_trained_on_gardening_date__c',\n dataValue(\n 'form.nutrition_enrollment.when_was_the_household_trained_on_gardening'\n )\n ),\n field(\n 'Seed_Input_Support__c',\n dataValue(\n 'form.nutrition_enrollment.household_provided_with_seed_input_support'\n )\n ),\n field(\n 'household_provided_with_seed_input_suppo__c',\n dataValue(\n 'form.nutrition_enrollment.when_was_the_household_provided_with_seed_input_support'\n )\n ),\n field(\n 'MIYCN_Trained__c',\n dataValue('form.nutrition_enrollment.household_trained_on_MIYCN')\n ),\n field(\n 'Kitchen_Garden__c',\n dataValue('form.nutrition_enrollment.household_has_kitchen_garden')\n ),\n\n field(\n 'Access_to_safe_water__c',\n dataValue('form.Household_Information.Safe_Water')\n ),\n field(\n 'Treats_Drinking_Water__c',\n dataValue('form.Household_Information.Treats_Drinking_Water')\n ),\n field(\n 'Tippy_Tap__c',\n dataValue('form.Household_Information.Active_Handwashing_Station')\n ),\n field(\n 'Pit_Latrine__c',\n dataValue('form.Household_Information.Functional_Latrine')\n ),\n field(\n 'Rubbish_Pit__c',\n dataValue('form.Household_Information.Rubbish_Pit')\n ),\n field(\n 'Drying_Rack__c',\n dataValue('form.Household_Information.Drying_Rack')\n ),\n field(\n 'Kitchen_Garden__c',\n dataValue('form.Household_Information.Kitchen_Garden')\n ),\n field(\n 'Cookstove__c',\n dataValue('form.Household_Information.Improved_Cooking_Method')\n ),\n field('Clothe__c', dataValue('form.Household_Information.Clothesline')),\n field(\n 'WASH_Trained__c',\n dataValue('form.Household_Information.WASH_Trained')\n ),\n field(\n 'Has_muac_tape__c',\n dataValue('form.Household_Information.family_muac_tape_available')\n ),\n field('Uses_ITNs__c', dataValue('form.Household_Information.ITNs')),\n field('Deaths_in_the_last_6_months__c', state => {\n var deaths = dataValue('form.household_deaths.deaths_in_past_6_months')(\n state\n );\n return deaths && deaths > 0 ? 'Yes' : 'No';\n }),\n //field(\n // 'Total_household_people__c',\n // dataValue('form.Total_Number_of_Members')\n // ),\n field('Supervisor_Visit__c', state =>\n state.data.form.supervisor_visit\n ? state.supervisorMap[state.data.form.supervisor_visit]\n : null\n ),\n field('Health_insurance__c', dataValue('form.health_insurace_cover')),\n field(\n 'Health_insurance_active_status__c',\n dataValue('form.healthinsurance_active')\n ),\n field('Health_insurance_type__c', state => {\n var status = dataValue('form.health_insurance')(state);\n var value =\n status && status !== ''\n ? status\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return state.insuranceMap[value] || value;\n })\n : undefined;\n return value ? value.join(';') : undefined;\n }),\n field(\n 'Other_Health_Insurance__c',\n dataValue('form.if_other_please_specify')\n ),\n //field('Last_Modified_Date_CommCare__c', dataValue('server_modified_on')),\n field('Case_Closed_Date__c', state => {\n var closed = dataValue('form.case.update.closed')(state);\n var date = dataValue('server_modified_on')(state);\n return closed && closed == true ? date : undefined;\n })\n )\n);\n", + "adaptor": "@openfn/language-salesforce@latest", + "project_credential_id": null + } + }, + "edges": { + "webhook->Upsert-Household-Visit": { + "enabled": false, + "id": "e234476b-f7fe-4bb9-9129-89d98b854a35", + "target_job_id": "eaca8d7a-febb-4ac4-8590-47a02b104d60", + "source_trigger_id": "6817ef95-7bc4-4665-8c40-5c90d0b3a6f2", + "condition_type": "js_expression", + "condition_label": "Upsert Household Visit App Release Q2-2022", + "condition_expression": "state.data.form[\"@name\"] == \"Update Household Revised\" && state.data.form[\"app_release\"] == \"Q2-2022\" && state.data.properties[\"test_user\"] != \"Yes\"" + } + } + }, + "x-[archive]-Workflow-Update-Person-in-CommCare": { + "id": "942cd1d0-96fc-46ab-abc8-0ba9d21ac906", + "name": "x [archive] Workflow Update Person in CommCare", + "inserted_at": "2024-09-10T15:45:42.185502Z", + "lock_version": 3, + "triggers": { + "webhook": { + "enabled": false, + "id": "8081b747-41df-4907-9e1a-eff7df9f93b1", + "type": "webhook" + } + }, + "jobs": { + "Update-Person-in-CommCare": { + "id": "3dd7a47b-29e5-4575-90f5-098557185224", + "name": "Update Person in CommCare", + "body": "submit(\n fields(\n field('@', state => {\n return {\n 'xmlns:jrm': 'http://dev.commcarehq.org/jr/xforms',\n xmlns:\n 'http://openrosa.org/formdesigner/a34af027a7fa943998c39f64bc84a337a668114a',\n uiVersion: '1',\n version: '81',\n name: 'Update Person',\n };\n }),\n field('Source', 0),\n field('Status', state => {\n return {\n Client_Status: dataValue('new[0].Client_Status__c')(state),\n Date_of_Transfer_Out: dataValue('new[0].Date_of_Transfer_Out__c')(\n state\n ),\n Date_Last_Seen: dataValue('new[0].Date_Last_Seen__c')(state),\n Date_of_Death: dataValue('new[0].Date_of_Death__c')(state),\n Cause_of_Death: dataValue('new[0].Cause_of_Death__c')(state),\n };\n }),\n field('Basic_Information', state => {\n return {\n Basic_Information: {\n Phone_Number: dataValue('new[0].Telephone__c')(state),\n Final_Program: () => {\n var program = '';\n if (\n dataValue('new[0].Active_In_Thrive_Thru_5__c')(state) == 'Yes' ||\n dataValue('new[0].Active_TT5_Mother__c')(state) == 'Yes'\n ) {\n if (dataValue('new[0].Active_In_HAWI__c')(state) == 'Yes') {\n program = 'Both';\n } else {\n program = 'Thrive_Through_5';\n }\n } else {\n if (dataValue('new[0].Active_In_HAWI__c')(state) == 'Yes') {\n program = 'HAWI';\n }\n }\n return program;\n },\n },\n };\n }),\n field('TT5', state => {\n return {\n Child_Information: {\n ANCs: {\n ANC_1: dataValue('new[0].ANC_1__c')(state),\n ANC_2: dataValue('new[0].ANC_2__c')(state),\n ANC_3: dataValue('new[0].ANC_3__c')(state),\n ANC_4: dataValue('new[0].ANC_4__c')(state),\n ANC_5: dataValue('new[0].ANC_5__c')(state),\n },\n Delivery_Information: {\n Person_Name: dataValue('new[0].Name')(state),\n DOB: dataValue('new[0].Date_of_Birth__c')(state),\n Delivery_Type: () => {\n var val = '';\n if (dataValue('new[0].Place_of_Delivery__c')(state) == 'Home') {\n val = 'Unskilled';\n } else if (\n dataValue('new[0].Place_of_Delivery__c')(state) == 'Facility'\n ) {\n val = 'Skilled';\n }\n return val;\n },\n Delivery_Facility: dataValue('new[0].Delivery_Facility__c')(state),\n },\n Immunizations: {\n BCG: dataValue('new[0].BCG__c')(state),\n OPV_0: dataValue('new[0].OPV_0__c')(state),\n OPV_PCV_Penta_1: dataValue('new[0].OPV_1__c')(state),\n OPV_PCV_Penta_2: dataValue('new[0].OPV_2__c')(state),\n OPV_PCV_Penta_3: dataValue('new[0].OPV_3__c')(state),\n Measles_6: dataValue('new[0].Measles_6__c')(state),\n Measles_9: dataValue('new[0].Measles_9__c')(state),\n Measles_18: dataValue('new[0].Measles_18__c')(state),\n Fully_Immunized: dataValue(\n 'new[0].Fully_Immunized_at_12_Months__c'\n )(state),\n },\n /*\"CCMM\":{\n \"Home_Test_Date\":dataValue(\"new[0].Measles_18__c\")(state),\n \"Home_Test_Date\":dataValue(\"new[0].Measles_18__c\")(state),\n \"Home_Test_Date\":dataValue(\"new[0].Measles_18__c\")(state),\n \"Home_Test_Date\":dataValue(\"new[0].Measles_18__c\")(state),\n \"Home_Test_Date\":dataValue(\"new[0].Measles_18__c\")(state),\n }*/\n },\n Mother_Information: {\n Pregnant: () => {\n if (dataValue('new[0].Pregnant__c')(state) === true) {\n return 'Yes';\n }\n },\n },\n };\n }),\n field('HAWI', state => {\n return {\n Unique_Patient_Code: dataValue('new[0].Unique_Patient_Code__c')(state),\n Support_Group: dataValue('new[0].Active_in_Support_Group__c')(state),\n Preferred_Care_F: {\n Preferred_Care_Facility: dataValue(\n 'new[0].Preferred_Care_Facility__c'\n )(state),\n },\n };\n }),\n\n field('n0:case', state => {\n return {\n '@': {\n case_id: dataValue('new[0].CommCare_ID__c')(state),\n date_modified: new Date().toISOString(),\n user_id: 'e298884bfb6ee2d2b38591a6e8ae0228',\n 'xmlns:n0': 'http://commcarehq.org/case/transaction/v2',\n },\n 'n0:create': {\n 'n0:case_name': () => {\n var name1 = dataValue('new[0].Name')(state);\n var name2 = name1.replace(/\\w\\S*/g, function (txt) {\n return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();\n });\n return name2;\n },\n 'n0:case_type': 'Person',\n 'n0:parent_id': dataValue('new[0].CommCare_HH_Code__c')(state),\n },\n 'n0:update': {\n 'n0:ANC_1': dataValue('new[0].ANC_1__c')(state),\n\n 'n0:ANC_2': dataValue('new[0].ANC_2__c')(state),\n 'n0:ANC_3': dataValue('new[0].ANC_3__c')(state),\n 'n0:ANC_4': dataValue('new[0].ANC_4__c')(state),\n 'n0:ANC_5': dataValue('new[0].ANC_5__c')(state),\n 'n0:BCG': dataValue('new[0].BCG__c')(state),\n 'n0:Fully_Immunized': dataValue(\n 'new[0].Fully_Immunized_at_12_Months__c'\n )(state),\n 'n0:Delivery_Type': () => {\n var val = '';\n if (dataValue('new[0].Place_of_Delivery__c')(state) == 'Home') {\n val = 'Unskilled';\n } else if (\n dataValue('new[0].Place_of_Delivery__c')(state) == 'Facility'\n ) {\n val = 'Skilled';\n }\n return val;\n },\n 'n0:Delivery_Facility': dataValue('new[0].Delivery_Facility__c')(\n state\n ),\n 'n0:Family_Planning_Method': dataValue(\n 'new[0].Family_Planning_Method__c'\n )(state),\n 'n0:Child_Status': dataValue('new[0].Child_Status__c')(state),\n 'n0:Active_in_OSG_Mentoring': dataValue('new[0].Active_in_OSG__c')(\n state\n ),\n 'n0:OSG_Mentoring_Group': dataValue('new[0].OSG_Group__c')(state),\n 'n0:OPV_0': dataValue('new[0].OPV_0__c')(state),\n 'n0:OPV_PCV_Penta_1': dataValue('new[0].OPV_1__c')(state),\n 'n0:OPV_PCV_Penta_2': dataValue('new[0].OPV_2__c')(state),\n 'n0:OPV_PCV_Penta_3': dataValue('new[0].OPV_3__c')(state),\n 'n0:Current_Height': dataValue('new[0].Current_Height__c')(state),\n 'n0:Current_Weight': dataValue('new[0].Current_Weight__c')(state),\n 'n0:Current_MUAC': dataValue('new[0].Current_MUAC__c')(state),\n 'n0:Measles_6': dataValue('new[0].Measles_6__c')(state),\n 'n0:Measles_9': dataValue('new[0].Measles_9__c')(state),\n 'n0:LMP': dataValue('new[0].LMP__c')(state),\n 'n0:EDD': dataValue('new[0].EDD__c')(state),\n 'n0:Measles_18': dataValue('new[0].Measles_18__c')(state),\n 'n0:Pregnant': () => {\n if (dataValue('new[0].Pregnant__c')(state) === true) {\n return 'Yes';\n }\n },\n 'n0:ART': dataValue('new[0].Currently_on_ART_s__c')(state),\n 'n0:ARVs': dataValue('new[0].ART_Regimen__c')(state),\n 'n0:Active_in_Support_Group': dataValue(\n 'new[0].Active_in_Support_Group__c'\n )(state),\n 'n0:Client_Program': () => {\n var program = '';\n if (\n dataValue('new[0].Active_in_Thrive_Thru_5__c')(state) == 'Yes' ||\n dataValue('new[0].Active_TT5_Mother__c')(state) == 'Yes'\n ) {\n if (dataValue('new[0].Active_in_HAWI__c')(state) == 'Yes') {\n program = 'Both';\n } else {\n program = 'Thrive_Through_5';\n }\n } else {\n if (dataValue('new[0].Active_in_HAWI__c')(state) == 'Yes') {\n program = 'HAWI';\n }\n }\n return program;\n },\n 'n0:Currently_on_family_planning': dataValue(\n 'new[0].Family_Planning__c'\n )(state),\n 'n0:DOB': dataValue('new[0].Date_of_Birth__c')(state),\n 'n0:Education_Level': () => {\n if (dataValue('new[0].Education_Level__c')(state) !== undefined) {\n return dataValue('new[0].Education_Level__c')(state)\n .toString()\n .replace(/ /g, '_');\n }\n },\n 'n0:Ever_on_Family_Planning': dataValue(\n 'new[0].Ever_on_Family_Planning__c'\n )(state),\n 'n0:Gender': dataValue('new[0].Gender__c')(state),\n 'n0:Gravida': dataValue('new[0].Gravida__c')(state),\n 'n0:Active_in_TT5': dataValue('new[0].Active_in_Thrive_Thru_5__c')(\n state\n ),\n 'n0:Active_in_HAWI': dataValue('new[0].Active_in_HAWI__c')(state),\n 'n0:Marital_Status': dataValue('new[0].Marital_Status__c')(state),\n 'n0:Exclusive_Breastfeeding': dataValue(\n 'new[0].Exclusive_Breastfeeding__c'\n )(state),\n 'n0:Next_of_Kin': dataValue('new[0].Next_of_Kin__c')(state),\n 'n0:Next_of_Kin_Phone': dataValue('new[0].Next_of_Kin_Phone__c')(\n state\n ),\n 'n0:Parity': dataValue('new[0].Parity__c')(state),\n\n 'n0:Phone_Number': dataValue('new[0].Telephone__c')(state),\n 'n0:Preferred_Care_Facility': dataValue(\n 'new[0].Preferred_Care_Facility__c'\n )(state),\n 'n0:Record_Type': () => {\n return dataValue('new[0].Record_Type_Name__c')(state)\n .toString()\n .replace(/ /g, '_');\n },\n 'n0:Unique_Patient_Code': dataValue('new[0].Unique_Patient_Code__c')(\n state\n ),\n },\n 'n0:index': {\n 'n0:parent': {\n '@': {\n case_type: 'Household',\n },\n '#': dataValue('new[0].CommCare_HH_Code__c')(state),\n },\n },\n };\n }),\n\n field('n2:meta', state => {\n return {\n '@': { 'xmlns:n2': 'http://openrosa.org/jr/xforms' },\n 'n2:deviceID': 'Formplayer',\n 'n2:timeStart': new Date().toISOString(),\n 'n2:timeEnd': new Date().toISOString(),\n 'n2:userID': 'e298884bfb6ee2d2b38591a6e8ae0228',\n };\n })\n )\n);\n", + "adaptor": "@openfn/language-commcare@latest", + "project_credential_id": null + } + }, + "edges": { + "webhook->Update-Person-in-CommCare": { + "enabled": false, + "id": "85ef411e-361b-44ed-864a-e9e28bae4440", + "target_job_id": "3dd7a47b-29e5-4575-90f5-098557185224", + "source_trigger_id": "8081b747-41df-4907-9e1a-eff7df9f93b1", + "condition_type": "js_expression", + "condition_label": "SF Update Person", + "condition_expression": "state.data.label == \"Update Person\"" + } + } + }, + "x-[archive]-Workflow-test-revised": { + "id": "26105feb-3978-44be-8a2d-08ef5a46370c", + "name": "x [archive] Workflow test revised", + "inserted_at": "2024-09-10T15:45:42.190498Z", + "lock_version": 3, + "triggers": { + "webhook": { + "enabled": false, + "id": "31a78d41-00d5-4256-9892-27260ab5a6eb", + "type": "webhook" + } + }, + "jobs": { + "test-revised": { + "id": "d8e2ccf9-6e4a-4c08-8cc3-2eca93065e2e", + "name": "test revised", + "body": "// REVISED Form - To replace old Update HH\nalterState(state => {\n const data = state.data.data;\n \n const deaths = state.data.data.form.household_deaths ? state.data.data.form.household_deaths.deaths : '';\n if (deaths !== '' &&!Array.isArray(deaths)) {\n state.data.data.form.household_deaths.deaths = [deaths];\n }\n\n const supervisorMap = {\n community_health_nurse: 'Community Health Nurse',\n chw_supervisor: 'CHW Supervisor',\n chewschas: 'CHEWs/CHAs',\n other: 'Other',\n none: 'None',\n };\n\n return { ...state, supervisorMap };\n});\nupsert(\n 'Household__c',\n 'CommCare_Code__c',\n fields(\n field('CommCare_Code__c', dataValue('form.case.@case_id')),\n field('MOH_household_code__c', state => {\n var moh = dataValue('form.Household_Information.moh_code')(state);\n var mohLinked = dataValue('form.MOH_household_code_linked')(state);\n return moh ? moh : mohLinked;\n }),\n field('Active_Household__c', state => {\n var status = dataValue('form.Household_Status')(state);\n if(status==='No'){\n status = false;\n } else if(status==='Yes'){\n status = true;\n }\n return status;\n //return status=='No'? false : true;\n }),\n /*field('Reactivated__c', state => {\n var status = dataValue('form.Household_Status')(state);\n return status=='No'? false : true;\n }),*/\n field('Inactive_Reason__c', state => {\n var reason = dataValue('form.Reason_for_Inactive')(state);\n return reason !== undefined ? reason : null;\n }),\n field('Source__c', 1),\n field('Household_village__c', dataValue('form.village')), \n field(\n 'Access_to_safe_water__c',\n dataValue('form.Household_Information.Safe_Water')\n ),\n field(\n 'Treats_Drinking_Water__c',\n dataValue('form.Household_Information.Treats_Drinking_Water')\n ),\n field(\n 'Tippy_Tap__c',\n dataValue('form.Household_Information.Active_Handwashing_Station')\n ),\n field(\n 'Pit_Latrine__c',\n dataValue('form.Household_Information.Functional_Latrine')\n ),\n field(\n 'Rubbish_Pit__c',\n dataValue('form.Household_Information.Rubbish_Pit')\n ),\n field(\n 'Drying_Rack__c',\n dataValue('form.Household_Information.Drying_Rack')\n ),\n field(\n 'Kitchen_Garden__c',\n dataValue('form.Household_Information.Kitchen_Garden')\n ),\n field(\n 'Cookstove__c',\n dataValue('form.Household_Information.Improved_Cooking_Method')\n ),\n field('Clothe__c', dataValue('form.Household_Information.Clothesline')),\n field(\n 'WASH_Trained__c',\n dataValue('form.Household_Information.WASH_Trained')\n ),\n field('Uses_ITNs__c', dataValue('form.Household_Information.ITNs')),\n //field(\"Family_planning__c\", dataValue(\"form.Household_Information.family_planning\")), // new mapping\n //field(\"Family_planning_method__c\", dataValue(\"form.Household_Information.Family_planning_method\")), // new mapping\n field('Deaths_in_the_last_6_months__c', state => {\n var deaths = dataValue('form.household_deaths.deaths_in_past_6_months')(\n state\n );\n return deaths && deaths > 0 ? 'Yes' : 'No';\n }),\n field(\n 'Total_household_people__c',\n dataValue('form.Total_Number_of_Members')\n ),\n field('Supervisor_Visit__c', state =>\n state.data.form.supervisor_visit\n ? state.supervisorMap[state.data.form.supervisor_visit]\n : null\n )\n )\n),\n upsert(\n 'Visit__c',\n 'CommCare_Visit_ID__c',\n fields(\n field('CommCare_Visit_ID__c', dataValue('id')),\n relationship(\n 'Household__r',\n 'CommCare_Code__c',\n dataValue('form.case.@case_id')\n ),\n field('Date__c', dataValue('form.metadata.timeEnd')),\n //field(\"Household_CHW__c\", \"a031x000002S9lm\"), //Hardcoded for sandbox testing\n field('Household_CHW__c', dataValue('form.chw')),\n field('Name', 'CHW Visit'),\n field('Supervisor_Visit__c', state =>\n state.data.form.supervisor_visit\n ? state.supervisorMap[state.data.form.supervisor_visit]\n : null\n )\n )\n ),\n //New logic to insert child Person records if person is marked as deceased in HH form\n each(\n merge(\n dataPath('$.form.household_deaths.deaths[*]'),\n fields(\n field('caseId', dataValue('form.case.@case_id')),\n field('catchment', dataValue('form.catchment')),\n field('Date', dataValue('form.Date'))\n )\n ),\n upsertIf(\n state.data.form.household_deaths && state.data.form.household_deaths.deaths_in_past_6_months > 0, //only insert deceased Person if deaths\n 'Person__c',\n 'CommCare_ID__c',\n fields(\n field('CommCare_ID__c', state => {\n var age = dataValue('age_dead')(state);\n return `${state.data.caseId}${age}`;\n }),\n field('CommCare_HH_Code__c', dataValue('caseId')),\n relationship('RecordType', 'Name', state => {\n var age = dataValue('age_dead')(state);\n var gender = dataValue('gender_dead')(state);\n var rt = '';\n if (age < 5) {\n rt = 'Child';\n } else if (age < 18) {\n rt = 'Youth';\n } else if (gender === 'female') {\n rt = 'Female Adult';\n } else {\n rt = 'Male Adult';\n }\n return rt;\n }),\n field('Name', 'Deceased Person'),\n field('Source__c', true),\n relationship('Catchment__r', 'Name', dataValue('catchment')),\n field('Client_Status__c', 'Deceased'),\n field('Dead_age__c', dataValue('age_dead')),\n field('Cause_of_Death__c', state => {\n var cause = dataValue('cause_of_death_dead')(state);\n return cause !== undefined\n ? cause.toString().replace(/_/g, ' ')\n : null;\n }),\n field('Verbal_autopsy__c', dataValue('verbal_autopsy')),\n field('Client_Status__c', 'Deceased'),\n field('Active_in_Thrive_Thru_5__c', 'No'),\n field('Active_in_HAWI__c', 'No'),\n field('Active_TT5_Mother__c', 'No'),\n field('TT5_Mother_Registrant__c', 'No'),\n field('Date_of_Death__c', dataValue('Date')),\n field('Inactive_Date__c', dataValue('Date'))\n )\n )\n );\n", + "adaptor": "@openfn/language-salesforce@v1.3.2", + "project_credential_id": null + } + }, + "edges": { + "webhook->test-revised": { + "enabled": false, + "id": "5cc36959-e784-47ca-a373-8bd308b33aa4", + "target_job_id": "d8e2ccf9-6e4a-4c08-8cc3-2eca93065e2e", + "source_trigger_id": "31a78d41-00d5-4256-9892-27260ab5a6eb", + "condition_type": "js_expression", + "condition_label": "test form csv", + "condition_expression": "state.data[\"form.@name\"] == \"Update Household Revised\"" + } + } + }, + "x-[archive]-Workflow-Test-Job": { + "id": "f2f93c6d-eeba-454d-9508-681069eef829", + "name": "x [archive] Workflow Test Job", + "inserted_at": "2024-09-10T15:45:42.194887Z", + "lock_version": 3, + "triggers": { + "webhook": { + "enabled": false, + "id": "6082f5eb-eb11-44b4-97a7-f00b17a42af5", + "type": "webhook" + } + }, + "jobs": { + "Test-Job": { + "id": "69e34d0b-d800-4ea4-ab04-1b7db08e7be5", + "name": "Test Job", + "body": "// Your job goes here.\n", + "adaptor": "@openfn/language-salesforce@v1.3.2", + "project_credential_id": null + } + }, + "edges": { + "webhook->Test-Job": { + "enabled": false, + "id": "205e70e9-4580-4111-8946-d69ffccfc61d", + "target_job_id": "69e34d0b-d800-4ea4-ab04-1b7db08e7be5", + "source_trigger_id": "6082f5eb-eb11-44b4-97a7-f00b17a42af5", + "condition_type": "js_expression", + "condition_label": "SF Update HH", + "condition_expression": "state.data.label == \"Update Household\"" + } + } + }, + "x-[archive]-Workflow-TEST-Create-HH-in-Sandbox": { + "id": "2598b000-c031-4795-abfd-8838a7045e63", + "name": "x [archive] Workflow TEST Create HH in Sandbox", + "inserted_at": "2024-09-10T15:45:42.199420Z", + "lock_version": 3, + "triggers": { + "webhook": { + "enabled": false, + "id": "3e5ceff0-a20e-408b-ab86-fa8a89875898", + "type": "webhook" + } + }, + "jobs": { + "TEST-Create-HH-in-Sandbox": { + "id": "26ed3add-1319-432c-ab53-e61f03559ab7", + "name": "TEST Create HH in Sandbox", + "body": "//Alters CommCare arrays so that they are formatted as arrays instead of just single values.\nalterState(state => {\n const person = state.data.form.Person;\n if (!Array.isArray(person)) {\n state.data.form.Person = [person];\n }\n return state;\n});\n\nupsert(\n 'Household__c',\n 'CommCare_Code__c',\n fields(\n field('Name', '00000'),\n //state =>{\n // return dataValue('$.form.case.@case_id')(state).substring(0,5); //<- Will, this change we made was causing errors? what does the '0000' do?\n // }),\n field('Catchment__c', state => {\n if (dataValue('form.catchment')(state) == 'East Kamagambo') {\n return 'a002400000pAcQt';\n } else {\n return 'a002400000pAcOe';\n }\n }),\n field('CommCare_Code__c', dataValue('$.form.case.@case_id')),\n field('Household_CHW__c', dataValue('$.form.CHW_ID')),\n field('Area__c', dataValue('$.form.area')),\n field('Household_Head_No_Program__c', dataValue('form.No_Program_Head')),\n field(\n 'Treats_Drinking_Water__c',\n dataValue('$.form.Household_Information.Treats_Drinking_Water')\n ),\n field(\n 'WASH_Trained__c',\n dataValue('$.form.Household_Information.WASH_Trained')\n ),\n field(\n 'Rubbish_Pit__c',\n dataValue('$.form.Household_Information.Rubbish_Pit')\n ),\n field(\n 'Kitchen_Garden__c',\n dataValue('$.form.Household_Information.Kitchen_Garden')\n ),\n field(\n 'Cookstove__c',\n dataValue('$.form.Household_Information.Improved_Cooking_Method')\n ),\n field('Uses_ITNs__c', dataValue('$.form.Household_Information.ITNs')),\n field(\n 'Pit_Latrine__c',\n dataValue('$.form.Household_Information.Functional_Latrine')\n ),\n field('Clothe__c', dataValue('$.form.Household_Information.Clothesline')),\n field(\n 'Drying_Rack__c',\n dataValue('$.form.Household_Information.Drying_Rack')\n ),\n field(\n 'Tippy_Tap__c',\n dataValue('$.form.Household_Information.Active_Handwashing_Station')\n ),\n field(\n 'Number_of_Over_5_Females__c',\n dataValue('$.form.Household_Information.Number_of_over_5_Females')\n ),\n field(\n 'Number_of_Under_5_Males__c',\n dataValue('$.form.Household_Information.Number_of_Under_5_Males')\n ),\n field(\n 'Number_of_Under_5_Females__c',\n dataValue('$.form.Household_Information.Number_of_Under_5_Females')\n ),\n field(\n 'Number_of_Over_5_Males__c',\n dataValue('$.form.Household_Information.Number_of_Over_5_Males')\n ),\n field('Source__c', true)\n )\n);\n\nalterState(state => {\n if (dataValue('$.form.Person[0].Source')(state) == 1) {\n return beta.each(\n dataPath('$.form.Person[*]'),\n upsert(\n 'Person__c',\n 'CommCare_ID__c',\n fields(\n field('Name', state => {\n var name1 = dataValue('Basic_Information.Person_Name')(state);\n var name2 = name1.replace(/\\w\\S*/g, function (txt) {\n return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();\n });\n return name2;\n }),\n relationship('RecordType', 'Name', state => {\n return dataValue('Basic_Information.Record_Type')(state)\n .toString()\n .replace(/_/g, ' ');\n }),\n field('Catchment__c', state => {\n if (dataValue('catchment')(state) == 'East Kamagambo') {\n return 'a002400000pAcQt';\n } else {\n return 'a002400000pAcOe';\n }\n }),\n field('HAWI_Registrant__c', state => {\n if (dataValue('Basic_Information.HAWI_Status')(state) == 'Yes') {\n return 'Yes';\n }\n }),\n field('Active_in_HAWI__c', state => {\n if (dataValue('Basic_Information.HAWI_Status')(state) == 'Yes') {\n return 'Yes';\n }\n }),\n field('Active_in_Thrive_Thru_5__c', state => {\n if (\n dataValue('Basic_Information.Record_Type')(state)\n .toString()\n .replace(/_/g, ' ') == 'Child' &&\n dataValue('Basic_Information.TT5_Status')(state) == 'Yes'\n ) {\n return 'Yes';\n }\n }),\n field('Thrive_Thru_5_Registrant__c', state => {\n if (\n dataValue('Basic_Information.Record_Type')(state)\n .toString()\n .replace(/_/g, ' ') == 'Child' &&\n dataValue('Basic_Information.TT5_Status')(state) == 'Yes'\n ) {\n return 'Yes';\n }\n }),\n field('Active_TT5_Mother__c', state => {\n if (\n dataValue('Basic_Information.Record_Type')(state)\n .toString()\n .replace(/_/g, ' ') == 'Female Adult' &&\n dataValue('Basic_Information.TT5_Status')(state) == 'Yes'\n ) {\n return 'Yes';\n }\n }),\n field('TT5_Mother_Registrant__c', state => {\n if (\n dataValue('Basic_Information.Record_Type')(state)\n .toString()\n .replace(/_/g, ' ') == 'Female Adult' &&\n dataValue('Basic_Information.TT5_Status')(state) == 'Yes'\n ) {\n return 'Yes';\n }\n }),\n field('Enrollment_Date__c', state => {\n if (dataValue('Basic_Information.TT5_Status')(state) == 'Yes') {\n return dataValue('case.@date_modified')(state);\n }\n }),\n field('HAWI_Enrollment_Date__c', state => {\n if (dataValue('Basic_Information.HAWI_Status')(state) == 'Yes') {\n return dataValue('case.@date_modified')(state);\n }\n }),\n field('LMP__c', dataValue('TT5.Child_Information.ANCs.LMP')),\n field('Source__c', true),\n field('CommCare_ID__c', dataValue('case.@case_id')),\n field('Date_of_Birth__c', dataValue('Basic_Information.DOB')),\n field(\n 'Exclusive_Breastfeeding__c',\n dataValue(\n 'TT5.Child_Information.Exclusive_Breastfeeding.Exclusive_Breastfeeding'\n )\n ),\n field('Gender__c', dataValue('Basic_Information.Final_Gender')),\n field(\n 'Marital_Status__c',\n dataValue('Basic_Information.Marital_Status')\n ),\n field(\n 'Telephone__c',\n dataValue('Basic_Information.Contact_Info.contact_phone_number')\n ),\n field(\n 'Next_of_Kin__c',\n dataValue('Basic_Information.Contact_Info.Next_of_Kin')\n ),\n field(\n 'Next_of_Kin_Phone__c',\n dataValue('Basic_Information.Contact_Info.next_of_kin_phone')\n ),\n field('Client_Status__c', 'Active'),\n field(\n 'Ever_on_Family_Planning__c',\n dataValue('Basic_Information.Ever_on_Family_Planning')\n ),\n field(\n 'Family_Planning__c',\n dataValue('Basic_Information.Currently_on_family_planning')\n ),\n field(\n 'Family_Planning_Method__c',\n dataValue('Basic_Information.Family_Planning_Method')\n ),\n field('ANC_1__c', dataValue('TT5.Child_Information.ANCs.ANC_1')),\n field('ANC_2__c', dataValue('TT5.Child_Information.ANCs.ANC_2')),\n field('ANC_3__c', dataValue('TT5.Child_Information.ANCs.ANC_3')),\n field('ANC_4__c', dataValue('TT5.Child_Information.ANCs.ANC_4')),\n field('ANC_5__c', dataValue('TT5.Child_Information.ANCs.ANC_5')),\n field('BCG__c', dataValue('TT5.Child_Information.Immunizations.BCG')),\n field(\n 'OPV_0__c',\n dataValue('TT5.Child_Information.Immunizations.OPV_0')\n ),\n field(\n 'OPV_1__c',\n dataValue('TT5.Child_Information.Immunizations.OPV_PCV_Penta_1')\n ),\n field(\n 'OPV_2__c',\n dataValue('TT5.Child_Information.Immunizations.OPV_PCV_Penta_2')\n ),\n field(\n 'OPV_3__c',\n dataValue('TT5.Child_Information.Immunizations.OPV_PCV_Penta_3')\n ),\n field(\n 'Measles_6__c',\n dataValue('TT5.Child_Information.Immunizations.Measles_6')\n ),\n field(\n 'Measles_9__c',\n dataValue('TT5.Child_Information.Immunizations.Measles_9')\n ),\n field(\n 'Measles_18__c',\n dataValue('TT5.Child_Information.Immunizations.Measles_18')\n ),\n field('Pregnant__c', state => {\n if (dataValue('TT5.Mother_Information.Pregnant')(state) == 'Yes')\n return 1;\n }),\n field('Education_Level__c', state => {\n if (\n dataValue('Basic_Information.Record_Type')(state) !== 'Child' &&\n dataValue('Basic_Information.Record_Type')(state) !== 'Youth'\n ) {\n return dataValue('Basic_Information.Education_Level')(state)\n .toString()\n .replace(/_/g, ' ');\n }\n }),\n field(\n 'Gravida__c',\n dataValue('TT5.Mother_Information.Pregnancy_Information.Gravida')\n ),\n field(\n 'Parity__c',\n dataValue('TT5.Mother_Information.Pregnancy_Information.Parity')\n ),\n field(\n 'Unique_Patient_Code__c',\n dataValue('HAWI.Unique_Patient_Code')\n ),\n field(\n 'Active_in_Support_Group__c',\n dataValue('HAWI.Active_in_Support_Group')\n ),\n\n field('Currently_on_ART_s__c', dataValue('HAWI.ART')),\n field('ART_Regimen__c', state => {\n var art = '';\n var str = dataValue('HAWI.ARVs')(state);\n if (str !== undefined) {\n art = str.replace(/ /g, '; ');\n }\n return art;\n }),\n field('Preferred_Care_Facility__c', state => {\n var val = '';\n if (\n dataValue('HAWI.Preferred_Care_Facility')(state) !== undefined\n ) {\n val = dataValue('HAWI.Preferred_Care_Facility')(state)\n .toString()\n .replace(/_/g, ' ');\n }\n return val;\n }),\n field('CommCare_HH_Code__c', dataValue('case.index.parent.#text')),\n field('Child_Status__c', dataValue('Basic_Information.Child_Status')),\n field('Place_of_Delivery__c', state => {\n var val = '';\n var placeholder = '';\n if (\n dataValue(\n 'TT5.Child_Information.Delivery_Information.Skilled_Unskilled'\n )(state) !== undefined\n ) {\n placeholder = dataValue(\n 'TT5.Child_Information.Delivery_Information.Skilled_Unskilled'\n )(state);\n if (placeholder == 'Skilled') {\n val = 'Facility';\n } else if (placeholder == 'Unskilled') {\n val = 'Home';\n }\n }\n return val;\n }),\n field('Delivery_Facility__c', state => {\n var val = '';\n var placeholder = '';\n if (\n dataValue(\n 'TT5.Child_Information.Delivery_Information.Birth_Facility'\n )(state) !== undefined\n ) {\n placeholder = dataValue(\n 'TT5.Child_Information.Delivery_Information.Birth_Facility'\n )(state);\n val = placeholder.toString().replace(/_/g, ' ');\n }\n return val;\n })\n )\n )\n )(state);\n }\n\n return state;\n});\n", + "adaptor": "@openfn/language-salesforce@v1.3.2", + "project_credential_id": null + } + }, + "edges": { + "webhook->TEST-Create-HH-in-Sandbox": { + "enabled": false, + "id": "e7c99dac-4518-4e12-af42-be8ec2a5fe01", + "target_job_id": "26ed3add-1319-432c-ab53-e61f03559ab7", + "source_trigger_id": "3e5ceff0-a20e-408b-ab86-fa8a89875898", + "condition_type": "js_expression", + "condition_label": "Commcare Create HH", + "condition_expression": "state.data.form.Source == \"1\" && state.data.form[\"@name\"] == \"Enroll New Household\"" + } + } + }, + "x-[archive]-Update-Person-in-CommCare-V2": { + "id": "b85284d1-0364-447c-8770-9b30ad008af6", + "name": "x [archive] Update Person in CommCare V2", + "inserted_at": "2024-09-10T15:45:42.206537Z", + "lock_version": 4, + "triggers": { + "webhook": { + "enabled": false, + "id": "b4064ade-7097-41fd-a4cb-99035ebf5cd6", + "type": "webhook" + } + }, + "jobs": { + "Update-Person-in-CommCare-V2": { + "id": "62eb5f9b-e8da-4b1c-8098-3f8d91dce14f", + "name": "Update Person in CommCare V2", + "body": "submit(\n fields(\n field('@', state => {\n return {\n 'xmlns:jrm': 'http://dev.commcarehq.org/jr/xforms',\n xmlns: () => {\n return dataValue('new[0].Catchment__c')(state) == 'a001p000017gpfZAAQ'\n ? 'http://openrosa.org/formdesigner/457C806C-B47D-44F0-BE4B-7E88F7162D1D'\n : 'http://openrosa.org/formdesigner/a34af027a7fa943998c39f64bc84a337a668114a';\n },\n uiVersion: '1',\n version: '81',\n name: () => {\n return dataValue('new[0].Catchment__c')(state) == 'a001p000017gpfZAAQ'\n ? 'Update Person MOH'\n : 'Update Person';\n },\n };\n }),\n field('Source', 0),\n field('Status', state => {\n return {\n Client_Status: dataValue('new[0].Client_Status__c')(state),\n Date_of_Transfer_Out: dataValue('new[0].Date_of_Transfer_Out__c')(\n state\n ),\n Date_Last_Seen: dataValue('new[0].Date_Last_Seen__c')(state),\n Date_of_Death: dataValue('new[0].Date_of_Death__c')(state),\n Cause_of_Death: dataValue('new[0].Cause_of_Death__c')(state),\n };\n }),\n field('Basic_Information', state => {\n return {\n Basic_Information: {\n Phone_Number: dataValue('new[0].Telephone__c')(state),\n Final_Program: () => {\n var program = '';\n if (\n dataValue('new[0].Active_In_Thrive_Thru_5__c')(state) == 'Yes' ||\n dataValue('new[0].Active_TT5_Mother__c')(state) == 'Yes'\n ) {\n if (dataValue('new[0].Active_In_HAWI__c')(state) == 'Yes') {\n program = 'Both';\n } else {\n program = 'Thrive_Through_5';\n }\n } else {\n if (dataValue('new[0].Active_In_HAWI__c')(state) == 'Yes') {\n program = 'HAWI';\n }\n }\n return program;\n },\n },\n };\n }),\n field('TT5', state => {\n return {\n Child_Information: {\n ANCs: {\n ANC_1: dataValue('new[0].ANC_1__c')(state),\n ANC_2: dataValue('new[0].ANC_2__c')(state),\n ANC_3: dataValue('new[0].ANC_3__c')(state),\n ANC_4: dataValue('new[0].ANC_4__c')(state),\n ANC_5: dataValue('new[0].ANC_5__c')(state),\n },\n Delivery_Information: {\n Person_Name: dataValue('new[0].Name')(state),\n DOB: dataValue('new[0].Date_of_Birth__c')(state),\n Delivery_Type: () => {\n var val = '';\n if (dataValue('new[0].Place_of_Delivery__c')(state) == 'Home') {\n val = 'Unskilled';\n } else if (\n dataValue('new[0].Place_of_Delivery__c')(state) == 'Facility'\n ) {\n val = 'Skilled';\n }\n return val;\n },\n Delivery_Facility: dataValue('new[0].Delivery_Facility__c')(state),\n },\n Immunizations: {\n BCG: dataValue('new[0].BCG__c')(state),\n OPV_0: dataValue('new[0].OPV_0__c')(state),\n OPV_PCV_Penta_1: dataValue('new[0].OPV_1__c')(state),\n OPV_PCV_Penta_2: dataValue('new[0].OPV_2__c')(state),\n OPV_PCV_Penta_3: dataValue('new[0].OPV_3__c')(state),\n Measles_6: dataValue('new[0].Measles_6__c')(state),\n Measles_9: dataValue('new[0].Measles_9__c')(state),\n Measles_18: dataValue('new[0].Measles_18__c')(state),\n Fully_Immunized: dataValue(\n 'new[0].Fully_Immunized_at_12_Months__c'\n )(state),\n },\n /*\"CCMM\":{\n \"Home_Test_Date\":dataValue(\"new[0].Measles_18__c\")(state),\n \"Home_Test_Date\":dataValue(\"new[0].Measles_18__c\")(state),\n \"Home_Test_Date\":dataValue(\"new[0].Measles_18__c\")(state),\n \"Home_Test_Date\":dataValue(\"new[0].Measles_18__c\")(state),\n \"Home_Test_Date\":dataValue(\"new[0].Measles_18__c\")(state),\n }*/\n },\n Mother_Information: {\n Pregnant: () => {\n if (dataValue('new[0].Pregnant__c')(state) === true) {\n return 'Yes';\n }\n },\n },\n };\n }),\n field('HAWI', state => {\n return {\n Unique_Patient_Code: dataValue('new[0].Unique_Patient_Code__c')(state),\n Support_Group: dataValue('new[0].Active_in_Support_Group__c')(state),\n Preferred_Care_F: {\n Preferred_Care_Facility: dataValue(\n 'new[0].Preferred_Care_Facility__c'\n )(state),\n },\n };\n }),\n\n field('n0:case', state => {\n return {\n '@': {\n case_id: dataValue('new[0].CommCare_ID__c')(state),\n date_modified: new Date().toISOString(),\n user_id: 'e298884bfb6ee2d2b38591a6e8ae0228',\n 'xmlns:n0': 'http://commcarehq.org/case/transaction/v2',\n },\n 'n0:create': {\n 'n0:case_name': () => {\n var name1 = dataValue('new[0].Name')(state);\n var name2 = name1.replace(/\\w\\S*/g, function (txt) {\n return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();\n });\n return name2;\n },\n 'n0:case_type': 'Person',\n 'n0:parent_id': dataValue('new[0].CommCare_HH_Code__c')(state),\n },\n 'n0:update': {\n 'n0:ANC_1': dataValue('new[0].ANC_1__c')(state),\n\n 'n0:ANC_2': dataValue('new[0].ANC_2__c')(state),\n 'n0:ANC_3': dataValue('new[0].ANC_3__c')(state),\n 'n0:ANC_4': dataValue('new[0].ANC_4__c')(state),\n 'n0:ANC_5': dataValue('new[0].ANC_5__c')(state),\n 'n0:BCG': dataValue('new[0].BCG__c')(state),\n 'n0:Fully_Immunized': dataValue(\n 'new[0].Fully_Immunized_at_12_Months__c'\n )(state),\n 'n0:Delivery_Type': () => {\n var val = '';\n if (dataValue('new[0].Place_of_Delivery__c')(state) == 'Home') {\n val = 'Unskilled';\n } else if (\n dataValue('new[0].Place_of_Delivery__c')(state) == 'Facility'\n ) {\n val = 'Skilled';\n }\n return val;\n },\n 'n0:Delivery_Facility': dataValue('new[0].Delivery_Facility__c')(\n state\n ),\n 'n0:Family_Planning_Method': dataValue(\n 'new[0].Family_Planning_Method__c'\n )(state),\n 'n0:Child_Status': dataValue('new[0].Child_Status__c')(state),\n 'n0:Active_in_OSG_Mentoring': dataValue('new[0].Active_in_OSG__c')(\n state\n ),\n 'n0:OSG_Mentoring_Group': dataValue('new[0].OSG_Group__c')(state),\n 'n0:OPV_0': dataValue('new[0].OPV_0__c')(state),\n 'n0:OPV_PCV_Penta_1': dataValue('new[0].OPV_1__c')(state),\n 'n0:OPV_PCV_Penta_2': dataValue('new[0].OPV_2__c')(state),\n 'n0:OPV_PCV_Penta_3': dataValue('new[0].OPV_3__c')(state),\n 'n0:Current_Height': dataValue('new[0].Current_Height__c')(state),\n 'n0:Current_Weight': dataValue('new[0].Current_Weight__c')(state),\n 'n0:Current_MUAC': dataValue('new[0].Current_MUAC__c')(state),\n 'n0:Measles_6': dataValue('new[0].Measles_6__c')(state),\n 'n0:Measles_9': dataValue('new[0].Measles_9__c')(state),\n 'n0:LMP': dataValue('new[0].LMP__c')(state),\n 'n0:EDD': dataValue('new[0].EDD__c')(state),\n 'n0:Measles_18': dataValue('new[0].Measles_18__c')(state),\n 'n0:Pregnant': () => {\n if (dataValue('new[0].Pregnant__c')(state) === true) {\n return 'Yes';\n }\n },\n 'n0:ART': dataValue('new[0].Currently_on_ART_s__c')(state),\n 'n0:ARVs': dataValue('new[0].ART_Regimen__c')(state),\n 'n0:Active_in_Support_Group': dataValue(\n 'new[0].Active_in_Support_Group__c'\n )(state),\n 'n0:Client_Program': () => {\n var program = '';\n if (\n dataValue('new[0].Active_in_Thrive_Thru_5__c')(state) == 'Yes' ||\n dataValue('new[0].Active_TT5_Mother__c')(state) == 'Yes'\n ) {\n if (dataValue('new[0].Active_in_HAWI__c')(state) == 'Yes') {\n program = 'Both';\n } else {\n program = 'Thrive_Through_5';\n }\n } else {\n if (dataValue('new[0].Active_in_HAWI__c')(state) == 'Yes') {\n program = 'HAWI';\n }\n }\n return program;\n },\n 'n0:Currently_on_family_planning': dataValue(\n 'new[0].Family_Planning__c'\n )(state),\n 'n0:DOB': dataValue('new[0].Date_of_Birth__c')(state),\n 'n0:Education_Level': () => {\n if (dataValue('new[0].Education_Level__c')(state) !== undefined) {\n return dataValue('new[0].Education_Level__c')(state)\n .toString()\n .replace(/ /g, '_');\n }\n },\n 'n0:Ever_on_Family_Planning': dataValue(\n 'new[0].Ever_on_Family_Planning__c'\n )(state),\n 'n0:Gender': dataValue('new[0].Gender__c')(state),\n 'n0:Gravida': dataValue('new[0].Gravida__c')(state),\n 'n0:Active_in_TT5': dataValue('new[0].Active_in_Thrive_Thru_5__c')(\n state\n ),\n 'n0:Active_in_HAWI': dataValue('new[0].Active_in_HAWI__c')(state),\n 'n0:Marital_Status': dataValue('new[0].Marital_Status__c')(state),\n 'n0:Exclusive_Breastfeeding': dataValue(\n 'new[0].Exclusive_Breastfeeding__c'\n )(state),\n 'n0:Next_of_Kin': dataValue('new[0].Next_of_Kin__c')(state),\n 'n0:Next_of_Kin_Phone': dataValue('new[0].Next_of_Kin_Phone__c')(\n state\n ),\n 'n0:Parity': dataValue('new[0].Parity__c')(state),\n\n 'n0:Phone_Number': dataValue('new[0].Telephone__c')(state),\n 'n0:Preferred_Care_Facility': dataValue(\n 'new[0].Preferred_Care_Facility__c'\n )(state),\n 'n0:Record_Type': () => {\n return dataValue('new[0].Record_Type_Name__c')(state)\n .toString()\n .replace(/ /g, '_');\n },\n 'n0:Unique_Patient_Code': dataValue('new[0].Unique_Patient_Code__c')(\n state\n ),\n },\n 'n0:index': {\n 'n0:parent': {\n '@': {\n case_type: 'Household',\n },\n '#': dataValue('new[0].CommCare_HH_Code__c')(state),\n },\n },\n };\n }),\n\n field('n2:meta', state => {\n return {\n '@': { 'xmlns:n2': 'http://openrosa.org/jr/xforms' },\n 'n2:deviceID': 'Formplayer',\n 'n2:timeStart': new Date().toISOString(),\n 'n2:timeEnd': new Date().toISOString(),\n 'n2:userID': 'e298884bfb6ee2d2b38591a6e8ae0228',\n };\n })\n )\n);\n", + "adaptor": "@openfn/language-commcare@latest", + "project_credential_id": null + } + }, + "edges": { + "webhook->Update-Person-in-CommCare-V2": { + "enabled": false, + "id": "613f3a4a-982b-4a92-879b-06f008b3b9ea", + "target_job_id": "62eb5f9b-e8da-4b1c-8098-3f8d91dce14f", + "source_trigger_id": "b4064ade-7097-41fd-a4cb-99035ebf5cd6", + "condition_type": "js_expression", + "condition_label": "SF Update Person", + "condition_expression": "state.data.label == \"Update Person\"" + } + } + }, + "x-[archive]-Input-Seed-Support-and-Kitchen-Garden-Adoption": { + "id": "31579507-0e7a-4b8c-9d26-392d863705ab", + "name": "x [archive] Input Seed Support and Kitchen Garden Adoption", + "inserted_at": "2024-09-10T15:45:42.211458Z", + "lock_version": 4, + "triggers": { + "webhook": { + "enabled": false, + "id": "a4e7dca8-5d9d-423b-b49c-9725e627fd89", + "type": "webhook" + } + }, + "jobs": { + "Input-Seed-Support-and-Kitchen-Garden-Adoption": { + "id": "8684f73a-f9b4-474d-8af2-69824eb239d3", + "name": "Input Seed Support and Kitchen Garden Adoption", + "body": "alterState(state => {\n var input_seed_support = dataValue('form.input_seed_support')(state).split(\n ' '\n );\n for (i = 0; i < input_seed_support.length; i++) {\n upsert(\n 'Household__c',\n 'CommCare_Code__c',\n fields(\n field('CommCare_Code__c', input_seed_support[i]),\n field('Seed_Input_Support__c', 'Yes')\n )\n )(state);\n }\n return state;\n});\n\nalterState(state => {\n var kitchen_garden = dataValue('form.kitchen_garden')(state).split(' ');\n for (i = 0; i < kitchen_garden.length; i++) {\n upsert(\n 'Household__c',\n 'CommCare_Code__c',\n fields(\n field('CommCare_Code__c', kitchen_garden[i]),\n field('Kitchen_Garden__c', 'Yes')\n )\n )(state);\n }\n return state;\n});\n// Your job goes here.\n", + "adaptor": "@openfn/language-salesforce@v1.3.2", + "project_credential_id": null + } + }, + "edges": { + "webhook->Input-Seed-Support-and-Kitchen-Garden-Adoption": { + "enabled": false, + "id": "98a6b755-25bd-42e5-b3e7-d4b15583ef90", + "target_job_id": "8684f73a-f9b4-474d-8af2-69824eb239d3", + "source_trigger_id": "a4e7dca8-5d9d-423b-b49c-9725e627fd89", + "condition_type": "js_expression", + "condition_label": "Input Seed Support and Kitchen Garden Adoption", + "condition_expression": "state.data.form[\"@name\"] == \"Copy of Register Training\"" + } + } + }, + "x-[archive-]Workflow-Q3-2022-Upsert-Person": { + "id": "d04d531b-3757-46dc-8f00-bda6182d7259", + "name": "x [archive ]Workflow Q3 2022 Upsert Person", + "inserted_at": "2024-09-10T15:45:42.238436Z", + "lock_version": 2, + "triggers": { + "webhook": { + "enabled": false, + "id": "b1e761e2-7051-4ce2-8d15-2844559ec721", + "type": "webhook" + } + }, + "jobs": { + "Q3-2022-Upsert-Person": { + "id": "5be3cfe2-5cc1-41ea-8de3-adcda9d425fe", + "name": "Q3 2022 Upsert Person", + "body": "// create constants and functions\nfn(state => {\n state.cleanChoice = function (state, choice) {\n if (choice) {\n return choice.charAt(0).toUpperCase() + choice.slice(1).replace('_', ' ');\n } else {\n return '';\n }\n };\n\n state.handleMultiSelect = function (state, multiField) {\n return multiField\n ? multiField\n .replace(/ /gi, ';')\n .toLowerCase()\n .split(';')\n .map(value => {\n return (\n value.charAt(0).toUpperCase() + value.slice(1).replace('_', ' ')\n );\n })\n .join(';')\n : '';\n };\n\n const pregDangerMap = {\n Vaginal_Bleeding: 'Vaginal Bleeding',\n Water_Breaks: 'Water Breaks before Time of Delivery',\n Prolonged_Labour: 'Prolonged Labour over 12 Hours',\n Convulsions: 'Convulsions or Fits',\n Abdominal_Pain: 'Severe Abdominal Pain before Delivery',\n High_Fever: 'High Fever',\n Low_Baby_Movement: 'Feeling the Baby move less or not at all',\n Swelling: 'Swelling of Face and Hands',\n Severe_Headache: 'Severe or Continuous Headache for more than 12 hours',\n Severe_Vomiting: 'Severe or Continuous Vomiting',\n none: 'None',\n };\n\n const counselMap = {\n anc_visits: 'ANC Visits',\n early_initiation_of_anc_less_than_3_months:\n 'Early initiation of ANC (less than 3 months)',\n completing_recomended_anc_visits: 'Completing recomended ANC visits',\n danger_signs: 'Danger signs',\n skilled_birth: 'Skilled birth',\n immunization: 'Immunization',\n individual_birth_plan: 'Individual Birth Plan',\n emergency_preparedness: 'Emergency preparedness',\n childcare_and_affection: 'Childcare and affection',\n nutrition_counseling: 'Nutrition counseling',\n growth_monitoring: 'Growth monitoring',\n exclusive_breastfeeding: 'Exclusive breastfeeding',\n complementary_feeding: 'Complementary feeding',\n sleeping_under_llitn: 'Sleeping under LLITN',\n knowing_hiv_status: 'Knowing HIV status',\n indoor_pollution: 'Indoor pollution',\n personal_hygiene: 'Personal Hygiene',\n safe_drinking_water: 'Safe drinking water',\n safe_disposal_of_human_waste: 'Safe disposal of human waste',\n };\n\n const serviceMap = {\n Scheduled_PSC_Apt: 'Scheduled PSC Apt',\n Adverse_Drug_Reaction_Side_Effect: 'Adverse Drug Reaction/Side Effect',\n Malnutrition: 'Malnutrition',\n Malaria: 'Malaria',\n TB: 'TB',\n Treatment_for_Other_OIs: 'Treatment for other Ols',\n ARI: 'ARI',\n Anemia: 'Anemia',\n Diarrhea: 'Diarrhea',\n Pregnancy_Care: 'Pregnancy Care (ANC)',\n Family_Planning: 'Family Planning (FP)',\n Preconception_Counseling: 'Preconception Counseling',\n Injury: 'Injury',\n Other: 'Other',\n };\n\n const reasonMapping = {\n lack_of_access_to_fp_information: 'Lack of access to FP information',\n no_access_to_fp_services_hospitals:\n 'Lack of hospitals or places where FP services can be accessed',\n not_willing_to_use_fp_due_to_negative_effects_myths_and_misconceptions:\n 'Myths and misconceptions',\n barriers_at_service_delivery_points: 'Barriers at service delivery points',\n pregnant: 'The client is pregnant',\n intentions_of_getting_pregnant: 'Intentions of getting pregnant',\n not_sexually_active: 'The client is not sexually active',\n other_barriers_culture_male_partners_parents_etc:\n 'Other barriers (culture, male partners, parents, etc)',\n };\n\n const milestoneTypeMap = {\n cognitive_delays_learning_difficulties:\n 'Cognitive Delays Learning Difficulties',\n motor_delays: 'Motor Delays',\n speech_and_language_delay: 'Delay Speech and Language Delay',\n social_and_emotional: 'Social and emotional',\n };\n\n const milestoneMap = {\n movement: 'Movement',\n hearing: 'Hearing',\n communication: 'Communication',\n seeing: 'Seeing',\n cognitive_delays: 'Cognitive Delays',\n play: 'Play',\n };\n const nutritionMap = {\n severe: 'Severely Malnourished',\n moderate: 'Moderately Malnourished',\n normal: 'Normal',\n };\n\n const fpMethodMap = {\n male_condoms: 'Male condoms',\n female_condoms: 'Female condoms',\n pop: 'POP',\n coc: 'COC',\n emergency_pills: 'Emergency pills',\n none: 'None',\n };\n\n return {\n ...state,\n counselMap,\n serviceMap,\n reasonMapping,\n milestoneTypeMap,\n milestoneMap,\n nutritionMap,\n pregDangerMap,\n fpMethodMap,\n };\n});\n\n// get data from SF\nquery(\n `SELECT Id, Parent_Geographic_Area__c, Parent_Geographic_Area__r.Name, Parent_Geographic_Area__r.Parent_Geographic_Area__c FROM Location__c WHERE CommCare_User_ID__c = '${dataValue(\n 'properties.owner_id'\n )(state)}'`\n);\n\n// build IDs from queried SF data\nfn(state => ({\n ...state,\n data: {\n ...state.data,\n villageNewId:\n state.references[0].records && state.references[0].records.length !== 0\n ? state.references[0].records[0].Id\n : undefined,\n areaNewId:\n state.references[0].records && state.references[0].records.length !== 0\n ? state.references[0].records[0].Parent_Geographic_Area__c\n : undefined,\n catchmentNewId:\n state.references[0].records && state.references[0].records.length !== 0\n ? state.references[0].records[0].Parent_Geographic_Area__r\n ? state.references[0].records[0].Parent_Geographic_Area__r\n .Parent_Geographic_Area__c\n : undefined\n : undefined,\n },\n}));\n\nupsertIf(\n state.data.properties.commcare_username !== 'test.2021' &&\n state.data.properties.test_user !== 'Yes', \n 'Household__c',\n 'CommCare_Code__c',\n fields(\n field('CommCare_Code__c', state => {\n return (\n dataValue('indices.parent.case_id')(state) ||\n dataValue('properties.parent_id')(state)\n );\n })\n )\n),\n\n// build sfRecord before upserting\nfn(state => {\n // This mapping was initially constructed with fields(field(), ...) syntax. We\n // preserve it here and use \"expandReferences\" but could also refactor this to\n // use standard object syntax, as Salesforce looks for { k: v, ... }.\n const originalMapping = fields(\n /* field(\n 'deworming_medication__c',\n dataValue('form.TT5.Child_Information.Deworming')\n ),depracated field*/\n field('Source__c', 1),\n field('CommCare_ID__c', dataValue('case_id')),\n relationship(\n 'Household__r',\n 'CommCare_Code__c', state => {\n // (dataValue('properties.parent_id') || dataValue('indices.parent.case_id'))\n return (\n dataValue('properties.parent_id')(state) ||\n dataValue('indices.parent.case_id')(state)\n );\n }),\n field('commcare_location_id__c',dataValue('properties.commcare_location_id')),\n field('CommCare_Username__c',dataValue('properties.commcare_username')),\n field('Telephone__c', dataValue('properties.contact_phone_number')), \n field(\n 'Consent_for_data_use__c',\n dataValue('properties.data_sharing_consent')\n ),\n field('CommCare_HH_Code__c', dataValue('indices.parent.case_id')),\n field('Client_Status__c', dataValue('properties.Client_Status')),\n field('Catchment__c', dataValue('catchmentNewId')),\n field('Area__c', dataValue('areaNewId')),\n field('Household_Village__c', dataValue('villageNewId')),\n field('Name', state => {\n var name1 = dataValue('properties.Person_Name')(state); //check\n var unborn = dataValue('properties.name')(state); //check\n var name2 =\n name1 === undefined || name1 === '' || name1 === null\n ? unborn\n : name1.replace(/\\w\\S*/g, function (txt) {\n return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();\n });\n return name1 !== null ? name2 : 'Unborn Child';\n }),\n field('Chronic_illness__c', state => {\n var choice = dataValue(\n 'properties.please_specify_which_chronic_illness_the_person_has'\n )(state);\n var choice2 = state.handleMultiSelect(state, choice);\n return choice2 ? choice2.replace(/_/g, ' ') : '';\n }),\n field(\n 'Currently_enrolled_in_school__c',\n dataValue('properties.enrolled_in_school')\n ),\n field('Education_Level__c', state => {\n var level = dataValue('properties.Education_Level')(state);\n return level ? level.toString().replace(/_/g, ' ') : null;\n }),\n field('Relation_to_the_head_of_the_household__c', state => {\n var relation = dataValue('properties.relation_to_hh')(state);\n if (relation) {\n relation = relation.toString().replace(/_/g, ' ');\n var toTitleCase = relation.charAt(0).toUpperCase() + relation.slice(1);\n return toTitleCase;\n }\n\n return null;\n }),\n field('Gender__c',dataValue('properties.Gender')),\n field('Disability__c', state => {\n var disability = dataValue('properties.disability')(state);\n var toTitleCase =\n disability !== undefined\n ? disability\n .toLowerCase()\n .split(' ')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(';')\n : null;\n return toTitleCase;\n }), //need case property\n field('Other_disability__c', state => {\n var disability = dataValue('properties.other_disability')(state);\n var toTitleCase =\n disability !== undefined\n ? disability\n .toLowerCase()\n .split(' ')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(';')\n : null;\n return toTitleCase;\n }), //need case property\n\n field('Use_mosquito_net__c', dataValue('properties.sleep_under_net')), //need case property\n // field('Birth_Certificate__c',dataValue('properties.birth_certificate')),\n field('Birth_Certificate__c', dataValue('properties.birth_certificate')),\n field('Child_Status__c', state => {\n var status = dataValue('properties.Child_Status')(state);\n var rt = dataValue('properties.Record_Type')(state); //check that this is the right one\n if (status && rt === 'Unborn') {\n status = 'Unborn';\n } else if (status && rt === 'Born') {\n status = 'Born';\n }\n return status;\n }),\n //===================================================//\n relationship('RecordType', 'Name', state => {\n var rt = dataValue('properties.Record_Type')(state);\n return rt === 'Unborn' || rt === ''\n ? 'Child'\n : rt.toString().replace(/_/g, ' '); //convert Unborn children to Child RT\n }),\n\n //TT5 Mother Information\n\n field('MCH_booklet__c', dataValue('properties.mch_booklet')), //need to create a case property\n field('Reason_for_not_taking_a_pregnancy_test__c', state => {\n var reason = dataValue('properties.No_Preg_Test')(state);\n return reason ? reason.toString().replace(/_/g, ' ') : undefined;\n }),\n field('Pregnancy_danger_signs__c', state => {\n var signs = dataValue('properties.pregnancy_danger_signs')(state);\n return signs ? state.pregDangerMap[signs] : undefined;\n }),\n field(\n 'Individual_birth_plan_counselling__c',\n dataValue('properties.individual_birth_plan')\n ),\n field('Child_Danger_Signs__c', state => {\n var signs = dataValue('properties.Other_Danger_Signs')(state);\n return signs\n ? signs\n .toLowerCase()\n .split(' ')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(';')\n .toString()\n .replace(/_/g, ' ')\n : signs;\n }),\n\n //HAWI\n field(\n 'Unique_Patient_Code__c',\n dataValue('properties.Unique_Patient_Code')\n ),\n field(\n 'Active_in_Support_Group__c',\n dataValue('properties.Active_in_Support_Group')\n ),\n field(\n 'Preferred_Care_Facility__c',\n dataValue('properties.Preferred_Care_Facility')\n ),\n field('Currently_on_ART_s__c', dataValue('properties.ART')),\n field('ART_Regimen__c', dataValue('properties.ARVs')),\n field('HAWI_Defaulter__c', state => {\n var hawi = dataValue('properties.default')(state);\n return hawi === 'Yes' ? true : false;\n }),\n field('Date_of_Default__c', dataValue('properties.date_of_default')),\n field('Know_HIV_status__c', dataValue('properties.known_hiv_status')),\n field('HIV_Status__c', dataValue('properties.hiv_status')),\n /*field('HIV_Status__c', state => {\n var status = dataValue('properties.hiv_status')(state);\n return status === 'yes'\n ? 'Known'\n : status === 'no'\n ? 'Unknown'\n : undefined;\n }),//CHECK MAPPING ON THIS ONE*/\n\n //Illness\n field('Persons_temperature__c', dataValue('properties.temperature')),\n field(\n 'Days_since_illness_start__c',\n dataValue('properties.duration_of_sickness')\n ),\n field(\n 'Current_Malaria_Status__c',\n dataValue('properties.malaria_test_results')\n ),\n field('Malaria_test__c', dataValue('properties.malaria_test')),\n field(\n 'Last_Malaria_Home_Test__c',\n dataValue('properties.malaria_test_date')\n ),\n field('Last_Malaria_Home_Treatment__c', state => {\n var choice = dataValue(\n 'properties.malaria_test_date'\n )(state);\n return state.cleanChoice(state, choice);\n }),\n /*field('Current_Malaria_Status__c', dataValue('form.Malaria_Status')),//check\n field('Malaria_Facility__c',dataValue('form.treatment_and_tracking.malaria_referral_facility')),\n field('Fever_over_7days__c',dataValue('form.treatment_and_tracking.symptoms_check_fever')),//check*/\n field('Cough_over_14days__c', dataValue('properties.symptoms_check_cough')),\n /*field('Diarrhoea_over_14days__c',dataValue('form.treatment_and_tracking.symptoms_check_diarrhea')),//check\n field('Diarrhoea_less_than_14_days__c',dataValue('form.treatment_and_tracking.mild_symptoms_check_diarrhea')),//check*/\n field(\n 'TB_patients_therapy_observed__c',\n dataValue('properties.observed_tb_therapy')\n ),\n field('Injuries_or_wounds__c', dataValue('properties.wounds_or_injuries')),\n field(\n 'Pulse_Oximeter__c',\n dataValue('properties.pulse_oximeter_available')\n ),\n field(\n 'Heart_Rate_Pulse_Oximeter__c',\n dataValue('properties.heart_rate_pulse_oximeter')\n ),\n field(\n 'Oxygen_Concentration_Pulse_Oximeter__c',\n dataValue('properties.oxygen_concentration')\n ),\n field('Can_child_drink__c', dataValue('properties.can_child_drink')),\n // field('Antibiotic_provided_for_fast_breathing__c',dataValue('properties.antibiotic_fast_breathing')),\n field('Antibiotic_provided_for_fast_breathing__c', state => {\n var choice = dataValue('properties.antibiotic_fast_breathing')(state);\n return state.cleanChoice(state, choice);\n }),\n // field('Antibiotic_provided_for_chest_indrawing__c',dataValue('properties.antibiotic_chest_indrawing')),\n field('Antibiotic_provided_for_chest_indrawing__c', state => {\n var choice = dataValue('properties.antibiotic_chest_indrawing')(state);\n return state.cleanChoice(state, choice);\n }),\n /*field('Child_zinc__c',dataValue('form.TT5.Child_Information.Clinical_Services.diarrhea_clinic_treatment_zinc')),//check\n field('Child_ORS__c',dataValue('form.TT5.Child_Information.Clinical_Services.diarrhea_clinic_treatment_ORS')),//check\n field('Childs_breath_per_minute__c',dataValue('form.psbi.breaths_per_minuite')),//check\n field('Child_chest_in_drawing__c',dataValue('form.psbi.Child_chest_in_drawing_c')),//check*/\n field('Default_on_TB_treatment__c', state => {\n var choice = dataValue('properties.default_tb_treatment')(state); //check\n return state.cleanChoice(state, choice);\n }),\n field('Treatment_Distribution__c', state => {\n var choice = dataValue('properties.distributed_treatments')(state);\n return state.cleanChoice(state, choice);\n }), //check\n\n //Delivery\n field(\n 'Immediate_Breastfeeding__c',\n dataValue('properties.Breastfeeding_Delivery')\n ),\n field('Place_of_Delivery__c', state => {\n var facility = dataValue('properties.Delivery_Type')(state);\n return facility === 'Skilled'\n ? 'Facility'\n : facility === 'Unskilled'\n ? 'Home'\n : undefined;\n }),\n field('Delivery_Facility__c', state => {\n var facility = dataValue('properties.Delivery_Facility')(state);\n return facility ? facility.toString().replace(/_/g, ' ') : null;\n }),\n /* field('Delivery_Facility__c', state => {\n //HMN 21//11/2022\n var birthFacility =dataValue('properties.Birth_Facility')(state);\n var deliveryFacility = dataValue('properties.Delivery_Facility')(state);\n var facilityOfBirth = dataValue ('properties.Facility_of_Birth')(state);\n var faciliy_val = \n facilityOfBirth //!== undefined || facilityOfBirth !== '' || facilityOfBirth !== null \n ? facilityOfBirth\n :birthFacility //!== undefined || birthFacility !== '' || birthFacility !== null \n ? birthFacility\n :deliveryFacility //!== undefined || deliveryFacility !== '' || deliveryFacility !== null \n ? deliveryFacility\n :\"\";\n return faciliy_val.toString().replace(/_/g, ' '); \n //HMN\n }), */\n //field('Delivery_Facility__c', state => {\n // var facility = dataValue('properties.Birth_Facility')(state);\n // return facility ? facility.toString().replace(/_/g, ' ') : null;\n //}),\n field(\n 'Delivery_Facility_Other__c',\n dataValue('properties.Delivery_Facility_Other')\n ),\n\n //Family Planning\n\n field('LMP__c', dataValue('properties.LMP')),\n field('Family_Planning__c', dataValue('properties.family_planning')),\n field(\n 'Family_Planning_Method__c',\n dataValue('properties.family_planning_method')\n ),\n field('FP_Method_Distributed__c', state => {\n var status = dataValue('properties.FP_commodity')(state);\n var value =\n status && status !== ''\n ? status\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return state.fpMethodMap[value] || value;\n })\n : undefined;\n return value ? value.join(';') : undefined;\n }),\n field('Reasons_for_not_taking_FP_method__c', state => {\n var status = dataValue('properties.No_FPmethod_reason')(state);\n var value =\n status && status !== ''\n ? status\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return state.reasonMapping[value] || value;\n })\n : undefined;\n return value ? value.join(';') : undefined;\n }),\n field('Pregnant__c', state => {\n var preg = dataValue('properties.Pregnant')(state);\n return preg === 'Yes' ? true : false;\n }),\n field('Date_of_Delivery__c', dataValue('properties.delivery_date')),\n field(\n 'Counselled_on_FP_Methods__c',\n dataValue('properties.CounselledFP_methods')\n ),\n field('Client_counselled_on__c', state => {\n var choices =\n dataValue('properties.counsel_topic')(state) ||\n dataValue('properties.counsel_topic')(state); //need to create a case property\n var choiceGroups = choices ? choices.split(' ') : null;\n var choicesMulti = choiceGroups\n ? choiceGroups\n .map(cg => {\n return state.counselMap[cg];\n })\n .join(';')\n : choiceGroups;\n return choicesMulti;\n }), //OpenFn Question - can this be simplified now that this is a case property\n field('Client_provided_with_FP__c', state => {\n var choice = dataValue(\n 'properties.was_the_woman_15-49yrs_provided_with_family_planning_commodities_by_chv'\n )(state);\n return state.cleanChoice(state, choice);\n }),\n field(\n 'Received_pregnancy_test__c',\n dataValue('properties.did_you_adminsiter_a_pregnancy_test')\n ),\n field(\n 'Pregnancy_test_result__c',\n dataValue('properties.pregnancy_test_result')\n ),\n field('Gravida__c', dataValue('properties.Gravida')),\n field('Parity__c', dataValue('properties.Parity')),\n\n //TT5 Child Information\n\n field(\n 'Exclusive_Breastfeeding__c',\n dataValue('properties.Exclusive_Breastfeeding')\n ),\n field(\n 'Counselled_on_Exclusive_Breastfeeding__c',\n dataValue('properties.counseling')\n ),\n field(\n 'Newborn_visited_48_hours_of_delivery__c',\n dataValue('properties.newborn_visited_48_hours_of_delivery')\n ),\n field('Newborn_visit_counselling__c', state => {\n var choice = dataValue('properties.did_you_consel_the_mother_on1')(state);\n return state.cleanChoice(state, choice);\n }),\n field(\n 'mother_visited_48_hours_of_the_delivery__c',\n dataValue('properties.visit_mother_48')\n ),\n /*\n //HMN -06012023- The object Visit_after_unskilled__c seems to be missing in sfRecord\n //Investigation issue https://lwala.atlassian.net/browse/LWAL-716 raised\n //Meanwhile this is being removed to allow re-processing\n field(\n 'Visit_after_unskilled__c',\n dataValue('properties.visit_24hours_after_unskilled_delivery')\n ),\n */\n field('Mother_visit_counselling__c', state => {\n var choice = dataValue('properties.did_you_consel_the_mother_on2')(state);\n return state.cleanChoice(state, choice);\n }),\n /*field('Newborn_visited_48_hours_of_delivery__c',dataValue('properties.newborn_visited_48_hours_of_delivery')), Duplicate Mapping*/\n field(\n 'Newborn_visited_by_a_CHW_within_6_days__c',\n dataValue('properties.visit_6_days_from_delivery')\n ),\n\n //Nutrition\n\n field(\n 'Caretaker_action_after_muac_screening__c',\n dataValue('properties.mother_screened_muac_action')\n ),\n field(\n 'Caretaker_muac_findings__c',\n dataValue('properties.mother_screened_child_muac_result')\n ),\n field('Food_groups_3_times_a_day__c',dataValue('properties.food_groups')),\n // field('Caretaker_screened_for_muac_this__c', dataValue('properties.mother_screened_child_muac')),\n field('Caretaker_screened_for_muac_this__c', state => {\n var choice = dataValue('properties.mother_screened_child_muac')(state); //check\n return state.cleanChoice(state, choice);\n }),\n // field('Caretaker_trained_in_muac__c', dataValue('properties.mother_trained_muac')),\n field('Caretaker_trained_in_muac__c', state => {\n var choice = dataValue('properties.mother_trained_muac')(state); //check\n return state.cleanChoice(state, choice);\n }),\n field(\n 'of_Caretaker_MUAC_screenings__c',\n dataValue('properties.mother_nb_screening')\n ),\n field('Current_Weight__c', dataValue('properties.Current_Weight')), //Only on task update\n field('Current_Height__c', dataValue('properties.current_height')),\n field('Current_MUAC__c', dataValue('properties.MUAC')),\n field('Current_Nutrition_Status__c', state => {\n var status = dataValue('properties.Nutrition_Status')(state);\n return status ? state.nutritionMap[status] : undefined;\n }),\n\n //TT5 & HAWI\n field('TT5_Mother_Registrant__c', state => {\n var preg = dataValue('properties.Pregnant')(state);\n return preg == 'Yes' ? 'Yes' : null;\n }),\n field('Enrollment_Date__c', state => {\n var age = dataValue('properties.age')(state);\n var date = dataValue('server_date_modified')(state);\n var preg = dataValue('properties.Pregnant')(state);\n return age < 5 || preg == 'Yes' ? date : null;\n }),\n field('HAWI_Enrollment_Date__c', state => {\n var date = dataValue('server_date_modified')(state);\n var status = dataValue('properties.hiv_status')(state);\n return status == 'positive' ? date : null;\n }),\n field('Thrive_Thru_5_Registrant__c', state => {\n var age = dataValue('properties.age')(state);\n var preg = dataValue('properties.Pregnant')(state);\n return age < 5 || preg == 'Yes' ? 'Yes' : 'No';\n }), //check mapping\n field('HAWI_Registrant__c', state => {\n var status = dataValue('properties.hiv_status')(state);\n return status == 'positive' ? 'Yes' : 'No';\n }),\n\n //ANC\n field('ANC_1__c', state => {\n var date = dataValue('properties.ANC_1')(state);\n return date && date !== '' ? date : undefined;\n }),\n field('ANC_2__c', state => {\n var date = dataValue('properties.ANC_2')(state);\n return date && date !== '' ? date : undefined;\n }),\n field('ANC_3__c', state => {\n var date = dataValue('properties.ANC_3')(state);\n return date && date !== '' ? date : undefined;\n }),\n field('ANC_4__c', state => {\n var date = dataValue('properties.ANC_4')(state);\n return date && date !== '' ? date : undefined;\n }),\n field('ANC_5__c', state => {\n var date = dataValue('properties.ANC_5')(state);\n return date && date !== '' ? date : undefined;\n }),\n field('Date_of_Birth__c', state => {\n var date = dataValue('properties.DOB')(state);\n return date && date !== '' ? date : undefined;\n }),\n\n //Immunization\n\n field(\n 'Child_missed_immunization_type__c',\n dataValue('form.TT5.Child_Information.Immunizations.immunization_type')\n ), //check\n field('BCG__c', dataValue('properties.BCG')),\n field('OPV_0__c', dataValue('properties.OPV_0')),\n field('Measles_6__c', dataValue('properties.Measles_6')),\n field('Measles_9__c', dataValue('properties.Measles_9')),\n field('Measles_18__c', dataValue('properties.Measles_18')),\n field('OPV_1__c', dataValue('properties.OPV_PCV_Penta_1')),\n field('OPV_2__c', dataValue('properties.OPV_PCV_Penta_2')),\n field('OPV_3__c', dataValue('properties.OPV_PCV_Penta_3')),\n field('Rotavirus_1__c', dataValue('properties.rotavirus_1')),\n field('Rotavirus_2__c', dataValue('properties.rotavirus_2')),\n field('IPV__c', dataValue('properties.IPV')),\n field('Vitamin_A_12__c', dataValue('properties.Vitamine_A')),\n field('Vitamin_A_18__c', dataValue('properties.Vitamine_A_2')),\n field('Vitamin_A_24__c', dataValue('properties.Vitamine_A_3')),\n field('Deworming_12__c', dataValue('properties.Deworming_1')),\n field('Deworming_18__c', dataValue('properties.Deworming_2')),\n field('Deworming_24__c', dataValue('properties.Deworming_3')),\n\n //ECD\n // field('Did_you_counsel_caregiver_on__c',dataValue('properties.did_you_counsel_the_caregiver_on_delayed_milestones')),\n field('Did_you_counsel_caregiver_on__c', state => {\n var choice = dataValue(\n 'properties.did_you_counsel_the_caregiver_on_delayed_milestones'\n )(state);\n return state.cleanChoice(state, choice);\n }),\n // field('Delayed_Milestone__c',dataValue('properties.does_the_child_has_a_delayed_milestone')),\n field('Delayed_Milestone__c', state => {\n var choice = dataValue(\n 'properties.does_the_child_has_a_delayed_milestone'\n )(state);\n return state.cleanChoice(state, choice);\n }),\n // field('Child_has_2_or_more_play_items__c',dataValue('properties.does_the_child_has_2_or_more_play_items_at_home')),\n field('Child_has_2_or_more_play_items__c', state => {\n var choice = dataValue(\n 'properties.does_the_child_has_2_or_more_play_items_at_home'\n )(state);\n return state.cleanChoice(state, choice);\n }),\n // field('Child_has_3_or_more_picture_books__c',dataValue('properties.does_the_child_has_3_or_more_picture_books')),\n field('Child_has_3_or_more_picture_books__c', state => {\n var choice = dataValue(\n 'properties.does_the_child_has_3_or_more_picture_books'\n )(state);\n return state.cleanChoice(state, choice);\n }),\n field('Delayed_Milestones_Counselled_On__c', state => {\n var ms = dataValue(\n 'properties.which_delayed_milestone_area_did_you_counsel_the_caregiver_on'\n )(state);\n return ms ? state.milestoneMap[ms] : undefined;\n }),\n field('Delayed_Milestone_Type__c', state => {\n var ms = dataValue('properties.which_delayed_milestone')(state);\n return ms ? state.milestoneTypeMap[ms] : undefined;\n }),\n\n //Death\n field('Date_of_Death__c', dataValue('properties.Date_of_Death')),\n field('Cause_of_Death__c', state => {\n var death = dataValue('properties.cause_of_death_dead')(state);\n return death ? death.toString().replace(/_/g, ' ') : death;\n }), //check which case property to use - there are 2\n field('Verbal_autopsy__c', dataValue('properties.verbal_autopsy')),\n\n //Closing\n field('Last_Modified_Date_CommCare__c', dataValue('date_modified')),\n field('Case_Closed_Date__c',dataValue('date_closed')),\n //field('Case_Closed_Date__c', state => {\n // var closed = dataValue('date_closed')(state);\n // var date = dataValue('date_modified')(state);\n // return closed && closed == true ? date : undefined;\n //}) //need case property\n );\n\n let sfRecord = expandReferences(originalMapping)(state);\n\n Object.entries(sfRecord).forEach(([key, value]) => {\n if (value === '') sfRecord[key] = undefined;\n });\n\n return { ...state, sfRecord };\n});\n\n// upsert data to SF\nupsertIf(\n state.data.properties.commcare_username !== 'test.2021' &&\n state.data.properties.test_user !== 'Yes' ,\n 'Person__c', 'CommCare_ID__c', state => state.sfRecord);\n\nupsertIf(\n state.data.properties.commcare_username !== 'test.2021' &&\n state.data.properties.test_user !== 'Yes' &&\n state.data.properties.caretaker_case_id !== undefined && state.data.properties.caretaker_case_id !== '', \n 'Person__c', 'CommCare_ID__c', \n fields(\n relationship('Primary_Caregiver_Lookup__r', 'CommCare_ID__c', state => {\n return caregiver = dataValue('properties.caretaker_case_id')(state);\n }),\n field('CommCare_ID__c', dataValue('case_id')),\n )\n);\n\nupsertIf(\n state.data.properties.commcare_username !== 'test.2021' &&\n state.data.properties.test_user !== 'Yes' &&\n state.data.properties.mother_case_id !== undefined && state.data.properties.mother_case_id !== '', \n 'Person__c', 'CommCare_ID__c', \n fields(\n relationship('Mother__r', 'CommCare_ID__c', state => {\n return caregiver = dataValue('properties.mother_case_id')(state);\n }),\n field('CommCare_ID__c', dataValue('case_id')),\n )\n);\n\nupsertIf(\n state.data.properties.commcare_username !== 'test.2021' &&\n state.data.properties.test_user !== 'Yes' &&\n state.data.properties.head_of_household_case_id !== undefined && state.data.properties.head_of_household_case_id !== '', \n 'Household__c', 'CommCare_Code__c',\n fields(\n field('CommCare_Code__c', state => {\n return (\n dataValue('indices.parent.case_id')(state) ||\n dataValue('properties.parent_id')(state)\n )\n }),\n relationship('Head_of_Household__r', 'CommCare_ID__c', dataValue('properties.head_of_household_case_id')),\n )\n )\n", + "adaptor": "@openfn/language-salesforce@latest", + "project_credential_id": "96a3843d-5d9c-4f03-8289-508b87901c9b" + } + }, + "edges": { + "webhook->Q3-2022-Upsert-Person": { + "enabled": false, + "id": "0e8852b1-f01f-40bb-9431-d076d0f7a7ba", + "target_job_id": "5be3cfe2-5cc1-41ea-8de3-adcda9d425fe", + "source_trigger_id": "b1e761e2-7051-4ce2-8d15-2844559ec721", + "condition_type": "js_expression", + "condition_label": "Person", + "condition_expression": "state.data.properties[\"case_type\"] == \"Person\" && state.data.properties[\"test_user\"] != \"Yes\"" + } + } + }, + "x-[archive]-Workflow-test-get-forms": { + "id": "060bfd95-0b67-4396-acf6-bc88fad3db5b", + "name": "x [archive] Workflow test get forms", + "inserted_at": "2024-09-10T15:45:42.244486Z", + "lock_version": 2, + "triggers": { + "cron": { + "enabled": false, + "id": "7d1ef225-56a7-4d21-a272-9a7e0066f4f4", + "type": "cron", + "cron_expression": "1 * * * *" + } + }, + "jobs": { + "test-get-forms": { + "id": "eae0c46f-e24b-419b-83dd-70a31d01c014", + "name": "test get forms", + "body": "get(\"https://www.commcarehq.org/a/lwala-community-alliance/api/v0.5/form/\", {\n headers: {\"content-type\": \"application/json\"},\n authentication: {username: \"aleksa@verasolutions.org\", password: \"chw$@kamo20\"},\n query: {\"limit\": \"1\"}\n },\n function(state) {\n return state;\n }\n );\n console.log(state);\n each(dataPath('objects[*]'), state => {\n return post(\"https://www.openfn.org/inbox/e77693cc-71d5-49a9-8192-5b15679450df\", { body: state => state.data })(state);\n });\n", + "adaptor": "@openfn/language-http@v2.4.15", + "project_credential_id": null + } + }, + "edges": { + "cron->test-get-forms": { + "enabled": false, + "id": "b986bc1d-e5e1-4782-bd5e-622f5c6b2b1d", + "target_job_id": "eae0c46f-e24b-419b-83dd-70a31d01c014", + "source_trigger_id": "7d1ef225-56a7-4d21-a272-9a7e0066f4f4", + "condition_type": "always" + } + } + }, + "x-[archive]-Workflow-Q3-2022-Upsert-Household-&-Household-Visit-in-SF": { + "id": "b2f0f8db-ebe4-4618-b2b7-11febc36d9d7", + "name": "x [archive] Workflow Q3 2022 Upsert Household & Household Visit in SF", + "inserted_at": "2024-09-10T15:45:42.387065Z", + "lock_version": 2, + "triggers": { + "webhook": { + "enabled": false, + "id": "9647f972-f847-4a70-9acb-0ab46d1fcc38", + "type": "webhook" + } + }, + "jobs": { + "Q3-2022-Upsert-Household-and-Household-Visit-in-SF": { + "id": "abb8158a-46d5-441e-92e9-84af6c614b92", + "name": "Q3 2022 Upsert Household and Household Visit in SF", + "body": "query(\n `SELECT Id, Parent_Geographic_Area__c, Parent_Geographic_Area__r.Name, Parent_Geographic_Area__r.Parent_Geographic_Area__c FROM Location__c WHERE CommCare_User_ID__c = '${dataValue(\n 'properties.owner_id'\n )(state)}'`\n);\n\nfn(state => { console.log(\"query1 done\"); return state; });\nfn(state => {\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n console.log('4 second cooldown finished.');\n resolve(state);\n }, 4000);\n });\n});\n\nfn(state => ({\n ...state,\n data: {\n ...state.data,\n villageNewId:\n state.references[0].records && state.references[0].records.length !== 0\n ? state.references[0].records[0].Id\n : undefined,\n areaNewId:\n state.references[0].records && state.references[0].records.length !== 0\n ? state.references[0].records[0].Parent_Geographic_Area__c\n : undefined,\n catchmentNewId:\n state.references[0].records && state.references[0].records.length !== 0\n ? (state.references[0].records[0].Parent_Geographic_Area__r \n ? state.references[0].records[0].Parent_Geographic_Area__r.Parent_Geographic_Area__c\n : undefined)\n : undefined,\n },\n}));\n\nupsertIf(\n state.data.properties.commcare_username !== 'openfn.test' &&\n state.data.properties.commcare_username !== 'test.2021' &&\n state.data.properties.test_user !== 'Yes' ,\n 'Household__c',\n 'CommCare_Code__c',\n fields(\n field('CommCare_Username__c', dataValue('properties.commcare_username')),\n field('MOH_household_code__c', dataValue('properties.moh_code')),\n field('CommCare_Code__c', dataValue('case_id')),\n field('Source__c', true),\n //field('Household_CHW__c', 'a030Q00000A0jeYQAR'), //sandbox hardcoded mapping\n field('Household_CHW__c', state => {\n var chw = dataValue('properties.CHW_ID')(state);\n return chw === 'a030800001zQrk'\n ? 'a030800001zQrk5'\n : chw\n ? chw\n : undefined;\n }),\n //TODO: Prod mapping to add back before go-live\n field('Catchment__c', dataValue('catchmentNewId')),\n field('Area__c', dataValue('areaNewId')),\n field('Village__c', dataValue('villageNewId')),\n field('Household_Village__c', dataValue('properties.village')),\n // relationship('Catchment__r', 'Name', state => {\n // var catchment =\n // state.data.properties.catchement ||\n // state.data.properties.catchment_name;\n // return catchment === '' || catchment === undefined\n // ? 'Unknown Location'\n // : catchment;\n // }), // check\n // field('Area__c', state => {\n // // var area = dataValue('properties.Area_Name')(state);\n // return area === '' || area === undefined ? 'a000Q00000Egmu4' : area;\n // }), // Commented out because it was causing a job error \n // field('Household_village__c', dataValue('properties.village')),//case property, but not in message\n \n // field('Village__c',dataValue('properties.village_name')), //lookup\n field('Deaths_in_the_last_6_months__c', state => {\n var death = dataValue(\n 'properties.deaths_in_past_6_months'\n )(state);\n return death > 0 ? 'Yes' : 'No';\n }),\n field('Access_to_safe_water__c',dataValue('properties.Safe_Water')),//not coming through\n field('Treats_Drinking_Water__c',dataValue('properties.Treats_Drinking_Water')),//not coming through\n field('Tippy_Tap__c',dataValue('properties.Active_Handwashing_Station')),//not coming through\n field('Pit_Latrine__c',dataValue('properties.Functional_Latrine')),//not coming through\n field('Rubbish_Pit__c',dataValue('properties.Rubbish_Pit')),//not coming through\n field('Drying_Rack__c',dataValue('properties.Drying_Rack')),//not coming through\n field('Kitchen_Garden__c',dataValue('properties.Kitchen_Garden')),//not coming through\n field('Cookstove__c',dataValue('properties.Improved_Cooking_Method')),//not coming through\n field('Clothe__c',dataValue('properties.Clothesline')),//not coming through\n field('WASH_Trained__c',dataValue('properties.WASH_Trained')),//not coming through\n field('Uses_ITNs__c',dataValue('properties.ITNs')),\n field(\n 'Has_muac_tape__c',\n dataValue('properties.family_muac_tape_available')\n ),\n //field('Total_household_people__c',dataValue('properties.Total_Number_of_Members')), //not coming through\n field('Health_insurance__c', dataValue('properties.health_insurace_cover')),\n field('Health_insurance_active_status__c',dataValue('properties.healthinsurance_active')),\n field('Health_insurance_type__c', state => {\n var status = dataValue('properties.health_insurance')(state);\n return status && status === 'other_please_specify_if_active'\n ? 'Other'\n : status === 'nhif'\n ? 'NHIF'\n : status === 'Linda_mama' || 'linda_mama'\n ? 'Linda mama'\n : status;\n }),\n field('Other_Health_Insurance__c',dataValue('properties.if_other_please_specify')),\n field('Work_with_TBA__c', dataValue('properties.tba')),\n field('TBA_name__c', dataValue('properties.which_tba')),\n field('Last_Modified_Date_CommCare__c', dataValue('server_date_modified')),//Need a case property),\n field('Active_Household__c', state => {\n var status = dataValue('properties.Household_Status')(state);\n return status && status === 'No'\n ? false\n : status === 'Yes'\n ? true\n : status;\n }),\n // relationship('Head_of_Household__r', 'CommCare_ID__c', dataValue('properties.head_of_household_case_id')),\n field('Inactive_Reason__c', state => {\n var reason = dataValue('properties.Reason_for_Inactive')(state);\n return reason ? reason.toString().replace(/_/g, ' ') : null;\n }),\n field(\n 'Active_in_Nutrition_Program__c',\n dataValue(\n 'properties.enrolled_in_a_lwala_nutrition_program'\n )\n ),\n field(\n 'lwala_nutrition_program_enrollment_date__c',\n dataValue(\n 'properties.lwala_nutrition_program_enrollment_date'\n )\n ),\n field(\n 'Trained_in_gardening__c',\n dataValue('properties.household_trained_on_gardening')\n ),\n field(\n 'household_trained_on_gardening_date__c',\n dataValue(\n 'properties.when_was_the_household_trained_on_gardening'\n )\n ),\n field(\n 'Seed_Input_Support__c',\n dataValue('properties.household_provided_with_seed_input_support'\n )\n ),\n field(\n 'household_provided_with_seed_input_suppo__c',\n dataValue(\n 'properties.when_was_the_household_provided_with_seed_input_support'\n )\n ),\n field(\n 'MIYCN_Trained__c',\n dataValue('properties.household_trained_on_MIYCN')\n ),\n // not in message:\n // field(\n // 'Kitchen_Garden__c',\n // dataValue('properties.nutrition_enrollment.household_has_kitchen_garden')\n // ),\n\n //field('Case_Closed_Date__c', state => {\n // var closed = dataValue('date_closed')(state); \n // var date = dataValue('server_date_modified')(state); \n // return closed && closed == true ? date : undefined; \n // })\n )\n);\n\nfn(state => { console.log(\"upsertIf1 done\"); return state; });\nfn(state => {\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n console.log('4 second cooldown finished.');\n resolve(state);\n }, 4000);\n });\n});\n\n//Household Visit\nquery(\n `SELECT Id, Parent_Geographic_Area__c, Parent_Geographic_Area__r.Name, Parent_Geographic_Area__r.Parent_Geographic_Area__c FROM Location__c WHERE CommCare_User_ID__c = '${dataValue(\n 'properties.owner_id'\n )(state)}'`\n);\n\nfn(state => { console.log(\"query2 done\"); return state; });\nfn(state => {\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n console.log('4 second cooldown finished.');\n resolve(state);\n }, 4000);\n });\n});\n\nfn(state => ({\n ...state,\n data: {\n ...state.data,\n catchmentNewId:\n state.references[0].records && state.references[0].records.length !== 0\n ? (state.references[0].records[0].Parent_Geographic_Area__r \n ? state.references[0].records[0].Parent_Geographic_Area__r.Parent_Geographic_Area__c\n : undefined)\n : undefined,\n },\n}));\n\nfn(state => {\n/* const deaths = state.data.form.household_deaths\n ? state.data.form.household_deaths.deaths\n : '';\n if (deaths !== '' && !Array.isArray(deaths)) {\n state.data.form.household_deaths.deaths = [deaths];\n }*/\n\n const supervisorMap = {\n community_health_nurse: 'Community Health Nurse',\n chw_supervisor: 'CHW Supervisor',\n chewschas: 'CHEWs/CHAs',\n other: 'Other',\n none: 'None',\n };\n\n const insuranceMap = {\n nhif: 'NHIF',\n Linda_mama: 'Linda mama',\n other_please_specify_if_active: 'Other',\n none: 'None',\n };\n\n return { ...state, supervisorMap, insuranceMap };\n});\n\nupsertIf(\n // state.data.properties.username !== 'openfn.test' &&\n state.data.properties.username !== 'test.2021' &&\n state.data.properties.test_user !== 'Yes' ,\n 'Visit__c',\n 'CommCare_Visit_ID__c',\n fields(\n field('CommCare_Username__c', dataValue('properties.commcare_username')),//\n // field('CommCare_Visit_ID__c', dataValue('id')),\n field('CommCare_Visit_ID__c', state => {\n var case_id = dataValue('case_id')(state);\n var submitted = dataValue('properties.last_form_opened_date_and_time')(state);\n return case_id + '_' + submitted;\n }),\n // field('Household_CHW__c', 'a030Q00000A0jeY'),\n // field('Catchment__c', dataValue('a000Q00000Egmtk')),\n field('Catchment__c', dataValue('catchmentNewId')),\n // field('Household__c','a010Q00000BL6lT'),\n // field('Household__c', dataValue('form.case.@case_id')),\n relationship(\n 'Household__r',\n 'CommCare_Code__c',\n dataValue('case_id')),\n field('Date__c',dataValue('properties.Date')),\n field('Form_Submitted__c', dataValue('properties.last_form_opened_name')),\n\n //field('MOH_household_code__c', state => {\n // var moh = dataValue('form.Household_Information.moh_code')(state);\n // var mohLinked = dataValue('form.MOH_household_code_linked')(state);\n // return moh ? moh : mohLinked && mohLinked !== '' ? mohLinked : undefined;\n // }),\n field('Active_Household__c', state => {\n var status = dataValue('properties.Household_Status')(state);\n return status && status === 'No'\n ? false\n : status === 'Yes'\n ? true\n : status;\n }),\n //field('Inactive_Reason__c', state => {\n // var reason = dataValue('form.Reason_for_Inactive')(state);\n // return reason ? reason.toString().replace(/_/g, ' ') : null;\n //}),\n //field('Source__c', 1),//\n //relationship(\n // 'Household_CHW__r', \n // 'CommCare_ID__c', \n // dataValue('form.sfid')),TO UPDATE IN PRODUCTION\n // field('Household_village__c', dataValue('form.village')),//\n //New Nutrition Field (MOTG)\n field(\n 'Active_in_Nutrition_Program__c',\n dataValue(\n 'properties.enrolled_in_a_lwala_nutrition_program'\n )\n ),\n field(\n 'lwala_nutrition_program_enrollment_date__c',\n dataValue(\n 'properties.lwala_nutrition_program_enrollment_date'\n )\n ),\n field(\n 'Trained_in_gardening__c',\n dataValue('properties.household_trained_on_gardening')\n ),\n field(\n 'household_trained_on_gardening_date__c',\n dataValue(\n 'properties.when_was_the_household_trained_on_gardening'\n )\n ),\n field(\n 'Seed_Input_Support__c',\n dataValue(\n 'properties.household_provided_with_seed_input_support'\n )\n ),\n field(\n 'household_provided_with_seed_input_suppo__c',\n dataValue(\n 'properties.when_was_the_household_provided_with_seed_input_support'\n )\n ),\n field(\n 'MIYCN_Trained__c',\n dataValue('properties.household_trained_on_MIYCN')\n ),\n field(\n 'Kitchen_Garden__c',\n dataValue('properties.Kitchen_Garden')\n ),\n\n field(\n 'Access_to_safe_water__c',\n dataValue('properties.Safe_Water')\n ),\n field(\n 'Treats_Drinking_Water__c',\n dataValue('properties.Treats_Drinking_Water')\n ),\n field(\n 'Tippy_Tap__c',\n dataValue('properties.Active_Handwashing_Station')\n ),\n field(\n 'Pit_Latrine__c',\n dataValue('properties.Functional_Latrine')\n ),\n field(\n 'Rubbish_Pit__c',\n dataValue('properties.Rubbish_Pit')\n ),\n field(\n 'Drying_Rack__c',\n dataValue('properties.Drying_Rack')\n ),\n field(\n 'Kitchen_Garden__c',\n dataValue('properties.Kitchen_Garden')\n ),\n field(\n 'Cookstove__c',\n dataValue('properties.Improved_Cooking_Method')\n ),\n field('Clothe__c', dataValue('properties.Clothesline')),\n field(\n 'WASH_Trained__c',\n dataValue('properties.WASH_Trained')\n ),\n field(\n 'Has_muac_tape__c',\n dataValue('properties.family_muac_tape_available')\n ),\n field('Uses_ITNs__c', dataValue('properties.ITNs')),\n field('Supervisor_Visit__c', state =>\n state.data.properties.supervisor_visit\n ? state.supervisorMap[state.data.properties.supervisor_visit]\n : null\n ),\n field('Health_insurance__c', dataValue('properties.health_insurace_cover')),\n field(\n 'Health_insurance_active_status__c',\n dataValue('properties.healthinsurance_active')\n ),\n field('Health_insurance_type__c', state => {\n var status = dataValue('properties.health_insurance')(state);\n var value =\n status && status !== ''\n ? status\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return state.insuranceMap[value] || value;\n })\n : undefined;\n return value ? value.join(';') : undefined;\n }),\n field(\n 'Other_Health_Insurance__c',\n dataValue('properties.if_other_please_specify')\n ),\n //field('Last_Modified_Date_CommCare__c', dataValue('server_modified_on')),\n field('CommCare_Form_Opened__c', state=> {\n var form_opened = dataValue('properties.last_form_opened_date_and_time')(state);\n var value1 = form_opened.split('-').slice(0, 2).join('-');\n var value2 = form_opened.split('-').slice(2).join('-');\n var formattedValue = [value1, value2].join(' ');\n return new Date(formattedValue).toISOString();\n }),\n field('Case_Closed_Date__c', state => {\n var closed = dataValue('date_closed')(state);\n var date = dataValue('server_modified_on')(state);\n return closed && closed == true ? date : undefined;\n })\n )\n);\n\nfn(state => { console.log(\"upsertIf2 done\"); return state; });\nfn(state => {\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n console.log('Final 4 second cooldown finished.');\n resolve(state);\n }, 4000);\n });\n});\n", + "adaptor": "@openfn/language-salesforce@latest", + "project_credential_id": null + } + }, + "edges": { + "webhook->Q3-2022-Upsert-Household-and-Household-Visit-in-SF": { + "enabled": false, + "id": "d4f1da88-fd11-49d2-baf3-91362d942733", + "target_job_id": "abb8158a-46d5-441e-92e9-84af6c614b92", + "source_trigger_id": "9647f972-f847-4a70-9acb-0ab46d1fcc38", + "condition_type": "js_expression", + "condition_label": "Household", + "condition_expression": "state.data.properties[\"app_release\"] == \"Q2-2022\" && state.data.properties[\"case_type\"] == \"Household\" && state.data.properties[\"test_user\"] != \"Yes\"" + } + } + }, + "z-[archive]-Upsert-Household": { + "id": "70441928-37ba-4874-b62e-b5ad95a8363a", + "name": "z [archive] Upsert Household", + "inserted_at": "2024-09-10T15:45:43.243158Z", + "lock_version": 4, + "triggers": { + "webhook": { + "enabled": false, + "id": "1b7a2970-947a-4070-b90e-1605e4c02e0d", + "type": "webhook" + } + }, + "jobs": { + "Upsert-Household": { + "id": "e2b55c71-f59c-4edf-8e69-71ccb9d2e898", + "name": "Upsert Household", + "body": "query(\n `SELECT Id, Parent_Geographic_Area__c, Parent_Geographic_Area__r.Name, Parent_Geographic_Area__r.Parent_Geographic_Area__c FROM Location__c WHERE CommCare_User_ID__c = '${dataValue(\n 'properties.owner_id'\n )(state)}'`\n);\n\nfn(state => ({\n ...state,\n data: {\n ...state.data,\n villageNewId:\n state.references[0].records && state.references[0].records.length !== 0\n ? state.references[0].records[0].Id\n : undefined,\n areaNewId:\n state.references[0].records && state.references[0].records.length !== 0\n ? state.references[0].records[0].Parent_Geographic_Area__c\n : undefined,\n catchmentNewId:\n state.references[0].records && state.references[0].records.length !== 0\n ? (state.references[0].records[0].Parent_Geographic_Area__r \n ? state.references[0].records[0].Parent_Geographic_Area__r.Parent_Geographic_Area__c\n : undefined)\n : undefined,\n },\n}));\n\nupsertIf(\n state.data.properties.commcare_username !== 'test.2021' &&\n state.data.properties.test_user !== 'Yes' ,\n 'Household__c',\n 'CommCare_Code__c',\n fields(\n field('CommCare_Username__c', dataValue('properties.commcare_username')),\n field('MOH_household_code__c', dataValue('properties.moh_code')),\n field('CommCare_Code__c', dataValue('case_id')),\n field('Source__c', true),\n //field('Household_CHW__c', 'a030Q00000A0jeYQAR'), //sandbox hardcoded mapping\n field('Household_CHW__c', state => {\n var chw = dataValue('properties.CHW_ID')(state);\n return chw === 'a030800001zQrk'\n ? 'a030800001zQrk5'\n : chw\n ? chw\n : undefined;\n }),\n //TODO: Prod mapping to add back before go-live\n field('Catchment__c', dataValue('catchmentNewId')),\n field('Area__c', dataValue('areaNewId')),\n field('Village__c', dataValue('villageNewId')),\n field('Household_Village__c', dataValue('properties.village')),\n // relationship('Catchment__r', 'Name', state => {\n // var catchment =\n // state.data.properties.catchement ||\n // state.data.properties.catchment_name;\n // return catchment === '' || catchment === undefined\n // ? 'Unknown Location'\n // : catchment;\n // }), // check\n // field('Area__c', state => {\n // // var area = dataValue('properties.Area_Name')(state);\n // return area === '' || area === undefined ? 'a000Q00000Egmu4' : area;\n // }), // Commented out because it was causing a job error \n // field('Household_village__c', dataValue('properties.village')),//case property, but not in message\n \n // field('Village__c',dataValue('properties.village_name')), //lookup\n field('Deaths_in_the_last_6_months__c', state => {\n var death = dataValue(\n 'properties.deaths_in_past_6_months'\n )(state);\n return death > 0 ? 'Yes' : 'No';\n }),\n field('Access_to_safe_water__c',dataValue('properties.Safe_Water')),//not coming through\n field('Treats_Drinking_Water__c',dataValue('properties.Treats_Drinking_Water')),//not coming through\n field('Tippy_Tap__c',dataValue('properties.Active_Handwashing_Station')),//not coming through\n field('Pit_Latrine__c',dataValue('properties.Functional_Latrine')),//not coming through\n field('Rubbish_Pit__c',dataValue('properties.Rubbish_Pit')),//not coming through\n field('Drying_Rack__c',dataValue('properties.Drying_Rack')),//not coming through\n field('Kitchen_Garden__c',dataValue('properties.Kitchen_Garden')),//not coming through\n field('Cookstove__c',dataValue('properties.Improved_Cooking_Method')),//not coming through\n field('Clothe__c',dataValue('properties.Clothesline')),//not coming through\n field('WASH_Trained__c',dataValue('properties.WASH_Trained')),//not coming through\n field('Uses_ITNs__c',dataValue('properties.ITNs')),\n field(\n 'Has_muac_tape__c',\n dataValue('properties.family_muac_tape_available')\n ),\n //field('Total_household_people__c',dataValue('properties.Total_Number_of_Members')), //not coming through\n field('Health_insurance__c', dataValue('properties.health_insurace_cover')),\n field('Health_insurance_active_status__c',dataValue('properties.healthinsurance_active')),\n field('Health_insurance_type__c', state => {\n var status = dataValue('properties.health_insurance')(state);\n return status && status === 'other_please_specify_if_active'\n ? 'Other'\n : status === 'nhif'\n ? 'NHIF'\n : status === 'Linda_mama' || 'linda_mama'\n ? 'Linda mama'\n : status;\n }),\n field('Other_Health_Insurance__c',dataValue('properties.if_other_please_specify')),\n field('Work_with_TBA__c', dataValue('properties.tba')),\n field('TBA_name__c', dataValue('properties.which_tba')),\n field('Last_Modified_Date_CommCare__c', dataValue('server_date_modified')),//Need a case property),\n field('Active_Household__c', state => {\n var status = dataValue('properties.Household_Status')(state);\n return status && status === 'No'\n ? false\n : status === 'Yes'\n ? true\n : status;\n }),\n // relationship('Head_of_Household__r', 'CommCare_ID__c', dataValue('properties.head_of_household_case_id')),\n field('Inactive_Reason__c', state => {\n var reason = dataValue('properties.Reason_for_Inactive')(state);\n return reason ? reason.toString().replace(/_/g, ' ') : null;\n }),\n field(\n 'Active_in_Nutrition_Program__c',\n dataValue(\n 'properties.enrolled_in_a_lwala_nutrition_program'\n )\n ),\n field(\n 'lwala_nutrition_program_enrollment_date__c',\n dataValue(\n 'properties.lwala_nutrition_program_enrollment_date'\n )\n ),\n field(\n 'Trained_in_gardening__c',\n dataValue('properties.household_trained_on_gardening')\n ),\n field(\n 'household_trained_on_gardening_date__c',\n dataValue(\n 'properties.when_was_the_household_trained_on_gardening'\n )\n ),\n field(\n 'Seed_Input_Support__c',\n dataValue('properties.household_provided_with_seed_input_support'\n )\n ),\n field(\n 'household_provided_with_seed_input_suppo__c',\n dataValue(\n 'properties.when_was_the_household_provided_with_seed_input_support'\n )\n ),\n field(\n 'MIYCN_Trained__c',\n dataValue('properties.household_trained_on_MIYCN')\n ),\n // not in message:\n // field(\n // 'Kitchen_Garden__c',\n // dataValue('properties.nutrition_enrollment.household_has_kitchen_garden')\n // ),\n\n //field('Case_Closed_Date__c', state => {\n // var closed = dataValue('date_closed')(state); \n // var date = dataValue('server_date_modified')(state); \n // return closed && closed == true ? date : undefined; \n // })\n )\n);\n", + "adaptor": "@openfn/language-salesforce@latest", + "project_credential_id": null + } + }, + "edges": { + "webhook->Upsert-Household": { + "enabled": false, + "id": "02b0f03b-ec18-4bb0-938c-1bd20976c9f8", + "target_job_id": "e2b55c71-f59c-4edf-8e69-71ccb9d2e898", + "source_trigger_id": "1b7a2970-947a-4070-b90e-1605e4c02e0d", + "condition_type": "js_expression", + "condition_label": "Household", + "condition_expression": "state.data.properties[\"app_release\"] == \"Q2-2022\" && state.data.properties[\"case_type\"] == \"Household\" && state.data.properties[\"test_user\"] != \"Yes\"" + } + } + }, + "x-[archive]-Workflow-Update-Household-in-CommCare-V2": { + "id": "992286fe-73c8-405d-9ca0-2ffcc831b4d2", + "name": "x [archive] Workflow Update Household in CommCare V2", + "inserted_at": "2024-09-10T15:45:43.248771Z", + "lock_version": 3, + "triggers": { + "webhook": { + "enabled": false, + "id": "648c9529-c419-425e-b162-f237aca692a2", + "type": "webhook" + } + }, + "jobs": { + "Update-Household-in-CommCare-V2": { + "id": "1813b73d-26dc-49c3-8b11-53d1973e1246", + "name": "Update Household in CommCare V2", + "body": "submit(\n fields(\n field('@', state => {\n return {\n 'xmlns:jrm': 'http://dev.commcarehq.org/jr/xforms',\n xmlns: () => {\n return dataValue('new[0].Catchment__c')(state) == 'a001p000017gpfZAAQ'\n ? 'http://openrosa.org/formdesigner/7bdbfcc02fd44260837d799d24051449'\n : 'http://openrosa.org/formdesigner/980c10cdb3b140101225e25c6e8aff48f471b3d';\n },\n uiVersion: '1',\n version: '46',\n name: 'Update Household',\n };\n }),\n field('Source', 0),\n field('Household_Status', state => {\n var str = '';\n if (dataValue('new[0].Active_Household__c')(state) === false) {\n str = 'No';\n } else {\n str = 'Yes';\n }\n return str;\n }),\n field('Run_Code', 'Household_Lwala'),\n field('name', state => {\n var name = dataValue('new[0].Name')(state); \n var code = dataValue('new[0].Household_Code_Autonumber__c')(state);\n return name.length > 6 ? code : name; \n //return hh autonumber if name = sf id\n }),\n field('area', dataValue('new[0].Area__c')),\n\n field('Household_Information', state => {\n return {\n moh_code: dataValue('new[0].MOH_household_code__c')(state), //NEW\n Active_Handwashing_Station: dataValue('new[0].Tippy_Tap__c')(state),\n Drying_Rack: dataValue('new[0].Drying_Rack__c')(state),\n\n WASH_Compliant: () => {\n var ans = '';\n if (dataValue('new[0].WASH_Compliant__c')(state) === true) {\n ans = 'Yes';\n } else {\n ans = 'No';\n }\n return ans;\n },\n Functional_Latrine: dataValue('new[0].Pit_Latrine__c')(state),\n Clothesline: dataValue('new[0].Clothe__c')(state),\n ITNs: dataValue('new[0].Uses_ITNs__c')(state),\n Improved_Cooking_Method: dataValue('new[0].Cookstove__c')(state),\n Kitchen_Garden: dataValue('new[0].Kitchen_Garden__c')(state),\n Number_of_Over_5_Males: dataValue('new[0].Number_of_Over_5_Males__c')(\n state\n ),\n Number_of_Over_5_Females: dataValue(\n 'new[0].Number_of_Over_5_Females__c'\n )(state),\n Number_of_Under_5_Males: dataValue('new[0].Number_of_Under_5_Males__c')(\n state\n ),\n Number_of_Under_5_Females: dataValue(\n 'new[0].Number_of_Under_5_Females__c'\n )(state),\n Rubbish_Pit: dataValue('new[0].Rubbish_Pit__c')(state),\n Treats_Drinking_Water: dataValue('new[0].Treats_Drinking_Water__c')(\n state\n ),\n WASH_Trained: dataValue('new[0].WASH_Trained__c')(state),\n Total_Under_5: dataValue('new[0].Total_Number_of_Under_5s__c')(state),\n Total_Males: dataValue('new[0].Total_Number_of_Males__c')(state),\n Total_Females: dataValue('new[0].Total_Number_of_Females__c')(state),\n Total_Household_Members: dataValue('new[0].Total_Number_of_Members__c')(\n state\n ),\n Total_Number_of_Members: dataValue('Total_household_people__c')(state), //NEW\n Total_Over_5: () => {\n var num = 0;\n num =\n dataValue('new[0].Total_Number_of_Members__c')(state) -\n dataValue('new[0].Total_Number_of_Under_5s__c')(state);\n return num;\n },\n };\n }),\n field('n0:case', state => {\n return {\n '@': {\n case_id: dataValue('new[0].Commcare_Code__c')(state),\n date_modified: new Date().toISOString(),\n user_id: 'e298884bfb6ee2d2b38591a6e8ae0228',\n 'xmlns:n0': 'http://commcarehq.org/case/transaction/v2',\n },\n 'n0:update': {\n 'n0:case_name': () => {\n var name = dataValue('new[0].Name')(state); \n var code = dataValue('new[0].Household_Code_Autonumber__c')(state);\n return name.length > 6 ? code : name; \n //return hh autonumber if name = sf id\n },\n 'n0:owner_id': () => {\n var id = '';\n if (dataValue('new[0].chw_owner_id__c')(state) === undefined) {\n id = 'acf8595692c76095eb5afd809c628091';\n } else {\n id = dataValue('new[0].chw_owner_id__c')(state);\n }\n return id;\n },\n 'n0:case_type': 'Household',\n 'n0:WASH_Compliant': () => {\n var ans = '';\n if (dataValue('new[0].WASH_Compliant__c')(state) === true) {\n ans = 'Yes';\n } else {\n ans = 'No';\n }\n return ans;\n },\n 'n0:Active_Handwashing_Station': dataValue('new[0].Tippy_Tap__c')(\n state\n ),\n 'n0:Drying_Rack': dataValue('new[0].Drying_Rack__c')(state),\n 'n0:Functional_Latrine': dataValue('new[0].Pit_Latrine__c')(state),\n 'n0:Clothesline': dataValue('new[0].Clothe__c')(state),\n 'n0:ITNs': dataValue('new[0].Uses_ITNs__c')(state),\n 'n0:Active_in_Nutrition_Program': dataValue(\n 'new[0].Active_in_Nutrition_Program__c'\n )(state),\n 'n0:Nutrition_Group': dataValue('new[0].Nutrition_Group__c')(state),\n 'n0:seed_input_support': dataValue('new[0].Seed_Input_Support__c')(\n state\n ),\n 'n0:name_concat': dataValue('new[0].Household_Code_Autonumber__c')(state),\n 'n0:CHW_ID': dataValue('new[0].Household_CHW__c')(state),\n 'n0:Improved_Cooking_Method': dataValue('new[0].Cookstove__c')(state),\n 'n0:Kitchen_Garden': dataValue('new[0].Kitchen_Garden__c')(state),\n 'n0:Number_of_Over_5_Males': dataValue(\n 'new[0].Number_of_Over_5_Males__c'\n )(state),\n 'n0:Number_of_Over_5_Females': dataValue(\n 'new[0].Number_of_Over_5_Females__c'\n )(state),\n 'n0:Number_of_Under_5_Males': dataValue(\n 'new[0].Number_of_Under_5_Males__c'\n )(state),\n 'n0:Number_of_Under_5_Females': dataValue(\n 'new[0].Number_of_Under_5_Females__c'\n )(state),\n 'n0:Rubbish_Pit': dataValue('new[0].Rubbish_Pit__c')(state),\n 'n0:Treats_Drinking_Water': dataValue(\n 'new[0].Treats_Drinking_Water__c'\n )(state),\n 'n0:WASH_Trained': dataValue('new[0].WASH_Trained__c')(state),\n 'n0:Total_Under_5': dataValue('new[0].Total_Number_of_Under_5s__c')(\n state\n ),\n 'n0:Total_Males': dataValue('new[0].Total_Number_of_Males__c')(state),\n 'n0:Total_Females': dataValue('new[0].Total_Number_of_Females__c')(\n state\n ),\n 'n0:area': dataValue('new[0].Area__c')(state),\n 'n0:Area_Name': dataValue('new[0].Area_Name__c')(state),\n 'n0:Total_Household_Members': dataValue(\n 'new[0].Total_Number_of_Members__c'\n )(state),\n Total_Number_of_Members: dataValue('new[0].Total_household_people__c')(\n state\n ), //NEW\n 'n0:Household_Status': () => {\n var str = '';\n if (dataValue('new[0].Active_Household__c')(state) === false) {\n str = 'No';\n } else {\n str = 'Yes';\n }\n return str;\n },\n 'n0:Total_Over_5': () => {\n var num = 0;\n num =\n dataValue('new[0].Total_Number_of_Members__c')(state) -\n dataValue('new[0].Total_Number_of_Under_5s__c')(state);\n return num;\n },\n },\n 'n0:index': {\n 'n0:parent': {\n '@': {\n case_type: 'Area',\n },\n '#': dataValue('new[0].Area_Case_ID__c')(state),\n },\n },\n };\n }),\n field('n1:meta', state => {\n return {\n '@': { 'xmlns:n1': 'http://openrosa.org/jr/xforms' },\n 'n1:deviceID': 'Formplayer',\n 'n1:timeStart': new Date().toISOString(),\n 'n1:timeEnd': new Date().toISOString(),\n 'n1:userID': 'e298884bfb6ee2d2b38591a6e8ae0228',\n };\n })\n )\n);\n", + "adaptor": "@openfn/language-commcare@latest", + "project_credential_id": null + } + }, + "edges": { + "webhook->Update-Household-in-CommCare-V2": { + "enabled": false, + "id": "69ecf485-3cab-4c16-9ec0-2c96d724c1f2", + "target_job_id": "1813b73d-26dc-49c3-8b11-53d1973e1246", + "source_trigger_id": "648c9529-c419-425e-b162-f237aca692a2", + "condition_type": "js_expression", + "condition_label": "SF Update HH", + "condition_expression": "state.data.label == \"Update Household\"" + } + } + }, + "x-[archive]-Workflow-Test-Service-Upsert": { + "id": "8e6351c7-63e0-4911-a97d-2ef1b528667b", + "name": "x [archive] Workflow Test Service Upsert", + "inserted_at": "2024-09-10T15:45:43.258964Z", + "lock_version": 3, + "triggers": { + "webhook": { + "enabled": false, + "id": "f780b737-5714-486f-af2b-7481fa1a8234", + "type": "webhook" + } + }, + "jobs": { + "Test-Service-Upsert": { + "id": "46f1ac91-088d-413a-8058-2c56a7a23c88", + "name": "Test Service Upsert", + "body": "upsert('Service__c', 'Service_UID__c', \n fields(\n relationship('Parent_Service__r',\n 'Service_UID__c',\n dataValue('indices.parent.case_id')),\n field('Service_UID__c', dataValue('case_id'))\n)); \n", + "adaptor": "@openfn/language-salesforce@v2.7.4", + "project_credential_id": null + } + }, + "edges": { + "webhook->Test-Service-Upsert": { + "enabled": false, + "id": "055a08dd-42f4-4588-b731-744fca89463e", + "target_job_id": "46f1ac91-088d-413a-8058-2c56a7a23c88", + "source_trigger_id": "f780b737-5714-486f-af2b-7481fa1a8234", + "condition_type": "js_expression", + "condition_label": "Case", + "condition_expression": "state.data.properties[\"case_type\"] == \"Case\" && state.data.properties[\"test_user\"] != \"Yes\"" + } + } + }, + "Referrals-Upsert-Service-in-SF-V2-[Q3-2022]-(private)": { + "id": "80adfd30-caf0-4d07-a0f3-d7b023acc442", + "name": "Referrals Upsert Service in SF V2 [Q3 2022] (private)", + "inserted_at": "2025-01-21T09:09:49.954361Z", + "lock_version": 4, + "triggers": { + "webhook": { + "enabled": true, + "id": "1babf313-9222-41dd-a89a-4447b251b570", + "type": "webhook" + } + }, + "jobs": { + "Q3-2022-Referrals-Upsert-Service-in-SF-V2": { + "id": "dd5e971e-05c8-42e4-a08c-1daf6ecbc55c", + "name": "Q3 2022 Referrals Upsert Service in SF V2", + "body": "// NOTE: We perform a query before anything else if this is a 'Case'\nfn(state => {\n state.type = state.data.indices.parent.case_type;\n\n if (state.type === 'Case')\n return query(\n `SELECT Person__r.CommCare_ID__c FROM Service__c WHERE Service_UID__c = '${state.data.indices.parent.case_id}'`\n )(state).then(state => {\n const { records } = state.references[0];\n const ccId =\n records.length == 1 ? records[0].Person__r.CommCare_ID__c : null;\n return { ...state, ccId };\n });\n\n return state;\n});\n\n// NOTE: We construct a facilityMap and populate some conditional relationships\nfn(state => {\n const facilityMap = {\n Lwala_Hospital: 'Lwala Hospital',\n Minyenya_Dispensary: 'Minyenya Dispensary',\n Ndege_Oriedo_Dispensary: 'Ndege Oriedo Dispensary',\n 'Rongo_Sub-District_Hospital': 'Rongo Sub-District Hospital',\n Kangeso_Dispensary: 'Kangeso Dispensary',\n Ngodhe_Dispensary: 'Ngodhe Dispensary',\n Ngere_Dispensary: 'Ngere Dispensary',\n Verna_Health_Center: 'Verna Health Center',\n Kochola_Dispensary: 'Kochola Dispensary',\n Ongo_Health_Center: 'Ongo Health Center',\n Royal_Medical_Center: 'Royal Medical Center',\n Rosewood_Facility: 'Rosewood Facility',\n Other: 'Other',\n };\n\n const pregDangerMap = {\n Vaginal_Bleeding: 'Vaginal Bleeding',\n Water_Breaks: 'Water Breaks before Time of Delivery',\n Prolonged_Labour: 'Prolonged Labour over 12 Hours',\n Convulsions: 'Convulsions or Fits',\n Abdominal_Pain: 'Severe Abdominal Pain before Delivery',\n High_Fever: 'High Fever',\n Low_Baby_Movement: 'Feeling the Baby move less or not at all',\n Swelling: 'Swelling of Face and Hands',\n Severe_Headache: 'Severe or Continuous Headache for more than 12 hours',\n Severe_Vomiting: 'Severe or Continuous Vomiting',\n none: 'None',\n };\n\n const serviceMap = {\n Scheduled_PSC_Apt: 'Scheduled PSC Apt',\n Adverse_Drug_Reaction_Side_Effect: 'Adverse Drug Reaction/Side Effect',\n Malnutrition: 'Malnutrition',\n Malaria: 'Malaria',\n TB: 'TB',\n Treatment_for_Other_OIs: 'Treatment for Other OIs',\n ARI: 'ARI',\n Anemia: 'Anemia',\n Diarrhea: 'Diarrhea',\n Pregnancy_Care: 'Pregnancy Care (ANC)',\n Family_Planning: 'Family Planning (FP)',\n Preconception_Counseling: 'Preconception Counseling',\n Injury: 'Injury',\n Other: 'Other',\n };\n\n const milestoneTypeMap = {\n cognitive_delays_learning_difficulties:\n 'Cognitive Delays (Learning Difficulties)',\n motor_delays: 'Motor Delays',\n speech_and_language_delay: 'Speech and language Delay',\n social_and_emotional: 'Social and emotional',\n };\n\n const symptomsMap = {\n convulsions: 'Convulsions',\n not_able_to_eatdrink: 'Not able to eat/drink',\n vomits_everything: 'Vomits everything',\n 'chest_in-drawing': 'Chest in-drawing',\n unusually_sleepyunconscious: 'Unusually sleepy/unconscious',\n swelling_of_both_feet: 'Swelling of both feet',\n };\n\n const childSignMap = {\n Poor_Breastfeeding: 'Poor Breastfeeding (under 6 months old child)',\n not_able_to_feed_since_birth_or_stopped_feeding_well:\n 'Not able to feed since birth, or stopped feeding well',\n not_able_to_breastfeed: 'Not able to breastfeed',\n Fever: 'Fever (37.5 C or more)',\n very_low_temperature: 'Very low temperature (35.4 C or less)',\n shivering: 'Shivering',\n Fast_Breathing: 'Fast Breathing',\n Very_Sleepy: 'Very Sleepy',\n Convulsions_and_Fits: 'Convulsions and Fits',\n only_moves_when_stimulated_or_does_not_move_even_on_stimulation:\n 'Only moves when stimulated, or does not move even on stimulation',\n yellow_solebaby_body_turning_yellow_especially_eyes_palms_soles:\n 'Yellow sole(Baby body turning yellow especially eyes, palms, soles)',\n bleeding_from_the_umbilical_stump: 'Bleeding from the umbilical stump',\n signs_of_local_infection_umbilicus_is_red_or_draining_pus_skin_boils_or_eye:\n 'Signs of local infection: umbilicus is red or draining pus, skin boils, or eyes draining pus',\n weight_chart_using_color_coded_scales_if_red_or_yellowweight_below_25kg_or_:\n 'Weight chart using color coded scales if RED or YELLOW(Weight below 2.5kg or born less than 36 weeks of age)',\n unable_to_cry: 'Unable to cry',\n cyanosis: 'Cyanosis',\n bulging_fontanelle: 'Bulging fontanelle',\n };\n\n const otherReferralMap = {\n HIV_Testing_and_Counseling: 'HIV Testing and Counseling',\n Visit_to_Clinician: 'Visit to Clinician',\n Adverse_Drug_Reaction_Side_Effect: 'Adverse Drug Reaction Side Effect',\n Malnutrition: 'Malnutrition',\n Malaria: 'Malaria',\n PMTCT: 'PMTCT',\n TB: 'TB',\n Treatment_for_other_OIs: 'Treatment for other OIs',\n ARI: 'ARI',\n Anemia: 'Anemia',\n Diarrhea: 'Diarrhea',\n Pregnancy_Care_ANCE: 'Pregnancy Care (ANC)',\n Family_Planning_FP: 'Family Planning (FP)',\n Preconception_Counseling: 'Preconception Counseling',\n Injury: 'Injury',\n blood_in_stool: 'Blood in Stool',\n Blood_in_Stool: 'Blood in Stool',\n Immunization: 'Immunization',\n Routine_Health_Check_ups: 'Routine Health Check ups',\n routine_health_check_ups: 'Routine Health Check ups',\n Other: 'Other',\n Poor_Breastfeeding: 'Poor Breastfeeding (under 6 months old child)',\n not_able_to_feed_since_birth_or_stopped_feeding_well:\n 'Not able to feed since birth, or stopped feeding well',\n not_able_to_breastfeed: 'Not able to breastfeed',\n Fever: 'Fever (37.5 C or more)',\n very_low_temperature: 'Very low temperature (35.4 C or less)',\n shivering: 'Shivering',\n Fast_Breathing: 'Fast Breathing',\n Very_Sleepy: 'Very Sleepy',\n Convulsions_and_Fits: 'Convulsions and Fits',\n only_moves_when_stimulated_or_does_not_move_even_on_stimulation:\n 'Only moves when stimulated, or does not move even on stimulation',\n yellow_solebaby_body_turning_yellow_especially_eyes_palms_soles:\n 'Yellow sole(Baby body turning yellow especially eyes, palms, soles)',\n bleeding_from_the_umbilical_stump: 'Bleeding from the umbilical stump',\n signs_of_local_infection_umbilicus_is_red_or_draining_pus_skin_boils_or_eye:\n 'Signs of local infection: umbilicus is red or draining pus, skin boils, or eyes draining pus',\n weight_chart_using_color_coded_scales_if_red_or_yellowweight_below_25kg_or_:\n 'Weight chart using color coded scales if RED or YELLOW(Weight below 2.5kg or born less than 36 weeks of age)',\n unable_to_cry: 'Unable to cry',\n cyanosis: 'Cyanosis',\n bulging_fontanelle: 'Bulging fontanelle',\n };\n\n const homeCareMap = {\n Adherence_Counseling: 'Adherence Counseling',\n Pill_Count_Monitoring: 'Pill Count Monitoring',\n Nutrition_Assessment_and_Counseling: 'Nutrition Assessment and Counseling',\n WASH_Counseling: 'WASH Counseling',\n Prevention_Counseling: 'Prevention Counseling',\n Psychosocial_Support: 'Psychosocial Support',\n Provision_of_Supplies: 'Provision of Supplies',\n OI_Management_Support: 'OI Management Support',\n };\n \n const ecdMap = {\n physiotherapy: 'Physiotherapy',\n speech_therapy: 'Speech Therapy',\n nutrition_education: 'Nutrition Education',\n play_therapy: 'Play Therapy',\n assessment: 'Assessment',\n counselling: 'Counselling',\n other: 'Other'\n };\n\n const clinicalMap = {\n diarrhea: 'Diarrhea',\n malnutrition: 'Malnutrition',\n malaria: 'Malaria',\n acute_respiratory_infection: 'Acute Respiratoy Infection (ARI)',\n accident_injury: 'Accident/Injury',\n other: 'Other',\n };\n\n let relationships = [];\n\n // If it's a person, add the person relationship\n if (state.type === 'Person') {\n relationships.push(\n relationship(\n 'Person__r',\n 'CommCare_ID__c',\n state.data.indices.parent.case_id\n )\n );\n }\n\n // If it's a service, add the service rship AND a different person rship\n if (state.type === 'Case') {\n relationships.push(\n relationship(\n 'Parent_Service__r',\n 'Service_UID__c',\n state.data.indices.parent.case_id\n )\n );\n relationships.push(relationship('Person__r', 'CommCare_ID__c', state.ccId));\n }\n\n return {\n ...state,\n facilityMap,\n relationships,\n serviceMap,\n pregDangerMap,\n milestoneTypeMap,\n symptomsMap,\n childSignMap,\n otherReferralMap,\n homeCareMap,\n clinicalMap,\n ecdMap\n };\n});\n\n// NOTE: We finally upsert to the Service__c object in Salesforce\nupsertIf(\n state.data.properties.owner_id !== '8e725928e3ce43d19b390dd604097069',\n'Service__c', 'Service_UID__c', state => ({\n ...fields(...state.relationships),\n ...fields(\n field('Service_UID__c', dataValue('case_id')),\n field('CommCare_Code__c', dataValue('case_id')),\n field('RecordTypeID', '01224000000YAuK'),\n //field('Household_CHW__c', 'a030Q000008XyXV'), //Sandbox MOTG test CHW\n // relationship( //ADD BACK BEFORE PROD DEPLOYMENT; removed for sandbox testing\n // 'Household_CHW__r',\n // 'CommCare_ID__c',\n // dataValue('properties.CHW_ID')\n // ),\n field('Open_Case__c', state => {\n var status = dataValue('closed')(state);\n return status === false ? true : false;\n }),\n field('Case_Closed_Date__c',dataValue('date_closed')),\n field('Age_Time_of_Service__c', dataValue('properties.age')),\n field('Source__c', dataValue('properties.Source') === '1'),\n field('Clinical_facility__c', state => {\n var facility = dataValue('properties.Facility_Visited')(state);\n return facility ? state.facilityMap[facility] : undefined;\n }),\n field('Client_Received_Services_at_Facility2__c',dataValue('properties.Facility_Visit')),\n field('Clinical_Visit_Date__c', state => {\n var date = dataValue('properties.Facility_Date')(state);\n return date === '' || date === undefined ? undefined : date;\n }),\n field(\n 'CHW_Followed_Up_with_the_Client__c',\n dataValue('properties.Follow-Up')\n ),\n field('Follow_Up_Date__c', dataValue('properties.Follow-Up_Date')),\n field(\n 'Person_Complied_w_Referral_in_24_hrs__c',\n dataValue('properties.referral_compliance')\n ),\n field('Skillled_Delivery__c', dataValue('properties.skilled_delivery')),\n field(\n 'Child_received_immunizations__c',\n dataValue('properties.immunization')\n ),\n field(\n 'Received_a_diagnosis_for_PSBI__c',\n dataValue('properties.psbi_diagnosis') //CHW.Follow-Up.PSBI.psbi_diagnosis\n ),\n field(\n 'Received_antibiotics_per_protocol__c',\n dataValue('properties.antibiotic_8days') //CHW.Follow-Up.PSBI.antibiotic_8day\n ),\n field(\n 'Distributed_Treatment_on_Last_Visit__c',\n dataValue('properties.distribute_treatment') //CHW.Follow-Up.distribute_treatment\n ),\n field(\n 'Person_had_an_adverse_drug_reaction__c',\n dataValue('properties.adverse_drug_reaction')\n ),\n field('Defaulted__c', state => {\n var date = dataValue('properties.date_of_default')(state);\n return date && date !== '' ? true : false;\n }),\n field('Date_of_Default__c', dataValue('properties.date_of_default')),\n field(\n 'Client_s_Symptoms_Improved__c',\n dataValue('properties.Client_Improved')\n ),\n field('Case_Type__c', dataValue('properties.Case_Type')),\n field('Follow_Up_By_Date__c', state => {\n var date = dataValue('properties.Follow-Up_By_Date')(state);\n return date && date !== '' ? date : undefined;\n }),\n field('Date__c', state =>\n new Date(state.data.properties.date_opened).toISOString()\n ),\n field('Reason_for_Service__c', dataValue('properties.Reason_for_Service')),\n field('Type_of_Service__c', dataValue('properties.Type_of_Service')),\n field('Malaria_Status__c', dataValue('properties.Malaria_Status')),\n field(\n 'Home_Treatment_Date__c',\n dataValue('properties.home_treatment_date')\n ),\n field(\n 'Malaria_Home_Test_Date__c',\n dataValue('properties.malaria_test_date')\n ),\n field('Home_ORS__c', dataValue('properties.clinic_ors')),\n field('Home_Zinc__c', dataValue('properties.clinic_zinc')),\n field('Height__c', dataValue('properties.height')),\n field('Weight__c', dataValue('properties.weight')),\n field('MUAC__c', dataValue('properties.muac')),\n field('Nutrition_Status__c', dataValue('properties.Nutrition_Status')),\n //===== NEW MAPPINGS - JAN 14 ===========================//\n field('Pregnancy_Danger_Signs__c', state => {\n var check = dataValue('properties.pregnancy_danger_signs')(state);\n var value =\n check && check !== ''\n ? check\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return state.pregDangerMap[value] || value;\n })\n : undefined;\n return value ? value.join(';') : undefined;\n }),\n field('Child_Danger_Signs__c', state => {\n var check = dataValue('properties.Other_Danger_Signs')(state);\n var value =\n check && check !== ''\n ? check\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return state.childSignMap[value] || value;\n })\n : undefined;\n return value ? value.join(';') : undefined;\n }),\n field('Delayed_Milestone__c', state => {\n var check = dataValue('properties.which_delayed_milestone')(state);\n var value =\n check && check !== ''\n ? check\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return state.milestoneTypeMap[value] || value;\n })\n : undefined;\n return value ? value.join(';') : undefined;\n }),\n field('Serious_Symptoms__c', state => {\n var check = dataValue('properties.symptoms_check_other')(state);\n var value =\n check && check !== ''\n ? check\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return state.symptomsMap[value] || value;\n })\n : undefined;\n return value ? value.join(';') : undefined;\n }),\n field('Other_Referral_Reasons__c', state => {\n var check = dataValue('properties.Other_Referral_Reasons')(state);\n var value =\n check && check !== ''\n ? check\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return state.otherReferralMap[value] || value;\n })\n : undefined;\n return value ? value.join(';') : undefined;\n }),\n field('Home_Based_Care_Rendered__c', state => {\n var check = dataValue('properties.Home_Based_Care_Provided')(state);\n var value =\n check && check !== ''\n ? check\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return state.homeCareMap[value] || value;\n })\n : undefined;\n return value ? value.join(';') : undefined;\n }),\n field('PSBI_Visit__c', state => {\n var number = dataValue('properties.psbi_task')(state);\n return number && number !== '' ? `Day ${number}` : undefined; //sample output: 'Day 3'\n }),\n field('Clinical_Services__c', state => {\n var check = dataValue('properties.TT5_Clinical_Service')(state);\n return check ? state.clinicalMap[check] : check;\n }),\n field('Referred_Facility__c', state => {\n var check = dataValue('properties.referred_facility')(state);\n return check ? state.facilityMap[check] : check;\n }),\n field('HAWI_Clinical_Services__c', state => {\n var check = dataValue('properties.HAWI_Clinical_Service')(state);\n return check ? state.serviceMap[check] : check;\n }),\n field('ECD_Clinical_Services__c', state => {\n var check = dataValue('properties.ECD_Clinical_Service')(state);\n var value =\n check && check !== ''\n ? check\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return state.ecdMap[value] || value;\n })\n : undefined;\n return value ? value.join(';') : undefined;\n }),\n //=====================================//\n ),\n}));\n", + "adaptor": "@openfn/language-salesforce@4.8.6", + "project_credential_id": "96a3843d-5d9c-4f03-8289-508b87901c9b" + } + }, + "edges": { + "webhook->Q3-2022-Referrals-Upsert-Service-in-SF-V2": { + "enabled": true, + "id": "f8194bf2-d17d-43fc-b096-b1d2c00ebfb4", + "target_job_id": "dd5e971e-05c8-42e4-a08c-1daf6ecbc55c", + "source_trigger_id": "1babf313-9222-41dd-a89a-4447b251b570", + "condition_type": "js_expression", + "condition_label": "\"Case\" task update ", + "condition_expression": "state.data.properties[\"case_type\"] == \"Case\" && state.data.properties[\"test_user\"] != \"Yes\"" + } + } + }, + "Create-Distribution-and-Referral-in-SF-[Q3-2022]": { + "id": "dc2e0bca-0649-4dca-b248-1d09f795d2be", + "name": "Create Distribution and Referral in SF [Q3 2022]", + "inserted_at": "2025-01-31T12:33:05.614938Z", + "lock_version": 5, + "triggers": { + "webhook": { + "enabled": true, + "id": "27fc87e9-9b1c-45a5-82b5-199dd65f7a84", + "type": "webhook" + } + }, + "jobs": { + "Q3-2022-Create-Distribution-and-Referral-in-SF": { + "id": "7d468879-4c21-48a8-9a41-6b850e6ce853", + "name": "Q3 2022 Create Distribution and Referral in SF", + "body": "//Job to integrate CommCare 'Distribution & Referrals' form\nupsert(\n 'Family_Planning_community_Distribution__c',\n 'Commcare_Case_ID__c',\n fields(\n field('Commcare_Case_ID__c', dataValue('id')),\n relationship('RecordType', 'Name', 'FP Community Distribution & Referrals'),\n field('Distribute_Date__c', dataValue('form.date')),\n field('Client_Name__c', dataValue('form.name')),\n field('Client_Gender__c', dataValue('form.gender')),\n field('Client_Age__c', dataValue('form.age')),\n field('Client_currently_on_FP__c', dataValue('form.current_use')),\n field('Referral_Date__c', dataValue('form.Referral_Date')),\n field('Referral_Method__c', state => {\n var method = dataValue('form.referral_method')(state);\n var newMethod = method\n ? method\n .split(/_/g)\n .map(\n word =>\n `${word.substring(0, 1).toUpperCase()}${word.substring(1)}`\n )\n .join(' ')\n : '';\n return newMethod;\n }),\n field('Implant_Type__c', state => {\n var type = dataValue('form.implant_type')(state);\n var newType = '';\n if (type) {\n if (type === 'implanon') {\n newType = '3-year Implanon';\n } else {\n newType = type === 'jadelle' ? '5-year Jadelle' : null;\n }\n }\n return newType;\n }),\n field('Male_Condoms__c', dataValue('form.male_condoms_count')),\n field('Female_Condoms__c', dataValue('form.female_condoms_count')),\n field('POP__c', dataValue('form.POP_count')),\n field('COC__c', dataValue('form.COC_count')),\n field('Emergency_Pills__c', dataValue('form.emergency_pills_count')),\n field(\n 'Pregnancy_test_positive__c',\n dataValue('form.positive_pregnancy_tests')\n ),\n field('Pregnancy_referrals__c', dataValue('form.pregnancy_referrals')),\n field(\n 'Contraception_referrals__c',\n dataValue('form.family_planning_referrals')\n )\n )\n);\n", + "adaptor": "@openfn/language-salesforce@4.8.6", + "project_credential_id": "25ba06d8-5559-4d1c-a8b8-828cc3021465" + } + }, + "edges": { + "webhook->Q3-2022-Create-Distribution-and-Referral-in-SF": { + "enabled": true, + "id": "67492a7e-8f78-4308-a4e0-b2f5dec8de82", + "target_job_id": "7d468879-4c21-48a8-9a41-6b850e6ce853", + "source_trigger_id": "27fc87e9-9b1c-45a5-82b5-199dd65f7a84", + "condition_type": "js_expression", + "condition_label": "CommCare Distribution & Referral form submitted", + "condition_expression": "state.data.form[\"@name\"] == \"Distribution and Referrals\" && state.data.form[\"test_user\"] != \"Yes\"" + } + } + }, + "Upsert-Supervision---Household-Spot-Check-[Q4-2022]": { + "id": "b430c682-3ce8-4120-b460-8984c418c1ac", + "name": "Upsert Supervision - Household Spot Check [Q4 2022]", + "inserted_at": "2025-01-31T12:34:27.426612Z", + "lock_version": 4, + "triggers": { + "webhook": { + "enabled": true, + "id": "daa22cef-92ab-4891-967e-f1eda8b3e61e", + "type": "webhook" + } + }, + "jobs": { + "Q4-2022-Upsert-Supervision---Household-Spot-Check": { + "id": "81ebc9c1-6c59-49e9-8b4c-532ed48aae94", + "name": "Q4 2022 Upsert Supervision - Household Spot Check", + "body": "//Job to integrate CommCare 'Household Spotcheck' form from the Supervision App\nfn(state => {\nstate.handleMultiSelect = function (state, multiField) {\n return multiField\n ? multiField\n .replace(/ /g, ';')\n : '';\n };\n return {\n ...state\n };\n});\n\n\nupsert(\n 'Supervision_Forms__c',\n 'CommCare_Form_ID__c',\n fields(\n field('CommCare_Form_ID__c', dataValue('id')),\n relationship('RecordType', 'Name', 'Household Spotcheck Form'),\n // relationship('Household_Code__r', \n //'Name',\n //dataValue('form.prologue.hh_code')\n // ),\n field('Supervisor_Name__c', dataValue('form.prologue.spot_checker_sfid')),\n field('CHW_Name__c', dataValue('form.prologue.chw_sfid')),\n relationship(\n 'Village__r',\n 'CommCare_User_ID__c',\n dataValue('form.prologue.village')\n ),\n relationship('Catchment__r', \n 'Name',\n dataValue('form.prologue.catchment')\n ),\n field('Form_Date__c',dataValue('form.Date')),\n field('CHW_Name_Identified__c',dataValue('form.chw_awareness.chw_name_reported')),\n field('Knows_where_CHW_lives__c',dataValue('form.chw_awareness.chw_location_confirmation')),\n field('Knows_CHW_contact_number__c',dataValue('form.chw_awareness.chw_contact_number')),\n field('CHW_paid_for_services__c',dataValue('form.chw_awareness.service_fee')),\n field('CHW_Visit_Frequency__c',dataValue('form.chw_awareness.chw_visit_frequency')),\n field('Household_member_reported_fever__c',dataValue('form.iccm.fever_management')),\n field('details_on_chw_conduct__c',dataValue('form.chw_behavior.chw_conduct_detail')),\n field('Tablet_used__c',dataValue('form.chw_behavior.tablet_use_check')),\n field('Other_Recommendations__c',dataValue('form.community_comments.community_recommendations_detail')),\n field('Other_comments__c',dataValue('form.community_comments.do_you_have_any_other_comments_at_this_time')),\n field('CHW_tested_treated_child_for_malaria__c',dataValue('form.iccm.malaria_management')),\n field('If_so_when_Within_the__c',dataValue('form.iccm.malaria_management_timeline')),\n field('CHW_ever_managed_your_child_for_diarrhea__c',dataValue('form.iccm.diarrhea_management')),\n field('CHW_measured_child_s_arm_past_90_days__c',dataValue('form.iccm.muac_check')),\n field('CHW_ever_managed_child_for__c',dataValue('form.iccm.pneumonia_management')),\n field('rate_the_quality_of_services__c',dataValue('form.iccm.chw_service_quality')),\n field('CHW_revisit__c',dataValue('form.referrals_and_follow-up_visits.follow_up_check_1')),\n field('follow_up_within_3_days_of_initial_visit__c',dataValue('form.referrals_and_follow-up_visits.follow_up_check_2')),\n field('does_CHW_revisit_child_for_follow_up__c',dataValue('form.referrals_and_follow-up_visits.follow_up_check_3')),\n field('when_child_is_sick__c',dataValue('form.referrals_and_follow-up_visits.follow_up_check_4')),\n field('CHW_conduct__c',dataValue('form.chw_behavior.chw_conduct_check')),\n field('comfortable_sharing_sensitive_info__c',dataValue('form.chw_behavior.sensitive_info_check')),\n field('Please_explain__c',dataValue('form.chw_behavior.sensitive_info_detail')),\n field('Does_your_CHW_listen_to_your_perspective__c',dataValue('form.chw_behavior.listening_check')),\n field('ever_experienced_a_problem_with_CHW__c', dataValue('form.chw_behavior.problem_check')),\n field('describe_problem_experienced_with_CHW__c',dataValue('form.chw_behavior.problem_detail')),\n field('any_recommendations_for_impr__c',dataValue('form.community_comments.community_recommendations')),\n field('How_was_the_fever_managed__c', state => {\n var choice = dataValue(\n 'form.iccm.fever_management_detail'\n )(state);\n return state.handleMultiSelect(state, choice);\n }),\n field('How_was_the_malaria_managed__c', state => {\n var choice = dataValue(\n 'form.iccm.malaria_management_detail'\n )(state);\n return state.handleMultiSelect(state, choice);\n }),\n field('How_did_she_he_manage_the_diarrhea__c', state => {\n var choice = dataValue(\n 'form.iccm.malaria_management_detail'\n )(state);\n return state.handleMultiSelect(state, choice);\n }),\n field('How_did_she_he_manage_the_pneumonia__c', state => {\n var choice = dataValue(\n 'form.iccm.pneumonia_managemnt_detail'\n )(state);\n return state.handleMultiSelect(state, choice);\n }),\n field('COHORT_ONE_Maternal_and_Child_Health__c', state => {\n var choice = dataValue(\n 'form.chw_service_provision.cohort_one'\n )(state);\n return state.handleMultiSelect(state, choice);\n }),\n field('COHORT_TWO_Childcare__c', state => {\n var choice = dataValue(\n 'form.chw_service_provision.cohort_two'\n )(state);\n return state.handleMultiSelect(state, choice);\n }),\n field('COHORT_THREE_WASH_and_Nutrition__c', state => {\n var choice = dataValue(\n 'form.chw_service_provision.cohort_three'\n )(state);\n return state.handleMultiSelect(state, choice);\n }),\n field('COHORT_FOUR_FIVE_Sexual_Reproductive__c', state => {\n var choice = dataValue(\n 'form.chw_service_provision.cohort_four_-_five'\n )(state);\n return state.handleMultiSelect(state, choice);\n }),\n )\n); \n\nupsertIf(\n state.data.form.prologue.hh_code !== '' &&\n state.data.form.prologue.hh_code !== null,\n 'Supervision_Forms__c',\n 'CommCare_Form_ID__c',\n relationship('Household_Code__r', \n 'Name',\n dataValue('form.prologue.hh_code')\n )\n );\n", + "adaptor": "@openfn/language-salesforce@4.8.6", + "project_credential_id": "25ba06d8-5559-4d1c-a8b8-828cc3021465" + } + }, + "edges": { + "webhook->Q4-2022-Upsert-Supervision---Household-Spot-Check": { + "enabled": true, + "id": "3e2cab0f-84f2-48bc-9e24-e5b83d152507", + "target_job_id": "81ebc9c1-6c59-49e9-8b4c-532ed48aae94", + "source_trigger_id": "daa22cef-92ab-4891-967e-f1eda8b3e61e", + "condition_type": "js_expression", + "condition_label": "Supervision - Household Spotcheck - Form", + "condition_expression": "state.data.form[\"@name\"] == \"Household Spotcheck Form \" && state.data.properties[\"test_user\"] != \"Yes\"" + } + } + }, + "Upsert-Supervision---Feedback-[Q4-2022]": { + "id": "52d4ff08-a7cd-41a2-8106-179d58dc2f6d", + "name": "Upsert Supervision - Feedback [Q4 2022]", + "inserted_at": "2025-01-31T12:34:42.239972Z", + "lock_version": 4, + "triggers": { + "webhook": { + "enabled": true, + "id": "4359f456-3781-4d2e-a9b1-333f17db3fe7", + "type": "webhook" + } + }, + "jobs": { + "Q4-2022-Upsert-Supervision---Feedback": { + "id": "438c20c3-c913-4025-b37b-9d093d55b908", + "name": "Q4 2022 Upsert Supervision - Feedback", + "body": "//Job to integrate CommCare 'Feedback' form from the Supervision App\n\nupsert(\n 'Supervision_Forms__c',\n 'CommCare_Form_ID__c',\n fields(\n field('CommCare_Form_ID__c', dataValue('id')),\n relationship('RecordType', 'Name', 'Feedback Form'),\n field('Supervisor_Name__c', dataValue('form.prologue.supervisor_sfid')),\n field('CHW_Name__c', dataValue('form.prologue.chw_sfid')),\n relationship(\n 'Village__r',\n 'CommCare_User_ID__c',\n dataValue('form.prologue.chw_village')\n ),\n relationship('Catchment__r', \n 'Name',\n dataValue('form.prologue.catchment')\n ),\n field('Form_Date__c',dataValue('form.Date')),\n field('Strengths__c', dataValue('form.chw_perspectives_and_reflections.chw_strengths')),\n field('Weaknesses__c', dataValue('form.chw_perspectives_and_reflections.chw_improvement_areas')), \n field('Challenges__c', dataValue('form.chw_perspectives_and_reflections.chw_challenges')),\n field('Solutions__c', dataValue('form.chw_perspectives_and_reflections.chw_improvement_areas')),\n field('of_Household_Visit_As_Expected__c', dataValue('form.supervision_dashboard_feedback.hh_visits_check')),\n field('of_Household_Visit_Explanation__c',dataValue('form.supervision_dashboard_feedback.hh_visits_explanation')),\n field('of_Priority_Clients_as_Expected__c', dataValue('form.supervision_dashboard_feedback.priority_hh_visits_check')),\n field('of_Priority_Clients_Explanation__c',dataValue('form.supervision_dashboard_feedback.priority_hh_visits_explanation')),\n field('Feedback_on_Indicators__c',dataValue('form.supervision_dashboard_feedback.chw_sd_feedback')),\n field('CHW_Strengths__c',dataValue('form.supervisor_perspectives_and_reflections.chw_strengths_supervisor')),\n field('CHW_Areas_for_Improvement__c',dataValue('form.supervisor_perspectives_and_reflections.chw_improvement_areas_supervisor')),\n field('CHW_Immediate_Solutions__c',dataValue('form.supervisor_perspectives_and_reflections.chw_solutions_supervisor')),\n field('Other_Recommendations__c',dataValue('form.supervisor_perspectives_and_reflections.chw_recommendation_other_supervisor')),\n )\n); \n", + "adaptor": "@openfn/language-salesforce@4.8.6", + "project_credential_id": "25ba06d8-5559-4d1c-a8b8-828cc3021465" + } + }, + "edges": { + "webhook->Q4-2022-Upsert-Supervision---Feedback": { + "enabled": true, + "id": "f88160eb-b2d6-4b79-9b15-cdaf8bb95e70", + "target_job_id": "438c20c3-c913-4025-b37b-9d093d55b908", + "source_trigger_id": "4359f456-3781-4d2e-a9b1-333f17db3fe7", + "condition_type": "js_expression", + "condition_label": "Supervision - Feedback - Form", + "condition_expression": "state.data.form[\"@name\"] == \"Feedback Form\" && state.data.properties[\"test_user\"] != \"Yes\"" + } + } + }, + "Upsert-Supervision---Accompaniment-[Q4-2022]": { + "id": "942eb84b-10d3-4ed9-b567-5cf6eeb19d38", + "name": "Upsert Supervision - Accompaniment [Q4 2022]", + "inserted_at": "2025-01-31T12:35:00.145169Z", + "lock_version": 4, + "triggers": { + "webhook": { + "enabled": true, + "id": "f8fffa95-408e-4f66-8559-8a982c9357e9", + "type": "webhook" + } + }, + "jobs": { + "Q4-2022-Upsert-Supervision---Accompaniment": { + "id": "08b9f369-f8b8-4b11-9a2f-6b7946750754", + "name": "Q4 2022 Upsert Supervision - Accompaniment", + "body": "//Job to integrate CommCare 'Accompaniement' form from the Supervision App\nfn(state => {\nstate.handleMultiSelect = function (state, multiField) {\n return multiField\n ? multiField\n .replace(/ /g, ';')\n : '';\n };\n \n state.cleanChoice = function (state, choice) {\n if (choice) {\n return choice.charAt(0).toUpperCase() + choice.slice(1).replace('_', ' ');\n } else {\n return '';\n }\n }\n\n return {\n ...state\n };\n \n});\n\n\nupsert(\n 'Supervision_Forms__c',\n 'CommCare_Form_ID__c',\n fields(\n field('CommCare_Form_ID__c', dataValue('id')),\n relationship('RecordType', 'Name', 'Accompanient Form'),\n field('Supervisor_Name__c', dataValue('form.prologue.supervisor_sfid')),\n field('CHW_Name__c', dataValue('form.prologue.chw_sfid')),\n relationship(\n 'Village__r',\n 'CommCare_User_ID__c',\n dataValue('form.prologue.chw_village')\n ),\n field('Form_Date__c',dataValue('form.Date')),\n field('Fertile_Women_in_Household__c',dataValue('form.WRA_check')),\n field('CHW_Asked_About_Family_Planning__c',dataValue('form.women_of_reproductive_age.fp_check')),\n field('Contraception_Distributed__c', state => {\n var choice = dataValue(\n 'form.women_of_reproductive_age.fp_resources_check'\n )(state);\n return state.handleMultiSelect(state, choice);\n }),\n \n \n field('Household_members_aware_of_CHW_SRH__c',dataValue('form.women_of_reproductive_age.srh_awareness_check')),\n field('Pregnant_Women_in_HH__c',dataValue('form.pregnancy_check')),\n field('CHW_Asked_About_ANC_Visits__c',dataValue('form.pregnant_women.anc_check')),\n field('CHW_Counseled_On_Value_of_ANC_Visits__c',dataValue('form.pregnant_women.anc_counsel_check')),\n field('CHW_Read_Each_Pregnancy_Danger_Sign__c',dataValue('form.pregnant_women.danger_sign_check')),\n field('Household_aware_of_CHW_MCH_Services__c',dataValue('form.pregnant_women.pregnancy_support_awareness_check')),\n field('Pregnant_Woman_Delivered__c',dataValue('form.pregnant_women.delivery_check')),\n field('Used_MCH_Booklet__c',dataValue('form.delivery.vaccination_check')),\n field('Counsel_on_vaccination_schedule__c',dataValue('form.delivery.vaccination_counsel_check')),\n field('Counselled_on_Exclusive_Breastfeeding__c',dataValue('form.delivery.ebf_check')),\n field('Children_Under_5_in_Household__c',dataValue('form.cu5_check')),\n field('All_children_under_5_registered__c',dataValue('form.children_under_5.cu5_enrollment_check')),\n field('MUAC_taken_for_all_children__c',dataValue('form.children_under_5.muac_check')),\n field('Measured_MUAC_circumference_properly__c',dataValue('form.children_under_5.muac_method_check')),\n // field('Measured_MUAC_circumference_properly__c', state => {\n // var choice = dataValue(\n // 'form.children_under_5.muac_method_check'\n // )(state);\n // return state.cleanChoice(state, choice);\n // }),\n field('HIV_Members_in_the_Household__c',dataValue('form.hiv_check')),\n field('Recorded_HIV_Status_Information__c',dataValue('form.hiv_clients.hiv_info_check')),\n field('Counselled_on_ART_Adherence_HIV_Services__c',dataValue('form.hiv_clients.hiv_counsel_check')),\n field('Sick_Household_Members_at_Visit__c',dataValue('form.illness_check')),\n field('Household_member_reported_fever__c',dataValue('form.illness_referrals.fever_check')),\n field('Conducted_malaria_home_test__c', dataValue('form.illness_referrals.malaria_test_check')),\n field('Malaria_test_protocol_followed__c',dataValue('form.illness_referrals.malaria_test_method_check')),\n field('Sick_person_referred__c',dataValue('form.illness_referrals.referral_accompaniment_check')),\n field('Referral_discussed_with_family__c',dataValue('form.illness_referrals.referral_followup_check')),\n field('Distributed_treatments_medications__c',dataValue('form.distribution_check')),\n field('Stock_is_full__c',dataValue('form.stocks_check')),\n field('Missing_Stock__c', state => {\n var choice = dataValue(\n 'form.missing_stocks_details'\n )(state);\n return state.handleMultiSelect(state, choice);\n }),\n field('Other_Missing_Stock__c',dataValue('form.missing_stocks_details_other')),\n field('Demonstrated_active_listening__c',dataValue('form.chw_behavior.active_listening_check')),\n field('Acted_with_respect_courtesy__c',dataValue('form.chw_behavior.respect_check')),\n field('CHW_Rating__c',dataValue('form.chw_behavior.interview_technique_check')),\n field('Tablet_used__c',dataValue('form.chw_behavior.tablet_use_check')),\n field('Tablet_used_effectively__c',dataValue('form.chw_behavior.tablet_competency_check')),\n field('Tablet_problem_observed__c', state => {\n var choice = dataValue(\n 'form.chw_behavior.tablet_issues'\n )(state);\n return state.handleMultiSelect(state, choice);\n }),\n field('Visit_Length_Mins__c',dataValue('form.visit_length')),\n field('Accompanient_components_covered__c', state => {\n var choice = dataValue(\n 'form.feedback_type'\n )(state);\n return state.handleMultiSelect(state, choice);\n }), \n field('Other_comments__c',dataValue('form.supervisor_comments')),\n field('Contraception_Distributed__c', state => {\n var choice = dataValue(\n 'form.women_of_reproductive_age.fp_resources_check'\n )(state);\n return state.handleMultiSelect(state, choice);\n }),\n )\n); \n\nupsertIf(\n state.data.form.prologue.hh_code !== '' &&\n state.data.form.prologue.hh_code !== null,\n 'Supervision_Forms__c',\n 'CommCare_Form_ID__c',\n relationship('Household_Code__r', \n 'Name',\n dataValue('form.prologue.hh_code')\n )\n );\n", + "adaptor": "@openfn/language-salesforce@4.8.6", + "project_credential_id": "25ba06d8-5559-4d1c-a8b8-828cc3021465" + } + }, + "edges": { + "webhook->Q4-2022-Upsert-Supervision---Accompaniment": { + "enabled": true, + "id": "2fe992d7-b4ba-48a8-a92e-efab34a4284e", + "target_job_id": "08b9f369-f8b8-4b11-9a2f-6b7946750754", + "source_trigger_id": "f8fffa95-408e-4f66-8559-8a982c9357e9", + "condition_type": "js_expression", + "condition_label": "Supervision - Accompaniment - Form", + "condition_expression": "state.data.form[\"@name\"] == \"Accompaniment Form\" && state.data.properties[\"test_user\"] != \"Yes\"" + } + } + }, + "x-[archive]-Upsert-Person-Visit-[Q3-2022]": { + "id": "bad14c8e-9a9b-4514-940c-a4cf6c35a6e9", + "name": "x [archive] Upsert Person Visit [Q3 2022]", + "inserted_at": "2025-01-31T12:49:21.961465Z", + "lock_version": 6, + "triggers": { + "webhook": { + "enabled": false, + "id": "0b479c86-e14f-43b2-a337-b0f1e4222baf", + "type": "webhook" + } + }, + "jobs": { + "Q3-2022-Upsert-Person-Visit": { + "id": "f739f177-a1c3-4dd0-ab08-b1320925312d", + "name": "Q3 2022 Upsert Person Visit", + "body": "//UPSERT PERSON VISIT\n query(\n `SELECT Id, Parent_Geographic_Area__c, Parent_Geographic_Area__r.Name, Parent_Geographic_Area__r.Parent_Geographic_Area__c FROM Location__c WHERE CommCare_User_ID__c = '${dataValue(\n 'properties.owner_id'\n )(state)}'`\n);\n\nfn(state => {\n state.cleanChoice = function (state, choice) {\n if (choice) {\n return choice.charAt(0).toUpperCase() + choice.slice(1).replace('_', ' ');\n } else {\n return '';\n }\n };\n\nfn(state => ({\n ...state,\n data: {\n ...state.data,\n catchmentNewId:\n state.references[0].records && state.references[0].records.length !== 0\n ? (state.references[0].records[0].Parent_Geographic_Area__r \n ? state.references[0].records[0].Parent_Geographic_Area__r.Parent_Geographic_Area__c\n : undefined)\n : undefined,\n },\n}));\n\n state.handleMultiSelect = function (state, multiField) {\n return multiField\n ? multiField\n .replace(/ /gi, ';')\n .toLowerCase()\n .split(';')\n .map(value => {\n return (\n value.charAt(0).toUpperCase() + value.slice(1).replace('_', ' ')\n );\n })\n .join(';')\n : '';\n };\n\n state.handleMultiSelectOriginal = function (state, multiField) {\n return multiField\n ? multiField\n .replace(/ /gi, ';')\n .toLowerCase()\n .split(';')\n .map(value => {\n return (\n value\n );\n })\n .join(';')\n : '';\n };\n\n const pregDangerMap = {\n Vaginal_Bleeding: 'Vaginal Bleeding',\n Water_Breaks: 'Water Breaks before Time of Delivery',\n Prolonged_Labour: 'Prolonged Labour over 12 Hours',\n Convulsions: 'Convulsions or Fits',\n Abdominal_Pain: 'Severe Abdominal Pain before Delivery',\n High_Fever: 'High Fever',\n Low_Baby_Movement: 'Feeling the Baby move less or not at all',\n Swelling: 'Swelling of Face and Hands',\n Severe_Headache: 'Severe or Continuous Headache for more than 12 hours',\n Severe_Vomiting: 'Severe or Continuous Vomiting',\n none: 'None',\n };\n\n const counselMap = {\n anc_visits: 'ANC Visits',\n early_initiation_of_anc_less_than_3_months:\n 'Early initiation of ANC (less than 3 months)',\n completing_recomended_anc_visits: 'Completing recomended ANC visits',\n danger_signs: 'Danger signs',\n skilled_birth: 'Skilled birth',\n immunization: 'Immunization',\n individual_birth_plan: 'Individual Birth Plan',\n emergency_preparedness: 'Emergency preparedness',\n childcare_and_affection: 'Childcare and affection',\n nutrition_counseling: 'Nutrition counseling',\n growth_monitoring: 'Growth monitoring',\n exclusive_breastfeeding: 'Exclusive breastfeeding',\n complementary_feeding: 'Complementary feeding',\n sleeping_under_llitn: 'Sleeping under LLITN',\n knowing_hiv_status: 'Knowing HIV status',\n indoor_pollution: 'Indoor pollution',\n personal_hygiene: 'Personal Hygiene',\n safe_drinking_water: 'Safe drinking water',\n safe_disposal_of_human_waste: 'Safe disposal of human waste',\n };\n\n const serviceMap = {\n Scheduled_PSC_Apt: 'Scheduled PSC Apt',\n Adverse_Drug_Reaction_Side_Effect: 'Adverse Drug Reaction/Side Effect',\n Malnutrition: 'Malnutrition',\n Malaria: 'Malaria',\n TB: 'TB',\n Treatment_for_Other_OIs: 'Treatment for other Ols',\n ARI: 'ARI',\n Anemia: 'Anemia',\n Diarrhea: 'Diarrhea',\n Pregnancy_Care: 'Pregnancy Care (ANC)',\n Family_Planning: 'Family Planning (FP)',\n Preconception_Counseling: 'Preconception Counseling',\n Injury: 'Injury',\n Other: 'Other',\n };\n\n const reasonMap = {\n lack_of_access_to_fp_information: 'Lack of access to FP information',\n no_access_to_fp_services_hospitals:\n 'Lack of hospitals or places where FP services can be accessed',\n not_willing_to_use_fp_due_to_negative_effects_myths_and_misconceptions:\n 'Myths and misconceptions',\n barriers_at_service_delivery_points: 'Barriers at service delivery points',\n pregnant: 'The client is pregnant',\n intentions_of_getting_pregnant: 'Intentions of getting pregnant',\n not_sexually_active: 'The client is not sexually active',\n other_barriers_culture_male_partners_parents_etc:\n 'Other barriers (culture, male partners, parents, etc)',\n };\n\n const milestoneTypeMap = {\n cognitive_delays_learning_difficulties:\n 'Cognitive Delays Learning Difficulties',\n motor_delays: 'Motor Delays',\n speech_and_language_delay: 'Delay Speech and Language Delay',\n social_and_emotional: 'Social and emotional',\n };\n\n const milestoneMap = {\n movement: 'Movement',\n hearing: 'Hearing',\n communication: 'Communication',\n seeing: 'Seeing',\n cognitive_delays: 'Cognitive Delays',\n play: 'Play',\n };\n const nutritionMap = {\n severe: 'Severely Malnourished',\n moderate: 'Moderately Malnourished',\n normal: 'Normal',\n };\n \n const fpMethodMap = {\n male_condoms: \"Male condoms\",\n female_condoms: \"Female condoms\",\n pop: \"POP\",\n coc: \"COC\",\n emergency_pills: \"Emergency pills\",\n none: \"None\",\n //HMN -12/01/2023- \n //adding normalization for the family_planning_method to Family_Planning_Method__c\n iucd: \"IUCD\",\n condoms: \"Condoms\",\n depo:\"Depo\",\n implant: \"Implant\",\n injection: \"Injection\",\n pills: \"Pills\",\n traditional: \"Traditional\"\n };\n\n const symptomsMap = {\n convulsions: 'Convulsions',\n not_able_to_eatdrink: 'Not able to drink or feed at all',\n vomits_everything: 'Vomits everything',\n 'chest_in-drawing': 'Chest in - drawing',\n unusually_sleepyunconscious: 'Unusually sleepy or unconscious',\n swelling_of_both_feet: 'Swelling of both feet',\n none: \"None\",\n };\n\n const supervisorMap ={\n community_health_nurse: \"Community_health_nurse\",\n chw_supervisor: \"CHW_supervisor\",\n chewschas: \"Chewschas\",\n other: \"Other\",\n none: \"None\"\n };\n \n const treatmentDistributionMap = {\n ors_205gltr_sachets: 'ORS (20.5h/ltr): Sachets',\n acts_6s: 'ACTs (6s)',\n acts_12s: 'ACTs (12s)',\n acts_18s: 'ACTs (18s)',\n acts_24s: 'ACTs (24s)',\n albendazole_abz_tabs: 'Albendazole (ABZ): Tabs',\n paracetamol_tabs: 'Tetracycline Eye Ointment (TEO): 1%:tube',\n tetracycline_eye_ointment_teo_1_tube: 'Tetracycline Eye Ointment (TEO): 1%:tube',\n amoxycillin: 'Amoxycillin (125mg/5mls: Bottle',\n none: 'None'\n};\n\nconst childDangerSignsMap = {\n none: 'None',\n Poor_Breastfeeding: 'Poor Breastfeeding',\n not_able_to_feed_since_birth_or_stopped_feeding_well: 'Not able to feed since birth, or stopped feeding well',\n not_able_to_breastfeed: 'Not able to breastfeed',\n Fever: 'Fever',\n very_low_temperature: 'Very low temperature (35.4 C or less)',\n shivering: 'Shivering',\n Fast_Breathing: 'Fast Breathing',\n Very_Sleepy: 'Very Sleepy',\n Convulsions_and_Fits: 'Convulsions and Fits',\n only_moves_when_stimulated_or_does_not_move_even_on_stimulation: 'Only moves when stimulated, or does not move even on stimulation',\n yellow_solebaby_body_turning_yellow_especially_eyes_palms_soles: 'Yellow sole(Baby body turning yellow especially eyes, palms,soles)',\n bleeding_from_the_umbilical_stump: 'Bleeding from the umbilical stump',\n signs_of_local_infection_umbilicus_is_red_or_draining_pus_skin_boils_or_eye: 'Signs of local infection: umbilicus is red or draining pus, skin boils, or eyes draining pus',\n weight_chart_using_color_coded_scales_if_red_or_yellowweight_below_25kg_or_: 'Weight chart using color coded scales if RED or YELLOW(Weight below 2.5kg or born less than 36 weeks of age)',\n unable_to_cry: 'Unable to cry',\n cyanosis: 'Cyanosis',\n bulging_fontanelle: 'Bulging fontanelle'\n}\n\n return {\n ...state,\n counselMap,\n serviceMap,\n reasonMap,\n milestoneTypeMap,\n milestoneMap,\n nutritionMap,\n pregDangerMap,\n fpMethodMap,\n symptomsMap,\n supervisorMap,\n treatmentDistributionMap,\n childDangerSignsMap\n };\n});\n\nupsertIf(\n // state.data.properties.username !== 'openfn.test' &&\n state.data.properties.username !== 'test.2021' &&\n state.data.properties.test_user !== 'Yes' ,\n 'Person_visit__c',\n 'CommCare_ID__c',\n fields(\n //field('CommCare_ID__c', dataValue('form.case.@case_id')),\n // field('CommCare_ID__c', dataValue('id')),\n //field('CommCare_ID__c', state => {\n // var case_id = dataValue('case_id')(state);\n // var submitted = dataValue('properties.last_form_opened_date_and_time')(state);\n // return case_id + '_' + submitted;\n //}),\n field('CommCare_ID__c',dataValue('case_id')),\n\n relationship(\n 'Person__r',\n 'CommCare_ID__c',\n dataValue('indices.parent.case_id')\n ),\n /*relationship(\n 'Household_CHW__r', \n 'CommCare_ID__c', \n dataValue('properties.sfid')),*/\n // field('CommCare_Visit_ID__c',dataValue('metadata.instanceID')),\n field('CommCare_Visit_ID__c', state => {\n var case_id = dataValue('case_id')(state);\n var submitted = dataValue('properties.last_form_opened_date_and_time')(state);\n return case_id + '_' + submitted;\n }),\n field('Date__c',dataValue('properties.Date')),\n field('Form_Submitted__c', dataValue('properties.last_form_opened_name')),\n field('Birth_Status__c',dataValue('properties.child_status')),\n field('Catchment__c', dataValue('catchmentNewId')),\n /*\n //HMN 05/01/2022 Caused alot of failures, removed this RecordType Field\n relationship('RecordType', 'Name', state => {\n var rt = dataValue('properties.RecordType')(state);\n if (rt === 'Unborn' || rt === 'Child') {\n return 'Child Visit';\n };\n if (rt === 'Youth') {\n return 'Youth Visit';\n };\n if (rt === 'Male Adult') {\n return 'Adult Male Visit';\n };\n if (rt === 'Female Adult') {\n return 'Adult Female Visit';\n };\n }),*/\n field('Use_mosquito_net__c', state => {\n var choice = dataValue(\n 'properties.sleep_under_net'\n )(state);\n return state.cleanChoice(state, choice);\n }),\n field(\n 'Individual_birth_plan_counselling__c',\n dataValue('properties.individual_birth_plan')\n ),\n field('Reason_for_not_taking_a_pregnancy_test__c', state => {\n var reason = dataValue('properties.No_Preg_Test')(state);\n return reason ? reason.toString().replace(/_/g, ' ') : undefined;\n }),\n field('Pregnancy_danger_signs__c', state => {\n var signs = dataValue(\n 'properties.No_Preg_Test'\n )(state);\n return signs ? state.pregDangerMap[signs] : undefined;\n }),\n field('Child_Danger_Signs__c', state => {\n var signs = dataValue(\n 'properties.Other_Danger_Signs'\n )(state);\n return signs ? state.childDangerSignsMap[signs] : undefined\n }),\n field('Current_Malaria_Status__c', state => {\n var choice = dataValue(\n 'properties.malaria_test_results'\n )(state);\n return state.cleanChoice(state, choice);\n }),\n field('Malaria_Home_Test__c', dataValue('properties.malaria_test_date')),\n /*field('Current_Malaria_Status__c', state => {\n var choice = dataValue(\n 'properties.Malaria_Status'\n )(state);\n return state.cleanChoice(state, choice);\n }),*/\n // field('Malaria_Home_Treatment__c',dataValue('form.treatment_and_tracking.home_treatment')),\n field('Malaria_Home_Treatment__c', dataValue('properties.malaria_test_date')),\n field('Persons_symptoms__c', state => {\n var check = dataValue('properties.symptoms_check_other')(state);\n var value =\n check && check !== ''\n ? check\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return state.symptomsMap[value] || value;\n })\n : undefined;\n return value ? value.join(';') : undefined;\n }),\n field('Active_in_Support_Group__c', dataValue('properties.Active_in_Support_Group')),\n field('HAWI_Defaulter__c', state => {\n var hawi = dataValue('properties.default')(state);\n return hawi === 'Yes' ? true : false;\n }),\n field(\n 'Date_of_Default__c',\n dataValue('properties.date_of_default')\n ),\n field(\n 'Persons_temperature__c',\n dataValue('properties.temperature')\n ),\n field(\n 'Days_since_illness_start__c',\n dataValue('properties.duration_of_sickness')\n ),\n field(\n 'Newborn_visited_48_hours_of_delivery__c',\n dataValue(\n 'properties.newborn_visited_48_hours_of_delivery'\n )\n ),\n field(\n 'Newborn_visited_by_a_CHW_within_6_days__c',\n dataValue('properties.visit_6_days_from_delivery')\n ),\n field(\n 'Current_Malaria_Status__c',\n dataValue('properties.malaria_test_results')\n ),\n field('Malaria_test__c', state => {\n var choice = dataValue(\n 'properties.malaria_test'\n )(state);\n return state.cleanChoice(state, choice);\n }),\n field('Fever__c', state => {\n var choice = dataValue(\n 'properties.symptoms_check_fever'\n )(state);\n return state.cleanChoice(state, choice);\n }),\n field('Cough__c', state => {\n var choice = dataValue(\n 'properties.symptoms_check_cough'\n )(state);\n return state.cleanChoice(state, choice);\n }),\n field('Diarrhoea__c', state => {\n var choice = dataValue(\n 'properties.symptoms_check_diarrhea'\n )(state);\n return state.cleanChoice(state, choice);\n }),\n field(\n 'TB_patients_therapy_observed__c',\n dataValue('properties.observed_tb_therapy')\n ),\n field(\n 'Injuries_or_wounds__c',\n dataValue('properties.wounds_or_injuries')\n ),\n field('Currently_on_ART_s__c', dataValue('properties.ART')),\n /*field('ART_Regimen__c', state => {\n var choice = dataValue(\n 'properties.ARVs'\n )(state);\n return state.cleanChoice(state, choice);\n }),*/\n field(\n 'Immediate_Breastfeeding__c',\n dataValue(\n 'properties.Breastfeeding_Delivery'\n )\n ),\n field(\n 'Exclusive_Breastfeeding__c',\n dataValue(\n 'properties.Exclusive_Breastfeeding'\n )\n ),\n field(\n 'Counselled_on_Exclusive_Breastfeeding__c',\n dataValue('properties.counseling')\n ),\n field('LMP__c',dataValue('properties.when_was_your_lmp')),\n field('Family_Planning__c', state => {\n var choice = dataValue(\n 'properties.family_planning'\n )(state);\n return state.cleanChoice(state, choice);\n }),\n //HMN 12/01/2023 Failures on picklist within Salesforce\n /*\n field(\n 'Family_Planning_Method__c',\n dataValue('properties.family_planning_method')\n ),*/\n field('Family_Planning_Method__c', state => {\n //var status = dataValue('form.treatment_and_tracking.distribution.distributed_treatments')(state);\n var status = dataValue('properties.family_planning_method')(state);\n var value =\n status && status !== ''\n ? status\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return state.fpMethodMap[value] || value;\n })\n : undefined;\n return value ? value.join(';') : undefined;\n }),\n field('FP_Method_Distributed__c', state => {\n //var status = dataValue('form.treatment_and_tracking.distribution.distributed_treatments')(state);\n var status = dataValue('properties.FP_commodity')(state);\n var value =\n status && status !== ''\n ? status\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return state.fpMethodMap[value] || value;\n })\n : undefined;\n return value ? value.join(';') : undefined;\n }),\n field('Reasons_for_not_taking_FP_method__c', state => {\n // var reason = dataValue('form.TT5.Mother_Information.No_FPmethod_reason')(state);\n // return reason ? state.reasonMap[reason] : undefined;\n var status = dataValue('properties.No_FPmethod_reason')(state);\n var value =\n status && status !== ''\n ? status\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return state.reasonMap[value] || value;\n })\n : undefined;\n return value ? value.join(';') : undefined;\n }),\n field('Pregnant__c', state => {\n var preg = dataValue('properties.Pregnant')(state);\n return preg === 'Yes' ? true : false;\n }),\n field('Counselled_on_FP_Methods__c', state => {\n var choice = dataValue(\n 'properties.CounselledFP_methods'\n )(state);\n return state.cleanChoice(state, choice);\n }),\n field('Client_counselled_on__c', state => {\n var choices =\n dataValue('properties.counsel_topic')(\n state\n ) || dataValue('properties.counsel_topic')(state);\n var choiceGroups = choices ? choices.split(' ') : null;\n var choicesMulti = choiceGroups\n ? choiceGroups\n .map(cg => {\n return state.counselMap[cg];\n })\n .join(';')\n : choiceGroups;\n return choicesMulti;\n }),\n field('Client_provided_with_FP__c', state => {\n var choice = dataValue(\n 'properties.was_the_woman_15-49yrs_provided_with_family_planning_commodities_by_chv'\n )(state);\n return state.cleanChoice(state, choice);\n }),\n field(\n 'Newborn_visited_48_hours_of_delivery__c',\n dataValue(\n 'properties.newborn_visited_48_hours_of_delivery'\n )\n ),\n field('Mother_visit_counselling__c', state => {\n var choice = dataValue(\n 'properties.did_you_consel_the_mother_on1'\n )(state);\n return state.handleMultiSelectOriginal(state, choice);\n }),\n field(\n 'mother_visited_48_hours_of_the_delivery__c',\n dataValue('properties.visit_mother_48')\n ),\n field('Newborn_visit_counselling__c', state => {\n var choice = dataValue(\n 'properties.did_you_consel_the_mother_on2'\n )(state);\n return state.handleMultiSelectOriginal(state, choice);\n }),\n field('Know_HIV_status__c', state => {\n var choice = dataValue(\n 'properties.known_hiv_status'\n )(state);\n return state.cleanChoice(state, choice);\n }),\n field('HIV_Status__c', dataValue('properties.hiv_status')),\n field('Treatment_Distribution__c', state => {\n //var status = dataValue('form.treatment_and_tracking.distribution.distributed_treatments')(state);\n var status = dataValue('properties.distributed_treatments')(state);\n var value =\n status && status !== ''\n ? status\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return state.treatmentDistributionMap[value] || value;\n })\n : undefined;\n return value ? value.join(';') : undefined;\n }),\n field(\n 'Current_Weight__c',\n dataValue('properties.Current_Weight')\n ),\n field(\n 'Current_Height__c',\n dataValue('properties.current_height')\n ),\n field(\n 'Current_MUAC__c',\n dataValue('properties.MUAC')\n ),\n field('Food_groups_3_times_a_day__c',dataValue('properties.food_groups')),\n field('Nutrition_Case_Managed__c',dataValue('properties.nutrition_case_managed')),\n field('Nutrition_Danger_Signs__c',state => {\n var choice = dataValue(\n 'properties.nutrition_danger_signs'\n )(state);\n return state.handleMultiSelectOriginal(state, choice);\n \n }),\n field('Why_was_nutrition_case_not_managed__c',dataValue('properties.nutrition_case_not_managed_why')),\n field('Community_Nutrition_Treatment__c',dataValue('properties.nutrition_treatment_severe')),\n field('Community_Nutrition_Treatment__c',dataValue('properties.nutrition_treatment_moderate')),\n field('Why_was_nutrition_treatment_not_given__c',dataValue('properties.nutrition_treatment_not_given')),\n field('Current_Nutrition_Status__c', state => {\n var status = dataValue(\n 'properties.Nutrition_Status'\n )(state);\n return status ? state.nutritionMap[status] : undefined;\n }),\n field('Default_on_TB_treatment__c', state => {\n var choice = dataValue(\n 'properties.default_tb_treatment'\n )(state);\n return state.cleanChoice(state, choice);\n }),\n field('Received_pregnancy_test__c', state => {\n var choice = dataValue(\n 'properties.did_you_adminsiter_a_pregnancy_test'\n )(state);\n return state.cleanChoice(state, choice);\n }),\n field('Pregnancy_test_result__c', state => {\n var choice = dataValue(\n 'properties.pregnancy_test_result'\n )(state);\n return state.cleanChoice(state, choice);\n }),\n field('Chronic_illness__c', state => {\n var choice = dataValue(\n 'properties.please_specify_which_chronic_illness_the_person_has'\n )(state);\n var choice2 = state.handleMultiSelect(state, choice);\n return choice2 ? choice2.replace(/_/g, ' ') : '';\n }),\n /*field(\n 'Birth_Certificate__c',\n dataValue('form.Status.birth_certificate')\n ),\n field(\n 'Child_zinc__c',\n dataValue(\n 'form.TT5.Child_Information.Clinical_Services.diarrhea_clinic_treatment_zinc'\n )\n ),\n field(\n 'Child_ORS__c',\n dataValue(\n 'form.TT5.Child_Information.Clinical_Services.diarrhea_clinic_treatment_ORS'\n )\n ),*/\n field(\n 'Childs_breath_per_minute__c',\n dataValue('properties.breaths_per_minuite')\n ),\n field(\n 'Child_chest_in_drawing__c',\n dataValue('properties.Child_chest_in_drawing_c')\n ),\n field(\n 'Caregiver_counseled_on_delayed_milestone__c',\n dataValue(\n 'properties.did_you_counsel_the_caregiver_on_delayed_milestones'\n )\n ),\n field(\n 'Delayed_Milestone__c',\n dataValue(\n 'properties.does_the_child_has_a_delayed_milestone'\n )\n ),\n field(\n 'Child_has_2_or_more_play_items__c',\n dataValue(\n 'properties.does_the_child_has_2_or_more_play_items_at_home'\n )\n ),\n field(\n 'Child_has_3_more_picture_books__c',\n dataValue(\n 'properties.does_the_child_has_3_or_more_picture_books'\n )\n ),\n field('Delayed_Milestones_Counselled_On__c', state => {\n var ms = dataValue(\n 'properties.which_delayed_milestone_area_did_you_counsel_the_caregiver_on'\n )(state);\n return ms ? state.milestoneMap[ms] : undefined;\n }),\n field('Delayed_Milestone_Type__c', state => {\n var ms = dataValue('properties.which_delayed_milestone')(\n state\n );\n return ms ? state.milestoneTypeMap[ms] : undefined;\n }),\n field(\n 'Caretaker_trained_in_muac__c',\n dataValue('properties.mother_trained_muac')\n ),\n field(\n 'Caretaker_screened_for_muac_this__c',\n dataValue(\n 'properties.mother_screened_child_muac'\n )\n ),\n field(\n 'Caretaker_muac_findings__c',\n dataValue(\n 'properties.mother_screened_child_muac_result'\n )\n ),\n field(\n 'Caretaker_action_after_muac_screening__c',\n dataValue(\n 'properties.mother_screened_muac_action'\n )\n ),\n field(\n 'of_Caretaker_MUAC_screenings__c',\n dataValue('properties.mother_nb_screening')\n ),\n field('Pulse_Oximeter__c', dataValue('properties.pulse_oximeter_available')),\n field(\n 'Heart_Rate_Pulse_Oximeter__c',\n dataValue('properties.heart_rate_pulse_oximeter')\n ),\n field(\n 'Oxygen_Concentration_Pulse_Oximeter__c',\n dataValue('properties.oxygen_concentration')\n ),\n field('Can_child_drink__c', dataValue('properties.can_child_drink')),\n field(\n 'Antibiotic_provided_for_fast_breathing__c',\n dataValue('properties.antibiotic_fast_breathing')\n ),\n field(\n 'Antibiotic_provided_for_chest_indrawing__c',\n dataValue('properties.antibiotic_chest_indrawing')\n ),\n field('Supervisor_Visit__c', state => {\n var check = dataValue('properties.supervisor_visit')(state);\n var value =\n check && check !== ''\n ? check\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return state.supervisorMap[value] || value;\n })\n : undefined;\n return value ? value.join(';') : undefined;\n }),\n /*\n //HMN- 05012023 - Removed field('Visit_Closed_Date__c', dataValue('date_closed')),\n //Because I could not find it in Salesforce. It was causing errors on staging\n field('Visit_Closed_Date__c', dataValue('date_closed')),\n */\n //field('Case_Closed_Date__c', state => {\n // var closed = dataValue('date_closed')(state);\n // var date = dataValue('date_modified')(state);\n // return closed && closed == true ? date : undefined;\n // })\n )\n);\n", + "adaptor": "@openfn/language-salesforce@4.8.6", + "project_credential_id": "25ba06d8-5559-4d1c-a8b8-828cc3021465" + } + }, + "edges": { + "webhook->Q3-2022-Upsert-Person-Visit": { + "enabled": true, + "id": "a813fb12-42cf-435d-abc6-4ab3822609f0", + "target_job_id": "f739f177-a1c3-4dd0-ab08-b1320925312d", + "source_trigger_id": "0b479c86-e14f-43b2-a337-b0f1e4222baf", + "condition_type": "js_expression", + "condition_label": "Person Visit", + "condition_expression": "state.data.properties[\"app_release\"] == \"Q2-2022\" && state.data.properties[\"case_type\"] == \"visite\" && state.data.properties[\"test_user\"] != \"Yes\"" + } + } + }, + "Update-HH-Name-in-CommCare-[Q3-2022]": { + "id": "d61db239-8d5f-493a-ac3a-177b15ce651a", + "name": "Update HH Name in CommCare [Q3 2022]", + "inserted_at": "2025-01-31T12:56:23.305930Z", + "lock_version": 3, + "triggers": { + "webhook": { + "enabled": true, + "id": "d4bcab3a-8af7-4db4-9007-3e9e102b5895", + "type": "webhook" + } + }, + "jobs": { + "Q3-2022-Update-HH-Name-in-CommCare": { + "id": "0f682a51-e260-4b43-9d79-73dc2354b7d4", + "name": "Q3 2022 Update HH Name in CommCare", + "body": "// Update CommCare case\nfn(state => {\n const { Notification } = state.data.Envelope.Body.notifications;\n\n const Notifications = Array.isArray(Notification)\n ? Notification\n : [Notification];\n\n const notifications = Notifications.map(notification => {\n console.log(\n `Mapping HH code to CommCare: `,\n notification.sObject.Household_Code_Autonumber__c\n );\n return {\n case_id: notification.sObject.Commcare_Code__c,\n name: notification.sObject.Household_Code_Autonumber__c,\n };\n });\n\n return { ...state, notifications };\n});\n\nsubmitXls(state => state.notifications, {\n case_type: 'Household',\n search_field: 'case_id',\n search_column: 'case_id',\n name_column: 'name',\n create_new_cases: 'off',\n});\n", + "adaptor": "@openfn/language-commcare@1.4.1", + "project_credential_id": "fee3669f-c133-4bb5-86ca-c090eec4bc99" + } + }, + "edges": { + "webhook->Q3-2022-Update-HH-Name-in-CommCare": { + "enabled": true, + "id": "7fda434a-98de-4c43-96a0-2aa37b19c0d9", + "target_job_id": "0f682a51-e260-4b43-9d79-73dc2354b7d4", + "source_trigger_id": "d4bcab3a-8af7-4db4-9007-3e9e102b5895", + "condition_type": "js_expression", + "condition_label": "SF HH Code Updated", + "condition_expression": "state.data.Envelope.Body.notifications.ActionId == \"04k24000000GsEhAAK\"" + } + } + }, + "1-Bulk-HH-cases": { + "id": "3ee610c7-414f-465b-bc19-80dd07a42fc2", + "name": "1-Bulk HH cases", + "inserted_at": "2025-01-31T13:02:40.975530Z", + "lock_version": 15, + "triggers": { + "cron": { + "enabled": true, + "id": "7d7f810a-529b-48fa-9e76-0ff9132eedf2", + "type": "cron", + "cron_expression": "0 * * * *" + } + }, + "jobs": { + "WF1-1-Bulk-get-HH-cases": { + "id": "925ba65a-23c9-4796-98d8-97c704fea8c8", + "name": "WF1-1 Bulk get HH cases", + "body": "// comment\nfn(state => {\n const { baseUrl } = state.configuration;\n\n const caseTypes = ['Household'];\n\n //NOTE: You can use 'limit' to modify this batch size as desired\n const limit = 1000; \n\n //NOTE: indexedOnStart is the default sync start data the FIRST time the job runs\n const indexedOnStart = '2022-01-18T10:00:00';\n\n //NOTE: After first job run, OpenFn will check the job sync data (\"lastRunAt\") to set as the indexedOnStart\n const lastRunAt =\n typeof state.lastRunAt !== 'undefined' ? state.lastRunAt : indexedOnStart;\n console.log('Filtering cases with indexed_on_start > than ::', lastRunAt);\n//May 31st, 2023 at 3:00:13 PM.\n const queries = caseTypes.map(\n t => `?type=${t}&indexed_on_start=${lastRunAt}&limit=${limit}\n &owner_id=a3c31c9be392427a97f8704262065661` // User id of test user test.2021. Remove for production\n \n //NOTE: If for testing, you want to fetch data for a specific historical range (e.g., between April 23 and 24)...\n //...then use the query string below instead of the one above on L16, and custom adjust the index_on start/end dates\n //t => `?type=${t}&indexed_on_start=2023-03-03T00:00:00&limit=${limit}&indexed_on_end=2023-03-06T00:00:00` //returns 14 records\n // t => `?type=${t}&indexed_on_start=2024-01-15T15:00:00&limit=${limit}&indexed_on_end=2024-01-16T23:59:59` \n );\n\n return { ...state, queries, baseUrl, payloads: [] };\n});\n\n// create a \"recursiveGet\" which will call itself if CommCare tells us there's\n// more data to fetch for the same form\nfn(state => {\n const recursiveGet = url =>\n get(\n url,\n {\n headers: { 'content-type': 'application/json' },\n },\n nextState => {\n const now = new Date();\n const { baseUrl, data, payloads } = nextState;\n\n const { meta, objects } = data;\n console.log('Metadata in CommCare response:', meta);\n\n const finalState = {\n ...nextState,\n payloads: [...payloads, ...objects],\n };\n\n if (meta.next) {\n console.log('Next query detected, recursing...');\n return recursiveGet(`${baseUrl}${meta.next}`)(finalState);\n }\n finalState.lastRunAt = now.toISOString().slice(0, 19);\n return finalState;\n }\n );\n\n return { ...state, recursiveGet };\n});\n\n// for each initial query, fetch data recursively\neach(\n '$.queries[*]',\n fn(state => {\n return state.recursiveGet(`${state.baseUrl}${state.data}`)(state);\n })\n);\n// log the total number of payloads returned\nfn(state => {\n console.log('Count of payloads', state.payloads.length);\n console.log(state.data);\n\n return { ...state, references: [], data: {} };\n});\n", + "adaptor": "@openfn/language-http@6.5.1", + "project_credential_id": "8d4d9b2d-e41a-40ab-92dc-e2280bb5ee2b" + }, + "WF1-2-Bulk-upsert-HHs-and-HH-Visits": { + "id": "833a8e2f-a01a-4559-95e9-c38398d42d62", + "name": "WF1-2 Bulk upsert HHs and HH Visits", + "body": "fn(state => {\n if (state.payloads.length == 0)\n return { ...state, housevisits: [], households: [] };\n\n const owner_ids = state.payloads.map(data => data.properties.owner_id);\n const uniq_owner_ids = [...new Set(owner_ids)];\n\n return { ...state, uniq_owner_ids };\n});\n\n\nfn(state => {\n if (state.payloads.length == 0) return state;\n\n return query(\n `SELECT CommCare_User_ID__c, Id village, Parent_Geographic_Area__c area, Parent_Geographic_Area__r.Name name, Parent_Geographic_Area__r.Parent_Geographic_Area__c catchment FROM Location__c catchment WHERE CommCare_User_ID__c IN ('${state.uniq_owner_ids.join(\n \"','\"\n )}') GROUP BY Id, CommCare_User_ID__c, Parent_Geographic_Area__c, Parent_Geographic_Area__r.Name, Parent_Geographic_Area__r.Parent_Geographic_Area__c`\n )(state);\n});\n\nfn(state => {\n if (state.payloads.length == 0) return state;\n\n console.log('Done querying ✅');\n\n return state;\n});\n\nfn(state => {\n if (state.payloads.length == 0) return state;\n\n console.log(\n 'Filtering out unwanted users and applying mapping for households and housevisits'\n );\n\n const [reference] = state.references;\n\n //HMN 06/11/2023\n // console.log(JSON.stringify(reference.records, null, 2));\n\n const records = reference.records;\n const fetchReference = (owner_id, arg) => {\n const result =\n records && records.length > 0\n ? records.filter(record => record.CommCare_User_ID__c === owner_id)\n : 0;\n\n //TODO: Update default value for 'unknown location' before go-live\n return result.length > 0\n ? result[0][arg]\n : 'a000800001tMobaAAC' /*unknown location*/;\n };\n\n const supervisorMap = {\n community_health_nurse: 'Community Health Nurse',\n chw_supervisor: 'CHW Supervisor',\n chewschas: 'CHEWs/CHAs',\n other: 'Other',\n none: 'None',\n };\n\n const insuranceMap = {\n nhif: 'NHIF',\n Linda_mama: 'Linda mama',\n other_please_specify_if_active: 'Other',\n none: 'None',\n };\n\n const households = state.payloads\n /* HMN 050723 \n .filter(\n h =>\n h.properties.commcare_username !== 'openfn.test' &&\n h.properties.commcare_username !== 'test.2021' &&\n h.properties.test_user !== 'Yes'\n )\n */\n .map(h => {\n // Special calculations ==================================================\n const insuranceStatus = h.properties.health_insurance;\n const Health_insurance_type__c =\n insuranceStatus && insuranceStatus === 'other_please_specify_if_active'\n ? 'Other'\n : insuranceStatus === 'nhif'\n ? 'NHIF'\n : insuranceStatus === 'Linda_mama' || 'linda_mama'\n ? 'Linda mama'\n : insuranceStatus;\n\n const hhStatus = h.properties.Household_Status;\n const Active_Household__c =\n hhStatus && hhStatus === 'No'\n ? false\n : hhStatus === 'Yes'\n ? true\n : hhStatus;\n\n const reason = h.properties.Reason_for_Inactive;\n const Inactive_Reason__c = reason\n ? reason.toString().replace(/_/g, ' ')\n : null;\n //HMN 06/11/2023\n// console.log(JSON.stringify(h.properties, null, 2));\n /*HMN remove this dependancy 07/07/2023\n const chw = h.properties.CHW_ID;\n const Household_CHW__c =\n chw === 'a030800001zQrk' ? 'a030800001zQrk5' : chw ? chw : undefined;\n // =======================================================================\n*/\n \n return {\n CommCare_Username__c: h.properties.commcare_username,\n MOH_household_code__c: h.properties.moh_code,\n CommCare_Code__c: h.case_id,\n Source__c: true,\n // TODO: Prod mapping to add back before go-live =======================\n Household_CHW__c: h.properties.CHW_ID, // Uncomment me to go live!\n //Household_CHW__c: 'a032400000GHpdsAAD', // Comment me OUT to go live!\n // Household_CHW__c: 'a03AW00000643nLYAQ',\n // =====================================================================\n Catchment__c: fetchReference(h.properties.owner_id, 'catchment'),\n Area__c: fetchReference(h.properties.owner_id, 'area'),\n Village__c: fetchReference(h.properties.owner_id, 'village'),\n Household_Village__c: h.properties.village,\n Deaths_in_the_last_6_months__c:\n h.properties.deaths_in_past_6_months > 0 ? 'Yes' : 'No',\n Access_to_safe_water__c: h.properties.Safe_Water,\n Treats_Drinking_Water__c: h.properties.Treats_Drinking_Water,\n Tippy_Tap__c: h.properties.Active_Handwashing_Station,\n Pit_Latrine__c: h.properties.Functional_Latrine,\n Rubbish_Pit__c: h.properties.Rubbish_Pit,\n Drying_Rack__c: h.properties.Drying_Rack,\n Kitchen_Garden__c: h.properties.Kitchen_Garden,\n Cookstove__c: h.properties.Improved_Cooking_Method,\n Clothe__c: h.properties.Clothesline,\n WASH_Trained__c: h.properties.WASH_Trained,\n Uses_ITNs__c: h.properties.ITNs,\n Has_muac_tape__c: h.properties.family_muac_tape_available,\n Health_insurance__c: h.properties.health_insurace_cover,\n Health_insurance_active_status__c: h.properties.healthinsurance_active,\n Health_insurance_type__c,\n Other_Health_Insurance__c: h.properties.if_other_please_specify,\n Work_with_TBA__c: h.properties.tba,\n TBA_name__c: h.properties.which_tba,\n Last_Modified_Date_CommCare__c: h.server_date_modified, //Need a case property,\n Active_Household__c,\n Inactive_Reason__c,\n Active_in_Nutrition_Program__c:\n h.properties.enrolled_in_a_lwala_nutrition_program,\n lwala_nutrition_program_enrollment_date__c:\n h.properties.lwala_nutrition_program_enrollment_date,\n Trained_in_gardening__c: h.properties.household_trained_on_gardening,\n household_trained_on_gardening_date__c:\n h.properties.when_was_the_household_trained_on_gardening,\n Seed_Input_Support__c:\n h.properties.household_provided_with_seed_input_support,\n household_provided_with_seed_input_suppo__c:\n h.properties.when_was_the_household_provided_with_seed_input_support,\n MIYCN_Trained__c: h.properties.household_trained_on_MIYC,\n // TODO: @Aleksa to find out if Case_Closed_Date__c still exist\n Case_Closed_Date__c: h.date_closed //&& h.date_closed == true\n ? h.date_closed\n : undefined \n };\n });\n\n const housevisits = state.payloads\n //HMN remove test user filters \n /*\n .filter(\n h =>\n h.properties.commcare_username !== 'openfn.test' &&\n h.properties.commcare_username !== 'test.2021' &&\n h.properties.test_user !== 'Yes'\n )*/\n .map(h => {\n // Special calculations ==================================================\n \n \n const visitIdC =\n h.case_id + '_' + h.properties.last_form_opened_date_and_time;\n\n const hVstatus = h.properties.Household_Status;\n const Active_Household__c =\n hVstatus === 'No' ? false : hVstatus === 'Yes' ? true : hVstatus;\n\n const insuranceTypeC = () => {\n let status = h.properties.health_insurance;\n\n let value =\n status && status !== ''\n ? status\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return insuranceMap[value] || value;\n })\n : undefined;\n return value ? value.join(';') : undefined;\n };\n\n const openedC = () => {\n const form_opened = h.properties.last_form_opened_date_and_time;\n\n if (form_opened) {\n const value1 = form_opened.split('-').slice(0, 2).join('-');\n const value2 = form_opened.split('-').slice(2).join('-');\n const formattedValue = [value1, value2].join(' ');\n return new Date(formattedValue).toISOString();\n }\n return undefined;\n };\n\n return {\n CommCare_Username__c: h.properties.commcare_username,\n CommCare_Visit_ID__c: visitIdC,\n Catchment__c: fetchReference(h.properties.owner_id, 'catchment'),\n 'Household__r.CommCare_Code__c': h.case_id,\n Date__c: h.properties.Date,\n Form_Submitted__c: h.properties.last_form_opened_name,\n Active_Household__c: Active_Household__c,\n Active_in_Nutrition_Program__c:\n h.properties.enrolled_in_a_lwala_nutrition_program,\n lwala_nutrition_program_enrollment_date__c:\n h.properties.lwala_nutrition_program_enrollment_date,\n Trained_in_gardening__c: h.properties.household_trained_on_gardening,\n household_trained_on_gardening_date__c:\n h.properties.when_was_the_household_trained_on_gardening,\n Seed_Input_Support__c:\n h.properties.household_provided_with_seed_input_support,\n household_provided_with_seed_input_suppo__c:\n h.properties.when_was_the_household_provided_with_seed_input_support,\n MIYCN_Trained__c: h.properties.household_trained_on_MIYCN,\n Kitchen_Garden__c: h.properties.Kitchen_Garden,\n Access_to_safe_water__c: h.properties.Safe_Water,\n Treats_Drinking_Water__c: h.properties.Treats_Drinking_Water,\n Tippy_Tap__c: h.properties.Active_Handwashing_Station,\n Pit_Latrine__c: h.properties.Functional_Latrine,\n Rubbish_Pit__c: h.properties.Rubbish_Pit,\n Drying_Rack__c: h.properties.Drying_Rack,\n Cookstove__c: h.properties.Improved_Cooking_Method,\n Clothe__c: h.properties.Clothesline,\n WASH_Trained__c: h.properties.WASH_Trained,\n Has_muac_tape__c: h.properties.family_muac_tape_available,\n Uses_ITNs__c: h.properties.ITNs,\n Supervisor_Visit__c: h.properties.supervisor_visit\n ? supervisorMap[h.properties.supervisor_visit]\n : null,\n Health_insurance__c: h.properties.health_insurace_cover,\n Health_insurance_active_status__c: h.properties.healthinsurance_active,\n Health_insurance_type__c: insuranceTypeC(),\n\n Other_Health_Insurance__c: h.properties.if_other_please_specify,\n CommCare_Form_Opened__c: openedC(),\n \n };\n });\n\n return { ...state, households, housevisits, fetchReference };\n});\n\n//JSON logging of records\n//HMN 06/11/2023\n/*fn(state => {\n console.log('HHs to upsert ::', JSON.stringify(state.households));\n return state;\n});*/\n\n\nbulk(\n 'Household__c',\n 'upsert',\n {\n extIdField: 'CommCare_Code__c',\n failOnError: true,\n allowNoOp: true,\n },\n state => {\n console.log('Bulk upserting households...');\n return state.households;\n }\n);\n\nfn(state => {\n if (state.payloads.length == 0) return state;\n\n console.log('house holds bulk upsert done');\n return state;\n});\n\n// TODO clean up in QA used for troubleshooting\n// Uncomment this block to add cooldown\n// fn(state => {\n// return new Promise((resolve, reject) => {\n// setTimeout(() => {\n// console.log('4 second cooldown finished.');\n// resolve(state);\n// }, 4000);\n// });\n// });\n\nbulk(\n 'Visit__c',\n 'upsert',\n {\n extIdField: 'CommCare_Visit_ID__c',\n failOnError: true,\n allowNoOp: true,\n },\n state => {\n console.log('Bulk upserting housevisits...');\n return state.housevisits;\n }\n);\n\nfn(state => {\n if (state.payloads.length == 0) return state;\n console.log('house visits bulk upsert done');\n return state;\n});\n\n// TODO clean up in QA for troubleshooting\n// Uncomment this block to add cooldown\n// fn(state => {\n// return new Promise((resolve, reject) => {\n// setTimeout(() => {\n// console.log('Final 4 second cooldown finished.');\n// resolve(state);\n// }, 4000);\n// });\n// });\n", + "adaptor": "@openfn/language-salesforce@4.8.6", + "project_credential_id": "25ba06d8-5559-4d1c-a8b8-828cc3021465" + } + }, + "edges": { + "cron->WF1-1-Bulk-get-HH-cases": { + "enabled": true, + "id": "05e5ccb9-aa25-4cae-80aa-f27839874bdd", + "target_job_id": "925ba65a-23c9-4796-98d8-97c704fea8c8", + "source_trigger_id": "7d7f810a-529b-48fa-9e76-0ff9132eedf2", + "condition_type": "always" + }, + "WF1-1-Bulk-get-HH-cases->WF1-2-Bulk-upsert-HHs-and-HH-Visits": { + "enabled": true, + "id": "3caaf6cc-d22a-4dc9-a158-2a4a3878e98c", + "target_job_id": "833a8e2f-a01a-4559-95e9-c38398d42d62", + "source_job_id": "925ba65a-23c9-4796-98d8-97c704fea8c8", + "condition_type": "on_job_success" + } + } + }, + "2-Bulk-Person-cases": { + "id": "a5ec2e75-2959-4a1a-b13b-ff8b5eb34fb3", + "name": "2-Bulk Person cases", + "inserted_at": "2025-01-31T13:02:42.953971Z", + "lock_version": 10, + "triggers": { + "cron": { + "enabled": true, + "id": "7b94e578-0abc-487a-8273-a58ade9e46b3", + "type": "cron", + "cron_expression": "1 * * * *" + } + }, + "jobs": { + "WF2-1-Bulk-get-Person-cases": { + "id": "568b74f3-c0b1-41f1-87af-8efb1321383c", + "name": "WF2-1 Bulk get Person cases", + "body": "fn(state => {\n const { baseUrl } = state.configuration;\n\n const caseTypes = ['Person'];\n\n //NOTE: You can use 'limit' to modify this batch size as desired\n const limit = 1000; //E.g., change to 10 to process records in smaller batch sizes\n\n //NOTE: indexedOnStart is the default sync start data the FIRST time the job runs\n const indexedOnStart = '2021-01-17T00:00:00';\n \n\n //NOTE: After first job run, OpenFn will check the job sync data (\"lastRunAt\") to set as the indexedOnStart\n const lastRunAt =\n typeof state.lastRunAt !== 'undefined' ? state.lastRunAt : indexedOnStart;\n console.log('Filtering cases with indexed_on_start > than ::', lastRunAt);\n\n const queries = caseTypes.map(\n t => `?type=${t}&indexed_on_start=${lastRunAt}&limit=${limit}\n &owner_id=a3c31c9be392427a97f8704262065661` // User id of test user test.2021. Remove for production\n //NOTE: If for testing, you want to fetch data for a specific historical range (e.g., between April 23 and 24)...\n //...then use the query string below instead of the one above on L16, and custom adjust the index_on start/end dates\n // t => `?type=${t}&indexed_on_start=2024-01-16T00:00:00&limit=${limit}&indexed_on_end=2024-01-16T23:59:59`\n );\n\n return { ...state, queries, baseUrl, payloads: [] };\n});\n\n// create a \"recursiveGet\" which will call itself if CommCare tells us there's\n// more data to fetch for the same form\nfn(state => {\n const recursiveGet = url =>\n get(\n url,\n {\n headers: { 'content-type': 'application/json' },\n },\n nextState => {\n const now = new Date();\n const { baseUrl, data, payloads } = nextState;\n\n const { meta, objects } = data;\n console.log('Metadata in CommCare response:', meta);\n\n const finalState = {\n ...nextState,\n payloads: [...payloads, ...objects],\n };\n\n if (meta.next) {\n console.log('Next query detected, recursing...');\n return recursiveGet(`${baseUrl}${meta.next}`)(finalState);\n }\n finalState.lastRunAt = now.toISOString().slice(0, 19);\n return finalState;\n }\n );\n\n return { ...state, recursiveGet };\n});\n\n// for each initial query, fetch data recursively\neach(\n '$.queries[*]',\n fn(state => {\n return state.recursiveGet(`${state.baseUrl}${state.data}`)(state);\n })\n);\n// log the total number of payloads returned\nfn(state => {\n console.log('Count of payloads', state.payloads.length);\n //HMN 11072023\n // console.log(JSON.stringify(state.payloads, null, 2));\n\n return { ...state, references: [], data: {} };\n});\n", + "adaptor": "@openfn/language-http@6.5.1", + "project_credential_id": "8d4d9b2d-e41a-40ab-92dc-e2280bb5ee2b" + }, + "WF2-2-Bulk-upsert-Persons": { + "id": "a5a75a25-fb1d-434f-b173-a9893f4c245c", + "name": "WF2-2 Bulk upsert Persons", + "body": "fn(state => {\n if (state.payloads.length == 0)\n return {\n ...state,\n householdMapping: [],\n headOfHouseholdMapping: [],\n motherMapping: [],\n caregiverMapping: [],\n sfRecordMapping: [],\n };\n // JSON logging of records\n //HMN debug\n //console.log('cases before query :: ', JSON.stringify(state.payloads, null, 2));\n const owner_ids = state.payloads.map(data => data.properties.owner_id);\n const uniq_owner_ids = [...new Set(owner_ids)];\n\n return { ...state, uniq_owner_ids };\n});\n\n// get data from SF\nfn(state => {\n if (state.payloads.length == 0) return state;\n\n return query(\n `SELECT CommCare_User_ID__c, Id village, Parent_Geographic_Area__c area, Parent_Geographic_Area__r.Name name, Parent_Geographic_Area__r.Parent_Geographic_Area__c catchment FROM Location__c WHERE CommCare_User_ID__c IN ('${state.uniq_owner_ids.join(\n \"','\"\n )}') GROUP BY Id, CommCare_User_ID__c, Parent_Geographic_Area__c, Parent_Geographic_Area__r.Name, Parent_Geographic_Area__r.Parent_Geographic_Area__c`\n )(state);\n});\n\nfn(state => {\n if (state.payloads.length == 0) return state;\n\n const [reference] = state.references;\n\n // console.log(JSON.stringify(reference.records, null, 2));\n\n const records = reference.records;\n const fetchReference = (owner_id, arg) => {\n const result =\n records && records.length > 0\n ? records.filter(record => record.CommCare_User_ID__c === owner_id)\n : 0;\n\n //TODO: Update default value for 'unknown location' before go-live\n return result.length > 0 ? result[0][arg] \n : 'a000800001tMobaAAC' /*unknown location*/;\n\n };\n\n const cleanChoice = choice => {\n if (choice) {\n return choice.charAt(0).toUpperCase() + choice.slice(1).replace('_', ' ');\n } else {\n return '';\n }\n };\n\n const handleMultiSelect = multiField => {\n return multiField\n ? multiField\n .replace(/ /gi, ';')\n .toLowerCase()\n .split(';')\n .map(value => {\n return (\n value.charAt(0).toUpperCase() + value.slice(1).replace('_', ' ')\n );\n })\n .join(';')\n : '';\n };\n\n const pregDangerMap = {\n Vaginal_Bleeding: 'Vaginal Bleeding',\n Water_Breaks: 'Water Breaks before Time of Delivery',\n Prolonged_Labour: 'Prolonged Labour over 12 Hours',\n Convulsions: 'Convulsions or Fits',\n Abdominal_Pain: 'Severe Abdominal Pain before Delivery',\n High_Fever: 'High Fever',\n Low_Baby_Movement: 'Feeling the Baby move less or not at all',\n Swelling: 'Swelling of Face and Hands',\n Severe_Headache: 'Severe or Continuous Headache for more than 12 hours',\n Severe_Vomiting: 'Severe or Continuous Vomiting',\n none: 'None',\n };\n\n const counselMap = {\n anc_visits: 'ANC Visits',\n early_initiation_of_anc_less_than_3_months:\n 'Early initiation of ANC (less than 3 months)',\n completing_recomended_anc_visits: 'Completing recomended ANC visits',\n danger_signs: 'Danger signs',\n skilled_birth: 'Skilled birth',\n immunization: 'Immunization',\n individual_birth_plan: 'Individual Birth Plan',\n emergency_preparedness: 'Emergency preparedness',\n childcare_and_affection: 'Childcare and affection',\n nutrition_counseling: 'Nutrition counseling',\n growth_monitoring: 'Growth monitoring',\n exclusive_breastfeeding: 'Exclusive breastfeeding',\n complementary_feeding: 'Complementary feeding',\n sleeping_under_llitn: 'Sleeping under LLITN',\n knowing_hiv_status: 'Knowing HIV status',\n indoor_pollution: 'Indoor pollution',\n personal_hygiene: 'Personal Hygiene',\n safe_drinking_water: 'Safe drinking water',\n safe_disposal_of_human_waste: 'Safe disposal of human waste',\n };\n\n const serviceMap = {\n Scheduled_PSC_Apt: 'Scheduled PSC Apt',\n Adverse_Drug_Reaction_Side_Effect: 'Adverse Drug Reaction/Side Effect',\n Malnutrition: 'Malnutrition',\n Malaria: 'Malaria',\n TB: 'TB',\n Treatment_for_Other_OIs: 'Treatment for other Ols',\n ARI: 'ARI',\n Anemia: 'Anemia',\n Diarrhea: 'Diarrhea',\n Pregnancy_Care: 'Pregnancy Care (ANC)',\n Family_Planning: 'Family Planning (FP)',\n Preconception_Counseling: 'Preconception Counseling',\n Injury: 'Injury',\n Other: 'Other',\n };\n\n const reasonMapping = {\n lack_of_access_to_fp_information: 'Lack of access to FP information',\n no_access_to_fp_services_hospitals:\n 'Lack of hospitals or places where FP services can be accessed',\n not_willing_to_use_fp_due_to_negative_effects_myths_and_misconceptions:\n 'Myths and misconceptions',\n barriers_at_service_delivery_points: 'Barriers at service delivery points',\n pregnant: 'The client is pregnant',\n intentions_of_getting_pregnant: 'Intentions of getting pregnant',\n not_sexually_active: 'The client is not sexually active',\n other_barriers_culture_male_partners_parents_etc:\n 'Other barriers (culture, male partners, parents, etc)',\n };\n\n const milestoneTypeMap = {\n cognitive_delays_learning_difficulties:\n 'Cognitive Delays Learning Difficulties',\n motor_delays: 'Motor Delays',\n speech_and_language_delay: 'Delay Speech and Language Delay',\n social_and_emotional: 'Social and emotional',\n };\n\n const milestoneMap = {\n movement: 'Movement',\n hearing: 'Hearing',\n communication: 'Communication',\n seeing: 'Seeing',\n cognitive_delays: 'Cognitive Delays',\n play: 'Play',\n };\n const nutritionMap = {\n severe: 'Severely Malnourished',\n moderate: 'Moderately Malnourished',\n normal: 'Normal',\n };\n\n const fpMethodMap = {\n male_condoms: 'Male condoms',\n female_condoms: 'Female condoms',\n pop: 'POP',\n coc: 'COC',\n emergency_pills: 'Emergency pills',\n none: 'None',\n };\n\n return {\n ...state,\n counselMap,\n serviceMap,\n reasonMapping,\n milestoneTypeMap,\n milestoneMap,\n nutritionMap,\n pregDangerMap,\n fpMethodMap,\n cleanChoice,\n handleMultiSelect,\n fetchReference,\n };\n});\n\n// build sfRecord before upserting\nfn(state => {\n if (state.payloads.length == 0) return state;\n\n const {\n counselMap,\n reasonMapping,\n milestoneTypeMap,\n milestoneMap,\n nutritionMap,\n pregDangerMap,\n fpMethodMap,\n cleanChoice,\n handleMultiSelect,\n fetchReference,\n } = state;\n\n const householdMapping = [\n ...new Map(\n state.payloads\n .filter(\n p =>\n p.indices.parent.case_id !== undefined &&\n p.indices.parent.case_id !== ''\n )\n .map(p => {\n return {\n CommCare_Code__c:\n p.indices.parent.case_id || p.properties.parent_id,\n };\n })\n .map(h => [h.CommCare_Code__c, h])\n ).values(),\n ];\n\n const headOfHouseholdMapping = state.payloads\n .filter(\n p =>\n p.properties.head_of_household_case_id !== undefined &&\n p.properties.head_of_household_case_id !== ''\n )\n .map(p => {\n return {\n CommCare_Code__c: p.indices.parent.case_id || p.properties.parent_id,\n 'Head_of_Household__r.CommCare_ID__c':\n p.properties.head_of_household_case_id,\n };\n });\n\n const motherMapping = state.payloads\n .filter(\n p =>\n /*HMN 050723 p.properties.commcare_username !== 'test.2021' &&\n p.properties.test_user !== 'Yes' &&\n */\n p.properties.mother_case_id !== undefined &&\n p.properties.mother_case_id !== '' &&\n p.case_id!== undefined\n )\n .map(p => {\n return {\n 'Mother__r.CommCare_ID__c': p.properties.mother_case_id,\n CommCare_ID__c: p.case_id,\n };\n });\n\n const caregiverMapping = state.payloads\n .filter(\n p =>\n /*HMN 070523 p.properties.commcare_username !== 'test.2021' &&\n p.properties.test_user !== 'Yes' &&\n */\n p.properties.caretaker_case_id !== undefined &&\n p.properties.caretaker_case_id !== '' &&\n p.case_id!== undefined\n )\n .map(p => {\n return {\n 'Primary_Caregiver_Lookup__r.CommCare_ID__c':\n p.properties.caretaker_case_id,\n CommCare_ID__c: p.case_id,\n };\n });\n\n const sfRecordMapping = state.payloads\n .filter(\n p =>\n /*HMN 050723 \n p.properties.commcare_username !== 'test.2021' &&\n p.properties.test_user !== 'Yes'\n */\n p.case_id !== undefined &&\n p.case_id !== ''\n ) \n .map(p => {\n // For unbornOrName\n const name1 = p.properties.Person_Name || p.properties.case_name;\n const unborn = p.properties.name;\n\n const name2 =\n name1 === undefined || name1 === '' || name1 === null\n ? unborn\n : name1.replace(/\\w\\S*/g, function (txt) {\n return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();\n });\n const unbornOrName = name1 !== null ? name2 : 'Unborn Child';\n // console.log('Person Name ::', unbornOrName);\n\n // For chronicIllness\n const chronicChoice =p.properties.please_specify_which_chronic_illness_the_person_has;\n const choice2 = handleMultiSelect(chronicChoice);\n const chronicIllness = choice2 ? choice2.replace(/_/g, ' ') : '';\n\n const disabilityC =\n p.properties.disability !== undefined && p.properties.disability !=='---' && p.properties.disability !== null\n ? p.properties.disability\n .toLowerCase()\n .split(' ')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(';')\n : null;\n//HMN remove\nconsole.log(p.case_id)\n//console.log(disabilityC)\n//\n const otherDisability =\n p.properties.other_disability !== undefined && p.properties.other_disability !=='---' && p.properties.other_disability !== null\n ? p.properties.other_disability\n .toLowerCase()\n .split(' ')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(';')\n : null;\n//HMN remove\n//console.log(otherDisability)\n//HMN\n const hh_relation = p.properties.relation_to_hh;\n\n const relationToTheHead = hh_relation !== undefined && hh_relation !== null\n ? hh_relation.toString().replace(/_/g, ' ').charAt(0).toUpperCase() +\n hh_relation.toString().replace(/_/g, ' ').slice(1)\n : null;\n\n const childStatus =\n p.properties.Child_Status && p.properties.Record_Type === 'Unborn'\n ? (p.properties.Child_Status = 'Unborn')\n : p.properties.Child_Status && p.properties.Record_Type === 'Born'\n ? (p.properties.Child_Status = 'Born')\n : p.properties.Child_Status;\n\n const childDangerSigns = p.properties.Other_Danger_Signs !== undefined && p.properties.Other_Danger_Signs !== null \n ? p.properties.Other_Danger_Signs.toLowerCase()\n .split(' ')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(';')\n .toString()\n .replace(/_/g, ' ')\n : p.properties.Other_Danger_Signs;\n\n //clientCounselled\n const clientChoices = p.properties.counsel_topic;\n const choiceGroups = clientChoices ? clientChoices.split(' ') : null;\n const clientCounselled = choiceGroups\n ? choiceGroups\n .map(cg => {\n return counselMap[cg];\n })\n .join(';')\n : choiceGroups;\n\n // fpMethodDistributed\n const fpStatus = p.properties.FP_commodity;\n const fpValue =\n fpStatus && fpStatus !== ''\n ? fpStatus\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return fpMethodMap[value] || value;\n })\n : undefined;\n const fpMethodDistributed = fpValue ? fpValue.join(';') : undefined;\n\n // placeOfDelivery\n const pFacility = p.properties.Delivery_Type;\n const placeOfDelivery =\n pFacility === 'Skilled'\n ? 'Facility'\n : pFacility === 'Unskilled'\n ? 'Home'\n : undefined;\n\n // reasonForNotTakingFP\n const rStatus = p.properties.No_FPmethod_reason;\n const rValue =\n rStatus && rStatus !== ''\n ? rStatus\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return reasonMapping[value] || value;\n })\n : undefined;\n const reasonForNotTakingFP = rValue ? rValue.join(';') : undefined;\n \n const recordType = p.properties.Record_Type;\n \n \n return {\n // TODO @aleksa, Source__c is causing an error\n Source__c: true,\n CommCare_ID__c: p.case_id,\n \n //HMN 05072023 'Primary_Caregiver_Lookup__r.CommCare_ID__c':p.properties.caretaker_case_id,\n //HMN 05072023 'Mother__r.CommCare_ID__c': p.properties.mother_case_id,\n 'Household__r.CommCare_Code__c':\n p.properties.parent_id || p.indices.parent.case_id,\n commcare_location_id__c: p.properties.commcare_location_id,\n CommCare_Username__c: p.properties.commcare_username,\n Telephone__c: p.properties.contact_phone_number,\n\n Consent_for_data_use__c: p.properties.data_sharing_consent,\n CommCare_HH_Code__c: p.indices.parent.case_id,\n Client_Status__c: p.properties.Client_Status,\n Catchment__c: fetchReference(p.properties.owner_id, 'catchment'),\n Area__c: fetchReference(p.properties.owner_id, 'area'),\n Household_Village__c: fetchReference(p.properties.owner_id, 'village'),\n Name: unbornOrName,\n Chronic_illness__c: chronicIllness,\n Currently_enrolled_in_school__c: p.properties.enrolled_in_school,\n Education_Level__c: p.properties.Education_Level !== null && p.properties.Education_Level !== undefined\n ? p.properties.Education_Level.toString().replace(/_/g, ' ')\n : null,\n Relation_to_the_head_of_the_household__c: relationToTheHead,\n Gender__c: p.properties.Gender !== undefined ? p.properties.Gender : null,\n Disability__c: disabilityC,\n Other_disability__c: otherDisability,\n Use_mosquito_net__c: p.properties.sleep_under_net,\n Birth_Certificate__c: p.properties.birth_certificate,\n Child_Status__c: childStatus,\n 'RecordType.Name': recordType === 'Unborn' || recordType === '' \n ? 'Child' \n : recordType.toString().replace(/_/g, ' '), //convert Unborn children to Child RT\n //TT5 Mother Information =====================//\n MCH_booklet__c: p.properties.mch_booklet,\n Reason_for_not_taking_a_pregnancy_test__c: p.properties.No_Preg_Test\n ? p.properties.No_Preg_Test.toString().replace(/_/g, ' ')\n : undefined,\n Pregnancy_danger_signs__c: p.properties.pregnancy_danger_signs\n ? pregDangerMap[p.properties.pregnancy_danger_signs]\n : undefined,\n Individual_birth_plan_counselling__c:\n p.properties.individual_birth_plan,\n Child_Danger_Signs__c: childDangerSigns,\n //HAWI =====================//\n\n Unique_Patient_Code__c: p.properties.Unique_Patient_Code,\n Active_in_Support_Group__c: p.properties.Active_in_Support_Group,\n Preferred_Care_Facility__c: p.properties.Preferred_Care_Facility,\n Currently_on_ART_s__c: p.properties.ART,\n ART_Regimen__c: p.properties.ARVs,\n HAWI_Defaulter__c: p.properties.default === 'Yes' ? true : false,\n Date_of_Default__c: p.properties.date_of_default,\n Know_HIV_status__c: p.properties.known_hiv_status,\n HIV_Status__c: p.properties.hiv_status,\n //Illness ========================//\n Persons_temperature__c: p.properties.temperature,\n Days_since_illness_start__c: p.properties.duration_of_sickness,\n Current_Malaria_Status__c: p.properties.malaria_test_results,\n Malaria_test__c: p.properties.malaria_test,\n Last_Malaria_Home_Test__c: p.properties.malaria_test_date,\n Last_Malaria_Home_Treatment__c: cleanChoice(\n p.properties.malaria_test_date\n ),\n Cough_over_14days__c: p.properties.symptoms_check_cough,\n TB_patients_therapy_observed__c: p.properties.observed_tb_therapy,\n Injuries_or_wounds__c: p.properties.wounds_or_injuries,\n Pulse_Oximeter__c: p.properties.pulse_oximeter_available,\n Heart_Rate_Pulse_Oximeter__c: p.properties.heart_rate_pulse_oximeter,\n Oxygen_Concentration_Pulse_Oximeter__c:\n p.properties.oxygen_concentration,\n Can_child_drink__c: p.properties.can_child_drink,\n Antibiotic_provided_for_fast_breathing__c: cleanChoice(\n p.properties.antibiotic_fast_breathing\n ),\n Antibiotic_provided_for_chest_indrawing__c: cleanChoice(\n p.properties.antibiotic_chest_indrawing\n ),\n Default_on_TB_treatment__c: cleanChoice(\n p.properties.default_tb_treatment\n ),\n Treatment_Distribution__c: cleanChoice(\n p.properties.distributed_treatments\n ),\n //Delivery =====================//\n Immediate_Breastfeeding__c: p.properties.Breastfeeding_Delivery,\n Place_of_Delivery__c: placeOfDelivery,\n Delivery_Facility__c: p.properties.Delivery_Facility\n ? p.properties.Delivery_Facility.toString().replace(/_/g, ' ')\n : null,\n Delivery_Facility_Other__c: p.properties.Delivery_Facility_Other,\n //Family Planning =====================//\n LMP__c: p.properties.LMP,\n Family_Planning__c: p.properties.family_planning,\n Family_Planning_Method__c: p.properties.family_planning_method,\n FP_Method_Distributed__c: fpMethodDistributed,\n Reasons_for_not_taking_FP_method__c: reasonForNotTakingFP,\n Pregnant__c: p.properties.Pregnant === 'Yes' ? true : false,\n Date_of_Delivery__c: p.properties.delivery_date,\n Counselled_on_FP_Methods__c: p.properties.CounselledFP_methods,\n Client_counselled_on__c: clientCounselled,\n Client_provided_with_FP__c: cleanChoice(\n p.properties[\n 'was_the_woman_15-49yrs_provided_with_family_planning_commodities_by_chv'\n ]\n ),\n Received_pregnancy_test__c:\n p.properties.did_you_adminsiter_a_pregnancy_test,\n Pregnancy_test_result__c: p.properties.pregnancy_test_result,\n Gravida__c: p.properties.Gravida,\n Parity__c: p.properties.Parity,\n //TT5 Child Information =====================//\n Exclusive_Breastfeeding__c: p.properties.Exclusive_Breastfeeding,\n Counselled_on_Exclusive_Breastfeeding__c: p.properties.counseling,\n Newborn_visited_48_hours_of_delivery__c:\n p.properties.newborn_visited_48_hours_of_delivery,\n Newborn_visit_counselling__c: cleanChoice(\n p.properties.did_you_consel_the_mother_on1\n ),\n mother_visited_48_hours_of_the_delivery__c:\n p.properties.visit_mother_48,\n Mother_visit_counselling__c: cleanChoice(\n p.properties.did_you_consel_the_mother_on2\n ),\n Newborn_visited_by_a_CHW_within_6_days__c:\n p.properties.visit_6_days_from_delivery,\n //Nutrition =====================//\n Caretaker_action_after_muac_screening__c:\n p.properties.mother_screened_muac_action,\n Caretaker_muac_findings__c:\n p.properties.mother_screened_child_muac_result,\n Food_groups_3_times_a_day__c: p.properties.food_groups,\n Caretaker_screened_for_muac_this__c: cleanChoice(\n p.properties.mother_screened_child_muac\n ),\n Caretaker_trained_in_muac__c: cleanChoice(\n p.properties.mother_trained_muac\n ),\n of_Caretaker_MUAC_screenings__c: p.properties.mother_nb_screening,\n Current_Height__c: p.properties.current_height,\n Current_MUAC__c: p.properties.MUAC,\n Current_Nutrition_Status__c: p.properties.Nutrition_Status\n ? nutritionMap[p.properties.Nutrition_Status]\n : undefined,\n //TT5 & HAWI =====================//\n TT5_Mother_Registrant__c: p.properties.Pregnant == 'Yes' ? 'Yes' : null,\n Enrollment_Date__c:\n p.properties.age < 5 || p.properties.Pregnant == 'Yes'\n ? p.server_date_modified\n : null,\n HAWI_Enrollment_Date__c:\n p.properties.hiv_status == 'positive' ? p.server_date_modified : null,\n Thrive_Thru_5_Registrant__c:\n p.properties.age < 5 || p.properties.Pregnant == 'Yes' ? 'Yes' : 'No',\n HAWI_Registrant__c:\n p.properties.hiv_status == 'positive' ? 'Yes' : 'No',\n //ANC =====================//\n ANC_1__c:\n p.properties.ANC_1 && p.properties.ANC_1 !== ''\n ? p.properties.ANC_1\n : undefined,\n ANC_2__c:\n p.properties.ANC_2 && p.properties.ANC_2 !== ''\n ? p.properties.ANC_2\n : undefined,\n ANC_3__c:\n p.properties.ANC_3 && p.properties.ANC_3 !== ''\n ? p.properties.ANC_3\n : undefined,\n ANC_4__c:\n p.properties.ANC_4 && p.properties.ANC_4 !== ''\n ? p.properties.ANC_4\n : undefined,\n ANC_5__c:\n p.properties.ANC_5 && p.properties.ANC_5 !== ''\n ? p.properties.ANC_5\n : undefined,\n Date_of_Birth__c:\n p.properties.DOB && p.properties.DOB !== ''\n ? p.properties.DOB.replace(/\\\\/g, '-')\n : undefined,\n //Immunization =====================//\n // Child_missed_immunization_type__c:\n // p.form.TT5.Child_Information.Immunizations.immunization_type,\n BCG__c: p.properties.BCG,\n OPV_0__c: p.properties.OPV_0,\n Measles_6__c: p.properties.Measles_6,\n Measles_9__c: p.properties.Measles_9,\n Measles_18__c: p.properties.Measles_18,\n OPV_1__c: p.properties.OPV_PCV_Penta_1,\n OPV_2__c: p.properties.OPV_PCV_Penta_2,\n OPV_3__c: p.properties.OPV_PCV_Penta_3,\n Rotavirus_1__c: p.properties.rotavirus_1,\n Rotavirus_2__c: p.properties.rotavirus_2,\n IPV__c: p.properties.IPV,\n Vitamin_A_12__c: p.properties.Vitamine_A,\n Vitamin_A_18__c: p.properties.Vitamine_A_2,\n Vitamin_A_24__c: p.properties.Vitamine_A_3,\n Deworming_12__c: p.properties.Deworming_1,\n Deworming_18__c: p.properties.Deworming_2,\n Deworming_24__c: p.properties.Deworming_3,\n //ECD =====================//\n Did_you_counsel_caregiver_on__c: cleanChoice(\n p.properties.did_you_counsel_the_caregiver_on_delayed_milestones\n ),\n Delayed_Milestone__c: cleanChoice(\n p.properties.does_the_child_has_a_delayed_milestone\n ),\n Child_has_2_or_more_play_items__c: cleanChoice(\n p.properties.does_the_child_has_2_or_more_play_items_at_home\n ),\n Child_has_3_or_more_picture_books__c: cleanChoice(\n p.properties.does_the_child_has_3_or_more_picture_books\n ),\n Delayed_Milestones_Counselled_On__c: p.properties\n .which_delayed_milestone_area_did_you_counsel_the_caregiver_on\n ? milestoneMap[\n p.properties\n .which_delayed_milestone_area_did_you_counsel_the_caregiver_on\n ]\n : undefined,\n Delayed_Milestone_Type__c: p.properties.which_delayed_milestone\n ? milestoneTypeMap[p.properties.which_delayed_milestone]\n : undefined,\n //Death =====================//\n Date_of_Death__c: p.properties.Date_of_Death,\n Cause_of_Death__c: p.properties.cause_of_death_dead\n ? p.properties.cause_of_death_dead.toString().replace(/_/g, ' ')\n : p.properties.cause_of_death_dead,\n Verbal_autopsy__c: p.properties.verbal_autopsy,\n //Closing =====================//\n Last_Modified_Date_CommCare__c: p.date_modified,\n Case_Closed_Date__c: p.date_closed,\n };\n });\n\n sfRecordMapping.forEach(rec => {\n Object.entries(rec).forEach(([key, value]) => {\n if (value === '' || value === null) rec[key] = undefined;\n });\n });\n\n // TODO clean up after QA\n // console.log(JSON.stringify(caregiverMapping, null, 2), 'careGiver');\n // console.log(JSON.stringify(motherMapping, null, 2), 'Mother');\n //console.log(JSON.stringify(sfRecordMapping, null, 2), 'sfRecordMapping');\n // console.log(JSON.stringify(householdMapping, null, 2), 'householdMapping');\n // console.log(\n // JSON.stringify(headOfHouseholdMapping, null, 2),\n // 'headOfHouseholdMapping'\n // );\n\n return {\n ...state,\n motherMapping,\n sfRecordMapping,\n caregiverMapping,\n householdMapping,\n headOfHouseholdMapping,\n };\n});\n\n\n// TODO, Clean up when pass QA\n /*fn(state => {\n state.sfRecordMapping.forEach(rec => {\n Object.entries(rec).forEach(([key, value]) => {\n if (typeof key !== 'string') throw `${key} is not a string`;\n });\n });\n return state;\n });\n*/\n// bulk(\n// 'Household__c',\n// 'upsert',\n// {\n// extIdField: 'CommCare_Code__c',\n// failOnError: true,\n// allowNoOp: true,\n// },\n// state => {\n// console.log('Bulk upserting...');\n// return state.householdMapping;\n// }\n// );\n\n// TODO, Clean up when pass QA\n// upsert data to SF\n// upsertIf(\n// state.data.properties.commcare_username !== 'test.2021' &&\n// state.data.properties.test_user !== 'Yes',\n// 'Person__c',\n// 'CommCare_ID__c',\n// state => state.sfRecord\n// );\n\nbulk(\n 'Person__c',\n 'upsert',\n {\n extIdField: 'CommCare_ID__c',\n failOnError: true,\n allowNoOp: true,\n },\n state => {\n console.log('Bulk upserting persons ::');\n //HMN commented this \n //console.log(JSON.stringify(state.sfRecordMapping, null, 2));\n return state.sfRecordMapping;\n }\n);\n// TODO, Clean up when pass QA\n// upsertIf(\n// state.data.properties.commcare_username !== 'test.2021' &&\n// state.data.properties.test_user !== 'Yes' &&\n// state.data.properties.caretaker_case_id !== undefined &&\n// state.data.properties.caretaker_case_id !== '',\n// 'Person__c',\n// 'CommCare_ID__c',\n// fields(\n// relationship('Primary_Caregiver_Lookup__r', 'CommCare_ID__c', state => {\n// return (caregiver = dataValue('properties.caretaker_case_id')(state));\n// }),\n// field('CommCare_ID__c', dataValue('case_id'))\n// )\n// );\n\nbulk(\n 'Person__c',\n 'upsert',\n {\n extIdField: 'CommCare_ID__c',\n failOnError: true,\n allowNoOp: true,\n },\n state => {\n console.log('Bulk upserting primary caregiver Persons ::');\n //console.log(JSON.stringify(state.caregiverMapping, null, 2));\n return state.caregiverMapping;\n }\n);\n\n// TODO, Clean up when pass QA\n// upsertIf(\n// state.data.properties.commcare_username !== 'test.2021' &&\n// state.data.properties.test_user !== 'Yes' &&\n// state.data.properties.mother_case_id !== undefined &&\n// state.data.properties.mother_case_id !== '',\n// 'Person__c',\n// 'CommCare_ID__c',\n// fields(\n// relationship('Mother__r', 'CommCare_ID__c', state => {\n// return (caregiver = dataValue('properties.mother_case_id')(state));\n// }),\n// field('CommCare_ID__c', dataValue('case_id'))\n// )\n// );\nbulk(\n 'Person__c',\n 'upsert',\n {\n extIdField: 'CommCare_ID__c',\n failOnError: true,\n allowNoOp: true,\n },\n state => {\n console.log('Bulk upserting mother Person::');\n // console.log(JSON.stringify(state.motherMapping, null, 2));\n return state.motherMapping;\n }\n);\n\n// TODO, Clean up when pass QA\n// upsertIf(\n// state.data.properties.commcare_username !== 'test.2021' &&\n// state.data.properties.test_user !== 'Yes' &&\n// state.data.properties.head_of_household_case_id !== undefined &&\n// state.data.properties.head_of_household_case_id !== '',\n// 'Household__c',\n// 'CommCare_Code__c',\n// fields(\n// field('CommCare_Code__c', dataValue('indices.parent.case_id')),\n// relationship(\n// 'Head_of_Household__r',\n// 'CommCare_ID__c',\n// dataValue('properties.head_of_household_case_id')\n// )\n// )\n// );\n\nbulk(\n 'Household__c',\n 'upsert',\n {\n extIdField: 'CommCare_Code__c',\n failOnError: true,\n allowNoOp: true,\n },\n state => {\n console.log('Bulk upserting head of household field on HH ::');\n // console.log(JSON.stringify(state.headOfHouseholdMapping, null, 2));\n return state.headOfHouseholdMapping;\n }\n);\n", + "adaptor": "@openfn/language-salesforce@4.8.6", + "project_credential_id": "25ba06d8-5559-4d1c-a8b8-828cc3021465" + } + }, + "edges": { + "cron->WF2-1-Bulk-get-Person-cases": { + "enabled": true, + "id": "6e271ed8-7a35-4ffd-a772-25a36ea14331", + "target_job_id": "568b74f3-c0b1-41f1-87af-8efb1321383c", + "source_trigger_id": "7b94e578-0abc-487a-8273-a58ade9e46b3", + "condition_type": "always" + }, + "WF2-1-Bulk-get-Person-cases->WF2-2-Bulk-upsert-Persons": { + "enabled": true, + "id": "c3c4b656-3491-4d06-aa5b-de658eaf37b9", + "target_job_id": "a5a75a25-fb1d-434f-b173-a9893f4c245c", + "source_job_id": "568b74f3-c0b1-41f1-87af-8efb1321383c", + "condition_type": "on_job_success" + } + } + }, + "3-Bulk-Person-Visit-cases": { + "id": "09f0e8aa-e120-45f5-859b-86ea2c994f46", + "name": "3-Bulk Person Visit cases", + "inserted_at": "2025-01-31T13:02:45.585243Z", + "lock_version": 11, + "triggers": { + "cron": { + "enabled": true, + "id": "741b5feb-cd4c-4acd-af47-0788b6ada29a", + "type": "cron", + "cron_expression": "2 * * * *" + } + }, + "jobs": { + "WF3-1-Bulk-get-Person-Visit-cases": { + "id": "622d2cc3-0ed1-410a-ac6e-9ba7b8fab05d", + "name": "WF3-1 Bulk get Person Visit cases", + "body": "fn(state => {\n const { baseUrl } = state.configuration;\n\n const caseTypes = ['visite'];\n\n //NOTE: You can use 'limit' to modify this batch size as desired\n const limit = 1000; //E.g., change to 10 to process records in smaller batch sizes\n\n //NOTE: indexedOnStart is the default sync start data the FIRST time the job runs\n const indexedOnStart = '2024-01-17T01:00:00';\n\n //NOTE: After first job run, OpenFn will check the job sync data (\"lastRunAt\") to set as the indexedOnStart\n const lastRunAt =\n typeof state.lastRunAt !== 'undefined' ? state.lastRunAt : indexedOnStart;\n console.log('Filtering cases with indexed_on_start > than ::', lastRunAt);\n \n const aMinuteAgo = new Date( Date.now() - 1000 * 60 );\n console.log(aMinuteAgo);\n\n const queries = caseTypes.map(\n t => `?type=${t}&indexed_on_start=${lastRunAt}&limit=${limit}\n &owner_id=a3c31c9be392427a97f8704262065661` // User id of test user test.2021. Remove for production\n //NOTE: If for testing, you want to fetch data for a specific historical range (e.g., between April 23 and 24)...\n //...then use the query string below instead of the one above on L16, and custom adjust the index_on start/end dates\n //t => `?type=${t}&indexed_on_start=2024-01-15T00:00:00&limit=${limit}&indexed_on_end=2024-01-16T23:59:59`\n );\n\n return { ...state, queries, baseUrl, payloads: [] };\n});\n\n// create a \"recursiveGet\" which will call itself if CommCare tells us there's\n// more data to fetch for the same form\n\nfn(state => {\n const recursiveGet = url =>\n get(\n url,\n {\n headers: { 'content-type': 'application/json' },\n },\n nextState => {\n const now = new Date();\n const { baseUrl, data, payloads } = nextState;\n\n const { meta, objects } = data;\n console.log('Metadata in CommCare response:', meta);\n\n const finalState = {\n ...nextState,\n payloads: [...payloads, ...objects],\n };\n\n if (meta.next) {\n console.log('Next query detected, recursing...');\n return recursiveGet(`${baseUrl}${meta.next}`)(finalState);\n }\n finalState.lastRunAt = now.toISOString().slice(0, 19);\n return finalState;\n }\n );\n\n return { ...state, recursiveGet };\n});\n\n// for each initial query, fetch data recursively\neach(\n '$.queries[*]',\n fn(state => {\n return state.recursiveGet(`${state.baseUrl}${state.data}`)(state);\n })\n);\n// log the total number of payloads returned\nfn(state => {\n console.log('Count of payloads', state.payloads.length);\n\n return { ...state, references: [], data: {} };\n});\n", + "adaptor": "@openfn/language-http@6.5.1", + "project_credential_id": "8d4d9b2d-e41a-40ab-92dc-e2280bb5ee2b" + }, + "WF3-2-Bulk-upsert-Person-Visits": { + "id": "19b00789-97a6-4642-87ef-5d3fbee7d423", + "name": "WF3-2 Bulk upsert Person Visits", + "body": "fn(state => {\n if (state.payloads.length == 0) return { ...state, personVisits: [] };\n\n const owner_ids = state.payloads.map(data => data.properties.owner_id);\n const uniq_owner_ids = [...new Set(owner_ids)];\n\n return { ...state, uniq_owner_ids };\n});\n\nfn(state => {\n if (state.payloads.length == 0) return state;\n return query(\n `SELECT CommCare_User_ID__c, Id village, Parent_Geographic_Area__c area, Parent_Geographic_Area__r.Name name, Parent_Geographic_Area__r.Parent_Geographic_Area__c catchment FROM Location__c WHERE CommCare_User_ID__c IN ('${state.uniq_owner_ids.join(\n \"','\"\n )}') GROUP BY Id, CommCare_User_ID__c, Parent_Geographic_Area__c, Parent_Geographic_Area__r.Name, Parent_Geographic_Area__r.Parent_Geographic_Area__c`\n )(state);\n});\n\nfn(state => {\n if (state.payloads.length == 0) return state;\n const [reference] = state.references;\n\n \n // console.log(JSON.stringify(reference, null, 2));\n const records = reference.records;\n const fetchReference = (owner_id, arg) => {\n const result =\n records && records.length > 0\n ? records.filter(record => record.CommCare_User_ID__c === owner_id)\n : 0;\n\n return result.length > 0 ? result[0][arg] : undefined;\n };\n const cleanChoice = choice => {\n if (choice) {\n return choice.charAt(0).toUpperCase() + choice.slice(1).replace('_', ' ');\n } else {\n return '';\n }\n };\n\n const handleMultiSelect = multiField => {\n return multiField\n ? multiField\n .replace(/ /gi, ';')\n .toLowerCase()\n .split(';')\n .map(value => {\n return (\n value.charAt(0).toUpperCase() + value.slice(1).replace('_', ' ')\n );\n })\n .join(';')\n : '';\n };\n\n const handleMultiSelectOriginal = multiField => {\n return multiField\n ? multiField\n .replace(/ /gi, ';')\n .toLowerCase()\n .split(';')\n .map(value => {\n return value;\n })\n .join(';')\n : '';\n };\n\n const pregDangerMap = {\n Vaginal_Bleeding: 'Vaginal Bleeding',\n Water_Breaks: 'Water Breaks before Time of Delivery',\n Prolonged_Labour: 'Prolonged Labour over 12 Hours',\n Convulsions: 'Convulsions or Fits',\n Abdominal_Pain: 'Severe Abdominal Pain before Delivery',\n High_Fever: 'High Fever',\n Low_Baby_Movement: 'Feeling the Baby move less or not at all',\n Swelling: 'Swelling of Face and Hands',\n Severe_Headache: 'Severe or Continuous Headache for more than 12 hours',\n Severe_Vomiting: 'Severe or Continuous Vomiting',\n none: 'None',\n };\n\n const counselMap = {\n anc_visits: 'ANC Visits',\n early_initiation_of_anc_less_than_3_months:\n 'Early initiation of ANC (less than 3 months)',\n completing_recomended_anc_visits: 'Completing recomended ANC visits',\n danger_signs: 'Danger signs',\n skilled_birth: 'Skilled birth',\n immunization: 'Immunization',\n individual_birth_plan: 'Individual Birth Plan',\n emergency_preparedness: 'Emergency preparedness',\n childcare_and_affection: 'Childcare and affection',\n nutrition_counseling: 'Nutrition counseling',\n growth_monitoring: 'Growth monitoring',\n exclusive_breastfeeding: 'Exclusive breastfeeding',\n complementary_feeding: 'Complementary feeding',\n sleeping_under_llitn: 'Sleeping under LLITN',\n knowing_hiv_status: 'Knowing HIV status',\n indoor_pollution: 'Indoor pollution',\n personal_hygiene: 'Personal Hygiene',\n safe_drinking_water: 'Safe drinking water',\n safe_disposal_of_human_waste: 'Safe disposal of human waste',\n };\n\n const serviceMap = {\n Scheduled_PSC_Apt: 'Scheduled PSC Apt',\n Adverse_Drug_Reaction_Side_Effect: 'Adverse Drug Reaction/Side Effect',\n Malnutrition: 'Malnutrition',\n Malaria: 'Malaria',\n TB: 'TB',\n Treatment_for_Other_OIs: 'Treatment for other Ols',\n ARI: 'ARI',\n Anemia: 'Anemia',\n Diarrhea: 'Diarrhea',\n Pregnancy_Care: 'Pregnancy Care (ANC)',\n Family_Planning: 'Family Planning (FP)',\n Preconception_Counseling: 'Preconception Counseling',\n Injury: 'Injury',\n Other: 'Other',\n };\n\n const reasonMap = {\n lack_of_access_to_fp_information: 'Lack of access to FP information',\n no_access_to_fp_services_hospitals:\n 'Lack of hospitals or places where FP services can be accessed',\n not_willing_to_use_fp_due_to_negative_effects_myths_and_misconceptions:\n 'Myths and misconceptions',\n barriers_at_service_delivery_points: 'Barriers at service delivery points',\n pregnant: 'The client is pregnant',\n intentions_of_getting_pregnant: 'Intentions of getting pregnant',\n not_sexually_active: 'The client is not sexually active',\n other_barriers_culture_male_partners_parents_etc:\n 'Other barriers (culture, male partners, parents, etc)',\n };\n\n const milestoneTypeMap = {\n cognitive_delays_learning_difficulties:\n 'Cognitive Delays Learning Difficulties',\n motor_delays: 'Motor Delays',\n speech_and_language_delay: 'Delay Speech and Language Delay',\n social_and_emotional: 'Social and emotional',\n };\n\n const milestoneMap = {\n movement: 'Movement',\n hearing: 'Hearing',\n communication: 'Communication',\n seeing: 'Seeing',\n cognitive_delays: 'Cognitive Delays',\n play: 'Play',\n };\n const nutritionMap = {\n severe: 'Severely Malnourished',\n moderate: 'Moderately Malnourished',\n normal: 'Normal',\n };\n\n const fpMethodMap = {\n male_condoms: 'Male condoms',\n female_condoms: 'Female condoms',\n pop: 'POP',\n coc: 'COC',\n emergency_pills: 'Emergency pills',\n none: 'None',\n //HMN -12/01/2023-\n //adding normalization for the family_planning_method to Family_Planning_Method__c\n iucd: 'IUCD',\n condoms: 'Condoms',\n depo: 'Depo',\n implant: 'Implant',\n injection: 'Injection',\n pills: 'Pills',\n traditional: 'Traditional',\n };\n\n const symptomsMap = {\n convulsions: 'Convulsions',\n not_able_to_eatdrink: 'Not able to drink or feed at all',\n vomits_everything: 'Vomits everything',\n 'chest_in-drawing': 'Chest in - drawing',\n unusually_sleepyunconscious: 'Unusually sleepy or unconscious',\n swelling_of_both_feet: 'Swelling of both feet',\n none: 'None',\n };\n\n const supervisorMap = {\n community_health_nurse: 'Community_health_nurse',\n chw_supervisor: 'CHW_supervisor',\n chewschas: 'Chewschas',\n other: 'Other',\n none: 'None',\n };\n\n const treatmentDistributionMap = {\n ors_205gltr_sachets: 'ORS (20.5h/ltr): Sachets',\n acts_6s: 'ACTs (6s)',\n acts_12s: 'ACTs (12s)',\n acts_18s: 'ACTs (18s)',\n acts_24s: 'ACTs (24s)',\n albendazole_abz_tabs: 'Albendazole (ABZ): Tabs',\n paracetamol_tabs: 'Tetracycline Eye Ointment (TEO): 1%:tube',\n tetracycline_eye_ointment_teo_1_tube:\n 'Tetracycline Eye Ointment (TEO): 1%:tube',\n amoxycillin: 'Amoxycillin (125mg/5mls: Bottle',\n none: 'None',\n };\n\n const childDangerSignsMap = {\n none: 'None',\n Poor_Breastfeeding: 'Poor Breastfeeding',\n not_able_to_feed_since_birth_or_stopped_feeding_well:\n 'Not able to feed since birth, or stopped feeding well',\n not_able_to_breastfeed: 'Not able to breastfeed',\n Fever: 'Fever',\n very_low_temperature: 'Very low temperature (35.4 C or less)',\n shivering: 'Shivering',\n Fast_Breathing: 'Fast Breathing',\n Very_Sleepy: 'Very Sleepy',\n Convulsions_and_Fits: 'Convulsions and Fits',\n only_moves_when_stimulated_or_does_not_move_even_on_stimulation:\n 'Only moves when stimulated, or does not move even on stimulation',\n yellow_solebaby_body_turning_yellow_especially_eyes_palms_soles:\n 'Yellow sole(Baby body turning yellow especially eyes, palms,soles)',\n bleeding_from_the_umbilical_stump: 'Bleeding from the umbilical stump',\n signs_of_local_infection_umbilicus_is_red_or_draining_pus_skin_boils_or_eye:\n 'Signs of local infection: umbilicus is red or draining pus, skin boils, or eyes draining pus',\n weight_chart_using_color_coded_scales_if_red_or_yellowweight_below_25kg_or_:\n 'Weight chart using color coded scales if RED or YELLOW(Weight below 2.5kg or born less than 36 weeks of age)',\n unable_to_cry: 'Unable to cry',\n cyanosis: 'Cyanosis',\n bulging_fontanelle: 'Bulging fontanelle',\n };\n\n return {\n ...state,\n counselMap,\n serviceMap,\n reasonMap,\n milestoneTypeMap,\n milestoneMap,\n nutritionMap,\n pregDangerMap,\n fpMethodMap,\n symptomsMap,\n supervisorMap,\n treatmentDistributionMap,\n childDangerSignsMap,\n fetchReference,\n cleanChoice,\n handleMultiSelect,\n handleMultiSelectOriginal,\n };\n});\n\nfn(state => {\n if (state.payloads.length == 0) return state;\n const {\n counselMap,\n serviceMap,\n reasonMap,\n milestoneTypeMap,\n milestoneMap,\n nutritionMap,\n pregDangerMap,\n fpMethodMap,\n symptomsMap,\n supervisorMap,\n treatmentDistributionMap,\n childDangerSignsMap,\n fetchReference,\n cleanChoice,\n handleMultiSelect,\n handleMultiSelectOriginal,\n } = state;\n\n const personVisits = state.payloads\n //HMN 30/06/2023 Allow test user to post\n /*\n .filter(\n p =>\n p.properties.username !== 'test.2021' &&\n p.properties.test_user !== 'Yes'\n )*/\n .map(p => {\n // commCareVisitID\n const commCareCase_id = p.case_id;\n const dateVisit = p.properties.date_opened;\n const commCareVisitID = commCareCase_id + '_' + dateVisit;\n\n // personsSymptoms\n const psCheck = p.properties.symptoms_check_other;\n const psValue =\n psCheck && psCheck !== ''\n ? psCheck\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return symptomsMap[value] || value;\n })\n : undefined;\n const personsSymptoms = psValue ? psValue.join(';') : undefined;\n\n // familyPlanningMethod\n const fpmStatus = p.properties.family_planning_method;\n const fpmValue =\n fpmStatus && fpmStatus !== ''\n ? fpmStatus\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return fpMethodMap[value] || value;\n })\n : undefined;\n const familyPlanningMethod = fpmValue ? fpmValue.join(';') : undefined;\n\n // fpMethodDistributed\n const fpmdStatus = p.properties.FP_commodity;\n const fpmdValue =\n fpmdStatus && fpmdStatus !== ''\n ? fpmdStatus\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return fpMethodMap[value] || value;\n })\n : undefined;\n const fpMethodDistributed = fpmdValue ? fpmdValue.join(';') : undefined;\n\n // reasonForNotTakingFPMethod\n const rfntStatus = p.properties.No_FPmethod_reason;\n const rfntValue =\n rfntStatus && rfntStatus !== ''\n ? rfntStatus\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return reasonMap[value] || value;\n })\n : undefined;\n const reasonForNotTakingFPMethod = rfntValue\n ? rfntValue.join(';')\n : undefined;\n\n // clientCounselledOnC\n const ccocChoices =\n p.properties.counsel_topic || p.properties.counsel_topic;\n const ccocVhoiceGroups = ccocChoices ? ccocChoices.split(' ') : null;\n const clientCounselledOnC = ccocVhoiceGroups\n ? ccocVhoiceGroups\n .map(cg => {\n return counselMap[cg];\n })\n .join(';')\n : ccocVhoiceGroups;\n\n // treatmentDistributionC\n //const tdcStatus = p.form.treatment_and_tracking.distribution.distributed_treatments;\n const tdcStatus = p.properties.distributed_treatments;\n const tdcValue =\n tdcStatus && tdcStatus !== ''\n ? tdcStatus\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return treatmentDistributionMap[value] || value;\n })\n : undefined;\n const treatmentDistributionC = tdcValue ? tdcValue.join(';') : undefined;\n\n // chronicIllnesC\n const ciChoice =\n p.properties.please_specify_which_chronic_illness_the_person_has;\n const ciChoice2 = handleMultiSelect(ciChoice);\n const chronicIllnesC = ciChoice2 ? ciChoice2.replace(/_/g, ' ') : '';\n\n // supervisorVisit\n const svCheck = p.properties.supervisor_visit;\n const svValue =\n svCheck && svCheck !== ''\n ? svCheck\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return supervisorMap[value] || value;\n })\n : undefined;\n const supervisorVisit = svValue ? svValue.join(';') : undefined;\n const recordType = p.properties.RecordType;\n\n return {\n CommCare_ID__c: p.case_id, //'visit' case_id\n 'Person__r.CommCare_ID__c':\n p.indices.parent.case_id || p.properties.parent_id,\n CommCare_Visit_ID__c: commCareVisitID,\n Date__c: p.properties.Date,\n Birth_Status__c: p.properties.child_status,\n Catchment__c: fetchReference(p.properties.owner_id, 'catchment'),\n //HMN Accommodating Record Type in Visit\n 'RecordType.Name': recordType === 'Unborn' || recordType === 'Child' \n ? 'Child Visit' \n :recordType === 'Youth'\n ? 'Youth Visit'\n :recordType === 'Male Adult'\n ? 'Adult Male Visit'\n : recordType === 'Female Adult'\n ? 'Adult Female Visit'\n :undefined,\n Use_mosquito_net__c: cleanChoice(p.properties.sleep_under_net),\n Individual_birth_plan_counselling__c:\n p.properties.individual_birth_plan,\n Reason_for_not_taking_a_pregnancy_test__c: p.properties.No_Preg_Test\n ? p.properties.No_Preg_Test.toString().replace(/_/g, ' ')\n : undefined,\n Pregnancy_danger_signs__c: p.properties.No_Preg_Test\n ? pregDangerMap[p.properties.No_Preg_Test]\n : undefined,\n Child_Danger_Signs__c: p.properties.Other_Danger_Signs\n ? childDangerSignsMap[p.properties.Other_Danger_Signs]\n : undefined,\n Current_Malaria_Status__c: cleanChoice(\n p.properties.malaria_test_results\n ),\n Malaria_Home_Test__c: p.properties.malaria_test_date,\n Malaria_Home_Treatment__c: p.properties.malaria_test_date,\n Persons_symptoms__c: personsSymptoms,\n Active_in_Support_Group__c: p.properties.Active_in_Support_Group,\n HAWI_Defaulter__c: p.properties.default === 'Yes' ? true : false,\n Date_of_Default__c: p.properties.date_of_default,\n Persons_temperature__c: p.properties.temperature,\n Days_since_illness_start__c: p.properties.duration_of_sickness,\n Newborn_visited_48_hours_of_delivery__c:\n p.properties.newborn_visited_48_hours_of_delivery,\n Newborn_visited_by_a_CHW_within_6_days__c:\n p.properties.visit_6_days_from_delivery,\n Current_Malaria_Status__c: p.properties.malaria_test_results,\n Malaria_test__c: cleanChoice(p.properties.malaria_test),\n Fever__c: cleanChoice(p.properties.symptoms_check_fever),\n Cough__c: cleanChoice(p.properties.symptoms_check_cough),\n Diarrhoea__c: cleanChoice(p.properties.symptoms_check_diarrhea),\n TB_patients_therapy_observed__c: p.properties.observed_tb_therapy,\n Injuries_or_wounds__c: p.properties.wounds_or_injuries,\n Currently_on_ART_s__c: p.properties.ART,\n // ART_Regimen__c: () => {\n // const choice = dataValue(\n // 'properties.ARVs;\n // return cleanChoice(choice);\n // },\n Immediate_Breastfeeding__c: p.properties.Breastfeeding_Delivery,\n Exclusive_Breastfeeding__c: p.properties.Exclusive_Breastfeeding,\n Counselled_on_Exclusive_Breastfeeding__c: p.properties.counseling,\n LMP__c: p.properties.when_was_your_lmp,\n Family_Planning__c: cleanChoice(p.properties.family_planning),\n Family_Planning_Method__c: p.properties.family_planning_method,\n Family_Planning_Method__c: familyPlanningMethod,\n FP_Method_Distributed__c: fpMethodDistributed,\n Reasons_for_not_taking_FP_method__c: reasonForNotTakingFPMethod,\n Pregnant__c: p.properties.Pregnant === 'Yes' ? true : false,\n Counselled_on_FP_Methods__c: cleanChoice(\n p.properties.CounselledFP_methods\n ),\n Client_counselled_on__c: clientCounselledOnC,\n Client_provided_with_FP__c: cleanChoice(\n p.properties[\n 'was_the_woman_15-49yrs_provided_with_family_planning_commodities_by_chv'\n ]\n ),\n Newborn_visited_48_hours_of_delivery__c:\n p.properties.newborn_visited_48_hours_of_delivery,\n Mother_visit_counselling__c: cleanChoice(\n p.properties.did_you_consel_the_mother_on1\n ),\n mother_visited_48_hours_of_the_delivery__c:\n p.properties.visit_mother_48,\n Newborn_visit_counselling__c: cleanChoice(\n p.properties.did_you_consel_the_mother_on2\n ),\n Know_HIV_status__c: cleanChoice(p.properties.known_hiv_status),\n HIV_Status__c: p.properties.hiv_status,\n Treatment_Distribution__c: treatmentDistributionC,\n // QUESTION: Field name not found : Current_Weight__c\n // Current_Weight__c: p.properties.Current_Weight,\n Current_Height__c: p.properties.current_height,\n Current_MUAC__c: p.properties.MUAC,\n Food_groups_3_times_a_day__c: p.properties.food_groups,\n Nutrition_Case_Managed__c: p.properties.nutrition_case_managed,\n Nutrition_Danger_Signs__c: handleMultiSelectOriginal(\n p.properties.nutrition_danger_signs\n ),\n Why_was_nutrition_case_not_managed__c:\n p.properties.nutrition_case_not_managed_why,\n Community_Nutrition_Treatment__c:\n p.properties.nutrition_treatment_severe,\n Community_Nutrition_Treatment__c:\n p.properties.nutrition_treatment_moderate,\n Why_was_nutrition_treatment_not_given__c:\n p.properties.nutrition_treatment_not_given,\n Current_Nutrition_Status__c: p.properties.Nutrition_Status\n ? nutritionMap[p.properties.Nutrition_Status]\n : undefined,\n Default_on_TB_treatment__c: cleanChoice(\n p.properties.default_tb_treatment\n ),\n Received_pregnancy_test__c: cleanChoice(\n p.properties.did_you_adminsiter_a_pregnancy_test\n ),\n Pregnancy_test_result__c: cleanChoice(\n p.properties.pregnancy_test_result\n ),\n Chronic_illness__c: chronicIllnesC,\n Childs_breath_per_minute__c: p.properties.breaths_per_minuite,\n Child_chest_in_drawing__c: p.properties.Child_chest_in_drawing_c,\n Caregiver_counseled_on_delayed_milestone__c:\n p.properties.did_you_counsel_the_caregiver_on_delayed_milestones,\n Delayed_Milestone__c:\n p.properties.does_the_child_has_a_delayed_milestone,\n Child_has_2_or_more_play_items__c:\n p.properties.does_the_child_has_2_or_more_play_items_at_home,\n Child_has_3_more_picture_books__c:\n p.properties.does_the_child_has_3_or_more_picture_books,\n Delayed_Milestones_Counselled_On__c: p.properties\n .which_delayed_milestone_area_did_you_counsel_the_caregiver_on\n ? milestoneMap[\n p.properties\n .which_delayed_milestone_area_did_you_counsel_the_caregiver_on\n ]\n : undefined,\n Delayed_Milestone_Type__c: p.properties.which_delayed_milestone\n ? milestoneMap[p.properties.which_delayed_milestone]\n : undefined,\n Caretaker_trained_in_muac__c: p.properties.mother_trained_muac,\n Caretaker_screened_for_muac_this__c:\n p.properties.mother_screened_child_muac,\n Caretaker_muac_findings__c:\n p.properties.mother_screened_child_muac_result,\n Caretaker_action_after_muac_screening__c:\n p.properties.mother_screened_muac_action,\n of_Caretaker_MUAC_screenings__c: p.properties.mother_nb_screening,\n Pulse_Oximeter__c: p.properties.pulse_oximeter_available,\n Heart_Rate_Pulse_Oximeter__c: p.properties.heart_rate_pulse_oximeter,\n Oxygen_Concentration_Pulse_Oximeter__c:\n p.properties.oxygen_concentration,\n Can_child_drink__c: p.properties.can_child_drink,\n Antibiotic_provided_for_fast_breathing__c:\n p.properties.antibiotic_fast_breathing,\n Antibiotic_provided_for_chest_indrawing__c:\n p.properties.antibiotic_chest_indrawing,\n Supervisor_Visit__c: supervisorVisit,\n //HMN commented this one due to error \"Error: InvalidBatch : Field name not found : Visit_Closed_Date__c\"\n //Visit_Closed_Date__c: p.properties.date_closed,\n //29/06/2023 Added Malaria Vaccine mapping \n malaria_vaccine_received__c:\n p.properties.malaria_vaccine_received,\n rts_s_1_date__c:\n p.properties.rts_s_1_date,\n rts_s_2_date__c:\n p.properties.rts_s_2_date, \n rts_s_3_date__c:\n p.properties.rts_s_3_date, \n rts_s_4_date__c:\n p.properties.rts_s_4_date, \n \n //HMN 29/06/2023\n };\n });\n\n personVisits.forEach(person => {\n Object.entries(person).forEach(([key, value]) => {\n if (value === '' || value === null) person[key] = undefined;\n });\n });\n\n // JSON logging of records\n //HMN debugger 19/10/2023\n // console.log(JSON.stringify(personVisits, null, 2));\n\n return { ...state, personVisits };\n});\n\nbulk(\n 'Person_visit__c',\n 'upsert',\n {\n extIdField: 'CommCare_ID__c',\n failOnError: true,\n allowNoOp: true,\n },\n state => {\n console.log('Bulk upserting person visit...');\n return state.personVisits;\n }\n);\n", + "adaptor": "@openfn/language-salesforce@4.8.6", + "project_credential_id": "25ba06d8-5559-4d1c-a8b8-828cc3021465" + } + }, + "edges": { + "cron->WF3-1-Bulk-get-Person-Visit-cases": { + "enabled": true, + "id": "e0aafc87-97d6-425f-8ed3-063c2f348bd0", + "target_job_id": "622d2cc3-0ed1-410a-ac6e-9ba7b8fab05d", + "source_trigger_id": "741b5feb-cd4c-4acd-af47-0788b6ada29a", + "condition_type": "always" + }, + "WF3-1-Bulk-get-Person-Visit-cases->WF3-2-Bulk-upsert-Person-Visits": { + "enabled": true, + "id": "d42f8845-c9a4-4034-9075-591611da9f1b", + "target_job_id": "19b00789-97a6-4642-87ef-5d3fbee7d423", + "source_job_id": "622d2cc3-0ed1-410a-ac6e-9ba7b8fab05d", + "condition_type": "on_job_success" + } + } + }, + "4-Bulk-Referral-cases": { + "id": "9b9f015e-d475-4dfc-af0a-9e8f44fe3b3f", + "name": "4-Bulk Referral cases", + "inserted_at": "2025-01-31T13:02:47.240277Z", + "lock_version": 10, + "triggers": { + "cron": { + "enabled": true, + "id": "81cb87ab-bb2a-4d09-94c2-22745147458f", + "type": "cron", + "cron_expression": "2 * * * *" + } + }, + "jobs": { + "WF4-1-Bulk-get-Referral-Cases": { + "id": "86131aad-63a9-4003-b562-a4428b719564", + "name": "WF4-1 Bulk get Referral Cases", + "body": "fn(state => {\n const { baseUrl } = state.configuration;\n\n const caseTypes = ['Case'];\n\n //NOTE: You can use 'limit' to modify this batch size as desired\n const limit = 1000; //E.g., change to 10 to process records in smaller batch sizes\n\n //NOTE: indexedOnStart is the default sync start data the FIRST time the job runs\n const indexedOnStart = '2024-01-17T00:00:00';\n\n //NOTE: After first job run, OpenFn will check the job sync data (\"lastRunAt\") to set as the indexedOnStart\n const lastRunAt =\n typeof state.lastRunAt !== 'undefined' ? state.lastRunAt : indexedOnStart;\n console.log('Filtering cases with indexed_on_start > than ::', lastRunAt);\n\n const queries = caseTypes.map(\n t => `?type=${t}&indexed_on_start=${lastRunAt}&limit=${limit}\n &owner_id=a3c31c9be392427a97f8704262065661` // User id of test user test.2021. Remove for production`\n //NOTE: If for testing, you want to fetch data for a specific historical range (e.g., between April 23 and 24)...\n //...then use the query string below instead of the one above on L16, and custom adjust the index_on start/end dates\n //t => `?type=${t}&indexed_on_start=2024-01-14T00:00:00&limit=${limit}&indexed_on_end=2024-01-16T23:59:59`\n );\n\n return { ...state, queries, baseUrl, payloads: [] };\n});\n\n// create a \"recursiveGet\" which will call itself if CommCare tells us there's\n// more data to fetch for the same form\nfn(state => {\n const recursiveGet = url =>\n get(\n url,\n {\n headers: { 'content-type': 'application/json' },\n },\n nextState => {\n const now = new Date();\n const { baseUrl, data, payloads } = nextState;\n\n const { meta, objects } = data;\n console.log('Metadata in CommCare response:', meta);\n\n const finalState = {\n ...nextState,\n payloads: [...payloads, ...objects],\n };\n\n if (meta.next) {\n console.log('Next query detected, recursing...');\n return recursiveGet(`${baseUrl}${meta.next}`)(finalState);\n }\n finalState.lastRunAt = now.toISOString().slice(0, 19);\n return finalState;\n }\n );\n\n return { ...state, recursiveGet };\n});\n\n// for each initial query, fetch data recursively\neach(\n '$.queries[*]',\n fn(state => {\n return state.recursiveGet(`${state.baseUrl}${state.data}`)(state);\n })\n);\n// log the total number of payloads returned\nfn(state => {\n console.log('Count of payloads', state.payloads.length);\n return { ...state, references: [], data: {} };\n});\n", + "adaptor": "@openfn/language-http@6.5.0", + "project_credential_id": "8d4d9b2d-e41a-40ab-92dc-e2280bb5ee2b" + }, + "WF4-2-Bulk-upsert-Services": { + "id": "e1ee9db3-e4bb-4051-8763-27946c9940d9", + "name": "WF4-2 Bulk upsert Services", + "body": "// NOTE: We perform a query before anything else if this is a 'Case'\nfn(state => {\n // state.type = state.data.indices.parent.case_type;\n if (state.payloads.length == 0) return { ...state, services: [] };\n\n const caseType = state.payloads\n .filter(c => c.indices.parent.case_type === 'Case')\n .map(c => c.indices.parent.case_id);\n\n console.log(JSON.stringify(caseType, null, 2));\n\n if (caseType.length > 0)\n return query(\n `SELECT Person__r.CommCare_ID__c FROM Service__c WHERE Service_UID__c IN ('${caseType.join(\n \"','\"\n )}')`\n )(state).then(state => {\n const { records } = state.references[0];\n const ccId =\n records.length == 1 ? records[0].Person__r.CommCare_ID__c : null;\n return { ...state, ccId };\n });\n\n return state;\n});\n\n// NOTE: We construct a facilityMap and populate some conditional relationships\nfn(state => {\n if (state.payloads.length == 0) return state;\n const facilityMap = {\n Lwala_Hospital: 'Lwala Hospital',\n Minyenya_Dispensary: 'Minyenya Dispensary',\n Ndege_Oriedo_Dispensary: 'Ndege Oriedo Dispensary',\n 'Rongo_Sub-District_Hospital': 'Rongo Sub-District Hospital',\n Kangeso_Dispensary: 'Kangeso Dispensary',\n Ngodhe_Dispensary: 'Ngodhe Dispensary',\n Ngere_Dispensary: 'Ngere Dispensary',\n Verna_Health_Center: 'Verna Health Center',\n Kochola_Dispensary: 'Kochola Dispensary',\n Ongo_Health_Center: 'Ongo Health Center',\n Royal_Medical_Center: 'Royal Medical Center',\n Rosewood_Facility: 'Rosewood Facility',\n Other: 'Other',\n };\n\n const pregDangerMap = {\n Vaginal_Bleeding: 'Vaginal Bleeding',\n Water_Breaks: 'Water Breaks before Time of Delivery',\n Prolonged_Labour: 'Prolonged Labour over 12 Hours',\n Convulsions: 'Convulsions or Fits',\n Abdominal_Pain: 'Severe Abdominal Pain before Delivery',\n High_Fever: 'High Fever',\n Low_Baby_Movement: 'Feeling the Baby move less or not at all',\n Swelling: 'Swelling of Face and Hands',\n Severe_Headache: 'Severe or Continuous Headache for more than 12 hours',\n Severe_Vomiting: 'Severe or Continuous Vomiting',\n none: 'None',\n };\n\n const serviceMap = {\n Scheduled_PSC_Apt: 'Scheduled PSC Apt',\n Adverse_Drug_Reaction_Side_Effect: 'Adverse Drug Reaction/Side Effect',\n Malnutrition: 'Malnutrition',\n Malaria: 'Malaria',\n TB: 'TB',\n Treatment_for_Other_OIs: 'Treatment for Other OIs',\n ARI: 'ARI',\n Anemia: 'Anemia',\n Diarrhea: 'Diarrhea',\n Pregnancy_Care: 'Pregnancy Care (ANC)',\n Family_Planning: 'Family Planning (FP)',\n Preconception_Counseling: 'Preconception Counseling',\n Injury: 'Injury',\n Other: 'Other',\n };\n\n const milestoneTypeMap = {\n cognitive_delays_learning_difficulties:\n 'Cognitive Delays (Learning Difficulties)',\n motor_delays: 'Motor Delays',\n speech_and_language_delay: 'Speech and language Delay',\n social_and_emotional: 'Social and emotional',\n };\n\n const symptomsMap = {\n convulsions: 'Convulsions',\n not_able_to_eatdrink: 'Not able to eat/drink',\n vomits_everything: 'Vomits everything',\n 'chest_in-drawing': 'Chest in-drawing',\n unusually_sleepyunconscious: 'Unusually sleepy/unconscious',\n swelling_of_both_feet: 'Swelling of both feet',\n };\n\n const childSignMap = {\n Poor_Breastfeeding: 'Poor Breastfeeding (under 6 months old child)',\n not_able_to_feed_since_birth_or_stopped_feeding_well:\n 'Not able to feed since birth, or stopped feeding well',\n not_able_to_breastfeed: 'Not able to breastfeed',\n Fever: 'Fever (37.5 C or more)',\n very_low_temperature: 'Very low temperature (35.4 C or less)',\n shivering: 'Shivering',\n Fast_Breathing: 'Fast Breathing',\n Very_Sleepy: 'Very Sleepy',\n Convulsions_and_Fits: 'Convulsions and Fits',\n only_moves_when_stimulated_or_does_not_move_even_on_stimulation:\n 'Only moves when stimulated, or does not move even on stimulation',\n yellow_solebaby_body_turning_yellow_especially_eyes_palms_soles:\n 'Yellow sole(Baby body turning yellow especially eyes, palms, soles)',\n bleeding_from_the_umbilical_stump: 'Bleeding from the umbilical stump',\n signs_of_local_infection_umbilicus_is_red_or_draining_pus_skin_boils_or_eye:\n 'Signs of local infection: umbilicus is red or draining pus, skin boils, or eyes draining pus',\n weight_chart_using_color_coded_scales_if_red_or_yellowweight_below_25kg_or_:\n 'Weight chart using color coded scales if RED or YELLOW(Weight below 2.5kg or born less than 36 weeks of age)',\n unable_to_cry: 'Unable to cry',\n cyanosis: 'Cyanosis',\n bulging_fontanelle: 'Bulging fontanelle',\n };\n\n const otherReferralMap = {\n HIV_Testing_and_Counseling: 'HIV Testing and Counseling',\n Visit_to_Clinician: 'Visit to Clinician',\n Adverse_Drug_Reaction_Side_Effect: 'Adverse Drug Reaction Side Effect',\n Malnutrition: 'Malnutrition',\n Malaria: 'Malaria',\n PMTCT: 'PMTCT',\n TB: 'TB',\n Treatment_for_other_OIs: 'Treatment for other OIs',\n ARI: 'ARI',\n Anemia: 'Anemia',\n Diarrhea: 'Diarrhea',\n Pregnancy_Care_ANCE: 'Pregnancy Care (ANC)',\n Family_Planning_FP: 'Family Planning (FP)',\n Preconception_Counseling: 'Preconception Counseling',\n Injury: 'Injury',\n blood_in_stool: 'Blood in Stool',\n Blood_in_Stool: 'Blood in Stool',\n Immunization: 'Immunization',\n Routine_Health_Check_ups: 'Routine Health Check ups',\n routine_health_check_ups: 'Routine Health Check ups',\n Other: 'Other',\n Poor_Breastfeeding: 'Poor Breastfeeding (under 6 months old child)',\n not_able_to_feed_since_birth_or_stopped_feeding_well:\n 'Not able to feed since birth, or stopped feeding well',\n not_able_to_breastfeed: 'Not able to breastfeed',\n Fever: 'Fever (37.5 C or more)',\n very_low_temperature: 'Very low temperature (35.4 C or less)',\n shivering: 'Shivering',\n Fast_Breathing: 'Fast Breathing',\n Very_Sleepy: 'Very Sleepy',\n Convulsions_and_Fits: 'Convulsions and Fits',\n only_moves_when_stimulated_or_does_not_move_even_on_stimulation:\n 'Only moves when stimulated, or does not move even on stimulation',\n yellow_solebaby_body_turning_yellow_especially_eyes_palms_soles:\n 'Yellow sole(Baby body turning yellow especially eyes, palms, soles)',\n bleeding_from_the_umbilical_stump: 'Bleeding from the umbilical stump',\n signs_of_local_infection_umbilicus_is_red_or_draining_pus_skin_boils_or_eye:\n 'Signs of local infection: umbilicus is red or draining pus, skin boils, or eyes draining pus',\n weight_chart_using_color_coded_scales_if_red_or_yellowweight_below_25kg_or_:\n 'Weight chart using color coded scales if RED or YELLOW(Weight below 2.5kg or born less than 36 weeks of age)',\n unable_to_cry: 'Unable to cry',\n cyanosis: 'Cyanosis',\n bulging_fontanelle: 'Bulging fontanelle',\n };\n\n const homeCareMap = {\n Adherence_Counseling: 'Adherence Counseling',\n Pill_Count_Monitoring: 'Pill Count Monitoring',\n Nutrition_Assessment_and_Counseling: 'Nutrition Assessment and Counseling',\n WASH_Counseling: 'WASH Counseling',\n Prevention_Counseling: 'Prevention Counseling',\n Psychosocial_Support: 'Psychosocial Support',\n Provision_of_Supplies: 'Provision of Supplies',\n OI_Management_Support: 'OI Management Support',\n };\n\n const ecdMap = {\n physiotherapy: 'Physiotherapy',\n speech_therapy: 'Speech Therapy',\n nutrition_education: 'Nutrition Education',\n play_therapy: 'Play Therapy',\n assessment: 'Assessment',\n counselling: 'Counselling',\n other: 'Other',\n };\n\n const clinicalMap = {\n diarrhea: 'Diarrhea',\n malnutrition: 'Malnutrition',\n malaria: 'Malaria',\n acute_respiratory_infection: 'Acute Respiratoy Infection (ARI)',\n accident_injury: 'Accident/Injury',\n other: 'Other',\n };\n\n const caseType = state.payloads\n .filter(c => c.indices.parent.case_type === 'Case')\n .map(c => c.indices.parent.case_id);\n\n const personType = state.payloads\n .filter(c => c.indices.parent.case_type === 'Person')\n .map(c => c.indices.parent.case_id);\n\n let relationships = [];\n\n // If it's a person, add the person relationship\n if (personType.length > 0) {\n personType.forEach(case_id => {\n relationships.push({ 'Person__r.CommCare_ID__c': case_id });\n });\n }\n\n // If it's a service, add the service rship AND a different person rship\n if (caseType.length > 0) {\n caseType.forEach(case_id => {\n relationships.push({ 'Parent_Service__r.Service_UID__c': case_id });\n });\n\n relationships.push({ 'Person__r.CommCare_ID__c': state.ccId });\n }\n\n return {\n ...state,\n facilityMap,\n relationships,\n serviceMap,\n pregDangerMap,\n milestoneTypeMap,\n symptomsMap,\n childSignMap,\n otherReferralMap,\n homeCareMap,\n clinicalMap,\n ecdMap,\n };\n});\n\n// NOTE: We finally upsert to the Service__c object in Salesforce\nfn(state => {\n if (state.payloads.length == 0) return state;\n const services = state.payloads\n .filter(r => r.properties.owner_id !== '8e725928e3ce43d19b390dd604097069')\n .map(r => {\n // pregnancyDangerSigns\n const pCheck = r.properties.pregnancy_danger_signs;\n const pValue =\n pCheck && pCheck !== ''\n ? pCheck\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return state.pregDangerMap[value] || value;\n })\n : undefined;\n const pregnancyDangerSigns = pValue ? pValue.join(';') : undefined;\n\n // childDangerSigns\n const cCheck = r.properties.Other_Danger_Signs;\n const cValue =\n cCheck && cCheck !== ''\n ? cCheck\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return state.childSignMap[value] || value;\n })\n : undefined;\n const childDangerSigns = cValue ? cValue.join(';') : undefined;\n\n // delayedMilestone\n const dCheck = r.properties.which_delayed_milestone;\n const dValue =\n dCheck && dCheck !== ''\n ? dCheck\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return state.milestoneTypeMap[value] || value;\n })\n : undefined;\n const delayedMilestone = dValue ? dValue.join(';') : undefined;\n\n // seriousSymptoms\n const sCheck = r.properties.symptoms_check_other;\n const sValue =\n sCheck && sCheck !== ''\n ? sCheck\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return state.symptomsMap[value] || value;\n })\n : undefined;\n const seriousSymptoms = sValue ? sValue.join(';') : undefined;\n\n // otherReferralReason\n const otCheck = r.properties.Other_Referral_Reasons;\n const otValue =\n otCheck && otCheck !== ''\n ? otCheck\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return state.otherReferralMap[value] || value;\n })\n : undefined;\n const otherReferralReason = otValue ? otValue.join(';') : undefined;\n\n // homeBasedCareRendered\n const homeCheck = r.properties.Home_Based_Care_Provided;\n const homeValue =\n homeCheck && homeCheck !== ''\n ? homeCheck\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return state.homeCareMap[value] || value;\n })\n : undefined;\n const homeBasedCareRendered = homeValue ? homeValue.join(';') : undefined;\n\n // ecdClinicalService\n const ecdCheck = r.properties.ECD_Clinical_Service;\n const ecdValue =\n ecdCheck && ecdCheck !== ''\n ? ecdCheck\n .replace(/ /gi, ';')\n .split(';')\n .map(value => {\n return state.ecdMap[value] || value;\n })\n : undefined;\n const ecdClinicalService = ecdValue ? ecdValue.join(';') : undefined;\n\n return {\n 'Person__r.CommCare_ID__c':\n r.indices.parent.case_type === 'Person'\n ? r.indices.parent.case_id\n : r.indices.parent.case_type === 'Case'\n ? state.ccId\n : undefined,\n Service_UID__c: r.case_id,\n CommCare_Code__c: r.case_id,\n RecordTypeID: '01224000000YAuK',\n 'Household_CHW__r.CommCare_ID__c': r.properties.CHW_ID,\n Open_Case__c: r.closed === false ? true : false,\n Case_Closed_Date__c: r.properties.date_closed,\n Age_Time_of_Service__c: r.properties.age,\n Source__c: r.properties.Source === '1',\n Clinical_facility__c: r.properties.Facility_Visited\n ? state.facilityMap[r.properties.Facility_Visited]\n : undefined,\n Client_Received_Services_at_Facility2__c: r.properties.Facility_Visit,\n Clinical_Visit_Date__c:\n r.properties.Facility_Date === '' ||\n r.properties.Facility_Date === undefined\n ? undefined\n : r.properties.Facility_Date,\n CHW_Followed_Up_with_the_Client__c: r['properties.Follow-Up']!== ''\n ? r['properties.Follow-Up']\n : undefined,\n Follow_Up_Date__c: r['properties.Follow-Up_Date'],\n \n Person_Complied_w_Referral_in_24_hrs__c:r.properties.referral_compliance,\n Skillled_Delivery__c: r.properties.skilled_delivery,\n Child_received_immunizations__c: r.properties.immunization,\n Received_a_diagnosis_for_PSBI__c: r.properties.psbi_diagnosis !== ''\n ? r.properties.psbi_diagnosis\n : undefined, //Form: CHW.Follow-Up.PSBI.psbi_diagnosis\n Received_antibiotics_per_protocol__c: r.properties.antibiotic_8days, //Form: CHW.Follow-Up.PSBI.antibiotic_8day\n \n Distributed_Treatment_on_Last_Visit__c:\n r.properties.distribute_treatment, //Form: CHW.Follow-Up.distribute_treatment\n Person_had_an_adverse_drug_reaction__c:\n r.properties.adverse_drug_reaction,\n Defaulted__c:\n r.properties.date_of_default && r.properties.date_of_default !== ''\n ? true\n : false,\n Date_of_Default__c: r.properties.date_of_default,\n Client_s_Symptoms_Improved__c: r.properties.Client_Improved,\n Case_Type__c: r.properties.Case_Type,\n Follow_Up_By_Date__c:\n r.properties['Follow-Up_By_Date'] &&\n r.properties['Follow-Up_By_Date'] !== ''\n ? r.properties['Follow-Up_By_Date']\n : undefined,\n Date__c: new Date(r.properties.date_opened).toISOString(),\n Reason_for_Service__c: r.properties.Reason_for_Service,\n Type_of_Service__c: r.properties.Type_of_Service,\n Malaria_Status__c: r.properties.Malaria_Status,\n Home_Treatment_Date__c: r.properties.home_treatment_date,\n Malaria_Home_Test_Date__c: r.properties.malaria_test_date,\n Home_ORS__c: r.properties.clinic_ors,\n Home_Zinc__c: r.properties.clinic_zinc,\n Height__c: r.properties.height,\n Weight__c: r.properties.weight,\n MUAC__c: r.properties.muac,\n Nutrition_Status__c: r.properties.Nutrition_Status,\n \n //===== NEW MAPPINGS - JAN 14 ===========================//\n Pregnancy_Danger_Signs__c: pregnancyDangerSigns,\n Child_Danger_Signs__c: childDangerSigns,\n Delayed_Milestone__c: delayedMilestone,\n Serious_Symptoms__c: seriousSymptoms,\n Other_Referral_Reasons__c: otherReferralReason,\n Home_Based_Care_Rendered__c: homeBasedCareRendered,\n PSBI_Visit__c:\n r.properties.psbi_task && r.properties.psbi_task !== ''\n ? `Day ${r.properties.psbi_task}`\n : undefined,\n Clinical_Services__c: r.properties.TT5_Clinical_Service\n ? state.clinicalMap[r.properties.TT5_Clinical_Service]\n : r.properties.TT5_Clinical_Service,\n Referred_Facility__c: r.properties.referred_facility\n ? state.facilityMap[r.properties.referred_facility]\n : r.properties.referred_facility,\n HAWI_Clinical_Services__c: r.properties.HAWI_Clinical_Service\n ? state.serviceMap[r.properties.HAWI_Clinical_Service]\n : r.properties.HAWI_Clinical_Service,\n ECD_Clinical_Services__c: ecdClinicalService,\n \n };\n });\n\n return { ...state, services };\n});\n/* JSON logging of records\nfn(state => {\n console.log('Services to upsert ::', JSON.stringify(state.services));\n return state;\n});\n*/\n\nbulk(\n 'Service__c',\n 'upsert',\n {\n extIdField: 'Service_UID__c',\n failOnError: true,\n allowNoOp: true,\n },\n state => {\n console.log('Bulk upserting service...');\n return state.services;\n }\n);\n", + "adaptor": "@openfn/language-salesforce@4.8.6", + "project_credential_id": "25ba06d8-5559-4d1c-a8b8-828cc3021465" + } + }, + "edges": { + "cron->WF4-1-Bulk-get-Referral-Cases": { + "enabled": true, + "id": "5374d98e-b750-4e77-a573-fdf2ac5035e1", + "target_job_id": "86131aad-63a9-4003-b562-a4428b719564", + "source_trigger_id": "81cb87ab-bb2a-4d09-94c2-22745147458f", + "condition_type": "always" + }, + "WF4-1-Bulk-get-Referral-Cases->WF4-2-Bulk-upsert-Services": { + "enabled": true, + "id": "9af5cee1-69d5-45bf-91c0-f60fcd385729", + "target_job_id": "e1ee9db3-e4bb-4051-8763-27946c9940d9", + "source_job_id": "86131aad-63a9-4003-b562-a4428b719564", + "condition_type": "on_job_success" + } + } + } + }, + "requires_mfa": false, + "collections": {} +} \ No newline at end of file